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
# -*- coding: utf-8 -*- from __future__ import print_function, absolute_import, division import unittest from pusher import Config, Pusher from pusher.util import GET try: import unittest.mock as mock except ImportError: import mock class TestPusher(unittest.TestCase): def setUp(self): self.pus...
pusher/pusher-python-rest
pusher_tests/test_pusher.py
Python
mit
3,426
#!/usr/bin/env python3 '''This should be the command-line pendant of ./test.html By Guillaume Lathoud glathoud@yahoo.fr ''' import subprocess from jsm_build import main from jsm_const import D8 ret = subprocess.check_output( [ D8, '-e', 'load("codeparse_test.js");print(codeparse_test());' ], ...
glathoud/js.metaret
test.py
Python
mit
663
import _plotly_utils.basevalidators class ColorValidator(_plotly_utils.basevalidators.ColorValidator): def __init__(self, plotly_name="color", parent_name="scatter3d.error_z", **kwargs): super(ColorValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, ...
plotly/python-api
packages/python/plotly/plotly/validators/scatter3d/error_z/_color.py
Python
mit
445
# 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 may ...
Azure/azure-sdk-for-python
sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/models/__init__.py
Python
mit
9,295
# -*- coding: utf-8 -*- """ Created on Thu Dec 29 14:04:43 2016 @author: 024536 """ from flask import render_template, redirect, url_for, abort, flash, request,\ current_app, make_response, jsonify from flask_login import login_required, current_user from flask_sqlalchemy import get_debug_queries from . import ct...
lyhrobin00007/FlaskCTA
app/ctaAlgo/views.py
Python
mit
10,753
#!/usr/bin/env python3 import os import time import psutil from typing import Optional import cereal.messaging as messaging from common.realtime import set_core_affinity, set_realtime_priority from selfdrive.swaglog import cloudlog MAX_MODEM_CRASHES = 3 MODEM_PATH = "/sys/devices/soc/2080000.qcom,mss/subsys5" WATCHE...
commaai/openpilot
selfdrive/hardware/eon/androidd.py
Python
mit
2,807
import Feeder, SourceList, Settings, Source, MyLogger, feedparser reload(Feeder); reload(Settings); reload(Source); reload(SourceList) sets = Settings.Settings(); log = MyLogger.defaultLogger('temp.log', sets); sourceList = SourceList.SourceList(sets=sets, log=log)
lzkelley/Feeder
isetup.py
Python
mit
269
from websocket import create_connection from processReturnMsg import processReturnMsg import json class Connection: def __init__(self, name, url): self.ws = create_connection(url) json_string = { "name": name } self.ws.send(json.dumps(json_string)) #Receive initial server greetings processReturnMsg(se...
np-overflow/minecraft-commander
mcpy_simplified/connection.py
Python
mit
476
""" Test for network group """ import unittest class TestNetworkGroup(unittest.TestCase): """ Test case for network group """ def test_network_group(self): """Test various types of network groups""" from pybitmessage.protocol import network_group test_ip = '1.2.3.4' se...
PeterSurda/PyBitmessage
src/tests/test_networkgroup.py
Python
mit
1,033
""" Django settings for CMS project. Generated by 'django-admin startproject' using Django 1.9. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # Build...
IEEEDTU/CMS
CMS/settings.py
Python
mit
4,034
import json from pathlib import Path from gravity.defaults import ( DEFAULT_GUNICORN_BIND, DEFAULT_GUNICORN_TIMEOUT, DEFAULT_GUNICORN_WORKERS, DEFAULT_INSTANCE_NAME, CELERY_DEFAULT_CONFIG ) def test_register_defaults(galaxy_yml, galaxy_root_dir, state_dir, default_config_manager): default_co...
galaxyproject/gravity
tests/test_config_manager.py
Python
mit
3,452
''' We are given an array asteroids of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all col...
tikael1011/leetcodejava
735. Asteroid Collision.py
Python
mit
1,833
import matplotlib matplotlib.use("agg") import matplotlib.pyplot as plt import seaborn as sns import pandas as pd sns.set(style="ticks", palette="colorblind", context="paper") plt.figure(figsize=snakemake.config["plots"]["figsize"]) for f in snakemake.input: counts = pd.read_table(f, index_col=[0, 1]) plt.s...
merfishtools/merfishtools-evaluation
scripts/plot-exact-vs-corrected.py
Python
mit
679
import _plotly_utils.basevalidators class SideValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__( self, plotly_name="side", parent_name="densitymapbox.colorbar.title", **kwargs ): super(SideValidator, self).__init__( plotly_name=plotly_name, paren...
plotly/plotly.py
packages/python/plotly/plotly/validators/densitymapbox/colorbar/title/_side.py
Python
mit
500
from LinkedList import LinkedList def length_of_linkedlist(ll): if ll.head is None: return 0 current = ll.head count = 0 while current: current = current.next count += 1 return count linked_list = LinkedList() linked_list.__generate__(10,0,9) linked_list.__print__() print(...
fahadkaleem/DataStructures
LinkedList/length_of_linkedlist.py
Python
mit
354
# -*- coding: utf-8 -*- import darr da = darr.DoubleArray() words = ['くるま', 'く', 'くる', 'りんご', 'オレンジ', 'baseball', 'soccer'] v = 0 for word in words: v += 1. da.insert(word, v) print('### common prefix search ###') ret = da.common_prefix_search('くるまで') for w in ret: print(w) print('### get values ###') ...
tma15/darr
python/sample.py
Python
mit
580
import sys import live from instruments.drums import Drums from instruments.synth_lead import SynthLead from instruments.synth_harmony import SynthHarmony from threading import Thread import time import mido # def start_ableton_thread(): # t = Thread(target=ableton_thread) # t.start() def ableton_thread(): ...
matangover/beatogether
ableton_playground.py
Python
mit
1,422
#!/usr/bin/env python3 import argparse import os import subprocess import sys def setup(): global args, workdir programs = ['ruby', 'git', 'make', 'wget', 'curl'] if args.kvm: programs += ['apt-cacher-ng', 'python-vm-builder', 'qemu-kvm', 'qemu-utils'] elif args.docker and not os.path.isfile('...
tjps/bitcoin
contrib/gitian-build.py
Python
mit
14,454
""" .. module:: kmeans :synopsis: python wrapper for a basic c implementation of the k-means algorithm. .. moduleauthor:: Joe Cross <joe.mcross@gmail.com> """ import os import ctypes import random import sysconfig from ctypes import Structure, c_uint8, c_uint32, c_uint64, byref __all__ = ['kmeans'] ...
numberoverzero/kmeans
kmeans/__init__.py
Python
mit
2,812
# The MIT License # # Copyright (c) 2010 Jeffrey Jenkins # # 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 limitation the rights # to use, copy, modify,...
bapakode/OmMongo
ommongo/update_expression.py
Python
mit
8,848
import errno import os import socket import sys import time import warnings import eventlet from eventlet.hubs import trampoline, notify_opened, IOClosed from eventlet.support import get_errno, six __all__ = [ 'GreenSocket', '_GLOBAL_DEFAULT_TIMEOUT', 'set_nonblocking', 'SOCKET_BLOCKING', 'SOCKET_CLOSED', 'CO...
collinstocks/eventlet
eventlet/greenio/base.py
Python
mit
17,181
from django.contrib import admin from .models import * class CaseAdmin(admin.ModelAdmin): list_display = ('name', 'firm', 'owner', 'active', 'created',) search_fields = ['owner__first_name', 'owner__email', 'firm__name', 'name'] admin.site.register(Move) admin.site.register(Case, CaseAdmin)
Maachi/Gestion
cases/admin.py
Python
mit
301
def foo(): pass class TestProcessor(unittest.TestCase): def test_does_something(self): pass def test_something_else(self): pass
bebraw/speccer
tests/testcases/expected_hoisting.py
Python
mit
159
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'gui/species_prompt.ui' # # Created by: PyQt5 UI code generator 5.5.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_SpeciesPrompt(object): def setupUi(self, SpeciesPrompt): ...
DanielWinklehner/py_particle_processor
py_particle_processor_qt/gui/species_prompt.py
Python
mit
3,621
#!/usr/bin/env python import unittest from src.lib import wsplit class TestUrlWord(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_url_split(self): url = "http://example.com/foo345-/43/23-1/bar" words = ["foo", "bar"] clean_url = wspli...
mad01/hermit
tests/test_url_words.py
Python
mit
484
''' Created on 04.04.2011 @author: michi ''' from sqlalchemy import Table, select, Column from sqlalchemy.sql.expression import _UnaryExpression,Alias from sqlalchemy.sql.operators import asc_op,desc_op import sqlalchemy.schema from sqlalchemy.sql import func class FromCalculator(object): def __init__(self, fro...
mtils/ems
ems/model/alchemy/querybuilder.py
Python
mit
8,236
#!/usr/bin/python import struct, array, fcntl class struxx: _fields = None _format = None _buffer = None def __init__(self): self.reset() def __len__(self): """binary represntation length, for fields, use __dict__ or something""" return struct.calcsize(self._format) def __iter__(self): re...
ActiveState/code
recipes/Python/576834_Interrogating_linux_devusbhiddev0/recipe-576834.py
Python
mit
6,781
# Copyright (c) 2011-2013, Alexander Kulakov # # 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 limitation the rights # to use, copy, modify, merge, publ...
momyc/gevent-fastcgi
gevent_fastcgi/base.py
Python
mit
10,374
import pprint import sublime import sublime_plugin def unexpanduser(path): from os.path import expanduser return path.replace(expanduser('~'), '~') try: import os, sys # stupid python module system sys.path.append(os.path.dirname(os.path.realpath(__file__))) from .editorconfig import get_properties, EditorConfi...
sindresorhus/editorconfig-sublime
EditorConfig.py
Python
mit
3,648
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('cfp', '0047_auto_20150412_0647'), ] operations = [ migrations.RemoveField( model_name='conference', ...
kyleconroy/speakers
cfp/migrations/0048_auto_20150412_0740.py
Python
mit
459
''' Created on 7 juin 2016 @author: saldenisov ''' from PyQt5.Qt import QMainWindow from PyQt5.QtGui import QCloseEvent from utility import MainObserver from utility import Meta from views import Ui_MainWindow from _functools import partial class MainView(QMainWindow, MainObserver, metaclass=Meta): """ """ ...
Saldenisov/QY_itegrating_sphere
views/windows_views/main_view.py
Python
mit
1,248
"""Routines for I/O.""" import fcntl import os if False: from typing import IO # noqa: F401 def set_nonblock(fd): # type: (int) -> None """Set the given file descriptor to non-blocking mode.""" fcntl.fcntl(fd, fcntl.F_SETFL, fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONB...
tueda/python-form
form/ioutil.py
Python
mit
1,515
from random import randrange from ai import tah_pocitace from tahnuti import tah def vyhodnot(herni_pole): "Vratí jednoznakový řetězec podle stavu hry" if 'xxx' in herni_pole: return 'x' if 'ooo' in herni_pole: return 'o' if '-' not in herni_pole: return '!' return '-' def...
Ajuska/pyladies
06/ukoly/piskvorky.py
Python
mit
1,883
def info_file_parser(filename, verbose=False): results = {} infile = open(filename,'r') for iline, line in enumerate(infile): if line[0]=='#': continue lines = line.split() if len(lines)<2 : continue if lines[0][0]=='#': continue infotype = lines[0] infotype...
carlomt/dicom_tools
dicom_tools/info_file_parser.py
Python
mit
421
#coding: utf-8 from django.test import TestCase from mock import patch from ..models import MangoPayBankAccount from .factories import (MangoPayIBANBankAccountFactory, MangoPayUSBankAccountFactory, MangoPayOTHERBankAccountFactory) from .client import MockMangoPayApi f...
FundedByMe/django-mangopay
mangopay/tests/bank_account.py
Python
mit
3,532
''' August 15 2014 James Houghton <james.p.houghton@gmail.com> Major edits June 22 2015 ''' from pysd.translators.SMILE2Py import SMILEParser from lxml import etree from pysd import builder def translate_xmile(xmile_file): """ Translate an xmile model file into a python class. Functionality is currently limit...
bpowers/pysd
pysd/translators/XMILE2Py.py
Python
mit
2,492
x = 0 def incr_x(): x = x + 1 # does not work def incr_x2(): global x x = x + 1 # does work
schmit/intro-python-course
lectures/code/functions_global.py
Python
mit
108
# ----------------------------------------------------------------------------- # LTL -> NBA # Copyright (C) Carsten Fritz, Björn Teegen 2002-2003 # Sponsored by Deutsche Forschungsgemeinschaft (DFG) # Distributed under the terms of the GNU Lesser General ...
arafato/ltl2fsm
tools/ltlnba/lexlib.py
Python
mit
4,174
from django.db import models from django.utils import timezone class MyRelatedModel(models.Model): name = models.CharField(max_length=255) key = models.IntegerField() def __str__(self): return str(self.key) class MyModel(models.Model): char_field = models.CharField(max_length=255, default...
onebit0fme/django-loadjson
loadjson/tests/models.py
Python
mit
734
# coding: utf-8 # In[1]: import numpy as np import numpy.random as npr import matplotlib.pyplot as plt get_ipython().magic(u'matplotlib inline') # In[34]: from sklearn.datasets import load_digits data = load_digits() X_tot,Y_tot = load_digits().data,load_digits().target # In[8]: len(X_tot) # In[9]: split = ...
maxentile/msm-learn
projects/metric-learning/Neighborhood components analysis.py
Python
mit
5,397
"""Remove the first and last char from a string.""" def remove_char(s): """Remove the first and last char from a string.""" return s[1:-1]
pasaunders/code-katas
src/remove_chars.py
Python
mit
149
# -*- coding: utf8 -*- # Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses...
tzpBingo/github-trending
codespace/python/tencentcloud/ecc/v20181213/errorcodes.py
Python
mit
3,671
import cmath from math import pi, ceil import numpy as np from numpy import sin, cos from scipy.interpolate import interp1d """ References: [Majkrzak2003] C. F. Majkrzak, N. F. Berk: Physica B 336 (2003) 27-38 Phase sensitive reflectometry and the unambiguous determination of scattering leng...
reflectometry/direfl
direfl/api/sld_profile.py
Python
mit
8,500
# coding: utf-8 from sqlalchemy import BINARY, Column, Float, Index, Integer, String, VARBINARY from sqlalchemy import String, Unicode, ForeignKey from sqlalchemy.orm import relationship, backref from dbdatetime import dbdatetime from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() metada...
veblush/PyPhabricatorDb
pyphabricatordb/system.py
Python
mit
1,153
import collections import numbers import re import warnings from rope.base import ast, codeanalyze, exceptions from rope.base.utils import pycompat try: basestring except NameError: basestring = (str, bytes) def get_patched_ast(source, sorted_children=False): """Adds ``region`` and ``sorted_children`` ...
ruchee/vimrc
vimfiles/bundle/vim-python/submodules/rope/rope/refactor/patchedast.py
Python
mit
34,226
from socket import * import picamera serverSocket = socket(AF_INET, SOCK_STREAM) HOST = '' PORT = 8080 serverSocket.bind((HOST,PORT)) serverSocket.listen(1) camera = picamera.PiCamera() camera.vflip = True camera.hflip = True while True: print 'Ready to serve...' connectionSocket, addr = serverSocket.accept() pr...
larwef/Stuff
Raspberry Pi/webcam/webcam.py
Python
mit
941
#!/usr/bin/env python from setuptools import setup setup( name="beerpy", version="0.1.0", packages=["beerpy"], scripts=[], url="", license="MIT", author="Stefan Lehmann", author_email="Stefan.St.Lehmann@gmail.com", description="", install_requires=["pandas", "scipy"], mainta...
MrLeeh/beerpy
setup.py
Python
mit
345
# # This is an example plugin that isn't bundled inside Plumeria. # Add "example_plugin" to the list of plugins in your config file to # load this plugin. Plugins can be regular Python packages and do not # need to be inside this plugins directory. # from plumeria.command import commands from plumeria.util.ratelimit i...
sk89q/Plumeria
plugins/example_plugin.py
Python
mit
604
# The MIT License (MIT) # # Copyright (c) 2016-2018 Albert Kottke # # 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 limitation the rights # to use, copy...
arkottke/pysra
pysra/tools.py
Python
mit
8,584
__author__ = 'Michael Fisher'
mikefishr/euchre-engine
Euchre-PY/euchre.py
Python
mit
30
# Import Flask from the flask library. from flask import Flask # Create a new Flask instance as a variable named app. # The name you pass to the Flask app should be __name__. app = Flask(__main__) # Add a view function named index. Give this view a route of "/". # Make the view return your name. You do no...
CaseyNord/Treehouse
Flask Basics/flask_app.py
Python
mit
1,505
#!/usr/bin/env python # Copyright 2017 Brook Boese, Finn Ellis, Jacob Martin, Matthew Popescu, Rubin Stricklin, and Sage Callon # 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 restrict...
NovelTorpedo/noveltorpedo
website/manage.py
Python
mit
1,958
# Plugin for gallery_get. import re from gallery_utils import * # Each definition can be one of the following: # - a string # - a regex string # - a function that takes source as a parameter and returns an array or a string. # If you comment out a parameter, it will use the default defined in __init__.py # identifier...
regosen/gallery_get
gallery_plugins/plugin_imagefap.py
Python
mit
1,699
import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), '../tools')) import files import probs def main(argv): k, N = files.read_line_of_ints(argv[0]) print '%0.3f' % probs.mendel2(k, N, 0.25) if __name__ == "__main__": main(sys.argv[1:])
cowboysmall/rosalind
src/stronghold/rosalind_lia.py
Python
mit
279
from behave import * from behave_webdriver.transformers import matcher_mapping try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse if 'transform-parse' not in matcher_mapping: use_step_matcher('re') else: use_step_matcher('transform-re') @given('the element "([^"]...
spyoungtech/behave-webdriver
behave_webdriver/steps/expectations.py
Python
mit
13,568
# 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 may ...
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_06_01/aio/operations/_local_network_gateways_operations.py
Python
mit
27,427
revision = '16de00f8ecc' down_revision = '1872f4529b3' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql def upgrade(): op.add_column('proposal', sa.Column('policy_domain_id', postgresql.UUID(), nullable=True)) op.create_foreign_key( 'policy_domain_id_fk...
mgax/mptracker
alembic/versions/16de00f8ecc_proposal_policy_doma.py
Python
mit
476
import math from Acquisition import aq_inner from five import grok from zope.component import getMultiAdapter from plone.dexterity.content import Container from plone.directives import form from plone.namedfile.interfaces import IImageScaleTraversable class IGalleryFolder(form.Schema, IImageScaleTraversable): "...
vwc/buildout.mycarman
src/newport.sitecontent/newport/sitecontent/galleryfolder.py
Python
mit
3,071
#!/usr/bin/env python3 # Copyright (c) 2020 The Fujicoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """ Utilities for working directly with the wallet's BDB database file This is specific to the configuration ...
fujicoin/fujicoin
test/functional/test_framework/bdb.py
Python
mit
5,534
# coding=utf-8 import base64 import tornado.ioloop import tornado.web from tornado.web import _create_signature_v1, _time_independent_equals import tornado.gen import tornado.httpclient import tornado.escape from tornado.escape import utf8 from tornado.concurrent import Future from qr import get_qrcode import uuid imp...
inuyasha2012/tornado-qrcode-login-example
example/main.py
Python
mit
4,259
# -*- coding: utf-8 -*- import logging import numpy as np from collections import OrderedDict import theano import theano.tensor as T from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams from theano.tensor.nnet.conv import conv2d, ConvOp from theano.sandbox.cuda.blas import GpuCorrMM from theano.san...
ryukinkou/ladder_customized
ladder_theano_customized/ladder.py
Python
mit
26,220
# elmr.config # The ELMR configuration file. # # Author: Benjamin Bengfort <benjamin@bengfort.com> # Created: Thu Apr 09 08:44:18 2015 -0400 # # Copyright (C) 2015 University of Maryland # For license information, see LICENSE.txt # # ID: config.py [] benjamin@bengfort.com $ """ The ELMR configuration file. """ ###...
bbengfort/jobs-report
elmr/config.py
Python
mit
4,794
from rtmidi.midiconstants import * from rtmidi.midiutil import open_midiport from router import Router import logging import time from config import ROUTER_IPS, DEBUG_LEVEL, MIDI_MAPPING ROUTERS = [Router(ip).connect() for ip in ROUTER_IPS] logging.basicConfig(level=DEBUG_LEVEL) ROUTERS = [Router(ip).connect() for i...
bdejong/router-gate
miditest.py
Python
mit
1,682
from typing import Dict from CreatureRogue.data_layer.location_area_rect import LocationAreaRect from CreatureRogue.data_layer.location_area_rect_collection import LocationAreaRectCollection from CreatureRogue.data_layer.map_data_tile_type import MapDataTileType # TODO - Change to enum? HP_STAT = 1 ATTACK_STAT = 2 D...
DaveTCode/CreatureRogue
CreatureRogue/data_layer/data.py
Python
mit
2,084
# encoding: utf8 from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( ...
vladimiroff/humble-media
humblemedia/causes/migrations/0001_initial.py
Python
mit
1,075
import _plotly_utils.basevalidators class MaxpointsValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name="maxpoints", parent_name="funnelarea.stream", **kwargs ): super(MaxpointsValidator, self).__init__( plotly_name=plotly_name, paren...
plotly/plotly.py
packages/python/plotly/plotly/validators/funnelarea/stream/_maxpoints.py
Python
mit
506
import os import urllib import jinja2 import webapp2 JINJA_ENVIRONMENT = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), extensions=['jinja2.ext.autoescape'], autoescape=True) class MainPage(webapp2.RequestHandler): def get(self): template = JINJA_ENVIRONMENT.ge...
spawnedc/rubberducksoftware.co.uk
duck/duck.py
Python
mit
469
# -*- coding: utf-8 -*- """#179 Largest Number (Medium). (https://leetcode.com/problems/largest-number/#/description) Given a list of non negative integers, arrange them such that they form the largest number. For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. Note: The result may be very l...
AppliedAlgorithmsGroup/leon-lee
src/python/largest_number.py
Python
mit
1,191
""" Django settings for digihel project. Generated by 'django-admin startproject' using Django 1.9.6. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ # Build path...
terotic/digihel
digihel/settings.py
Python
mit
6,952
TM = "TM" # if no targets except realizations from TM fundsAvailable = "fundsAvailable" itemsAvailable = "itemsAvailable" oid = "oid" side = "side" # events onDelta = "onDelta" deltaSide = "side" onBatchDeltas = "onBatchDeltas" onTrade = "onTrade" onBatchTrades = "onBatchTrades" onOrderbook = "onOrderbook" onTicker = ...
jmakov/market_tia
tia/trad/tools/ipc/naming_conventions.py
Python
mit
1,741
import datetime import json import types from uuid import UUID import lazy_object_proxy from future.utils import iteritems from simpleflow.futures import Future def serialize_complex_object(obj): if isinstance( obj, bytes ): # Python 3 only (serialize_complex_object not called here in Python 2) ...
botify-labs/simpleflow
simpleflow/utils/json_tools.py
Python
mit
2,806
#!/usr/bin/env python3 ''' Chapter 4 of Automate the Boring Stuff The first assignment for this chapter is to write a program - comma_code.py This program includes the function `comma_code(list)` to process one step of the sequence. Included is a second way to do this easier with join() - a function not yet introduced...
jakdept/pythonbook
ch4/comma_code.py
Python
mit
765
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2017-01-11 10:05 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('servicos', '0001_initial'), ] operations = [ migrations.AlterModelOptions( ...
eduardoedson/scp
servicos/migrations/0002_auto_20170111_1005.py
Python
mit
892
# coding=utf-8 def game(function): """Decorator for check available game in attribute named `_game`.""" def _decorator(self, *args, **kwargs): if self._game is None: raise RuntimeError('Not chosen game.') return function(self, *args, **kwargs) return _decorator
pyvim/barbot
barbot/decorators.py
Python
mit
304
import random import numpy as np from ..common import w2tok from ..constants import EOW, UNK def _grouped(col, n): i, l, dst = 0, len(col), [] while i < l: dst.append(col[i: i + min(l - i, n)]) i += len(dst[-1]) return dst def make_generator(batch_size, dataset, to_samples, shuffle): max_words = m...
milankinen/c2w2c
src/dataset/generator.py
Python
mit
3,902
#!/usr/bin/env python3 """creates an MD-file.""" import configparser import os import platform import shutil import subprocess import sys import syslog import time import traceback from mausy5043libs.libdaemon3 import Daemon import mausy5043funcs.fileops3 as mf # constants DEBUG = False IS_JOURNALD = os.path....
Mausy5043/upsdiagd
daemons/ups82d.py
Python
mit
3,978
import re PYTHON_SHEBANG_PATTERN = re.compile(r'#![\w /]*python') def read_header(filename): with open(filename, 'r') as f: return f.read(100) def has_python_shebang(filename): header = read_header(filename) return bool(PYTHON_SHEBANG_PATTERN.match(header)) def matches_any_pattern(filenames, pat...
EliRibble/mothermayi
mothermayi/files.py
Python
mit
899
# -*- coding: utf-8 -*- import os import unittest # prepare for test os.environ['ANIMA_TEST_SETUP'] = "" from pymel import core as pm from anima.dcc.mayaEnv import ai2rs class Ai2RSTester(unittest.TestCase): """tests for anima.dcc.mayaEnv.ai2rs classes """ def setUp(self): """create the test s...
eoyilmaz/anima
tests/dcc/maya/test_ai2rs.py
Python
mit
15,063
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Partially based on AboutMethods in the Ruby Koans # from runner.koan import * def my_global_function(a,b): return a + b class AboutMethods(Koan): def test_calling_a_global_function(self): self.assertEqual(5, my_global_function(2,3)) # NOTE: Wron...
gerardolopezduenas/python-koans-solutions
about_methods.py
Python
mit
5,504
# -*- coding: utf-8 -*- """ Transforms: Vincent Data Class for Vega Transform types """ from __future__ import (print_function, division) from .core import grammar, GrammarClass from ._compat import str_types class Transform(GrammarClass): """Container to Transforma metrics As detailed in the Vega wiki: ...
myusuf3/vincent
vincent/transforms.py
Python
mit
8,421
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- from typin...
Azure/azure-sdk-for-python
sdk/tables/azure-data-tables/azure/data/tables/_table_batch.py
Python
mit
27,928
""" WSGI config for agt project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_...
ArtGeekTech/Coding-Project-STEM-OPT-01
agt/wsgi.py
Python
mit
383
# -*- coding: utf-8 -*- nick = '' #Your chosen default nickname second = '' #Backup nick (if the first happens to be taken) username = '' realname = ''
gentoomen/Pymn
config.py
Python
mit
152
class Solution(object): def subsetsWithDup(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ res=[[]] nums=sorted(nums) for i in range(len(nums)): if i==0 or nums[i]!=nums[i-1]: lastlengh=len(res) re...
Hehwang/Leetcode-Python
code/090 Subsets II.py
Python
mit
466
"""Restricted execution facilities. The class RExec exports methods r_exec(), r_eval(), r_execfile(), and r_import(), which correspond roughly to the built-in operations exec, eval(), execfile() and import, but executing the code in an environment that only exposes those built-in operations that are deemed safe. To t...
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-2.2/Lib/rexec.py
Python
mit
12,831
# fbdata.generic # FBDATA from .models import ( FBAlbum, FBEvent, FBLink, FBPhoto, FBStatus, FBVideo, StreamPost ) _FB_CLASSES = { 'album': FBAlbum, 'event': FBEvent, 'link': FBLink, 'photo': FBPhoto, 'status': FBStatus, 'video': FBVideo, 'post': StreamPost } de...
valuesandvalue/valuesandvalue
vavs_project/fbdata/generic.py
Python
mit
1,183
import pandas as pd def _partitions(n: int): """Generate partitions of the integer in lexicographic order. """ # base case of recursion: zero is the sum of the empty list if n == 0: yield [] return # modify partitions of n-1 to form partitions of n for p in _partitions(n-1): ...
jnfrye/local_plants_book
src/PyFloraBook/threshold/partition.py
Python
mit
2,589
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, m) = str_to_int(args[0]) strings = [ args[i + 1].strip() for i in xrange(n) ] return(n, m, strings) def solve(args, verbose=False): (n, m, strings) = proc_input(args) acc = [...
cripplet/practice
codeforces/496/soln/c_columns.py
Python
mit
1,075
from django.db import models from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token from jsonfield import JSONField from . import consts @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_au...
telminov/email-service
core/models.py
Python
mit
1,001
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The PlanBcoin developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the listtransactions API.""" from test_framework.test_framework import PlanbcoinTestFramework from t...
planbcoin/planbcoin
test/functional/listtransactions.py
Python
mit
10,477
from gmrf import CovKernel from mesh import QuadMesh from mesh import Mesh1D from fem import QuadFE from fem import DofHandler from function import Nodal from plot import Plot import matplotlib.pyplot as plt from gmrf import modchol_ldlt, Covariance from scipy import linalg import numpy as np from scipy import linalg ...
hvanwyk/quadmesh
tests/test_gmrf/test_covariance.py
Python
mit
541
from decimal import Decimal from datetime import datetime import pytz import pytest from poker.card import Card from poker.hand import Combo from poker.constants import Currency, GameType, Game, Limit, Action, MoneyType from poker.handhistory import _Player, _PlayerAction from poker.room.pokerstars import PokerStarsHan...
pokerregion/poker
tests/handhistory/test_stars.py
Python
mit
23,153
""" Tests for the HistoryNode module """ import unittest from unittest.mock import patch from src import historynode from test import helper class TestHistoryNode(unittest.TestCase): """ Tests for the historynode module, containing the HistoryNode class """ # pylint: disable=too-many-public-methods # Ne...
blairck/jaeger
test/test_historynode.py
Python
mit
8,660
default_app_config = 'stories.apps.StoriesConfig'
kendricktan/laice
stories/__init__.py
Python
mit
49
class Solution(object): def canWinNim(self, n): """ :type n: int :rtype: bool """ return False if n % 4 == 0 else True def test(): s = Solution() for i in range(20): print('%d %s' % (i, s.canWinNim(i))) if __name__ == '__main__': test()
mistwave/leetcode
Python3/no292_Nim_Game.py
Python
mit
305
import tensorflow as tf def multilayer_perceptron(x, weights, biases): """ This function takes in the input placeholder, weights and biases and returns the output tensor of a network with two hidden ReLU layers, and an output layer with linear activation. :param tf.placeholder x: Placeholder for input...
jessegeerts/neural-nets
old_files/network.py
Python
mit
3,125
""" ``python-future``: pure Python implementation of Python 3 round(). """ from __future__ import division from future.utils import PYPY, PY26, bind_method # Use the decimal module for simplicity of implementation (and # hopefully correctness). from decimal import Decimal, ROUND_HALF_EVEN def newround(number, ndigi...
PythonCharmers/python-future
src/future/builtins/newround.py
Python
mit
3,190
# -*- coding: utf-8 -*- import logging logger = logging.getLogger(__name__) import ldap from django_auth_ldap.config import ActiveDirectoryGroupType from django_auth_ldap.backend import LDAPSettings class LiULDAPSettings(LDAPSettings): """ Defines common settings for all LDAP connections to LiU Active Direct...
ovidner/python-liu
liu/django/settings.py
Python
mit
1,861
""" tests.pretty_print ~~~~~~~~~~~~~~~~~~ :synopsis: Test utility functions. :copyright: (c) 2017, Tommy Ip. :license: MIT """ from tabled.utils import (columns_width, max_width, rotate_table, normalize_list) class TestMaxWidth: def test_normal(self) -> None: column = ['Some t...
tommyip/tabled
tests/test_utils.py
Python
mit
2,778
# Copyright © 2016-2022 Jakub Wilk <jwilk@jwilk.net> # # 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 limitation the rights # to use, copy, modify, mer...
jwilk/anorack
tests/test_cli.py
Python
mit
6,465