code stringlengths 2 1.05M | repo_name stringlengths 5 104 | path stringlengths 4 251 | language stringclasses 1
value | license stringclasses 15
values | size int32 2 1.05M |
|---|---|---|---|---|---|
import math
from service.fake_api_results import ALL_TITLES, OFFICIAL_COPY_RESULT, SELECTED_FULL_RESULTS
SEARCH_RESULTS_PER_PAGE = 20
def get_title(title_number):
return SELECTED_FULL_RESULTS.get(title_number)
def _get_titles(page_number):
nof_results = len(ALL_TITLES)
number_pages = math.ceil(nof_resu... | LandRegistry/drv-flask-based-prototype | service/api_client.py | Python | mit | 898 |
#!/usr/bin/env python3
#
# grmpy documentation build configuration file, created by
# sphinx-quickstart on Fri Aug 18 13:05:32 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All ... | grmToolbox/grmpy | docs/conf.py | Python | mit | 5,902 |
import datetime
import re
import sys
from collections import deque
from decimal import Decimal
from enum import Enum
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
from pathlib import Path
from types import GeneratorType
from typing import Any, Callable, Dict, Typ... | glenngillen/dotfiles | .vscode/extensions/ms-python.python-2021.5.842923320/pythonFiles/lib/jedilsp/pydantic/json.py | Python | mit | 3,365 |
import ROOT
from math import pi, sqrt, pow, exp
import scipy.integrate
import numpy
from array import array
alpha = 7.2973e-3
m_e = 0.51099892
Z_Xe = 54
Q = 2.4578
def F(Z, KE):
E = KE + m_e
W = E/m_e
Z0 = Z + 2
if W <= 1:
W = 1 + 1e-4
if W > 2.2:
a = -8.46e-2 + 2.48e-2*Z0 + 2.... | steveherrin/PhDThesis | Thesis/scripts/make_bb_spectrum_plot.py | Python | mit | 5,583 |
class SubscriptionTracking(object):
def __init__(self, enable=None, text=None, html=None, substitution_tag=None):
self._enable = None
self._text = None
self._html = None
self._substitution_tag = None
if enable is not None:
self.enable = enable
if text is... | galihmelon/sendgrid-python | sendgrid/helpers/mail/subscription_tracking.py | Python | mit | 1,603 |
import novaclient
from novaclient.exceptions import NotFound
import novaclient.client
from keystoneauth1 import loading
from keystoneauth1 import session
import neutronclient.v2_0.client
import cinderclient.v2.client
from osc_lib.utils import wait_for_delete
import taskflow.engines
from taskflow.patterns import line... | CSC-IT-Center-for-Science/pouta-blueprints | pebbles/services/openstack_service.py | Python | mit | 23,846 |
#!/usr/bin/env python3
import unittest
import greatest_common_divisor as gcd
class TestGreatestCommonDivisor(unittest.TestCase):
def setUp(self):
# use tuple of tuples instead of list of tuples because data won't change
# https://en.wikipedia.org/wiki/Algorithm
# a, b, expected
s... | beepscore/greatest_common_divisor | test/test_greatest_common_divisor.py | Python | mit | 2,281 |
# coding: utf-8
"""
Модуль с преднастроенными панелями-деевьями
"""
from __future__ import absolute_import
from m3.actions.urls import get_url
from m3_ext.ui import containers
from m3_ext.ui import controls
from m3_ext.ui import menus
from m3_ext.ui import render_component
from m3_ext.ui.fields import ExtSearchField
... | barsgroup/m3-ext | src/m3_ext/ui/panels/trees.py | Python | mit | 9,988 |
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
if MYPY_CHECK_RUNNING:
from typing import List, Optional
__version__ = "20.0.dev0"
def main(args=None):
# type: (Optional[List[str]]) -> int
"""This is an internal API only meant for use by pip's own console scripts.
For additional details,... | xavfernandez/pip | src/pip/__init__.py | Python | mit | 458 |
from keras.models import Sequential, model_from_json
from keras.layers import Dense, Dropout, Activation, Flatten, Convolution2D, MaxPooling2D, Lambda, ELU
from keras.layers.normalization import BatchNormalization
from keras.optimizers import Adam
import cv2
import csv
import numpy as np
import os
from random import r... | shernshiou/CarND | Term1/04-CarND-Behavioral-Cloning/model.py | Python | mit | 6,595 |
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
# called from wnf.py
# lib/wnf.py --install [rootpassword] [dbname] [source]
from __future__ import unicode_literals
import os, sys, json
import webnotes
import webnotes.db
import getpass
from webnotes.model.db_s... | saurabh6790/omnisys-lib | webnotes/install_lib/install.py | Python | mit | 8,275 |
import random
class ai:
def __init__(self, actions, responses):
self.IN = actions
self.OUT = responses
def get_act(self, action, valres):
if action in self.IN:
mList = {}
for response in self.OUT:
if self.IN[self.OUT.index(response)] == ... | iTecAI/Stixai | Module/Stixai.py | Python | mit | 1,343 |
# pylint: disable-msg=too-many-lines
"""OPP Hardware interface.
Contains the hardware interface and drivers for the Open Pinball Project
platform hardware, including the solenoid, input, incandescent, and neopixel
boards.
"""
import asyncio
from collections import defaultdict
from typing import Dict, List, Set, Union,... | missionpinball/mpf | mpf/platforms/opp/opp.py | Python | mit | 53,276 |
from django.db import models
from constituencies.models import Constituency
from uk_political_parties.models import Party
from elections.models import Election
class Person(models.Model):
name = models.CharField(blank=False, max_length=255)
remote_id = models.CharField(blank=True, max_length=255, null=True)... | JustinWingChungHui/electionleaflets | electionleaflets/apps/people/models.py | Python | mit | 1,603 |
import json
from app import models
from django.test import Client, TestCase
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
# Create your tests here.
class TestLecturerWeb(TestCase):
def _init_test_lecturer(self):
... | malaonline/Server | server/lecturer/tests.py | Python | mit | 4,001 |
from settings.common import Common
class Dev(Common):
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'ffrpg.sql', # Or path to database file if using sqlite3.
#... | Critical-Impact/ffrpg-gen | django/settings/dev.py | Python | mit | 650 |
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACCOUNT_SID"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)
number = client.lookups.phone_numbers("+16502530000... | teoreteetik/api-snippets | lookups/lookup-get-cname-example-1/lookup-get-cname-example-1.6.x.py | Python | mit | 417 |
import json
from dateutil import parser as datetime_parser
from occam.app import get_redis
from occam.runtime import OCCAM_SERVER_CONFIG_KEY
def get_servers():
redis = get_redis()
servers = json.loads(redis.get(OCCAM_SERVER_CONFIG_KEY))
return servers.items()
def iterate_servers():
redis = get_re... | Yelp/occam | occam/util.py | Python | mit | 715 |
import json
f = open('text-stripped-3.json')
out = open('text-lines.json', 'w')
start_obj = json.load(f)
end_obj = {'data': []}
characters_on_stage = []
currently_speaking = None
last_scene = '1.1'
for i in range(len(start_obj['data'])):
obj = start_obj['data'][i]
if obj['type'] == 'entrance':
if obj['characte... | SyntaxBlitz/syntaxblitz.github.io | mining-lear/process/step6.py | Python | mit | 1,654 |
from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth.decorators import login_required
from .views import UploadBlackListView, DemoView, UdateBlackListView
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^upload-blacklist$', login_required(Upload... | nirvaris/nirvaris-djangofence | djangofence/urls.py | Python | mit | 566 |
import requests
from flask import session, Blueprint, redirect
from flask import request
from grano import authz
from grano.lib.exc import BadRequest
from grano.lib.serialisation import jsonify
from grano.views.cache import validate_cache
from grano.core import db, url_for, app
from grano.providers import github, twi... | clkao/grano | grano/views/sessions_api.py | Python | mit | 5,328 |
import json
import logging
from foxglove import glove
from httpx import Response
from .settings import Settings
logger = logging.getLogger('ext')
def lenient_json(v):
if isinstance(v, (str, bytes)):
try:
return json.loads(v)
except (ValueError, TypeError):
pass
return... | tutorcruncher/morpheus | src/ext.py | Python | mit | 3,555 |
from distutils.core import setup
setup(
name='sequencehelpers',
py_modules=['sequencehelpers'],
version='0.2.1',
description="A library consisting of functions for interacting with sequences and iterables.",
author='Zach Swift',
author_email='cras.zswift@gmail.com',
url='https://github.com/2achary/sequen... | 2achary/sequencehelpers | setup.py | Python | mit | 467 |
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('kirppu', '0039_counter_private_key'),
]
operations = [
migrations.AlterUniqueTogether(
name='itemtype',
unique_together={('event', 'order')},
),
migrations.R... | jlaunonen/kirppu | kirppu/migrations/0040_remove_itemtype_key.py | Python | mit | 408 |
from django.contrib import admin
from .models import BackgroundImages, Widget
class WidgetAdmin(admin.ModelAdmin):
list_display = ('name', 'link', 'is_featured')
ordering = ('-id',)
class BackgroundAdmin(admin.ModelAdmin):
list_display = ('name', 'created_at')
ordering = ('-id',)
admin.site.regis... | malikshahzad228/widget-jack | widgets/admin.py | Python | mit | 400 |
from pandac.PandaModules import *
from toontown.toonbase.ToonBaseGlobal import *
from DistributedMinigame import *
from direct.interval.IntervalGlobal import *
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from toontown.safezone import Walk
from toontown.toonbase import ToontownTimer
from direct... | ToonTownInfiniteRepo/ToontownInfinite | toontown/minigame/DistributedTagGame.py | Python | mit | 10,955 |
"""Pipeline configuration parameters."""
from os.path import dirname, abspath, join
from sqlalchemy import create_engine
OS_TYPES_URL = ('https://raw.githubusercontent.com/'
'openspending/os-types/master/src/os-types.json')
PIPELINE_FILE = 'pipeline-spec.yaml'
SOURCE_DATAPACKAGE_FILE = 'source.datapa... | Victordeleon/os-data-importers | eu-structural-funds/common/config.py | Python | mit | 3,382 |
from pokemongo_bot.human_behaviour import sleep
from pokemongo_bot.base_task import BaseTask
class IncubateEggs(BaseTask):
SUPPORTED_TASK_API_VERSION = 1
last_km_walked = 0
def initialize(self):
self.ready_incubators = []
self.used_incubators = []
self.eggs = []
self.km_w... | Compjeff/PokemonGo-Bot | pokemongo_bot/cell_workers/incubate_eggs.py | Python | mit | 8,649 |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Verify data doesn't have basic mistakes, like empty text fields or empty label
candidates.
## Examples
```shell
par... | facebookresearch/ParlAI | parlai/scripts/verify_data.py | Python | mit | 5,106 |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.desk.notifications import delete_notification_count_for
from frappe.core.doctype.user.user import STANDARD_USERS
from frappe.utils.u... | vCentre/vFRP-6233 | frappe/desk/page/messages/messages.py | Python | mit | 3,886 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
from __future__ import (unicode_literals, absolute_import,
division, print_function)
import logging
from django.core.management.base import BaseCommand
from optparse import make_option
from py3compat import PY2
from... | yeleman/snisi | snisi_maint/management/commands/entities_to_cascades.py | Python | mit | 2,414 |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#
# sl-ls.py: get information utility
# Created by NAKAJIMA Takaaki
# Last modified: Apr 16, 2014.
#
# Require: Python v3
#
# See also https://softlayer-api-python-client.readthedocs.org
#
# You should set env variables
# SL_USER... | ryumei/softlayer-utility | sl-ls.py | Python | mit | 3,178 |
from .View import View
class MethuselahView(View):
type = "Methuselah"
trans = {
"stableAfter": {"pick": "l"}
}
| mir3z/life.js | library-scrapper/views/Methuselah.py | Python | mit | 134 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
# Greed is a dice game where you roll up to five dice to accumulate
# points. The following "score" function will be used calculate the
# score of a single roll of the dice.
#
# A greed roll is scored as follows:
#
# * A set of three ones is 100... | kimegitee/python-koans | python3/koans/about_scoring_project.py | Python | mit | 2,731 |
# coding=utf-8
"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page i... | angadpc/Alexa-Project- | twilio/rest/api/v2010/account/message/feedback.py | Python | mit | 5,676 |
""" Tests barbante.api.generate_product_templates_tfidf.
"""
import json
import nose.tools
import barbante.api.generate_product_templates_tfidf as script
import barbante.utils.logging as barbante_logging
import barbante.tests as tests
log = barbante_logging.get_logger(__name__)
def test_script():
""" Tests a... | hypermindr/barbante | barbante/api/tests/test_generate_product_templates_tfidf_api.py | Python | mit | 603 |
param = dict(
useAIon=True,
verbose=False,
chargePreXlinkIons=[1, 3],
chargePostXlinkIons=[2, 5],
basepeakint = 100.0,
dynamicrange = 0.001,
missedsites = 2,
minlength = 4,
maxlength = 51,
modRes = '',
modMass = 0.0,
linkermass = 136.10005,
ms1tol = dict(measure='ppm', val=5),
ms2tol = dict(measure='da', ... | COL-IU/XLSearch | library/Parameter.py | Python | mit | 1,380 |
# coding: utf-8
"""
Talon.One API
The Talon.One API is used to manage applications and campaigns, as well as to integrate with your application. The operations in the _Integration API_ section are used to integrate with our platform, while the other operations are used to manage applications and campaigns. #... | talon-one/talon_one.py | talon_one/models/integration_entity.py | Python | mit | 5,337 |
from math import radians, cos, sin, asin, sqrt
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
... | anduslim/codex | codex_project/actors/haversine.py | Python | mit | 554 |
# -*- coding: utf-8 -*-
#
# This file is part of Karesansui.
#
# Copyright (C) 2009-2012 HDE, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without lim... | karesansui/karesansui | karesansui/gadget/guestby1currentsnapshot.py | Python | mit | 4,377 |
# Stack implementation
class Stack (object):
def __init__ (self):
self.stack = []
def push (self, data):
self.stack.append(data)
def peek (self):
if self.isEmpty():
return None
return self.stack[-1]
def pop (self):
if self.isEmpty():
return None
return self.stack.pop()
def isEmpty (self):
... | mag6367/Cracking_the_Coding_Interview_Python_Solutions | chapter3/stack.py | Python | mit | 418 |
#!/usr/bin/env python
import os,sys
folder = "/media/kentir1/Development/Linux_Program/Fundkeep/"
def makinGetYear():
return os.popen("date +'%Y'").read()[:-1]
def makinGetMonth():
return os.popen("date +'%m'").read()[:-1]
def makinGetDay():
return os.popen("date +'%d'").read()[:-1]
def makinGetPrevYear(daypassed)... | imakin/PersonalAssistant | Fundkeep/modul/b__main_backu.py | Python | mit | 2,347 |
# Created by PyCharm Community Edition
# User: Kaushik Talukdar
# Date: 22-03-2017
# Time: 03:52 PM
#python doesn't allow you to mix strings and numbers directly. numbers must be converted to strings
age = 28
print("Greetings on your " + str(age) + "th birthday... | KT26/PythonCourse | 1. Getting Started/11.py | Python | mit | 322 |
# -*- coding: utf-8 -*-
from cachy import CacheManager
from cachy.serializers import PickleSerializer
class Cache(CacheManager):
_serializers = {
'pickle': PickleSerializer()
}
| sdispater/orator-cache | orator_cache/cache.py | Python | mit | 197 |
import unittest
import os
import os.path
import json
# The folder holding the test data
data_path = os.path.dirname(__file__)
# Set the temporal config for testing
os.environ['TIMEVIS_CONFIG'] = os.path.join(data_path, 'config.py')
import timevis
class TestExperiment(unittest.TestCase):
def setUp(self):
... | gaoce/TimeVis | tests/test_api.py | Python | mit | 1,185 |
# coding=utf-8
import os
import unittest
from hashlib import md5
from django.conf import settings
from djblets.testing.decorators import add_fixtures
from kgb import SpyAgency
from reviewboard.diffviewer.diffutils import patch
from reviewboard.diffviewer.testing.mixins import DiffParserTestingMixin
from reviewboard.... | reviewboard/reviewboard | reviewboard/scmtools/tests/test_svn.py | Python | mit | 39,691 |
import os
from setuptools import setup
import sys
if sys.version_info < (2, 6):
raise Exception('Wiggelen requires Python 2.6 or higher.')
install_requires = []
# Python 2.6 does not include the argparse module.
try:
import argparse
except ImportError:
install_requires.append('argparse')
# Python 2.6 do... | martijnvermaat/wiggelen | setup.py | Python | mit | 2,054 |
#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, panu.ranta@iki.fi, https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile... | panur/kartalla | gtfs2json/generate.py | Python | mit | 6,008 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Student CNN encoder for XE training."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
from models.encoders.core.cnn_util import conv_layer, max_pool, batch_norm... | hirofumi0810/tensorflow_end2end_speech_recognition | models/encoders/core/student_cnn_xe.py | Python | mit | 4,732 |
# -*- coding utf-8 -*-
from __future__ import unicode_literals
import pytest
from structures.insertion_sort import insertion_sort
@pytest.fixture
def sorted_list():
return [i for i in xrange(10)]
@pytest.fixture
def reverse_list():
return [i for i in xrange(9, -1, -1)]
@pytest.fixture
def average_list():
... | tlake/data-structures-mk2 | tests/test_insertion_sort.py | Python | mit | 1,008 |
from flask import Flask
app = Flask(__name__)
app.config.from_object('blog.config')
from blog import views
| t4ec/blog | blog/__init__.py | Python | mit | 110 |
import fileinput
def str_to_int(s):
return([ int(x) for x in s.split() ])
# args = [ 'line 1', 'line 2', ... ]
def proc_input(args):
(n, l) = str_to_int(args[0])
a = tuple(str_to_int(args[1]))
return(l, a)
def solve(args, verbose=False):
(l, a) = proc_input(args)
list_a = list(a)
list_a.sort()
max_dist = max... | cripplet/practice | codeforces/492/attempt/b_lanterns.py | Python | mit | 897 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright (C), 2013, The Schilduil Team. All rights reserved.
"""
import sys
import pony.orm
import suapp.orm
from suapp.logdecorator import loguse, logging
__all__ = ["Wooster", "Drone", "Jeeves"]
class FlowException(Exception):
pass
class ApplicationClos... | schilduil/suapp | suapp/jandw.py | Python | mit | 11,304 |
import numpy
from chainer import cuda
from chainer import function
from chainer.utils import array
from chainer.utils import type_check
class BilinearFunction(function.Function):
def check_type_forward(self, in_types):
n_in = type_check.eval(in_types.size())
if n_in != 3 and n_in != 6:
... | kashif/chainer | chainer/functions/connection/bilinear.py | Python | mit | 6,625 |
# coding: utf-8
import datetime
from sqlalchemy import bindparam
from sqlalchemy import Column
from sqlalchemy import DateTime
from sqlalchemy import func
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy import Table
from sqlalchemy import testing
from sqlalchemy.dialects import mysql
fr... | graingert/sqlalchemy | test/dialect/mysql/test_dialect.py | Python | mit | 14,932 |
from accounts.models import Practice
def create_practice(request, strategy, backend, uid, response={}, details={}, user=None, social=None, *args, **kwargs):
"""
if user has a practice skip else create new practice
"""
practice, created = Practice.objects.update_or_create(user=user)
return None... | TimothyBest/Appointment_Booking_drchrono | appointment_booking_drchrono/accounts/pipeline.py | Python | mit | 321 |
from flask import Flask
from flask import render_template, request
app = Flask(__name__)
@app.route("/")
def main():
room = request.args.get('room', '')
if room:
return render_template('watch.html')
return render_template('index.html')
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True)
| victorpoluceno/webrtc-sample-client | app/__init__.py | Python | mit | 314 |
from nose.tools import with_setup
import os
import hk_glazer as js2deg
import subprocess
import json
class TestClass:
@classmethod
def setup_class(cls):
cls.here = os.path.dirname(__file__)
cls.data = cls.here + '/data'
def test_1(self):
'''Test 1: Check that json_to_degree works when imported'... | fmuzf/python_hk_glazer | hk_glazer/test/test.py | Python | mit | 1,705 |
from django.conf.urls import url
from . import views
from django.views.decorators.cache import cache_page
app_name = 'webinter'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^logout/$', views.logout_view, name='logout'),
]
| ipriver/0x71aBot-Web-Interface | webinter/urls.py | Python | mit | 262 |
# -*- coding: utf-8 -*-
"""
Money doctests as unittest Suite
"""
# RADAR: Python2
from __future__ import absolute_import
import doctest
import unittest
# RADAR: Python2
import money.six
FILES = (
'../../README.rst',
)
def load_tests(loader, tests, pattern):
# RADAR Python 2.x
if money.six.PY2:
#... | carlospalol/money | money/tests/test_docs.py | Python | mit | 424 |
# encoding: UTF-8
"""
一个ATR-RSI指标结合的交易策略,适合用在股指的1分钟和5分钟线上。
注意事项:
1. 作者不对交易盈利做任何保证,策略代码仅供参考
2. 本策略需要用到talib,没有安装的用户请先参考www.vnpy.org上的教程安装
3. 将IF0000_1min.csv用ctaHistoryData.py导入MongoDB后,直接运行本文件即可回测策略
"""
from ctaBase import *
from ctaTemplate import CtaTemplate
import talib
import numpy as np
###################... | lukesummer/vnpy | vn.trader/ctaAlgo/strategyAtrRsi.py | Python | mit | 9,927 |
import os
import yaml
MONGO_USERNAME = os.getenv('MONGO_USERNAME', None)
MONGO_PASSWORD = os.getenv('MONGO_PASSWORD', None)
MONGODB_HOST = os.getenv('MONGODB_HOST', '127.0.0.1')
MONGODB_PORT = int(os.getenv('MONGODB_PORT', '27017'))
MONGODB_SERVERS = os.getenv('MONGODB_SERVERS') \
or '{}:{}'.format(... | ymind/docker-mongo-es | conf/appconfig.py | Python | mit | 1,677 |
# coding: UTF-8
import unittest
import play_file
class TestAssemblyReader(unittest.TestCase):
def test_version_reader(self):
assembly_reader = play_file.AssemblyReader()
version = assembly_reader.get_assembly_version('AssemblyInfo.cs')
self.assertEqual(version, '7.3.1.0210')
def test_... | biztudio/JustPython | syntaxlab/src/test_play_file.py | Python | mit | 570 |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 14 02:17:11 2017
@author: guida
"""
import json
import requests
def get_url(url):
response = requests.get(url)
content = response.content.decode("utf8")
return content
#Json parser
def get_json_from_url(url):
content = get_url(url)
j... | DiegoGuidaF/telegram-raspy | modules.py | Python | mit | 358 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2014 Alan Aguiar alanjas@hotmail.com
# Copyright (c) 2012-2014 Butiá Team butia@fing.edu.uy
# Butia is a free and open robotic platform
# www.fing.edu.uy/inco/proyectos/butia
# Facultad de Ingeniería - Universidad de la República - Uruguay
#
# This p... | nvazquez/Turtlebots | plugins/butia/pybot/__init__.py | Python | mit | 1,171 |
import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import Co... | dmateusp/PokemonGo-Bot | pokemongo_bot/cell_workers/recycle_items.py | Python | mit | 5,073 |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
node = parent = None
def deleteNode(self, root: TreeNode, key: int) -> TreeNode:
# search for the node and its parent
self.findNodeAndParent(root, key)
if s... | shobhitmishra/CodingProblems | LeetCode/Session3/DeleteNodeBST.py | Python | mit | 2,274 |
# coding=utf-8
"""
Collects all number values from the db.serverStatus() command, other
values are ignored.
#### Dependencies
* pymongo
"""
import diamond.collector
from diamond.collector import str_to_bool
import re
import zlib
try:
import pymongo
pymongo # workaround for pyflakes issue #13
except Impo... | metamx/Diamond | src/collectors/mongodb/mongodb.py | Python | mit | 12,462 |
# -*- coding: utf-8 -*-
# @Author: yancz1989
# @Date: 2017-01-17 23:43:18
# @Last Modified by: yancz1989
# @Last Modified time: 2017-02-22 20:33:29
import utilities as util
from utilities import parse_image_file, filterBoxes, voxel_2_world, mkdir
import numpy as np
import os
import json
import sys
from PIL import I... | yancz1989/cancer | scan.py | Python | mit | 2,610 |
from django.conf.urls import url
from audiotracks import feeds
from audiotracks import views
urlpatterns = [
url(r"^$", views.index, name="audiotracks"),
url(r"^(?P<page_number>\d+)/?$", views.index, name="audiotracks"),
url(r"^track/(?P<track_slug>.*)$", views.track_detail,
name="track_detail"),... | amarandon/django-audiotracks | audiotracks/urls.py | Python | mit | 955 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import bottle
import datetime
import time
@bottle.get('/')
def index():
return bottle.static_file('index.html', root='.')
@bottle.get('/stream')
def stream():
bottle.response.content_type = 'text/event-stream'
bottle.response.cache_control = 'no... | hustbeta/python-web-recipes | server-sent-events/bottle-sse.py | Python | mit | 517 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
destination.factory
'''
from destination.zeus import ZeusDestination
from destination.aws import AwsDestination
from exceptions import AutocertError
from config import CFG
from app import app
class DestinationFactoryError(AutocertError):
def __init__(self, destin... | mozilla-it/autocert | autocert/api/destination/factory.py | Python | mit | 854 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | AutorestCI/azure-sdk-for-python | azure-servicefabric/azure/servicefabric/models/partition_health.py | Python | mit | 2,612 |
import os,sys
from trans_rot_coords import *
import numpy as np
from read_energy_force_new import *
from grids_structures_general import DS,Grid_Quarts
from orient_struct_2 import OrientDS as OrientDS_2
from orient_struct_3 import OrientDS as OrientDS_3
AU2KCAL = 23.0605*27.2116
R2D = 180.0/3.14159265358979
## np.pi/... | sethbrin/QM | version2/python/calculate_energy_new_coords_general.py | Python | mit | 32,462 |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
from scrapy.conf import settings
import pymongo
from datetime import datetime
from .models import PQDataModel
class Parliamen... | mthipparthi/parliament-search | parliamentsearch/pipelines.py | Python | mit | 1,789 |
import arrow
import settings
from . import misc
from . import voting
from . import comments
from . import exceptions as exc
def merge_pr(api, urn, pr, votes, total, threshold):
""" merge a pull request, if possible, and use a nice detailed merge commit
message """
pr_num = pr["number"]
pr_title = pr[... | eukaryote31/chaos | github_api/prs.py | Python | mit | 8,393 |
#!/usr/bin/env python
__copyright__ = "Copyright 2013-2014, http://radical.rutgers.edu"
__license__ = "MIT"
import sys
import radical.pilot as rp
# READ: The RADICAL-Pilot documentation:
# http://radicalpilot.readthedocs.org/en/latest
#
# Try running this example with RADICAL_PILOT_VERBOSE=debug set if
# you w... | JensTimmerman/radical.pilot | examples/running_mpi_executables.py | Python | mit | 5,342 |
from riotwatcher import *
from time import sleep
import logging
log = logging.getLogger('log')
def getTeamOfSummoner( summonerId, game ):
for p in game['participants']:
if p['summonerId'] == summonerId:
return p['teamId']
def getSummonerIdsOfOpponentTeam( summonerId, game ):
teamId = getTeamOfS... | DenBaum/lolm8guesser | friendship.py | Python | mit | 3,046 |
import unittest
from datetime import datetime
import numpy as np
import pandas as pd
from excel_helper.helper import DataSeriesLoader
class TestDataFrameWithCAGRCalculation(unittest.TestCase):
def test_simple_CAGR(self):
"""
Basic test case, applying CAGR to a Pandas Dataframe.
:return:... | dschien/PyExcelModelingHelper | tests/test_DataSeriesLoader.py | Python | mit | 3,547 |
from django.dispatch import Signal
pre_save = Signal(providing_args=['instance', 'action', ])
post_save = Signal(providing_args=['instance', 'action', ])
pre_delete = Signal(providing_args=['instance', 'action', ])
post_delete = Signal(providing_args=['instance', 'action', ])
| thoas/django-sequere | sequere/contrib/timeline/signals.py | Python | mit | 279 |
#!/usr/bin/env python
'''
Import this module to have access to a global redis cache named GLOBAL_CACHE.
USAGE:
from caching import GLOBAL_CACHE
GLOBAL_CACHE.store('foo', 'bar')
GLOBAL_CACHE.get('foo')
>> bar
'''
from redis_cache import SimpleCache
try:
GLOBAL_CACHE
except NameError:
GLOBAL_C... | miketwo/pylacuna | pylacuna/caching.py | Python | mit | 434 |
# https://graphics.stanford.edu/~seander/bithacks.html#NextBitPermutation
def selector(values, setBits):
maxBits = len(values)
def select(v):
out = []
for i in range(maxBits):
if (v & (1 << i)):
out.append(values[i])
return out
v = (2 ** setBits) - 1
... | asgeir/old-school-projects | python/verkefni2/cpattern.py | Python | mit | 1,006 |
# testStr = "Hello {name}, How long have you bean?. I'm {myName}"
#
# testStr = testStr.format(name="Leo", myName="Serim")
#
# print(testStr)
limit = None
hello = str(limit, "")
print(hello)
# print( "4" in "3.5")
| SELO77/seloPython | 3.X/ex/strFormat.py | Python | mit | 217 |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'App.created_at'
db.add_column('mobile_apps_app', 'created_at', self.gf('django.db.models.f... | katemsu/kate_website | kate3/mobile_apps/migrations/0002_auto__add_field_app_created_at.py | Python | mit | 2,545 |
import math
import urwid
from mitmproxy.tools.console import common
from mitmproxy.tools.console import signals
from mitmproxy.tools.console import grideditor
class SimpleOverlay(urwid.Overlay):
def __init__(self, master, widget, parent, width, valign="middle"):
self.widget = widget
self.master ... | xaxa89/mitmproxy | mitmproxy/tools/console/overlay.py | Python | mit | 3,855 |
import os
ADMINS = (
# ('Eduardo Lopez', 'eduardo.biagi@gmail.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': os.path.join(os.path.dirname(__file__), 'highways.db')... | tapichu/highway-maps | project/settings.py | Python | mit | 3,183 |
import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class ... | GunnerJnr/_CodeInstitute | Stream-2/Back-End-Development/18.Using-Python-with-MySQL-Part-Three-Intro/3.How-to-Build-an-Update-SQL-String/database/mysql.py | Python | mit | 7,289 |
"""
https://codility.com/programmers/task/equi_leader/
"""
from collections import Counter, defaultdict
def solution(A):
def _is_equi_leader(i):
prefix_count_top = running_counts[top]
suffix_count_top = total_counts[top] - prefix_count_top
return (prefix_count_top * 2 > i + 1) and (suffi... | py-in-the-sky/challenges | codility/equi_leader.py | Python | mit | 707 |
import os
import shutil
from glob import glob
print 'Content-type:text/html\r\n\r\n'
print '<html>'
found_pages = glob('archive/*.py')
if found_pages:
path = "/cgi-bin/archive/"
moveto = "/cgi-bin/pages/"
files = os.listdir(path)
files.sort()
for f in files:
src = path+f
dst = mov... | neva-nevan/ConfigPy | ConfigPy-Portable/ConfigPy/cgi-bin/restore.py | Python | mit | 516 |
"""
@brief test log(time=0s)
"""
import os
import unittest
from pyquickhelper.loghelper import fLOG
from pyquickhelper.filehelper import explore_folder_iterfile
from pyquickhelper.ipythonhelper import upgrade_notebook, remove_execution_number
class TestConvertNotebooks(unittest.TestCase):
"""Converts notebo... | sdpython/python3_module_template | _unittests/ut_module/test_convert_notebooks.py | Python | mit | 1,224 |
from itertools import permutations
import re
def create_formula(combination,numbers):
formula = ""
index = 0
for op in combination:
formula += str(numbers[index]) + op
index += 1
formula += numbers[index]
return formula
'''
Unnecessary Funtion
'''
def evaluate(form):
result ... | F0lha/UJunior-Projects | DailyProgrammer/Challenge#318/src.py | Python | mit | 2,546 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | AutorestCI/azure-sdk-for-python | azure-mgmt-servicebus/azure/mgmt/servicebus/models/destination.py | Python | mit | 1,856 |
"""94. Binary Tree Inorder Traversal
https://leetcode.com/problems/binary-tree-inorder-traversal/
Given a binary tree, return the in-order traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?... | isudox/leetcode-solution | python-algorithm/leetcode/problem_94.py | Python | mit | 1,229 |
# -*- coding: utf-8 -*-
from django.core.cache import cache
from django.shortcuts import render
from django.http import Http404
from styleguide.utils import (Styleguide, STYLEGUIDE_DIR_NAME,
STYLEGUIDE_DEBUG, STYLEGUIDE_CACHE_NAME,
STYLEGUIDE_ACCESS)
def in... | andrefarzat/django-styleguide | styleguide/views.py | Python | mit | 897 |
from quotes.models import Quote
from django.contrib import admin
class QuoteAdmin(admin.ModelAdmin):
list_display = ('message', 'name', 'program', 'class_of',
'submission_time')
admin.site.register(Quote, QuoteAdmin)
| k4rtik/alpo | quotes/admin.py | Python | mit | 243 |
from tkinter import *
import tkinter
import HoursParser
class UserInterface(tkinter.Frame):
def __init__(self, master):
self.master = master
self.events_list = []
# Set window size
master.minsize(width=800, height=600)
master.maxsize(width=800, height=600)
... | itsknob/TechnicalServicesScheduler-Python | interface.py | Python | mit | 3,856 |
required_states = ['accept', 'reject', 'init']
class TuringMachine(object):
def __init__(self, sigma, gamma, delta):
self.sigma = sigma
self.gamma = gamma
self.delta = delta
self.state = None
self.tape = None
self.head_position = None
return
... | ssanderson/turing.py | turing.py | Python | mit | 2,182 |
#!/usr/bin/python
import argparse
from os import path as os_path
import demo_project as demo
import traceback
def set_host_url_arg():
parser.add_argument('--host', required=True,
help='the url for the Materials Commons server')
def set_datapath_arg():
parser.add_argument('--datapath', ... | materials-commons/materialscommons.org | backend/scripts/demo-project/build_project.py | Python | mit | 1,400 |
# -*- coding: utf-8 -*-
# ProjectEuler/src/python/problem404.py
#
# Crisscross Ellipses
# ===================
# Published on Sunday, 2nd December 2012, 01:00 am
#
# Ea is an ellipse with an equation of the form x2 + 4y2 = 4a2. Ea' is the
# rotated image of Ea by θ degrees counterclockwise around the origin O(0, 0)
# ... | olduvaihand/ProjectEuler | src/python/problem404.py | Python | mit | 944 |
from pwn.internal.shellcode_helper import *
@shellcode_reqs(arch=['i386', 'amd64'], os=['linux', 'freebsd'])
def fork(parent, child = None, os = None, arch = None):
"""Fork this shit."""
if arch == 'i386':
if os in ['linux', 'freebsd']:
return _fork_i386(parent, child)
elif arch == 'am... | Haabb/pwnfork | pwn/shellcode/misc/fork.py | Python | mit | 910 |