commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13
values | lang stringclasses 23
values |
|---|---|---|---|---|---|---|---|---|
81cd0b74e611532f8421d0dfb22266cd789a5a6a | add in oauth_keys to dev (bug 858813) | muffinresearch/solitude,muffinresearch/solitude | solitude/settings/sites/dev/db.py | solitude/settings/sites/dev/db.py | """private_base will be populated from puppet and placed in this directory"""
import logging
import dj_database_url
import private_base as private
from solitude.settings import base
from django_sha2 import get_password_hashers
ADMINS = ()
ALLOWED_HOSTS = ['payments-dev.allizom.org', 'localhost']
DATABASES = {}
D... | """private_base will be populated from puppet and placed in this directory"""
import logging
import dj_database_url
import private_base as private
from solitude.settings import base
from django_sha2 import get_password_hashers
ADMINS = ()
ALLOWED_HOSTS = ['payments-dev.allizom.org', 'localhost']
DATABASES = {}
D... | bsd-3-clause | Python |
3422c60553c6cd1a746e7c6e39a3e2ac707b0cf7 | return only mean predictions for cost and omit variance | numairmansur/RoBO,automl/RoBO,aaronkl/RoBO,aaronkl/RoBO,aaronkl/RoBO,numairmansur/RoBO,automl/RoBO | robo/acquisition/EnvEntropySearch.py | robo/acquisition/EnvEntropySearch.py | '''
Created on Jun 8, 2015
@author: Aaron Klein
'''
import emcee
import numpy as np
from robo.acquisition.LogEI import LogEI
from robo.acquisition.EntropyMC import EntropyMC
from scipy import stats
class EnvEntropySearch(EntropyMC):
'''
classdocs
'''
def __init__(self, model, cost_model, X_lower,... | '''
Created on Jun 8, 2015
@author: Aaron Klein
'''
import emcee
import numpy as np
from robo.acquisition.LogEI import LogEI
from robo.acquisition.EntropyMC import EntropyMC
from scipy import stats
class EnvEntropySearch(EntropyMC):
'''
classdocs
'''
def __init__(self, model, cost_model, X_lower,... | bsd-3-clause | Python |
2d8c8cce8885b24ac1766912ee7bd1897900ae0c | fix up Comment model | lionleaf/dwitter,lionleaf/dwitter,lionleaf/dwitter | dwitter/models.py | dwitter/models.py | from django.db import models
from django.contrib.auth import get_user_model
from django.contrib.auth.models import User
from django.dispatch import receiver
from django.db.models.signals import pre_delete
def get_sentinel_user():
users = get_user_model().objects
return users.get_or_create(username='[deleted]'... | from django.db import models
from django.contrib.auth import get_user_model
from django.contrib.auth.models import User
from django.dispatch import receiver
from django.db.models.signals import pre_delete
def get_sentinel_user():
users = get_user_model().objects
return users.get_or_create(username='[deleted]'... | apache-2.0 | Python |
c98662bf577afa1dcf1b847193dd2e856a90e864 | Fix flopped windows comment | glumpy/glumpy,glumpy/glumpy | examples/app-two-programs.py | examples/app-two-programs.py | # -----------------------------------------------------------------------------
# Copyright (c) 2009-2016 Nicolas P. Rougier. All rights reserved.
# Distributed under the (new) BSD License.
# -----------------------------------------------------------------------------
import numpy as np
from glumpy import gl, app, glo... | # -----------------------------------------------------------------------------
# Copyright (c) 2009-2016 Nicolas P. Rougier. All rights reserved.
# Distributed under the (new) BSD License.
# -----------------------------------------------------------------------------
import numpy as np
from glumpy import gl, app, glo... | bsd-3-clause | Python |
818f1431fe67120967f385ee090d06c1038e48c4 | Add project level imports so users don't have to worry about the module names. | caseywstark/dimensionful | dimensionful/__init__.py | dimensionful/__init__.py | from units import Unit
from quantity import Quantity
from common_units import *
from constants import *
| bsd-2-clause | Python | |
c713aa4953063cb6e64ecaaaed464f2a441482bb | Add testing scaffolding. | pgorla/lil-kv | lilkv/testsuite/test_basic.py | lilkv/testsuite/test_basic.py | # -*- coding: utf-8 -*-
"""
lilkv.testsuite.basic
Test lilkv basic functionality.
"""
from lilkv.testsuite import LilKVTestCase
from lilkv.keyspace import Keyspace
from lilkv.columnfamily import ColumnFamily
from lilkv.column import Column
class BasicTests(LilKVTestCase):
"""Baseclass for testing out ... | # -*- coding: utf-8 -*-
"""
lilkv.testsuite.basic
Test lilkv basic functionality.
"""
from lilkv.testsuite import LilKVTestCase
from lilkv.keyspace import Keyspace
from lilkv.columnfamily import ColumnFamily
from lilkv.column import Column
class BasicTests(LilKVTestCase):
"""Baseclass for testing out ... | mit | Python |
573d1e2498467da357a79bb865683e162e16eb14 | increment version to 0.13.1 | Farama-Foundation/Gymnasium,Farama-Foundation/Gymnasium | gym/version.py | gym/version.py | VERSION = '0.13.1'
| VERSION = '0.13.0'
| mit | Python |
d83e8f8702755766c1c15a35297b40d25051d55e | Bump version | Farama-Foundation/Gymnasium,dianchen96/gym,Farama-Foundation/Gymnasium,dianchen96/gym | gym/version.py | gym/version.py | VERSION = '0.4.9'
| VERSION = '0.4.8'
| mit | Python |
bb9aafe090d71c2a25eb3f3a6d591a205dbb7e5e | bump to 0.9.5 | dmpetrov/dataversioncontrol,dmpetrov/dataversioncontrol,efiop/dvc,efiop/dvc,dataversioncontrol/dvc,dataversioncontrol/dvc | dvc/__init__.py | dvc/__init__.py | """
DVC
----
Make your data science projects reproducible and shareable.
"""
import os
VERSION = '0.9.5'
if os.getenv('APPVEYOR_REPO_TAG', '').lower() != 'true' and os.getenv('TRAVIS_TAG', '') == '':
# Dynamically update version
try:
import git
repo = git.Repo(os.curdir, search_parent_director... | """
DVC
----
Make your data science projects reproducible and shareable.
"""
import os
VERSION = '0.9.4'
if os.getenv('APPVEYOR_REPO_TAG', '').lower() != 'true' and os.getenv('TRAVIS_TAG', '') == '':
# Dynamically update version
try:
import git
repo = git.Repo(os.curdir, search_parent_director... | apache-2.0 | Python |
3aac2716972c49eb3b1b688cb1fad89ce690ca58 | fix incorrect empty list condition | cielpy/build_ipa | filter_log.py | filter_log.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 ciel <ciel@cieldeMBP>
#
# Distributed under terms of the MIT license.
"""
filter git log
"""
import codecs
from call_cmd import call
import config
def filter_log(last_commit):
commit_valid = call('git -C {} cat-file -e '.format(... | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 ciel <ciel@cieldeMBP>
#
# Distributed under terms of the MIT license.
"""
filter git log
"""
import codecs
from call_cmd import call
import config
def filter_log(last_commit):
commit_valid = call('git -C {} cat-file -e '.format(... | mit | Python |
ee795da3215374f30005c9daa42de6f9d581580f | Make finglonger output a bit easier to read | nibalizer/finglonger | finglonger.py | finglonger.py | #!/usr/bin/python
import os
import sys
import subprocess
import tempfile
import yaml
def validate_config(config):
environment = config.get('environment')
if environment is None:
print "No environment set, set one in config.yaml "
sys.exit(1)
def validate_environment(config):
if os.path... | #!/usr/bin/python
import os
import sys
import subprocess
import tempfile
import yaml
def validate_config(config):
environment = config.get('environment')
if environment is None:
print "No environment set, set one in config.yaml "
sys.exit(1)
def validate_environment(config):
if os.path... | apache-2.0 | Python |
cb4f022fb1fe0780eb2e37c8fdc8ff6a4409115c | Test and implementation for !ptr+offset loading | benstreb/os-test-harness,benstreb/os-test-harness | ostester/yamlreader.py | ostester/yamlreader.py | import collections.abc
from io import StringIO
import yaml
import ast
def parse(file):
return yaml.safe_load(file)
def parse_from_string(string):
return parse(StringIO(string))
class Zeros(collections.abc.Sequence):
"""
Represents a zeroed region of memory in C
>>> yaml.load("!zeros 5")
... | import collections.abc
from io import StringIO
import yaml
import ast
def parse(file):
return yaml.safe_load(file)
def parse_from_string(string):
return parse(StringIO(string))
class Zeros(collections.abc.Sequence):
"""
Represents a zeroed region of memory in C
>>> yaml.load("!zeros 5")
... | isc | Python |
3329b260fbea858dcfe3f6f6a9ff365467352d1f | optimize sum_lines for time consuming | edonyM/toolkitem,edonyM/toolkitem,edonyM/toolkitem | fileprocess/filesline.py | fileprocess/filesline.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""
# .---. .-----------
# / \ __ / ------
# / / \( )/ ----- (`-') _ _(`-') <-. (`-')_
# ////// '\/ ` --- ( OO).-/( (OO ).-> .-> \( OO) ) .->
# //// / // : : --- (,------... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""
# .---. .-----------
# / \ __ / ------
# / / \( )/ ----- (`-') _ _(`-') <-. (`-')_
# ////// '\/ ` --- ( OO).-/( (OO ).-> .-> \( OO) ) .->
# //// / // : : --- (,------... | mit | Python |
e1f1f0ca797b639a730e8804dbd5595ad0f395e0 | Add docstring for module.py | scottclowe/python-continuous-integration,scottclowe/python-ci,scottclowe/python-continuous-integration,scottclowe/python-ci | package_name/module.py | package_name/module.py | """
Module provides a simple cubic_rectification function.
"""
import numpy as np
def cubic_rectification(x):
'''
Returns the rectified value of the cube of X.
If X is positive, this is the cube of X, if X is negative it is 0.
'''
return np.maximum(0, x**3)
| import numpy as np
def cubic_rectification(x):
'''
Returns the rectified value of the cube of X.
If X is positive, this is the cube of X, if X is negative it is 0.
'''
return np.maximum(0, x**3)
| mit | Python |
d71c0745a4032ce60dd506e91665e46c4c98271f | Update forwarder_ZMQ_Server.py | VitorHugoAguiar/ProBot,VitorHugoAguiar/ProBot,VitorHugoAguiar/ProBot,VitorHugoAguiar/ProBot | ProBot_Server/Midi_Device/forwarder_ZMQ_Server.py | ProBot_Server/Midi_Device/forwarder_ZMQ_Server.py | #!/usr/bin/python
import zmq
def main():
print "\nProBot's ZMQ Server is running..."
try:
context = zmq.Context(1)
# Socket facing clients
frontend = context.socket(zmq.SUB)
frontend.bind("tcp://*:5559")
frontend.setsockopt(zmq.SUBSCRIBE, "")
#... | #!/usr/bin/python
import zmq
def main():
print "\nServer for ProBot is running..."
try:
context = zmq.Context(1)
# Socket facing clients
frontend = context.socket(zmq.SUB)
frontend.bind("tcp://*:5559")
frontend.setsockopt(zmq.SUBSCRIBE, "")
# So... | agpl-3.0 | Python |
788cc159e4d734b972e22ccf06dbcd8ed8f94885 | Update DictStack implementation from jaraco.collections 3.5.1 | pypa/setuptools,pypa/setuptools,pypa/setuptools | distutils/_collections.py | distutils/_collections.py | import collections
import itertools
# from jaraco.collections 3.5.1
class DictStack(list, collections.abc.Mapping):
"""
A stack of dictionaries that behaves as a view on those dictionaries,
giving preference to the last.
>>> stack = DictStack([dict(a=1, c=2), dict(b=2, a=2)])
>>> stack['a']
2... | import collections
import itertools
# from jaraco.collections 3.5
class DictStack(list, collections.abc.Mapping):
"""
A stack of dictionaries that behaves as a view on those dictionaries,
giving preference to the last.
>>> stack = DictStack([dict(a=1, c=2), dict(b=2, a=2)])
>>> stack['a']
2
... | mit | Python |
3ff2ecfd26097b37832a397a43db6121a0bc3627 | Remove superfluous comment. | maykinmedia/djadyen,maykinmedia/djadyen,maykinmedia/djadyen | djadyen/management/commands/adyen_maintenance.py | djadyen/management/commands/adyen_maintenance.py | from datetime import timedelta
from django.apps import apps
from django.core.management.base import BaseCommand
from django.utils import timezone
from djadyen import settings
from djadyen.choices import Status
from djadyen.models import AdyenNotification
class Command(BaseCommand):
help = "Process the adyen not... | from datetime import timedelta
from django.apps import apps
from django.core.management.base import BaseCommand
from django.utils import timezone
from djadyen import settings
from djadyen.choices import Status
from djadyen.models import AdyenNotification
class Command(BaseCommand):
help = "Process the adyen not... | bsd-3-clause | Python |
32eba84ec5527f1afc82998e98f5d15035e311c1 | Allow forced loading. Contemplating changing the default too. | dipakvwarade/pychef,jarosser06/pychef,dipakvwarade/pychef,cread/pychef,coderanger/pychef,coderanger/pychef,Scalr/pychef,jarosser06/pychef,Scalr/pychef,cread/pychef | chef/base.py | chef/base.py | from chef.api import ChefAPI
class DelayedAttribute(object):
"""Descriptor that calls ._populate() before access to implement lazy loading."""
def __init__(self, attr):
self.attr = attr
def __get__(self, instance, owner):
if instance is None:
return self
if not getattr... | from chef.api import ChefAPI
class DelayedAttribute(object):
"""Descriptor that calls ._populate() before access to implement lazy loading."""
def __init__(self, attr):
self.attr = attr
def __get__(self, instance, owner):
if instance is None:
return self
if not getattr... | apache-2.0 | Python |
6ba2dc8cf06efd74cae941c370e75ccddcf1d25c | fix broken arg of DnnL2Pool2DNode | nsauder/treeano,jagill/treeano,jagill/treeano,jagill/treeano,nsauder/treeano,diogo149/treeano,nsauder/treeano,diogo149/treeano,diogo149/treeano | treeano/sandbox/nodes/l2_pool.py | treeano/sandbox/nodes/l2_pool.py | import numpy as np
import theano
import theano.tensor as T
import treeano
import treeano.nodes as tn
fX = theano.config.floatX
@treeano.register_node("l2_pool")
class L2PoolNode(treeano.Wrapper1NodeImpl):
"""
node that takes the L2 norm of the pooled over region
"""
hyperparameter_names = ("pool_s... | import numpy as np
import theano
import theano.tensor as T
import treeano
import treeano.nodes as tn
fX = theano.config.floatX
@treeano.register_node("l2_pool")
class L2PoolNode(treeano.Wrapper1NodeImpl):
"""
node that takes the L2 norm of the pooled over region
"""
hyperparameter_names = ("pool_s... | apache-2.0 | Python |
372ce38d1ddcf2fd65d83df2499d97d4fc2128e6 | Fix issue in cbb.py | explosiveduck/ed2d,explosiveduck/ed2d | ed2d/physics/cbb.py | ed2d/physics/cbb.py | from ed2d.physics.collisiondata import*
from ed2d.glmath import vector
# Circle Bounding Box
class CBB(object):
def __init__(self, radius, center):
'''Creates a circle bounding box object to be used with the physics engine. Takes in a float for the radius and an array for the center.'''
self.radius =... | from ed2d.physics.collisiondata import*
from ed2d.glmath import vector
# Circle Bounding Box
class CBB(object):
def __init__(self, radius, center):
'''Creates a circle bounding box object to be used with the physics engine. Takes in a float for the radius and an array for the center.'''
self.radius =... | bsd-2-clause | Python |
1451d199833b405929105f939f57b4d4faf50fa2 | Use new py.test to generate vector-vs-scalar tests | ozialien/python-skyfield,GuidoBR/python-skyfield,exoanalytic/python-skyfield,skyfielders/python-skyfield,GuidoBR/python-skyfield,ozialien/python-skyfield,skyfielders/python-skyfield,exoanalytic/python-skyfield | skyfield/tests/test_vectorization.py | skyfield/tests/test_vectorization.py | """Determine whether arrays work as well as individual inputs."""
from itertools import izip
from numpy import array
from ..constants import T0
from ..planets import earth, mars
from ..timescales import JulianDate, julian_date
dates = array([
julian_date(1969, 7, 20, 20. + 18. / 60.),
T0,
julian_date(2012... | """Determine whether arrays work as well as individual inputs."""
import pytest
from numpy import array
from ..constants import T0
from ..planets import earth, mars
from ..timescales import JulianDate, julian_date
dates = array([
julian_date(1969, 7, 20, 20. + 18. / 60.),
T0,
julian_date(2012, 12, 21),
... | mit | Python |
0ea687403b01dbc6268c15550f0caf45a54e9106 | Fix Joust picking with multiple minions in the deck | NightKev/fireplace,jleclanche/fireplace,amw2104/fireplace,Ragowit/fireplace,Ragowit/fireplace,smallnamespace/fireplace,beheh/fireplace,smallnamespace/fireplace,amw2104/fireplace | fireplace/cards/utils.py | fireplace/cards/utils.py | import random
from hearthstone.enums import CardClass, CardType, GameTag, Race, Rarity
from ..actions import *
from ..aura import Refresh
from ..dsl import *
from ..events import *
from ..utils import custom_card
# For buffs which are removed when the card is moved to play (eg. cost buffs)
# This needs to be Summon, ... | import random
from hearthstone.enums import CardClass, CardType, GameTag, Race, Rarity
from ..actions import *
from ..aura import Refresh
from ..dsl import *
from ..events import *
from ..utils import custom_card
# For buffs which are removed when the card is moved to play (eg. cost buffs)
# This needs to be Summon, ... | agpl-3.0 | Python |
42462135cec040d17f8ce4488c1ee6bb3b59f406 | Bump mono-basic to @mono/mono-basic/b8011b2f274606323da0927214ed98336465f467 | mono/bockbuild,mono/bockbuild | packages/mono-basic.py | packages/mono-basic.py | GitHubTarballPackage ('mono', 'mono-basic', '4.0.1', 'b8011b2f274606323da0927214ed98336465f467',
configure = './configure --prefix="%{prefix}"',
override_properties = { 'make': 'make' }
)
| GitHubTarballPackage ('mono', 'mono-basic', '3.0', '0d0440feccf648759f7316f93ad09b1e992ea13a',
configure = './configure --prefix="%{prefix}"',
override_properties = { 'make': 'make' }
)
| mit | Python |
3ddddbd24bb37c30df80233ec4c70c38b6c29e82 | Update leaflet request to be over https | EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient | emstrack/forms.py | emstrack/forms.py | from django.contrib.gis.forms import widgets
class LeafletPointWidget(widgets.BaseGeometryWidget):
template_name = 'leaflet/leaflet.html'
class Media:
css = {
'all': ('https://cdnjs.cloudflare.com/ajax/libs/leaflet/v0.7.7/leaflet.css',
'leaflet/css/location_form.css',
... | from django.contrib.gis.forms import widgets
class LeafletPointWidget(widgets.BaseGeometryWidget):
template_name = 'leaflet/leaflet.html'
class Media:
css = {
'all': ('https://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css',
'leaflet/css/location_form.css',
... | bsd-3-clause | Python |
612698f37ab726fb77aa1f284c97d01d1d726abf | Bump version | ClemsonSoCUnix/django-anyvcs,ClemsonSoCUnix/django-anyvcs | django_anyvcs/__init__.py | django_anyvcs/__init__.py | # Copyright (c) 2014-2016, Clemson University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditio... | # Copyright (c) 2014-2016, Clemson University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditio... | bsd-3-clause | Python |
9674a0869c2a333f74178e305677259e7ac379c3 | Make the Websocket's connection header value case-insensitive | liorvh/mitmproxy,ccccccccccc/mitmproxy,dwfreed/mitmproxy,mhils/mitmproxy,ryoqun/mitmproxy,Kriechi/mitmproxy,azureplus/mitmproxy,dufferzafar/mitmproxy,ikoz/mitmproxy,jpic/mitmproxy,tfeagle/mitmproxy,rauburtin/mitmproxy,MatthewShao/mitmproxy,pombredanne/mitmproxy,pombredanne/mitmproxy,laurmurclar/mitmproxy,StevenVanAcker... | examples/ignore_websocket.py | examples/ignore_websocket.py | # This script makes mitmproxy switch to passthrough mode for all HTTP
# responses with "Connection: Upgrade" header. This is useful to make
# WebSockets work in untrusted environments.
#
# Note: Chrome (and possibly other browsers), when explicitly configured
# to use a proxy (i.e. mitmproxy's regular mode), send a CON... | # This script makes mitmproxy switch to passthrough mode for all HTTP
# responses with "Connection: Upgrade" header. This is useful to make
# WebSockets work in untrusted environments.
#
# Note: Chrome (and possibly other browsers), when explicitly configured
# to use a proxy (i.e. mitmproxy's regular mode), send a CON... | mit | Python |
7c90e73d3ffa2a8209a751b01c7cd8bd3122b13b | Use actual feature values instead of binary for making pivot predictions | tmills/uda,tmills/uda | scripts/build_pivot_training_data.py | scripts/build_pivot_training_data.py | #!/usr/bin/env python
from os.path import join, dirname
from sklearn.datasets import load_svmlight_file, dump_svmlight_file
import numpy as np
import scipy.sparse
import sys
from uda_common import read_feature_groups
def main(args):
if len(args) < 3:
sys.stderr.write("Three required arguments: <pivot file... | #!/usr/bin/env python
from os.path import join, dirname
from sklearn.datasets import load_svmlight_file, dump_svmlight_file
import numpy as np
import scipy.sparse
import sys
from uda_common import read_feature_groups
def main(args):
if len(args) < 3:
sys.stderr.write("Three required arguments: <pivot file... | apache-2.0 | Python |
d981caff4b6710a3779f25fd8955fd111d9ea0cf | fix export error in dj 19 | joshourisman/django-tablib,joshourisman/django-tablib | django_tablib/datasets.py | django_tablib/datasets.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from .base import BaseDataset
class SimpleDataset(BaseDataset):
def __init__(self, queryset, headers=None, encoding='utf-8'):
self.queryset = queryset
self.encoding = encoding
if headers is None:
... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from .base import BaseDataset
class SimpleDataset(BaseDataset):
def __init__(self, queryset, headers=None, encoding='utf-8'):
self.queryset = queryset
self.encoding = encoding
if headers is None:
... | mit | Python |
4c500ce1995da97861e37647b61efaf14c6b08d0 | Load saved RDD | Nathx/parental_advisory_ml,Nathx/parental_advisory_ml,Nathx/subs_check,Nathx/subs_check | code/main.py | code/main.py | from spark_model import SparkModel
import socket
from document import Document
from pyspark import SparkContext, SparkConf
from boto.s3.connection import S3Connection
from pyspark import SparkConf, SparkContext
import json
import sys
from datetime import datetime
def log_results(saved, model_type, start_time, end_time... | from spark_model import SparkModel
import socket
from document import Document
from pyspark import SparkContext, SparkConf
from boto.s3.connection import S3Connection
from pyspark import SparkConf, SparkContext
import json
import sys
from datetime import datetime
def log_results(model_type, start_time, end_time, score... | mit | Python |
9ec2382de5a3d5377fee03a6151e5afbf36f8e71 | add doc link | joshhartigan/semicircle,joshhartigan/semicircle,joshhartigan/semicircle,joshhartigan/semicircle,joshhartigan/semicircle,joshhartigan/semicircle,joshhartigan/semicircle,joshhartigan/semicircle,joshhartigan/semicircle,joshhartigan/semicircle,joshhartigan/semicircle | code/mode.py | code/mode.py | # an in-depth rundown of this program
# can be found at:
# https://github.com/joshhartigan/learn-programming/blob/master/Most%20Frequent%20Integer.md
def mode(array):
count = {}
for elem in array:
try:
count[elem] += 1
except (KeyError):
count[elem] = 1
# get max cou... | def mode(array):
count = {}
for elem in array:
try:
count[elem] += 1
except (KeyError):
count[elem] = 1
# get max count
maximum = 0
modeKey = 0
for key in count.keys():
if count[key] > maximum:
maximum = count[key]
modeKey =... | bsd-2-clause | Python |
ae2284fa85e1ef7be43792b72480018729b1c2ba | Bump PEP version for __version__ comment | edoburu/django-fluent-blogs,edoburu/django-fluent-blogs | fluent_blogs/__init__.py | fluent_blogs/__init__.py | # following PEP 440
__version__ = "1.0"
# Fix for internal messy imports.
# When base_models is imported before models/__init__.py runs, there is a circular import:
# base_models -> models/managers.py -> invoking models/__init__.py -> models/db.py -> base_models.py
#
# This doesn't occur when the models are imported f... | # following PEP 386
__version__ = "1.0"
# Fix for internal messy imports.
# When base_models is imported before models/__init__.py runs, there is a circular import:
# base_models -> models/managers.py -> invoking models/__init__.py -> models/db.py -> base_models.py
#
# This doesn't occur when the models are imported f... | apache-2.0 | Python |
ef9cd0033ccfd314592be7987c262a61d0ec2fba | fix thing I apparently never testedgit add light.py | jeremybmerrill/bigappleserialbus,jeremybmerrill/bigappleserialbus,jeremybmerrill/bigappleserialbus,jeremybmerrill/bigappleserialbus | light.py | light.py | import RPi.GPIO as GPIO
class Light:
def __init__(self, pin):
self.pin = pin
self.status = False
GPIO.setup(pin, GPIO.OUT)
def toggle(self):
self.status = not self.status
self.do()
def on(self):
self.status = True
self.do()
def off(self):
self.status = False
self.do()
... | import RPi.GPIO as GPIO
class Light:
def __init__(self, pin):
self.pin = pin
self.status = False
GPIO.setup(pin, GPIO.OUT)
def toggle(self):
self.status = not self.status
self.do()
def on(self):
self.status = True
self.do()
def off(self):
self.status = False
self.do()
... | apache-2.0 | Python |
f0d4b430b627fb9e2b18ba3f82c936698fac6430 | Update to version 1.3 | xcgd/account_report_csv | __openerp__.py | __openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Account Report CSV, for OpenERP
# Copyright (C) 2013 XCG Consulting (http://odoo.consulting)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Aff... | # -*- coding: utf-8 -*-
##############################################################################
#
# Account Report CSV, for OpenERP
# Copyright (C) 2013 XCG Consulting (http://odoo.consulting)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Aff... | agpl-3.0 | Python |
7b176d1e775ddec384a76d6de9c121e114a8738e | load ACL | xcgd/analytic_structure | __openerp__.py | __openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Account Analytic Online, for OpenERP
# Copyright (C) 2013 XCG Consulting (www.xcg-consulting.fr)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | # -*- coding: utf-8 -*-
##############################################################################
#
# Account Analytic Online, for OpenERP
# Copyright (C) 2013 XCG Consulting (www.xcg-consulting.fr)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | agpl-3.0 | Python |
08fddbdc0ac70a549bac82131771218107186def | add discription | kholioeg/account_discount | __openerp__.py | __openerp__.py | # -*- coding: utf-8 -*-
{
'name': "Account Discount",
'summary': """
Use Tax model for discounts as well""",
'description': """
Odoo OpenERP Account Discount from Tax
This module adds new concept to use tax model as discount model and print both taxes and discounts separetly.... | # -*- coding: utf-8 -*-
{
'name': "Account Discount",
'summary': """
Apply Discount model to taxes""",
'description': """
The purpose is to apply discount record for the same tax model
""",
'author': "Khaled Hamed",
'website': "http://www.grandtk.com",
# Categories can be... | agpl-3.0 | Python |
6d83f2150f7c6177385b9f2d8abbe48cd2979130 | Add staleness to MonthCache Admin display | Kromey/fbxnano,Kromey/akwriters,Kromey/akwriters,Kromey/fbxnano,Kromey/fbxnano,Kromey/akwriters,Kromey/fbxnano,Kromey/akwriters | events/admin.py | events/admin.py | from django.contrib import admin
from .models import Calendar,MonthCache
# Register your models here.
@admin.register(Calendar)
class CalendarAdmin(admin.ModelAdmin):
list_display = ('name','remote_id','css_class')
@admin.register(MonthCache)
class MonthCacheAdmin(admin.ModelAdmin):
list_display = ('calend... | from django.contrib import admin
from .models import Calendar,MonthCache
# Register your models here.
@admin.register(Calendar)
class CalendarAdmin(admin.ModelAdmin):
list_display = ('name','remote_id','css_class')
@admin.register(MonthCache)
class MonthCacheAdmin(admin.ModelAdmin):
list_display = ('calend... | mit | Python |
d308bbd0200e1b4783bf63cafda03650579b9351 | change help text | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative | ynr/apps/official_documents/models.py | ynr/apps/official_documents/models.py | import os
from django.db import models
from django.urls import reverse
from django_extensions.db.models import TimeStampedModel
DOCUMENT_UPLOADERS_GROUP_NAME = "Document Uploaders"
def document_file_name(instance, filename):
return os.path.join(
"official_documents", str(instance.ballot.ballot_paper_id)... | import os
from django.db import models
from django.urls import reverse
from django_extensions.db.models import TimeStampedModel
DOCUMENT_UPLOADERS_GROUP_NAME = "Document Uploaders"
def document_file_name(instance, filename):
return os.path.join(
"official_documents", str(instance.ballot.ballot_paper_id)... | agpl-3.0 | Python |
cedae39716587fcc0459a05e74acc43b190d7457 | split download | ecmwf/cdsapi | example-era5.py | example-era5.py | #!/usr/bin/env python
# (C) Copyright 2018 ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status... | #!/usr/bin/env python
# (C) Copyright 2018 ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status... | apache-2.0 | Python |
3846907435da720c075ab89579b970da5019b49f | Add Tapastic/AmpleTime | webcomics/dosage,webcomics/dosage | dosagelib/plugins/tapastic.py | dosagelib/plugins/tapastic.py | # SPDX-License-Identifier: MIT
# Copyright (C) 2019-2020 Tobias Gruetzmacher
# Copyright (C) 2019-2020 Daniel Ring
import json
import re
from ..scraper import _ParserScraper
from ..helpers import indirectStarter
class Tapastic(_ParserScraper):
baseUrl = 'https://tapas.io/'
imageSearch = '//article[contains(@... | # SPDX-License-Identifier: MIT
# Copyright (C) 2019-2020 Tobias Gruetzmacher
# Copyright (C) 2019-2020 Daniel Ring
import json
import re
from ..scraper import _ParserScraper
from ..helpers import indirectStarter
class Tapastic(_ParserScraper):
baseUrl = 'https://tapas.io/'
imageSearch = '//article[contains(@... | mit | Python |
62314491b148c51e7c27e13aded283a0622c47f4 | improve h5py config check | IntelLabs/hpat,IntelLabs/hpat,IntelLabs/hpat,IntelLabs/hpat | hpat/config.py | hpat/config.py | try:
from .io import _hdf5
import h5py
# TODO: make sure h5py/hdf5 supports parallel
except ImportError:
_has_h5py = False
else:
_has_h5py = True
try:
import pyarrow
except ImportError:
_has_pyarrow = False
else:
_has_pyarrow = True
try:
from . import ros_cpp
except ImportError:
... | try:
from .io import _hdf5
except ImportError:
_has_h5py = False
else:
_has_h5py = True
try:
import pyarrow
except ImportError:
_has_pyarrow = False
else:
_has_pyarrow = True
try:
from . import ros_cpp
except ImportError:
_has_ros = False
else:
_has_ros = True
try:
from . impo... | bsd-2-clause | Python |
ae7a5bef1e3ee0216651dc4aeef3abcbab3cf76e | update code | Murillo/Hackerrank-Algorithms | Strings/alternating-characters.py | Strings/alternating-characters.py | # Alternating Characters
# Developer: Murillo Grubler
# Link: https://www.hackerrank.com/challenges/alternating-characters/problem
# Time complexity: O(n)
def alternatingCharacters(s):
sumChars = 0
for i in range(len(s)):
if i == 0 or tempChar != s[i]:
tempChar = s[i]
continue
... | # Alternating Characters
# Developer: Murillo Grubler
# Link: https://www.hackerrank.com/challenges/alternating-characters/problem
def alternatingCharacters(s):
sumChars = 0
for i in range(len(s)):
if i == 0 or tempChar != s[i]:
tempChar = s[i]
continue
if tempChar == s[... | mit | Python |
44fbc835354b7612d5d203250255a323c8759b64 | fix log %(levelname)-8s to align | ClericPy/torequests,ClericPy/torequests | torequests/logs.py | torequests/logs.py | #! coding:utf-8
import logging
dummy_logger = logging.getLogger('torequests.dummy')
main_logger = logging.getLogger('torequests.main')
def init_logger(name='', handler_path_levels=None,
level=logging.INFO, formatter=None,
formatter_str=None, datefmt="%Y-%m-%d %H:%M:%S"):
"""Args:
... | #! coding:utf-8
import logging
dummy_logger = logging.getLogger('torequests.dummy')
main_logger = logging.getLogger('torequests.main')
def init_logger(name='', handler_path_levels=None,
level=logging.INFO, formatter=None,
formatter_str=None, datefmt="%Y-%m-%d %H:%M:%S"):
"""Args:
... | mit | Python |
db47a651e380709c33c54c86f9a3861187772406 | Add metrics to MNIST | israelg99/eva | eva/examples/mnist.py | eva/examples/mnist.py | #%% Setup.
from collections import namedtuple
import numpy as np
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.optimizers import Nadam
from keras.layers.adva... | #%% Setup.
from collections import namedtuple
import numpy as np
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.optimizers import Nadam
from keras.layers.adva... | apache-2.0 | Python |
f6672fd0074052ba71bc1266590f0ef0db8f14d0 | fix import. | soasme/blackgate | blackgate/cli.py | blackgate/cli.py | # -*- coding: utf-8 -*-
import click
from blackgate.core import component
from blackgate.server import run
@click.group()
def main():
# README CONFIG
component.install_from_config(config)
@main.command()
def start():
run(config.get('port', 9654))
if __name__ == '__main__':
main()
| # -*- coding: utf-8 -*-
import click
from blackgate.core import component
from blackgate.server importrun
@click.group()
def main():
# README CONFIG
component.install_from_config(config)
@main.command()
def start():
run(config.get('port', 9654))
if __name__ == '__main__':
main()
| mit | Python |
1c9a16a0896cd39aca2b44c0ef5c4eb155d1dab7 | Add a test for 2 framgnets case. | kcaa/kcaa,kcaa/kcaa,kcaa/kcaa,kcaa/kcaa | server/kcaa/manipulator_util_test.py | server/kcaa/manipulator_util_test.py | #!/usr/bin/env python
import pytest
import manipulator_util
class TestManipulatorManager(object):
def pytest_funcarg__manager(self, request):
return manipulator_util.ManipulatorManager(None, {}, 0)
def test_in_schedule_fragment(self):
in_schedule_fragment = (
manipulator_util.M... | #!/usr/bin/env python
import pytest
import manipulator_util
class TestManipulatorManager(object):
def pytest_funcarg__manager(self, request):
return manipulator_util.ManipulatorManager(None, {}, 0)
def test_in_schedule_fragment(self):
in_schedule_fragment = (
manipulator_util.M... | apache-2.0 | Python |
3bd383a15902d8367097a4348de64c929732767b | Fix Test | Lab-317/NewsParser | tests/NewsParser_Test.py | tests/NewsParser_Test.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: balicanta
# @Date: 2014-10-25 09:57:26
# @Last Modified by: balicanta
# @Last Modified time: 2014-10-27 23:44:57
from NewsParser import NewsParser
from requests.utils import get_encodings_from_content
test_fixtures = [
{"url": "http://udn.com/NEWS/NATIO... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: balicanta
# @Date: 2014-10-25 09:57:26
# @Last Modified by: bustta
# @Last Modified time: 2014-10-27 23:22:08
from NewsParser import NewsParser
from requests.utils import get_encodings_from_content
test_fixtures = [
{"url": "http://udn.com/NEWS/NATIONAL... | mit | Python |
97478d2bb38b94a5effbbc74db3ae1a0360f9a19 | remove vm.id usage in exeption message | 2gis/vmmaster,2gis/vmmaster,sh0ked/vmmaster,sh0ked/vmmaster,2gis/vmmaster | vmpool/endpoint.py | vmpool/endpoint.py | # coding: utf-8
from core.utils import generator_wait_for
from core.logger import log_pool
from core.config import config
from core.exceptions import PlatformException, NoSuchEndpoint, \
CreationException
from vmpool.virtual_machines_pool import pool
from vmpool.platforms import Platforms
from vmpool.vmqueue impo... | # coding: utf-8
from core.utils import generator_wait_for
from core.logger import log_pool
from core.config import config
from core.exceptions import PlatformException, NoSuchEndpoint, \
CreationException
from vmpool.virtual_machines_pool import pool
from vmpool.platforms import Platforms
from vmpool.vmqueue impo... | mit | Python |
08125322609e97e868c5c712df9e35e4c556434d | Use enumerate() instead of managing an index variable. | ting-yuan/web-page-replay,andrey-malets/web-page-replay,bpsinc-native/src_third_party_webpagereplay,colin-scott/web-page-replay,bpsinc-native/src_third_party_webpagereplay,colin-scott/web-page-replay,snorp/web-page-replay,bpsinc-native/src_third_party_webpagereplay,ting-yuan/web-page-replay,andrey-malets/web-page-repla... | httparchive.py | httparchive.py | #!/usr/bin/env python
# Copyright 2010 Google Inc. 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/LICENSE-2.0
#
# Unless required... | #!/usr/bin/env python
# Copyright 2010 Google Inc. 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/LICENSE-2.0
#
# Unless required... | apache-2.0 | Python |
d5482b10a712863c36a59d8ce82f3958ec41e78b | Add CORS on /swagger.json | l-vincent-l/APITaxi,openmaraude/APITaxi,l-vincent-l/APITaxi,openmaraude/APITaxi | APITaxi/api/__init__.py | APITaxi/api/__init__.py | # -*- coding: utf-8 -*-
from flask.ext.restplus import apidoc, Api
from flask import Blueprint, render_template
from flask_cors import cross_origin
api_blueprint = Blueprint('api', __name__)
api = Api(api_blueprint, doc=False, catch_all_404s=True,
title='API version 2.0')
ns_administrative = api.namespace('ad... | # -*- coding: utf-8 -*-
from flask.ext.restplus import apidoc, Api
from flask import Blueprint, render_template
api_blueprint = Blueprint('api', __name__)
api = Api(api_blueprint, doc=False, catch_all_404s=True,
title='API version 2.0')
ns_administrative = api.namespace('administrative',
description="... | agpl-3.0 | Python |
6e525872537cd31a80cb791d6594a1f6800c61b4 | add invers option, add args-parsing | lnitram/pi-playground,lnitram/pi-playground | i2c/PCF8574.py | i2c/PCF8574.py | #!/usr/bin/python
import sys
import smbus
import time
import argparse
# Reads data from PCF8574 and prints the state of each port
def readPCF8574(busnumber,address):
address = int(address,16)
busnumber = int(busnumber)
bus = smbus.SMBus(busnumber)
state = bus.read_byte(address);
for i in range(0,8)... | #!/usr/bin/python
import sys
import smbus
import time
# Reads data from PCF8574 and prints the state of each port
def readPCF8574(busnumber,address):
address = int(address,16)
busnumber = int(1)
bus = smbus.SMBus(busnumber)
state = bus.read_byte(address);
for i in range(0,8):
port = "port... | mit | Python |
c888e52788ec37641f97f761d2052902db20582a | Add missing dates | gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext | erpnext/accounts/dashboard.py | erpnext/accounts/dashboard.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
from itertools import groupby
from operator import itemgetter
import frappe
from frappe.utils import add_to_date, date_diff, getdate, nowdate
from erpne... | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
from itertools import groupby
from operator import itemgetter
import frappe
from frappe.utils import add_to_date
from erpnext.accounts.report.general_le... | agpl-3.0 | Python |
dca8dce24e0bea671b52d456909c35e43c4f5929 | move exchange endpoint into consumer urlspace | wanghe4096/website,wanghe4096/website,evonove/django-oauth-toolkit-example,evonove/django-oauth-toolkit-example,wanghe4096/website,wanghe4096/website | example/urls.py | example/urls.py | from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
from django.contrib import admin
from .views import ConsumerView, ConsumerExchangeView
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^$', TemplateView.as_view(template_name='example/home.html'), name=... | from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
from django.contrib import admin
from .views import ConsumerView, ConsumerExchangeView
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^$', TemplateView.as_view(template_name='example/home.html'), name='ho... | bsd-2-clause | Python |
dcc472a6c8e15e7fc105277332681b38e40640df | Revert open_file_dialog example | r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview,shivaprsdv/pywebview,shivaprsdv/pywebview,shivaprsdv/pywebview,shivaprsdv/pywebview,r0x0r/pywebview,r0x0r/pywebview | examples/open_file_dialog.py | examples/open_file_dialog.py | import webview
import threading
"""
This example demonstrates creating an open file dialog.
"""
def open_file_dialog():
import time
time.sleep(5)
print(webview.create_file_dialog(webview.OPEN_DIALOG, allow_multiple=True))
if __name__ == '__main__':
t = threading.Thread(target=open_file_dialog)
t... | import webview
import threading
"""
This example demonstrates creating an open file dialog.
"""
def open_file_dialog():
import time
time.sleep(5)
print(webview.create_file_dialog(webview.OPEN_DIALOG, allow_multiple=False))
if __name__ == '__main__':
t = threading.Thread(target=open_file_dialog)
... | bsd-3-clause | Python |
965236870ce5bf6dcbe9398b444b977c796b096e | set the right keyword to the close function | simphony/simphony-paraview,simphony/simphony-paraview | simphony_paraview/tests/test_show.py | simphony_paraview/tests/test_show.py | import unittest
from hypothesis import given
from paraview import servermanager
from paraview.simple import Disconnect
from simphony_paraview.show import show
from simphony_paraview.core.testing import cuds_containers
class TestShow(unittest.TestCase):
def setUp(self):
if servermanager.ActiveConnection... | import unittest
from hypothesis import given
from paraview import servermanager
from paraview.simple import Disconnect
from simphony_paraview.show import show
from simphony_paraview.core.testing import cuds_containers
class TestShow(unittest.TestCase):
def setUp(self):
if servermanager.ActiveConnection... | bsd-2-clause | Python |
c0358584f2b5a05947ebb558c6d10293cc969a1a | Fix tests | Pawamoy/dependenpy,Pawamoy/dependenpy | tests/test_dependenpy.py | tests/test_dependenpy.py | # -*- coding: utf-8 -*-
"""Main test script."""
from dependenpy.cli import main
def test_main():
"""Main test method."""
main(['-lm', 'dependenpy'])
| # -*- coding: utf-8 -*-
"""Main test script."""
from dependenpy.cli import main
def test_main():
"""Main test method."""
main('dependenpy')
| isc | Python |
a6435a8713985464b8c37a438ac035d65f66b4cd | Add more user mapfiles and validate | geographika/mappyfile,geographika/mappyfile | tests/test_large_file.py | tests/test_large_file.py | import logging
import os
import cProfile
import glob
import json
import mappyfile
from mappyfile.parser import Parser
from mappyfile.pprint import PrettyPrinter
from mappyfile.transformer import MapfileToDict
from mappyfile.validator import Validator
def output(fn):
"""
Parse, transform, and pretty print
... | import logging
import cProfile
from mappyfile.parser import Parser
from mappyfile.pprint import PrettyPrinter
from mappyfile.transformer import MapfileToDict
def output(fn):
"""
Parse, transform, and pretty print
the result
"""
p = Parser()
m = MapfileToDict()
ast = p.parse_file(fn)
... | mit | Python |
ddf311b4dc7c08f3f08516c702531053f8919720 | Tidy imports | lamby/django-slack | tests/test_validation.py | tests/test_validation.py | import json
from django.test import TestCase
from django_slack.exceptions import ChannelNotFound, MsgTooLong
from django_slack.backends import Backend
class TestOverride(TestCase):
def test_ok_result(self):
backend = Backend()
backend.validate('application/json', json.dumps({'ok': True}), {})
... | import json
from django.conf import settings
from django.test import TestCase, override_settings
from django_slack.exceptions import ChannelNotFound, MsgTooLong
from django_slack.backends import Backend
class TestOverride(TestCase):
def test_ok_result(self):
backend = Backend()
backend.validate('... | bsd-3-clause | Python |
4f8429e9cd17f207ef429bdf21508cfac4200c4c | improve display | UGentPortaal/django-ldapdb-archived,crito/django-ldapdb,chronossc/django-ldapdb,UGentPortaal/django-ldapdb,crito/django-ldapdb | examples/admin.py | examples/admin.py | # -*- coding: utf-8 -*-
#
# django-granadilla
# Copyright (C) 2009 Bolloré telecom
# See AUTHORS file for a full list of contributors.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either ... | # -*- coding: utf-8 -*-
#
# django-granadilla
# Copyright (C) 2009 Bolloré telecom
# See AUTHORS file for a full list of contributors.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either ... | bsd-3-clause | Python |
cbc8632a74f32415b2819b678340b6e4f0944dba | Use build_context factory | translationexchange/tml-python,translationexchange/tml-python | tests/unit/tools/list.py | tests/unit/tools/list.py | # encoding: UTF-8
import unittest
from tml.tools.list import List
from tml.tools.template import Template
from tests.mock import Client
from tml import build_context
class ListTest(unittest.TestCase):
def setUp(self):
self.context = build_context(client = Client.read_all(), locale = 'ru')
def test_... | # encoding: UTF-8
import unittest
from tml.tools.list import List
from tml.tools.template import Template
from tests.mock import Client
from tml import Context
class list(unittest.TestCase):
def setUp(self):
self.context = Context(client = Client.read_all(), locale = 'ru')
def test_render(self):
... | mit | Python |
dbce79102efa8fee233af95939f1ff0b9d060b00 | Update example workflow to show you can use classes | botify-labs/simpleflow,botify-labs/simpleflow | examples/basic.py | examples/basic.py | import time
from simpleflow import (
activity,
Workflow,
futures,
)
@activity.with_attributes(task_list='quickstart', version='example')
def increment(x):
return x + 1
@activity.with_attributes(task_list='quickstart', version='example')
def double(x):
return x * 2
# A simpleflow activity can b... | import time
from simpleflow import (
activity,
Workflow,
futures,
)
@activity.with_attributes(task_list='quickstart', version='example')
def increment(x):
return x + 1
@activity.with_attributes(task_list='quickstart', version='example')
def double(x):
return x * 2
@activity.with_attributes(ta... | mit | Python |
9308152c67bc2ad2150a76e7897c8fd2568bf590 | Bump version: 0.0.4 -> 0.0.5 | polysquare/include-what-you-use-target-cmake,polysquare/iwyu-target-cmake | conanfile.py | conanfile.py | from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.5"
class IWYUCTargetCmakeConan(ConanFile):
name = "iwyu-target-cmake"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspillaz/cmake... | from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.4"
class IWYUCTargetCmakeConan(ConanFile):
name = "iwyu-target-cmake"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspillaz/cmake... | mit | Python |
09ab8f6290e3c5bf33e01857d11b124444a4c990 | add sendaddr support to isotp | commaai/panda,commaai/panda,commaai/panda,commaai/panda | examples/isotp.py | examples/isotp.py | DEBUG = False
def msg(x):
if DEBUG:
print "S:",x.encode("hex")
if len(x) <= 7:
ret = chr(len(x)) + x
else:
assert False
return ret.ljust(8, "\x00")
def isotp_send(panda, x, addr, bus=0):
if len(x) <= 7:
panda.can_send(addr, msg(x), bus)
else:
ss = chr(0x10 + (len(x)>>8)) + chr(len(x)&0... | DEBUG = False
def msg(x):
if DEBUG:
print "S:",x.encode("hex")
if len(x) <= 7:
ret = chr(len(x)) + x
else:
assert False
return ret.ljust(8, "\x00")
def isotp_send(panda, x, addr, bus=0):
if len(x) <= 7:
panda.can_send(addr, msg(x), bus)
else:
ss = chr(0x10 + (len(x)>>8)) + chr(len(x)&0... | mit | Python |
ba1186c47e5f3466faeea9f2d5bf96948d5f7183 | Add --strict flag to raise exception on undefined variables | j4mie/confuzzle | confuzzle.py | confuzzle.py | import sys
import argparse
import yaml
import jinja2
def render(template_string, context_dict, strict=False):
template = jinja2.Template(template_string)
if strict:
template.environment.undefined = jinja2.StrictUndefined
return template.render(**context_dict)
def main():
parser = argparse.A... | import sys
import argparse
import yaml
from jinja2 import Template
def render(template_string, context_dict):
template = Template(template_string)
return template.render(**context_dict)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('template', nargs='?', type=argparse.FileType(... | unlicense | Python |
b336e83a63722b3a3e4d3f1779686149d5cef8d1 | Add compatibility for Python 2 | pypa/setuptools,pypa/setuptools,pypa/setuptools | setuptools/tests/test_setopt.py | setuptools/tests/test_setopt.py | # coding: utf-8
from __future__ import unicode_literals
import io
import six
from setuptools.command import setopt
from setuptools.extern.six.moves import configparser
class TestEdit:
@staticmethod
def parse_config(filename):
parser = configparser.ConfigParser()
with io.open(filename, enco... | # coding: utf-8
from __future__ import unicode_literals
import io
import six
from setuptools.command import setopt
from setuptools.extern.six.moves import configparser
class TestEdit:
@staticmethod
def parse_config(filename):
parser = configparser.ConfigParser()
with io.open(filename, enco... | mit | Python |
71f67f02dd26e29002ced50298b245c6114ece3b | Update mathfunctions.py | kaitheslayer/developingprojects | Python/Math/mathfunctions.py | Python/Math/mathfunctions.py | # File with the functions which will be used in math script
# Number to the power of
def po (number, pof):
b = number
for _ in range(pof - 1):
b = int(b) * int(number)
return b
# Factors of a number
def factors (number):
current, ao, nums = 0, 0, []
while current < number:
ao = ao... | # File with the functions which will be used in math script
# Number to the power of
def po (number, pof):
b = number
for _ in range(pof - 1):
b = int(b) * int(number)
return b
# Factors of a number
def factors (number):
current, ao, nums = 0, 0, []
while current < number:
ao = ao... | mit | Python |
1d3eb0bafd46f3e9cfb7d6395ad1a100052ff821 | Clean up parameter types (#52527) | thaim/ansible,thaim/ansible | lib/ansible/plugins/doc_fragments/online.py | lib/ansible/plugins/doc_fragments/online.py | # -*- coding: utf-8 -*-
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
class ModuleDocFragment(object):
# Standard documentation fragment
DOCUMENTATION = r'''
options:
api_token:
description:
- Online OAuth token.
type: str
aliases: [ oauth_t... | # -*- coding: utf-8 -*-
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
class ModuleDocFragment(object):
# Standard documentation fragment
DOCUMENTATION = '''
options:
api_token:
description:
- Online OAuth token.
aliases: ['oauth_token']
api_url... | mit | Python |
eb3f93ac64953eacecdd48e2cb8d5ca80554a95b | Update search-for-a-range.py | yiwen-luo/LeetCode,jaredkoontz/leetcode,tudennis/LeetCode---kamyu104-11-24-2015,jaredkoontz/leetcode,githubutilities/LeetCode,jaredkoontz/leetcode,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,yiwen-luo/LeetCode,yiwen-luo/LeetCode,githubutilities/LeetCode,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24... | Python/search-for-a-range.py | Python/search-for-a-range.py | # Time: O(logn)
# Space: O(1)
#
# Given a sorted array of integers, find the starting and ending position of a given target value.
#
# Your algorithm's runtime complexity must be in the order of O(log n).
#
# If the target is not found in the array, return [-1, -1].
#
# For example,
# Given [5, 7, 7, 8, 8, 10] and ... | # Time: O(logn)
# Space: O(1)
#
# Given a sorted array of integers, find the starting and ending position of a given target value.
#
# Your algorithm's runtime complexity must be in the order of O(log n).
#
# If the target is not found in the array, return [-1, -1].
#
# For example,
# Given [5, 7, 7, 8, 8, 10] and ... | mit | Python |
946b3867f464d96e85056b60d94593346a39cc51 | add map to tweet list | KingPixil/ice,KingPixil/ice | index.py | index.py | import os
import time
import TwitterAPI
import src.art.fluid
import src.art.gas
import src.art.map
# Configuration
twitterAPI = TwitterAPI.TwitterAPI(
consumer_key=os.environ["CONSUMER_KEY"],
consumer_secret=os.environ["CONSUMER_SECRET"],
access_token_key=os.environ["ACCESS_TOKEN_KEY"],
access_token_se... | import os
import time
import TwitterAPI
import src.art.fluid
import src.art.gas
# Configuration
twitterAPI = TwitterAPI.TwitterAPI(
consumer_key=os.environ["CONSUMER_KEY"],
consumer_secret=os.environ["CONSUMER_SECRET"],
access_token_key=os.environ["ACCESS_TOKEN_KEY"],
access_token_secret=os.environ["AC... | mit | Python |
34adb8bb30860eb7748188a7d1a9345a09c4519f | Implement punctuation filtering | ikaruswill/vector-space-model,ikaruswill/boolean-retrieval | index.py | index.py | from nltk.tokenize import word_tokenize, sent_tokenize
import getopt
import sys
import os
import io
import string
def build_dict(docs):
dictionary = set()
for doc_id, doc in docs.items():
dictionary.update(doc)
dictionary = list(dictionary)
dictionary.sort()
return dictionary
def build_postings(dictionary):
... | from nltk.tokenize import word_tokenize, sent_tokenize
import getopt
import sys
import os
import io
def build_dict(docs):
dictionary = set()
for doc_id, doc in docs.items():
dictionary.update(doc)
dictionary = list(dictionary)
dictionary.sort()
return dictionary
def build_postings(dictionary):
postings = {}... | mit | Python |
e320c8558646233b78760e1c84c5334a3a743d6d | Fix test_ensemble on Python 3.5 | RasaHQ/rasa_nlu,RasaHQ/rasa_core,RasaHQ/rasa_core,RasaHQ/rasa_core,RasaHQ/rasa_nlu,RasaHQ/rasa_nlu | tests/test_ensemble.py | tests/test_ensemble.py | import pytest
from rasa_core.policies import Policy
from rasa_core.policies.ensemble import PolicyEnsemble
class WorkingPolicy(Policy):
@classmethod
def load(cls, path):
return WorkingPolicy()
def persist(self, path):
pass
def train(self, training_trackers, domain, **kwargs):
... | import pytest
from rasa_core.policies import Policy
from rasa_core.policies.ensemble import PolicyEnsemble
class WorkingPolicy(Policy):
@classmethod
def load(cls, path):
return WorkingPolicy()
def persist(self, path):
pass
def train(self, training_trackers, domain, **kwargs):
... | apache-2.0 | Python |
ed410e81af61699a16c34c1edbbaa18a80bcdcfe | use global DocSimServer instance in views | ConsumerAffairs/django-document-similarity,ConsumerAffairs/django-document-similarity | docsim/documents/views.py | docsim/documents/views.py | from ujson import dumps
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from rest_framework.generics import ListAPIView, RetrieveAPIView
from .docsimserver import DocSimServer
from .models import Cl... | from ujson import dumps
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from rest_framework.generics import ListAPIView, RetrieveAPIView
from .docsimserver import DocSimServer
from .models import Cl... | agpl-3.0 | Python |
829d68f842c5076be7a8b2c3963c032977fe2f47 | Bump to 4.4-dp2. | gregoiresage/pebble-tool,pebble/pebble-tool,pebble/pebble-tool,gregoiresage/pebble-tool,gregoiresage/pebble-tool,pebble/pebble-tool,gregoiresage/pebble-tool,pebble/pebble-tool | pebble_tool/version.py | pebble_tool/version.py | version_base = (4, 4, 0)
version_suffix = 'dp2'
if version_suffix is None:
__version_info__ = version_base
else:
__version_info__ = version_base + (version_suffix,)
__version__ = '{}.{}'.format(*version_base)
if version_base[2] != 0:
__version__ += '.{}'.format(version_base[2])
if version_suffix is not N... | version_base = (4, 4, 0)
version_suffix = 'dp1'
if version_suffix is None:
__version_info__ = version_base
else:
__version_info__ = version_base + (version_suffix,)
__version__ = '{}.{}'.format(*version_base)
if version_base[2] != 0:
__version__ += '.{}'.format(version_base[2])
if version_suffix is not N... | mit | Python |
752132f83cacb15273625f819eed1dab1d558e97 | Make sure all relevant fields are shown in the admin interface | sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer | dictionary/admin.py | dictionary/admin.py | from daisyproducer.dictionary.models import Word
from django.contrib import admin
class WordAdmin(admin.ModelAdmin):
list_display = ('untranslated', 'grade1', 'grade2', 'type', 'isConfirmed', 'isLocal')
ordering = ('untranslated',)
search_fields = ('untranslated',)
admin.site.register(Word, WordAdmin)
| from daisyproducer.dictionary.models import Word
from django.contrib import admin
class WordAdmin(admin.ModelAdmin):
list_display = ('untranslated', 'grade1', 'grade2', 'type', 'isConfirmed')
ordering = ('untranslated',)
search_fields = ('untranslated',)
admin.site.register(Word, WordAdmin)
| agpl-3.0 | Python |
bda269c5b745703cf517222e004caf0233b40699 | refactor p4io to io | michaelaye/planet4,michaelaye/planet4,michaelaye/planet4,michaelaye/planet4 | tests/test_get_data.py | tests/test_get_data.py | from planet4 import io
import datetime as dt
def test_get_numbers_from_date_from_fname():
fname1 = '/a/b/c/2014-06-02_some_name.h5'
assert io.split_date_from_fname(fname1) == [2014, 6, 2]
def test_get_datetime_object_from_fname():
fname1 = '/a/b/c/2014-06-02_some_name.h5'
dt_obj = dt.datetime(2014, ... | from planet4 import p4io
import datetime as dt
def test_get_numbers_from_date_from_fname():
fname1 = '/a/b/c/2014-06-02_some_name.h5'
assert p4io.split_date_from_fname(fname1) == [2014, 6, 2]
def test_get_datetime_object_from_fname():
fname1 = '/a/b/c/2014-06-02_some_name.h5'
dt_obj = dt.datetime(20... | isc | Python |
3cc7e0cebc8a7a7410ce6b239e55db0cf55b1dc8 | Fix broken tests in test_messages | tysonholub/twilio-python,twilio/twilio-python | tests/test_messages.py | tests/test_messages.py | from datetime import date
import unittest
from mock import patch
from six import u
from twilio.rest.resources import Messages
DEFAULT = {
'From': None,
'DateSent<': None,
'DateSent>': None,
'DateSent': None,
}
class MessageTest(unittest.TestCase):
def setUp(self):
self.resource = Messa... | from datetime import date
import unittest
from mock import patch
from six import u
from twilio.rest.resources import Messages
DEFAULT = {
'From': None,
'DateSent<': None,
'DateSent>': None,
'DateSent': None,
}
class MessageTest(unittest.TestCase):
def setUp(self):
self.resource = Messa... | mit | Python |
f6ecf6a45e2749261a20869aca5dfca6d7c03494 | Correct method doc. | ohsu-qin/qiprofile-rest-client | qiprofile_rest_client/helpers/database.py | qiprofile_rest_client/helpers/database.py | """Mongo Engine interaction utilities."""
def get_or_create(klass, key=None, **non_key):
"""
This function stands in for the Mongo Engine ``get_or_create``
collection method which was deprecated in mongoengine v0.8.0
and dropped in mongoengine v0.10.0, since MongoDB does not
support transactions.
... | """Mongo Engine interaction utilities."""
def get_or_create(klass, pk, **non_pk):
"""
This function stands in for the Mongo Engine ``get_or_create``
collection method which was deprecated in mongoengine v0.8.0
and dropped in mongoengine v0.10.0, since MongoDB does not
support transactions.
... | bsd-2-clause | Python |
c2df896183f80fe3ca0eab259874bc4385d399e9 | Clean up detrius in parallel test file | bitprophet/fabric,MjAbuz/fabric,likesxuqiang/fabric,sdelements/fabric,opavader/fabric,TarasRudnyk/fabric,tekapo/fabric,haridsv/fabric,SamuelMarks/fabric,bspink/fabric,tolbkni/fabric,rane-hs/fabric-py3,mathiasertl/fabric,askulkarni2/fabric,fernandezcuesta/fabric,elijah513/fabric,xLegoz/fabric,raimon49/fabric,amaniak/fab... | tests/test_parallel.py | tests/test_parallel.py | from __future__ import with_statement
from fabric.api import run, parallel, env, hide
from utils import FabricTest, eq_
from server import server, RESPONSES
class TestParallel(FabricTest):
@server()
@parallel
def test_parallel(self):
"""
Want to do a simple call and respond
"""
... | from __future__ import with_statement
from datetime import datetime
import copy
import getpass
import sys
import paramiko
from nose.tools import with_setup
from fudge import (Fake, clear_calls, clear_expectations, patch_object, verify,
with_patched_object, patched_context, with_fakes)
from fabric.context_manager... | bsd-2-clause | Python |
8f86eacf1b85a0c497f9e8586a59cc19e6a0484f | Stop passing a recorder argument unecessarily in tests | jstutters/Plumbium | tests/test_pipeline.py | tests/test_pipeline.py | from __future__ import print_function
import pytest
from plumbium.processresult import record, pipeline, call
class DummyRecorder(object):
def write(self, results):
self.results = results
@pytest.fixture
def simple_pipeline():
@record('an_output')
def recorded_function():
call(['echo', '... | from __future__ import print_function
import pytest
from plumbium.processresult import record, pipeline, call
class DummyRecorder(object):
def write(self, results):
self.results = results
@pytest.fixture
def simple_pipeline():
@record('an_output')
def recorded_function():
call(['echo', '... | mit | Python |
7b75f508bf651bdeb57bdc4d263ced26434054c8 | add pct test | SunPower/PVMismatch | tests/test_pvmodule.py | tests/test_pvmodule.py | """
Tests for pvmodules.
"""
from nose.tools import ok_
from pvmismatch.pvmismatch_lib.pvmodule import PVmodule, TCT96, PCT96
def test_calc_mod():
pvmod = PVmodule()
ok_(isinstance(pvmod, PVmodule))
return pvmod
def test_calc_TCT_mod():
pvmod = PVmodule(cell_pos=TCT96)
ok_(isinstance(pvmod, PVm... | """
Tests for pvmodules.
"""
from nose.tools import ok_
from pvmismatch.pvmismatch_lib.pvmodule import PVmodule, TCT96
def test_calc_mod():
pvmod = PVmodule()
ok_(isinstance(pvmod, PVmodule))
return pvmod
def test_calc_TCT_mod():
pvmod = PVmodule(cell_pos=TCT96)
ok_(isinstance(pvmod, PVmodule))... | bsd-3-clause | Python |
9744226621e27d4bd5d19a52b75b718e86bfef87 | Add extra filter for equipment | GETLIMS/LIMS-Backend,GETLIMS/LIMS-Backend | lims/equipment/views.py | lims/equipment/views.py |
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.exceptions import PermissionDenied
import django_filters
from lims.permissions.permissions import IsInAdminGroupOrRO
from .models import Equipment, EquipmentReservation
from .serializers import EquipmentSerializer, ... |
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.exceptions import PermissionDenied
import django_filters
from lims.permissions.permissions import IsInAdminGroupOrRO
from .models import Equipment, EquipmentReservation
from .serializers import EquipmentSerializer, ... | mit | Python |
368d46ba4bec2da22abfba306badf39a3a552e88 | Remove now-unused imports | mozilla/snippets-service,mozilla/snippets-service,mozmar/snippets-service,glogiotatidis/snippets-service,glogiotatidis/snippets-service,mozmar/snippets-service,mozilla/snippets-service,mozmar/snippets-service,glogiotatidis/snippets-service,glogiotatidis/snippets-service,mozilla/snippets-service,mozmar/snippets-service | tests/test_snippets.py | tests/test_snippets.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
from xml.dom.minidom import parseString
from xml.parsers.expat import ExpatError
import pytest
import requests
from bs4... | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
import json
import re
from xml.dom.minidom import parseString
from xml.parsers.expat import ExpatError
import pytest
im... | mpl-2.0 | Python |
142ef9b907868f53c696bd4426a7f08b7ef57528 | Change metatdata test | imageio/imageio | tests/test_tifffile.py | tests/test_tifffile.py | """ Test tifffile plugin functionality.
"""
import os
import numpy as np
from pytest import raises
from imageio.testing import run_tests_if_main, get_test_dir, need_internet
from imageio.core import get_remote_file
import imageio
test_dir = get_test_dir()
def test_tifffile_format():
# Test selection
for ... | """ Test tifffile plugin functionality.
"""
import os
import numpy as np
from pytest import raises
from imageio.testing import run_tests_if_main, get_test_dir, need_internet
from imageio.core import get_remote_file
import imageio
test_dir = get_test_dir()
def test_tifffile_format():
# Test selection
for ... | bsd-2-clause | Python |
8d09e745f24e663cb81ff5be6bc7b643c6c5bd76 | call it pennyblack 0.3.0 | nickburlett/pennyblack,nickburlett/pennyblack | pennyblack/__init__.py | pennyblack/__init__.py | VERSION = (0, 3, 0,)
__version__ = '.'.join(map(str, VERSION))
# Do not use Django settings at module level as recommended
try:
from django.utils.functional import LazyObject
except ImportError:
pass
else:
class LazySettings(LazyObject):
def _setup(self):
from pennyblack import default_... | VERSION = (0, 3, 0, 'pre')
__version__ = '.'.join(map(str, VERSION))
# Do not use Django settings at module level as recommended
try:
from django.utils.functional import LazyObject
except ImportError:
pass
else:
class LazySettings(LazyObject):
def _setup(self):
from pennyblack import de... | bsd-3-clause | Python |
57d5622d205854eafd8babf8dfa1ad45bf05ebcb | Update ipc_lista1.15.py | any1m1c/ipc20161 | lista1/ipc_lista1.15.py | lista1/ipc_lista1.15.py | #ipc_lista1.15
#Professor: Jucimar Junior
#Any Mendes Carvalho - 1615310044
#
#
#
#
##Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. Calcule e mostre o total do seu salário no referido mês, sabendo-se que são descontados 11% para o Imposto de Renda, 8% para o INSS e 5% ... | #ipc_lista1.15
#Professor: Jucimar Junior
#Any Mendes Carvalho - 1615310044
#
#
#
#
##Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. Calcule e mostre o total do seu salário no referido mês, sabendo-se que são descontados 11% para o Imposto de Renda, 8% para o INSS e 5% ... | apache-2.0 | Python |
b37432e914b6c6e45803a928f35fbaa8964780aa | test by uuid | kurin/py-raft | tests/unit/test_log.py | tests/unit/test_log.py | import pytest
from raft import log
def mle(index, term, committed=False, msgid='', msg={}):
return dict(index=index, term=term, committed=committed,
msgid=msgid, msg=msg)
def test_le():
# a's term is greater than b's
a = {1: mle(1, 2),
2: mle(2, 2),
3: mle(3, 4)}
b =... | import pytest
from raft import log
def mle(index, term, committed=False, msgid='', msg={}):
return dict(index=index, term=term, committed=committed,
msgid=msgid, msg=msg)
def test_le():
# a's term is greater than b's
a = {1: mle(1, 2),
2: mle(2, 2),
3: mle(3, 4)}
b =... | unlicense | Python |
62d5a4446c4c0a919557dd5f2e95d21c5a8259a8 | Test the optimized set | grigi/pypred,armon/pypred | tests/unit/test_set.py | tests/unit/test_set.py | import pytest
from pypred import OptimizedPredicateSet, PredicateSet, Predicate
class TestPredicateSet(object):
def test_two(self):
p1 = Predicate("name is 'Jack'")
p2 = Predicate("name is 'Jill'")
s = PredicateSet([p1, p2])
match = s.evaluate({'name': 'Jill'})
assert match ... | from pypred import PredicateSet, Predicate
class TestPredicateSet(object):
def test_two(self):
p1 = Predicate("name is 'Jack'")
p2 = Predicate("name is 'Jill'")
s = PredicateSet([p1, p2])
match = s.evaluate({'name': 'Jill'})
assert match == [p2]
def test_dup(self):
... | bsd-3-clause | Python |
cae0764f2cbb8d00de1832079e55b8e4d45f55f2 | Fix for short OTU name when there is a species but no genus or higher | smdabdoub/phylotoast,akshayparopkari/phylotoast | phylotoast/otu_calc.py | phylotoast/otu_calc.py | from __future__ import division
import ast
from collections import defaultdict
from phylotoast import biom_calc as bc
def otu_name(tax):
"""
Determine a simple Genus-species identifier for an OTU, if possible.
If OTU is not identified to the species level, name it as
Unclassified (familly/genus/etc...... | from __future__ import division
import ast
from collections import defaultdict
from phylotoast import biom_calc as bc
def otu_name(tax):
"""
Determine a simple Genus-species identifier for an OTU, if possible.
If OTU is not identified to the species level, name it as
Unclassified (familly/genus/etc...... | mit | Python |
7c4d3fffe62190b8c27317ed83bd5e7110b103ec | Update parser.py | Lagostra/MusicPlayer,Lagostra/MusicPlayer | MusicXMLParser/parser.py | MusicXMLParser/parser.py | '''
Takes a musicXML file, and creates a file that can be played by my MusicPlayer arduino library.
Written by Eivind Lie Andreassen, 2016
Licensed under the MIT license.
'''
import xml.dom.minidom
import valueHelper
xmlPath = input("Enter path to MusicXML file: ")
savePath = input("Enter save path of con... | '''
Takes a musicXML file, and creates a file that can be played by my MusicPlayer arduino library.
Written by Eivind Lie Andreassen, 2016
Licensed under Creative Commons Attribution-ShareAlike 4.0 International. http://creativecommons.org/licenses/by-sa/4.0/
'''
import xml.dom.minidom
import valueHelper
xml... | mit | Python |
83b83cb3491bd4ccf39e2c6ade72f8f526ea27fe | Increase toolbox reporting | maphew/arcplus,maphew/arcplus | ArcToolbox/Scripts/ExportFolder2PDF.py | ArcToolbox/Scripts/ExportFolder2PDF.py | #Export a folder of maps to PDFs at their Map Document set sizes
#Written using ArcGIS 10 and Python 2.6.5
#by: Guest
# https://gis.stackexchange.com/questions/7147/how-to-batch-export-mxd-to-pdf-files
import arcpy, os
#Read input parameter from user.
path = arcpy.GetParameterAsText(0)
#Write MXD names in folder to ... | #Export a folder of maps to PDFs at their Map Document set sizes
#Written using ArcGIS 10 and Python 2.6.5
#by: Guest
# https://gis.stackexchange.com/questions/7147/how-to-batch-export-mxd-to-pdf-files
import arcpy, os
#Read input parameter from user.
path = arcpy.GetParameterAsText(0)
#Write MXD names in folder to ... | mit | Python |
b614436766e8ee3316936c5718262b35cfae3869 | Add slug field on save | 0x0mar/memex-explorer,0x0mar/memex-explorer,firebitsbr/memex-explorer,kod3r/memex-explorer,firebitsbr/memex-explorer,firebitsbr/memex-explorer,YongchaoShang/memex-explorer,0x0mar/memex-explorer,firebitsbr/memex-explorer,YongchaoShang/memex-explorer,0x0mar/memex-explorer,memex-explorer/memex-explorer,0x0mar/memex-explor... | memex_explorer/base/models.py | memex_explorer/base/models.py | from django.db import models
from django.utils.text import slugify
class Project(models.Model):
name = models.CharField(max_length=64)
slug = models.SlugField(max_length=64, unique=True)
description = models.TextField()
icon = models.CharField(max_length=64)
def __str__(self):
return sel... | from django.db import models
class Project(models.Model):
name = models.CharField(max_length=64)
slug = models.SlugField(max_length=64, unique=True)
description = models.TextField()
icon = models.CharField(max_length=64)
def __str__(self):
return self.name
class DataModel(models.Model):... | bsd-2-clause | Python |
1018d6bde32a8d18a2315dafd084826443209ba1 | Update clock.py | lmperez2/Pi-Seven-Segment | examples/clock.py | examples/clock.py | #!/usr/bin/python
import time
import datetime
from Adafruit_LED_Backpack import SevenSegment
# ===========================================================================
# Clock Example
# ===========================================================================
segment = SevenSegment.SevenSegment(address=0x70)
#... | #!/usr/bin/python
import time
import datetime
from Adafruit_LED_Backpack import SevenSegment
# ===========================================================================
# Clock Example
# ===========================================================================
segment = SevenSegment.SevenSegment(address=0x70)
#... | mit | Python |
37da8a56f127a871c4133f0ba58921779e9b487c | Update __init__.py | uchicago-cs/deepdish,uchicago-cs/deepdish,agarbuno/deepdish,agarbuno/deepdish | deepdish/io/__init__.py | deepdish/io/__init__.py | from __future__ import division, print_function, absolute_import
from .mnist import load_mnist
from .norb import load_small_norb
from .casia import load_casia
from .cifar import load_cifar_10
try:
import tables
_pytables_ok = True
del tables
except ImportError:
_pytables_ok = False
if _pytables_ok:
... | from __future__ import division, print_function, absolute_import
from .mnist import load_mnist
from .norb import load_small_norb
from .casia import load_casia
from .cifar import load_cifar_10
try:
import tables
_pytables_ok = True
except ImportError:
_pytables_ok = False
del tables
if _pytables_ok:
fr... | bsd-3-clause | Python |
0d914a4843e5959c108077e8c5275a1ddd05f617 | Upgrade version number | ljean/djaloha,ljean/djaloha,ljean/djaloha,ljean/djaloha | djaloha/__init__.py | djaloha/__init__.py | # -*- coding: utf-8 -*-
VERSION = (0, 2)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
# if VERSION[2]:
# version = '%s.%s' % (version, VERSION[2])
# if VERSION[3] != "final":
# version = '%s%s%s' % (version, VERSION[3], VERSION[4])
return version
__version__ = get_versi... | # -*- coding: utf-8 -*-
VERSION = (0, 1)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
# if VERSION[2]:
# version = '%s.%s' % (version, VERSION[2])
# if VERSION[3] != "final":
# version = '%s%s%s' % (version, VERSION[3], VERSION[4])
return version
__version__ = get_versi... | bsd-3-clause | Python |
0f5433458be9add6a879e8e490017663714d7664 | fix cron job FailedRunsNotificationCronJob to import get_class routine from new place | Tivix/django-cron,eriktelepovsky/django-cron,mozillazg/django-cron | django_cron/cron.py | django_cron/cron.py | from django.conf import settings
from django_cron import CronJobBase, Schedule, get_class
from django_cron.models import CronJobLog
from django_common.helper import send_mail
class FailedRunsNotificationCronJob(CronJobBase):
"""
Send email if cron failed to run X times in a row
"""
RUN_EVERY_MINS... | from django.conf import settings
from django_cron import CronJobBase, Schedule
from django_cron.models import CronJobLog
from django_cron.management.commands.runcrons import get_class
from django_common.helper import send_mail
class FailedRunsNotificationCronJob(CronJobBase):
"""
Send email if cron faile... | mit | Python |
7f3b2b0ab21e4dadffb55da912684eb84ce6da3d | Check if remot git is already on commit | dbravender/gitric | gitric/api.py | gitric/api.py | from __future__ import with_statement
from fabric.state import env
from fabric.api import local, run, abort, task, cd, puts
from fabric.context_managers import settings
@task
def allow_dirty():
'''allow pushing even when the working copy is dirty'''
env.gitric_allow_dirty = True
@task
def force_push():
... | from __future__ import with_statement
from fabric.state import env
from fabric.api import local, run, abort, task
from fabric.context_managers import settings
@task
def allow_dirty():
'''allow pushing even when the working copy is dirty'''
env.gitric_allow_dirty = True
@task
def force_push():
'''allow p... | mit | Python |
47e7fcc3b837b459a2800e09ee87c2a6f87cdfba | Update SController.py | nvthanh1/Skypybot | skype_controller/SController.py | skype_controller/SController.py | """Import somes important packages"""
import Skype4Py
import config as gbconfig
import json
from common import get_project_path
# Get Skype class instance
SKYPE_OBJ = Skype4Py.Skype()
# Establish the connection from the Skype object to the Skype ddclient.
SKYPE_OBJ.Attach()
# Get all contact from object. This funct... | """Import somes important packages"""
import Skype4Py
import config as gbconfig
import json
from common import get_project_path
# Get Skype class instance
SKYPE_OBJ = Skype4Py.Skype()
# Establish the connection from the Skype object to the Skype ddclient.
SKYPE_OBJ.Attach()
# Get all contact from object. This funct... | mit | Python |
f21e732eada64a18e08524052ec66ce8705d9e9b | make imagemagick env var default to 'convert' instead of None | leovoel/glc.py | glc/config.py | glc/config.py | """
glc.config
==========
At the moment this only houses the environmental variable
for the ImageMagick binary. If you don't want to set that,
or can't for some reason, you can replace ``"convert"`` with the
path where the ``convert`` application that comes with it
lives in, if it doesn't ... | """
glc.config
==========
At the moment this only houses the environmental variable
for the ImageMagick binary. If you don't want to set that,
or can't for some reason, you can replace ``None`` with the
path where the ``convert`` application that comes with it
lives in.
(c) 2016 LeoV
... | mit | Python |
09a313a2cd74c391c12761306cb8ae641e9f0d28 | fix logs app prompt | synctree/synctree-awsebcli,synctree/synctree-awsebcli | ebcli/controllers/logs.py | ebcli/controllers/logs.py | # Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... | # Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... | apache-2.0 | Python |
d3cd1778f4ccb1651feb2186ecfdd0c81f86088c | Improve Instruction parsing | mossberg/spym,mossberg/spym | instruction.py | instruction.py | class Instruction(object):
def __init__(self, line):
instr = line.split(' ')
self.name = instr[0]
self.ops = []
if len(instr) > 4:
raise Exception('too many operands: {}'.format(line))
# iterate through operands, perform some loose checks, and append
# t... | class Instruction(object):
def __init__(self, line):
instr = line.split(' ')
self.name = instr[0]
self.ops = []
if len(instr) > 4:
raise Exception('too many operands: {}'.format(line))
# iterate through operands, perform some loose checks, and append
# t... | mit | Python |
8d0a41391fae5c66c296d5dfacc0ac6f82a6b355 | fix gridsearch path | rshkv/goethe | gridsearch.py | gridsearch.py | import time
import itertools as it
from gensim.models import word2vec
from goethe.corpora import Corpus
model_config = {
'size': [200, 300, 400, 500, 600],
'window': [5, 10, 20],
'sg': [0, 1] # Skip-gram or CBOW
}
sample_size = 10000000
epochs = 10
def train_model(config):
size, window, sg = config
... | import time
import itertools as it
from gensim.models import word2vec
from goethe.corpora import Corpus
model_config = {
'size': [200, 300, 400, 500, 600],
'window': [5, 10, 20],
'sg': [0, 1] # Skip-gram or CBOW
}
sample_size = 10000000
epochs = 10
def train_model(config):
size, window, sg = config
... | mit | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.