commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
d6b8b7bf471f6e78147eb0b8ad518c4f8964deb3 | cle/backends/cgc.py | cle/backends/cgc.py | from .elf import ELF
from ..loader import Loader
ELF_HEADER = "7f45 4c46 0101 0100 0000 0000 0000 0000".replace(" ","").decode('hex')
class CGC(ELF):
def __init__(self, path, *args, **kwargs):
self.elf_path = Loader._make_tmp_copy(path)
f = open(self.elf_path, 'r+b')
f.write(ELF_HEADER)
... | from .elf import ELF
from ..loader import Loader
ELF_HEADER = "7f45 4c46 0101 0100 0000 0000 0000 0000".replace(" ","").decode('hex')
CGC_HEADER = "7f43 4743 0101 0143 014d 6572 696e 6f00".replace(" ","").decode('hex')
class CGC(ELF):
def __init__(self, path, *args, **kwargs):
self.elf_path = Loader._make... | Repair CGC file header after loading | Repair CGC file header after loading
| Python | bsd-2-clause | chubbymaggie/cle,angr/cle |
e0a5b6d44de699dab48cb9de1f745f77c3674352 | blackgate/executor.py | blackgate/executor.py | # -*- coding: utf-8 -*-
import sys
from concurrent.futures import ThreadPoolExecutor
from tornado import gen, queues
from tornado.concurrent import Future, run_on_executor
class WorkItem(object):
executor = ThreadPoolExecutor(20)
def __init__(self, future, fn, args, kwargs):
self.future = future
... | # -*- coding: utf-8 -*-
import sys
from concurrent.futures import ThreadPoolExecutor
from tornado import gen, queues
from tornado.concurrent import Future, run_on_executor
class WorkItem(object):
executor = ThreadPoolExecutor(20)
def __init__(self, future, fn, args, kwargs):
self.future = future
... | Fix exc info setter for future. | Fix exc info setter for future.
| Python | mit | soasme/blackgate |
ab2f98539272c8dfb64031cd009c70f7987be359 | importer/importer/indices.py | importer/importer/indices.py | import aioes
import os.path
from datetime import datetime
from .utils import read_json_file
from .settings import ELASTICSEARCH_ALIAS
def create_new_index(elastic):
print("Creating new index...")
module_path = os.path.dirname(__file__)
config_filename = os.path.join(module_path, 'configuration', 'index.... | import elasticsearch
import os.path
from datetime import datetime
from .utils import read_json_file
from .settings import ELASTICSEARCH_ALIAS
def create_new_index(elastic):
print("Creating new index...")
module_path = os.path.dirname(__file__)
config_filename = os.path.join(module_path, 'configuration',... | Replace one last place where aioes was used | Replace one last place where aioes was used
| Python | mit | despawnerer/theatrics,despawnerer/theatrics,despawnerer/theatrics |
20450788fd0ddb59f80397542b02a2165333e963 | intercom/__main__.py | intercom/__main__.py | import cherrypy
import click
from intercom.roots import IntercomRoot
CLICK_FILE_TYPE = click.Path(exists=True, dir_okay=False)
def run_server(global_config_filename, app_config_filename):
cherrypy.config.update(global_config_filename)
cherrypy.quickstart(root=IntercomRoot(), config=app_config_filename)
@cl... | import cherrypy
import click
from intercom.roots import IntercomRoot
from cherrypy.process.plugins import Daemonizer, PIDFile
def run_server(
global_config_filename,
app_config_filename,
daemon_pid_filename=None):
if daemon_pid_filename is not None:
Daemonizer(cherrypy.engine).subs... | Add support for daemon mode. | Add support for daemon mode.
| Python | isc | alexhanson/intercom |
a7dc058cf8a1d08d02b16a635b7a05d93ab42c1f | shuup/core/utils/db.py | shuup/core/utils/db.py | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
import math
def extend_sqlite_functions(connection=None, **kwarg... | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
import math
def float_wrap(value, func):
try:
return... | Add wrapper to parse values to float in SQLite | Add wrapper to parse values to float in SQLite
Refs TREES-359
| Python | agpl-3.0 | suutari-ai/shoop,shoopio/shoop,shoopio/shoop,suutari-ai/shoop,suutari-ai/shoop,shoopio/shoop |
3602759b633f0643979c8f0970e088f29644b758 | icekit/plugins/brightcove/models.py | icekit/plugins/brightcove/models.py | from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from fluent_contents.models import ContentItem
try:
from django_brightcove.fields import BrightcoveField
except ImportError:
raise NotImplementedError(
_(
'Please install `... | from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from fluent_contents.models import ContentItem
try:
from django_brightcove.fields import BrightcoveField
except ImportError:
raise NotImplementedError(
_(
'Please install `... | Remove comment as media addition automatically happens. | Remove comment as media addition automatically happens.
| Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit |
aa49e27f1dd385b7cfa3706e4e1a25ad8a72f00e | tardis/io/tests/test_decay.py | tardis/io/tests/test_decay.py | import pytest
import pandas as pd
from tardis.io.decay import IsotopeAbundances
@pytest.fixture
def simple_abundance_model():
index = pd.MultiIndex.from_tuples([(28, 56)],
names=['atomic_number', 'mass_number'])
return IsotopeAbundances([[1.0, 1.0]], index=index)
def te... | import pytest
import pandas as pd
from tardis.io.decay import IsotopeAbundances
from numpy.testing import assert_almost_equal
@pytest.fixture
def simple_abundance_model():
index = pd.MultiIndex.from_tuples([(28, 56)],
names=['atomic_number', 'mass_number'])
return Isotope... | Add unit test for decay method | Add unit test for decay method
| Python | bsd-3-clause | kaushik94/tardis,kaushik94/tardis,kaushik94/tardis,kaushik94/tardis |
f86c925604356b25a8c5c0c71644f0df6f1b48f8 | setup_directory.py | setup_directory.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division, print_function, absolute_import
import argparse
import os
import subprocess as sp
from contextlib import contextmanager
import tempfile
try:
import urllib.request as urllib2
except ImportError:
import urllib2
MINICONDA_URL = 'https... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division, print_function, absolute_import
import argparse
import os
import subprocess as sp
from contextlib import contextmanager
import tempfile
try:
import urllib.request as urllib2
except ImportError:
import urllib2
MINICONDA_URL = 'https... | Add function to install miniconda | Add function to install miniconda
| Python | mit | NGTS/pipeline-output-analysis-setup-script |
f965e5d32e79789cac0ac2f2bae80a399cbeea8a | sirius/__init__.py | sirius/__init__.py | import os as _os
from . import LI_V01_01
from . import TB_V01_03
from . import BO_V03_02
from . import TS_V03_03
from . import SI_V21_02
from . import coordinate_system
from . import discs
with open(_os.path.join(__path__[0], 'VERSION'), 'r') as _f:
__version__ = _f.read().strip()
__all__ = ['LI_V01_01', 'TB_V01_... | import os as _os
from . import LI_V01_01
from . import TB_V01_03
from . import BO_V03_02
from . import TS_V03_03
from . import SI_V21_02
from . import coordinate_system
with open(_os.path.join(__path__[0], 'VERSION'), 'r') as _f:
__version__ = _f.read().strip()
__all__ = ['LI_V01_01', 'TB_V01_03', 'BO_V03_02', '... | Fix bug in deletion of discs | Fix bug in deletion of discs
| Python | mit | lnls-fac/sirius |
f0e76bbe2f73514b5663f65dfdc394e02485bc33 | hello.py | hello.py | # Hello World
import sys
def hello(thing):
print "Hello {}".format(thing)
return
if __name__ == "__main__":
sys.exit(hello())
| # Hello World
import sys
def hello(thing):
print "Hello {}".format(thing)
return
if __name__ == "__main__":
user_thing = sys.argv[-1]
sys.exit(hello(user_thing))
| Allow user to specify thing. | Allow user to specify thing.
| Python | mit | fgalloway/hg-git-test |
9f64d5e2f9447233df8d3b841c519196c3213e05 | pyflation/analysis/tests/test_deltaprel.py | pyflation/analysis/tests/test_deltaprel.py | ''' test_deltaprel - Test functions for deltaprel module
Author: Ian Huston
For license and copyright information see LICENSE.txt which was distributed with this file.
'''
import numpy as np
from numpy.testing import assert_, assert_raises
from pyflation.analysis import deltaprel
import nose
class TestSoundSpeeds... | ''' test_deltaprel - Test functions for deltaprel module
Author: Ian Huston
For license and copyright information see LICENSE.txt which was distributed with this file.
'''
import numpy as np
from numpy.testing import assert_, assert_raises
from pyflation.analysis import deltaprel
import nose
class TestSoundSpeeds... | Add test for scalar values. | Add test for scalar values.
| Python | bsd-3-clause | ihuston/pyflation,ihuston/pyflation |
28e00395cd29dee1449ec522b55d08f68518eb70 | pyoctree/__init__.py | pyoctree/__init__.py | # -*- coding: utf-8 -*-
# Copyright (C) 2015 Michael Hogg
# This file is part of pyoctree - See LICENSE.txt for information on usage and redistribution
# Version
import version
__version__ = version.__version__
| # -*- coding: utf-8 -*-
# Copyright (C) 2017 Michael Hogg
# This file is part of pyoctree - See LICENSE.txt for information on usage and redistribution
# Version
from .version import __version__
__version__ = version.__version__
| Fix import bug in Python 3 | Fix import bug in Python 3 | Python | mit | mhogg/pyoctree,mhogg/pyoctree |
bfd887bdb77ea2c8fb4d67895d98d8c923135045 | Lib/dbhash.py | Lib/dbhash.py | """Provide a (g)dbm-compatible interface to bsdhash.hashopen."""
import bsddb
error = bsddb.error
def open(file, flag, mode=0666):
return bsddb.hashopen(file, flag, mode)
| """Provide a (g)dbm-compatible interface to bsdhash.hashopen."""
import bsddb
error = bsddb.error # Exported for anydbm
def open(file, flag, mode=0666):
return bsddb.hashopen(file, flag, mode)
| Clarify why we define error. Suggested by Andrew Dalke. | Clarify why we define error. Suggested by Andrew Dalke.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator |
785892356bde4c20da265844ae77773266d7c01b | tests/iris_test.py | tests/iris_test.py | #!/usr/bin/env python
from sklearn import datasets
from random import shuffle
# This example loads the IRIS dataset and classifies
# using our neural network implementation.
# The results are visualized in a 2D-plot.
def main():
iris = datasets.load_iris()
X = iris.data
Y = iris.target
# Randomize (s... | #!/usr/bin/env python
from sklearn import datasets
from random import shuffle
import numpy as np
from neuralnet import NeuralNet
# This example loads the IRIS dataset and classifies
# using our neural network implementation.
# The results are visualized in a 2D-plot.
def main():
iris = datasets.load_iris()
X... | Convert output values from int to binary for neural network | Convert output values from int to binary for neural network
| Python | mit | akajuvonen/simple-neuralnet-python |
3906e118f56b3bcd158c35426955b9f827ad0de8 | teams/viewsets.py | teams/viewsets.py | from rest_framework.viewsets import ModelViewSet
from . import models
from rest_framework.permissions import BasePermission
class IsOwnerPermission(BasePermission):
def has_object_permission(self, request, view, obj):
return request.user == obj.owner
class TeamViewSet(ModelViewSet):
model = models.Te... | from rest_framework.viewsets import ModelViewSet
from . import models
from . import permisssions
class TeamViewSet(ModelViewSet):
model = models.Team
permission_classes = (permisssions.IsOwnerPermission, )
class PlayerViewSet(ModelViewSet):
model = models.Player
| Move to a module permissions | Move to a module permissions
| Python | mit | mfernandezmsistemas/phyton1,migonzalvar/teamroulette |
8fef7f60ed99e3dd92b3d5ef04a1a9ce3140ffaf | measurator/main.py | measurator/main.py | import argparse, csv, datetime, time
def run_main():
fails = 0
succeeds = 0
not_yet = list()
path = file_path()
# read file
with open(path) as f:
reader = csv.reader(f)
for row in reader:
status = row[0]
if status == 'F':
fails = fails + 1... | import argparse, csv, datetime, time
def run_main():
fails = list()
succeeds = list()
not_yet = list()
path = file_path()
# read file
with open(path) as f:
reader = csv.reader(f)
for row in reader:
status = row[0]
if status == 'F':
fails.a... | Read all records from the file | Read all records from the file
| Python | mit | ahitrin-attic/measurator-proto |
0106ca8c4204aaa818ad14878452b29e7dd62f8c | tests/__init__.py | tests/__init__.py | # -*- coding: utf-8 -*-
import os
from hycc.util import hycc_main
def clean():
for path in os.listdir("tests/resources"):
if path not in ["hello.hy", "__init__.py"]:
path = os.path.join("tests/resources", path)
if os.path.isdir(path):
os.rmdir(path)
else... | # -*- coding: utf-8 -*-
import os
import shutil
from hycc.util import hycc_main
def clean():
for path in os.listdir("tests/resources"):
if path not in ["hello.hy", "__init__.py"]:
path = os.path.join("tests/resources", path)
if os.path.isdir(path):
shutil.rmtree(pat... | Change to use 'shutil.rmtree' instead of 'os.rmdir' | Change to use 'shutil.rmtree' instead of 'os.rmdir'
| Python | mit | koji-kojiro/hylang-hycc |
ad53de29a29d495fb8958c4e5d1a2cfe206de03e | tests/settings.py | tests/settings.py | import warnings
warnings.simplefilter('always')
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
},
}
USE_I18N = True
USE_L10N = True
INSTALLED_APPS = [
'django_superform',
'tests',
]
STATIC_URL = '/static/'
SECRET_KEY = '0'
import django
if django.VERSION < (1, 6):
T... | import warnings
warnings.simplefilter('always')
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
},
}
USE_I18N = True
USE_L10N = True
INSTALLED_APPS = [
'django_superform',
'tests',
]
MIDDLEWARE_CLASSES = ()
STATIC_URL = '/static/'
SECRET_KEY = '0'
import django
if djang... | Remove warning about not-set MIDDLEWARE_CLASSES setting. | Remove warning about not-set MIDDLEWARE_CLASSES setting.
| Python | bsd-3-clause | gregmuellegger/django-superform,gregmuellegger/django-superform |
ab434ccb502a5bc0dc0581fb64a0d00ec5f08f0f | tests/urls.py | tests/urls.py | from django.conf.urls import include, url
urlpatterns = [
url('', include('rest_friendship.urls', namespace='rest_friendship')),
]
| from django.urls import path, include
urlpatterns = [
path('', include(('rest_friendship.urls', 'rest_friendship'), namespace='rest_friendship')),
]
| Fix deprecated url import, (to path) | Fix deprecated url import, (to path)
| Python | isc | dnmellen/django-rest-friendship |
86066890322e3c3654946a49c8d1cd2e1a1c2980 | celery/tests/test_backends/__init__.py | celery/tests/test_backends/__init__.py | import unittest2 as unittest
from celery import backends
from celery.backends.amqp import AMQPBackend
from celery.backends.pyredis import RedisBackend
class TestBackends(unittest.TestCase):
def test_get_backend_aliases(self):
expects = [("amqp", AMQPBackend),
("redis", RedisBackend)]
... | import unittest2 as unittest
from celery import backends
from celery.backends.amqp import AMQPBackend
from celery.backends.database import DatabaseBackend
class TestBackends(unittest.TestCase):
def test_get_backend_aliases(self):
expects = [("amqp", AMQPBackend),
("database", Database... | Test using DatabaseBackend instead of RedisBackend, as the latter requires the redis module to be installed. | tests.backends: Test using DatabaseBackend instead of RedisBackend, as the latter requires the redis module to be installed.
| Python | bsd-3-clause | WoLpH/celery,ask/celery,mitsuhiko/celery,mitsuhiko/celery,WoLpH/celery,frac/celery,cbrepo/celery,cbrepo/celery,frac/celery,ask/celery |
dc87c5d000f06e1618c7fbd0daae602131e0602e | commands/globaladd.py | commands/globaladd.py | from devbot import chat
def call(message: str, name, protocol, cfg, commands):
if ' ' in message:
chat.say('/msg {} Sorry, that was not a valid player name: It contains spaces.'.format(name))
return
chat.say_wrap('/msg {}',
'You have been added to global chat. Use /g GlobalCh... | from devbot import chat
def call(message: str, name, protocol, cfg, commands):
if ' ' in message:
chat.say('/msg {} Sorry, that was not a valid player name: It contains spaces.'.format(name))
return
chat.say('/msg {} Invited {} to GlobalChat'.format(name, message))
chat.say_wrap('/msg {}'.... | Fix formatting issues with gadd | Fix formatting issues with gadd
| Python | mit | Ameliorate/DevotedBot,Ameliorate/DevotedBot |
2913ab59af16fe1d2861c11fb12420b2bbd4a880 | udp_client.py | udp_client.py | import socket
import time
UDP_IP = "127.0.0.1"
UDP_PORT = 1234
MESSAGES = ["start_horn", "stop_horn", "classic_destroy"]
for message in MESSAGES:
print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT
print "message:", message
sock = socket.socket(socket.AF_INET, # Internet
socke... | import socket
import time
UDP_IP = "127.0.0.1"
UDP_PORT = 1234
MESSAGES = ["start_horn", "classic_destroy", "stop_horn"]
for message in MESSAGES:
print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT
print "message:", message
sock = socket.socket(socket.AF_INET, # Internet
socke... | Put them in the right order | Put them in the right order
| Python | mit | BenIanGifford/Key-Button,BenIanGifford/Key-Button |
39a16e50ad5f4164aed6cce58fb828cc78a9e4f3 | myhome/blog/tests.py | myhome/blog/tests.py | from django.test import SimpleTestCase, Client
from .models import BlogPost
class BlogTestCase(SimpleTestCase):
def setUp(self):
BlogPost.objects.create(
datetime='2014-01-01 12:00:00',
title='title',
content='content',
live=True)
def _test_get(self, url... | from test_base import MyHomeTest
from .models import BlogPost
class BlogTestCase(MyHomeTest):
def setUp(self):
BlogPost.objects.create(
datetime='2014-01-01T12:00:00Z',
title='livetitle',
content='livecontent',
live=True)
BlogPost.objects.create(
... | Adjust blog test to use the base class | Adjust blog test to use the base class
| Python | mit | plumdog/myhome,plumdog/myhome,plumdog/myhome,plumdog/myhome |
27923a5490e5e5d2c0503c84fd979b5af6bcba13 | nn/tests/mlp_test.py | nn/tests/mlp_test.py | from sklearn.datasets import make_classification, make_regression
from sklearn.metrics import log_loss
from ..mlp import MLP
class TestFitting(object):
def __init__(self):
self.X_cl, self.y_cl = make_classification(100)
self.X_re, self.y_re = make_classification(100)
def test_if_fit_classifi... | from sklearn.datasets import make_classification, make_regression
from sklearn.metrics import log_loss
from sklearn.preprocessing import StandardScaler
from ..mlp import MLP
class TestFitting(object):
def __init__(self):
sc = StandardScaler()
self.X_cl, self.y_cl = make_classification(100)
... | Scale inputs in test cases | Scale inputs in test cases
| Python | mit | JakeMick/graymatter |
5432ba5b64902f3dd2b491504d06af8237926e37 | aws/awslib.py | aws/awslib.py | import boto3
def await_volume(client, volumeId, waitingState, finishedState):
while True:
volumes = client.describe_volumes(VolumeIds=[volumeId])
state = volumes['Volumes'][0]['State']
if state != waitingState:
break
if state != finishedState:
print 'Unexpected volu... | import boto3
import time
def await_volume(client, volumeId, waitingState, finishedState):
while True:
volumes = client.describe_volumes(VolumeIds=[volumeId])
state = volumes['Volumes'][0]['State']
if state != waitingState:
break
time.sleep(1)
if state != finishedSta... | Add sleep calls for AWS loops | Add sleep calls for AWS loops
| Python | mpl-2.0 | bill-mccloskey/searchfox,bill-mccloskey/mozsearch,bill-mccloskey/mozsearch,bill-mccloskey/searchfox,bill-mccloskey/mozsearch,bill-mccloskey/mozsearch,bill-mccloskey/searchfox,bill-mccloskey/searchfox,bill-mccloskey/mozsearch,bill-mccloskey/mozsearch,bill-mccloskey/searchfox,bill-mccloskey/searchfox |
2bcf457d03610b5b4ade891446b7645721b74480 | sum.py | sum.py | import sublime, sublime_plugin
class SumCommand(sublime_plugin.TextCommand):
def run(self, edit):
sum_view = self.view.window().new_file()
sum_view.set_name('Sum')
file_text = self.view.substr(sublime.Region(0, self.view.size()))
numbers = []
for s in file_text.split():
... | import sublime, sublime_plugin
class SumCommand(sublime_plugin.TextCommand):
def run(self, edit):
sum_view = self.view.window().new_file()
sum_view.set_name('Sum')
file_text = self.view.substr(sublime.Region(0, self.view.size()))
numbers = [to_number(s) for s in file_text.split() i... | Refactor using functions and a list comprehension | Refactor using functions and a list comprehension
| Python | mit | jbrudvik/sublime-sum,jbrudvik/sublime-sum |
49af73f2903580d55093e8e001585010fb3a3c46 | locarise_drf_oauth2_support/users/factories.py | locarise_drf_oauth2_support/users/factories.py | from datetime import timedelta
from django.utils import timezone
from locarise_drf_oauth2_support.users.models import User
try:
import factory
class UserF(factory.DjangoModelFactory):
first_name = factory.Sequence(lambda n: "first_name%s" % n)
last_name = factory.Sequence(lambda n: "last_name... | from datetime import timedelta
from django.utils import timezone
from locarise_drf_oauth2_support.users.models import User
try:
import factory
class UserF(factory.DjangoModelFactory):
first_name = factory.Sequence(lambda n: "first_name%s" % n)
last_name = factory.Sequence(lambda n: "last_name... | Add organization_set field in UserF | Add organization_set field in UserF
| Python | mit | locarise/locarise-drf-oauth2-support,locarise/locarise-drf-oauth2-support |
18c4ba9325fe7a460c9c92ffd7bae3ce5d257332 | tests/test_database.py | tests/test_database.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 io import StringIO
import pytest
from django.core.management import call_command
def test_for_missing_migrations(... | # 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 io import StringIO
import pytest
from django.core.management import call_command
def test_for_missing_migrations(... | Use new command line option for checking if all migrations have been applied. | Use new command line option for checking if all migrations have been applied.
| Python | mpl-2.0 | mozilla/telemetry-analysis-service,mozilla/telemetry-analysis-service,mozilla/telemetry-analysis-service,mozilla/telemetry-analysis-service |
ee7b5353c039d6e1d2aeabcb084aee79e07b71f8 | emoji/templatetags/emoji_tags.py | emoji/templatetags/emoji_tags.py | from django import template
from django.core.urlresolvers import reverse, NoReverseMatch
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe
from emoji import Emoji
register = template.Library()
@register.filter(name='emoji_replace', is_safe=True)
@stringfilter
def... | from django import template
from django.core.urlresolvers import reverse, NoReverseMatch
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe, SafeData
from django.utils.html import escape
from emoji import Emoji
register = template.Library()
@register.filter(name='... | Update the filters to escape the characters before replacing them. | Update the filters to escape the characters before replacing them.
This prevents the filters from allowing XSS attacks. This follows
the pattern used by django's linebreaksbr filter.
| Python | mit | gaqzi/django-emoji,gaqzi/django-emoji,gaqzi/django-emoji |
649c87174711de93261cd7703e67032281e2e8ee | salt/modules/scsi.py | salt/modules/scsi.py | # -*- coding: utf-8 -*-
"""
SCSI administration module
"""
import logging
log = logging.getLogger(__name__)
def lsscsi():
'''
List scsi devices
CLI Example:
.. code-block:: bash
salt '*' scsi.lsscsi
'''
cmd = 'lsscsi'
return __salt__['cmd.run'](cmd).splitlines()
def rescan_all(host):... | # -*- coding: utf-8 -*-
'''
SCSI administration module
'''
import os.path
import logging
log = logging.getLogger(__name__)
def lsscsi():
'''
List SCSI devices
CLI Example:
.. code-block:: bash
salt '*' scsi.lsscsi
'''
cmd = 'lsscsi'
return __salt__['cmd.run'](cmd).splitlines()... | Update formatting to Salt guidelines | Update formatting to Salt guidelines
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
eb5944d9e55f01687aaf53992bc975c2cac5047a | code/marv/marv_webapi/__init__.py | code/marv/marv_webapi/__init__.py | # -*- coding: utf-8 -*-
#
# Copyright 2016 - 2018 Ternaris.
# SPDX-License-Identifier: AGPL-3.0-only
from __future__ import absolute_import, division, print_function
from .auth import auth
from .comment import comment
from .dataset import dataset
from .delete import delete
from .tag import tag
from .collection impor... | # -*- coding: utf-8 -*-
#
# Copyright 2016 - 2018 Ternaris.
# SPDX-License-Identifier: AGPL-3.0-only
from __future__ import absolute_import, division, print_function
from pkg_resources import iter_entry_points
from .auth import auth
from .comment import comment
from .dataset import dataset
from .delete import delet... | Support webapi extension via entry points | [marv] Support webapi extension via entry points
| Python | agpl-3.0 | ternaris/marv-robotics,ternaris/marv-robotics |
ecb0922db7aca55bde6177e37b5e20f94fb59b60 | copy/opt/core/bin/remove_mailbox.py | copy/opt/core/bin/remove_mailbox.py | #!/usr/bin/env python
import redis
import os.path
import shutil
import glob
""" ***** CONFIG START ***** """
REDIS_SOCKET = '/tmp/redis.sock'
MAILDIR = '/var/mail'
""" ***** CONFIG END ***** """
os.chdir(MAILDIR)
r = redis.Redis(unix_socket_path=REDIS_SOCKET)
filesDepth = glob.glob('*/*')
dirsDepth = filter(... | #!/usr/bin/env python
# Thomas Merkel <tm@core.io>
import redis
import os
import shutil
import glob
import time
""" ***** CONFIG START ***** """
REDIS_SOCKET = '/tmp/redis.sock'
MAILDIR = '/var/mail'
ARCHIVE = '/var/mail/.archive'
RM_FILE = 'core-remove-mailbox'
""" ***** CONFIG END ***** """
os.chd... | Rebuild mailbox remove script with some verify checks | Rebuild mailbox remove script with some verify checks
We should not remove a mailbox and only archive it. Also it should
be good to be sure the mailbox doesn't exists in redis anymore after
two runs.
| Python | mit | skylime/mi-core-mbox,skylime/mi-core-mbox |
514997ba994f19b7933f9794e16f0668c7c64502 | kismetclient/handlers.py | kismetclient/handlers.py | from kismetclient.utils import csv
from kismetclient.exceptions import ServerError
def kismet(server, version, starttime, servername, dumpfiles, uid):
""" Handle server startup string. """
print version, servername, uid
def capability(server, CAPABILITY, capabilities):
""" Register a server's capability... | from kismetclient.utils import csv
from kismetclient.exceptions import ServerError
def kismet(client, version, starttime, servername, dumpfiles, uid):
""" Handle server startup string. """
print version, servername, uid
def capability(client, CAPABILITY, capabilities):
""" Register a server capability. ... | Switch first handler arg from "server" to "client". | Switch first handler arg from "server" to "client".
| Python | mit | PaulMcMillan/kismetclient |
6ccd9722a6db66666a9400caf7d124c5ac25ab08 | post_pizza_slices.py | post_pizza_slices.py | import boto3, json
sdb = boto3.client('sdb')
def lambda_handler(data, context):
"""
Handler for posting data to SimpleDB.
Args:
data -- Data to be stored (Dictionary).
context -- AWS context for the request (Object).
"""
if data['Password'] and data['Password'] == 'INSERT PASSWORD':
try:
for person in ['... | import boto3
sdb = boto3.client('sdb')
def lambda_handler(data, context):
"""
Handler for posting data to SimpleDB.
Args:
data -- Data to be stored (Dictionary).
context -- AWS context for the request (Object).
"""
if data['Password'] and data['Password'] == 'INSERT PASSWORD':
try:
for person in ['Sharon... | Remove JSON dependency in POST logic. | Remove JSON dependency in POST logic.
| Python | mit | ryandasher/pizza-tracker,ryandasher/pizza-tracker,ryandasher/pizza-tracker,ryandasher/pizza-tracker |
68db590eb373ea2b293f5619dcd7d6515f454507 | sparkback/__init__.py | sparkback/__init__.py | # -*- coding: utf-8 -*-
from __future__ import division
import argparse
ticks = ('▁', '▂', '▃', '▄', '▅', '▆', '▇', '█')
def scale_data(data):
m = min(data)
n = (max(data) - m) / (len(ticks) - 1)
# if every element is the same height return all lower ticks, else compute
# the tick height
if n == ... | # -*- coding: utf-8 -*-
from __future__ import division
import argparse
ansi_ticks = ('▁', '▂', '▃', '▄', '▅', '▆', '▇', '█')
def scale_data(data, ticks):
m = min(data)
n = (max(data) - m) / (len(ticks) - 1)
# if every element is the same height return all lower ticks, else compute
# the tick height
... | Make ticks passable argument to data | Make ticks passable argument to data
| Python | mit | mmichie/sparkback |
017182e317aa33c0bb4c13541ef19b11bb48e250 | members/views.py | members/views.py | from django.shortcuts import render
from django.http import HttpResponse
from .models import User
def homepage(request):
return render(request, "index.html", {})
def search(request, name):
members = User.objects.filter(first_name__icontains=name) or \
User.objects.filter(last_name__icontains=name) ... | from django.shortcuts import render
from django.http import HttpResponse
from hackfmi.utils import json_view
from .models import User
def homepage(request):
return render(request, "index.html", {})
@json_view
def search(request, name):
members = User.objects.filter(first_name__icontains=name) or \
... | Add view for searching users and return json format | Add view for searching users and return json format
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum |
375cff83beb17f52ead364eef6e690a8bd118be4 | app/assets.py | app/assets.py | from flask_assets import Bundle, Environment, Filter
# fixes missing semicolon in last statement of jquery.pjax.js
class ConcatFilter(Filter):
def concat(self, out, hunks, **kw):
out.write(';'.join([h.data() for h, info in hunks]))
js = Bundle(
'node_modules/jquery/dist/jquery.js',
'node_modules/j... | from flask_assets import Bundle, Environment, Filter
class ConcatFilter(Filter):
"""
Filter that merges files, placing a semicolon between them.
Fixes issues caused by missing semicolons at end of JS assets, for example
with last statement of jquery.pjax.js.
"""
def concat(self, out, hunks, **... | Move inline comment to class docstring | Move inline comment to class docstring
| Python | mit | cburmeister/flask-bones,cburmeister/flask-bones,cburmeister/flask-bones |
5363224395b26528465417ff550d6a2163cbe8e6 | spacy/zh/__init__.py | spacy/zh/__init__.py | from ..language import Language
from ..tokenizer import Tokenizer
from ..tagger import Tagger
class CharacterTokenizer(Tokenizer):
def __call__(self, text):
return self.tokens_from_list(list(text))
class Chinese(Language):
lang = u'zh'
def __call__(self, text):
doc = self.tokenizer.toke... | import jieba
from ..language import Language
from ..tokens import Doc
class Chinese(Language):
lang = u'zh'
def make_doc(self, text):
words = list(jieba.cut(text, cut_all=True))
return Doc(self.vocab, words=words, spaces=[False]*len(words))
| Add draft Jieba tokenizer for Chinese | Add draft Jieba tokenizer for Chinese
| Python | mit | spacy-io/spaCy,explosion/spaCy,oroszgy/spaCy.hu,explosion/spaCy,recognai/spaCy,honnibal/spaCy,banglakit/spaCy,explosion/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,recognai/spaCy,banglakit/spaCy,recognai/spaCy,oroszgy/spaCy.hu,oroszgy/spaCy.hu,spacy-io/spaCy,aikramer2/spaCy,aikramer2/spaCy,explosion/spaCy,honnibal/spaCy... |
ff7b10fe2b32f6c6b988ac1094c494cb986dded4 | tests/smolder_tests.py | tests/smolder_tests.py | #!/usr/bin/env python2
import smolder
import nose
import json
import os
from nose.tools import assert_raises
from imp import reload
THIS_DIR = os.path.dirname(os.path.realpath(__file__))
def test_noop_test():
assert smolder.noop_test()
def test_github_status():
myfile = open(THIS_DIR + '/github_status.json')
t... | #!/usr/bin/env python2
import smolder
import json
import os
from nose.tools import assert_raises
from imp import reload
THIS_DIR = os.path.dirname(os.path.realpath(__file__))
def test_noop_test():
assert smolder.noop_test()
def test_github_status():
myfile = open(THIS_DIR + '/github_status.json')
test_json = j... | Clean up imports in smolder tests | Clean up imports in smolder tests
| Python | bsd-3-clause | sky-shiny/smolder,sky-shiny/smolder |
6e80bcef30b6b4485fa5e3f269f13fc62380c422 | tests/test_evaluate.py | tests/test_evaluate.py | import numpy as np
from numpy.testing import assert_equal
from gala import evaluate as ev
def test_contingency_table():
seg = np.array([0, 1, 1, 1, 2, 2, 2, 3])
gt = np.array([1, 1, 1, 2, 2, 2, 2, 0])
ct = ev.contingency_table(seg, gt, ignore_seg=[], ignore_gt=[])
ct0 = ev.contingency_table(seg, gt, ig... | import numpy as np
from numpy.testing import assert_equal
from gala import evaluate as ev
def test_contingency_table():
seg = np.array([0, 1, 1, 1, 2, 2, 2, 3])
gt = np.array([1, 1, 1, 2, 2, 2, 2, 0])
ct = ev.contingency_table(seg, gt, ignore_seg=[], ignore_gt=[])
ct0 = ev.contingency_table(seg, gt, ig... | Add in test for ARE | Add in test for ARE
| Python | bsd-3-clause | jni/gala,janelia-flyem/gala |
11fb371098b258348e5b9efc92abe31f2cac5ef3 | tests/test_settings.py | tests/test_settings.py | from os.path import dirname, join
TEST_ROOT = dirname(__file__)
INSTALLED_APPS = ('adminfiles', 'tests',
'django.contrib.contenttypes',
'django.contrib.admin',
'django.contrib.sites',
'django.contrib.auth',
'django.contrib.sessio... | from os.path import dirname, join
TEST_ROOT = dirname(__file__)
INSTALLED_APPS = ('adminfiles', 'tests',
'django.contrib.contenttypes',
'django.contrib.admin',
'django.contrib.sites',
'django.contrib.auth',
'django.contrib.sessio... | Fix deprecation warning: DATABASE_* -> DATABASES | Fix deprecation warning: DATABASE_* -> DATABASES
| Python | bsd-3-clause | carljm/django-adminfiles,carljm/django-adminfiles,carljm/django-adminfiles |
0bdea433da15d70ce841edbffb9316085ca8a647 | main.py | main.py | #! /usr/bin/env python
import numpy as np
def plot_elevation(avulsion):
import matplotlib.pyplot as plt
z = avulsion.get_value('land_surface__elevation')
plt.imshow(z, origin='lower', cmap='terrain')
plt.colorbar().ax.set_label('Elevation (m)')
plt.show()
def main():
import argparse
fr... | #! /usr/bin/env python
import sys
import numpy as np
def plot_elevation(avulsion):
import matplotlib.pyplot as plt
z = avulsion.get_value('land_surface__elevation')
plt.imshow(z, origin='lower', cmap='terrain')
plt.colorbar().ax.set_label('Elevation (m)')
plt.show()
def main():
import arg... | Print final surface elevations to stdout. | Print final surface elevations to stdout.
| Python | mit | mcflugen/avulsion-bmi,katmratliff/avulsion-bmi |
1ee1496439f4dcd654df0a1f119b05a8288e3dd2 | query.py | query.py | from numpy import uint16
from numpy import bool_
from query_result_list import QueryResultList
from data_record import DataRecord
from has_actions import HasActions
class Query(DataRecord, HasActions):
def __init__(self, query_id, topic = None, result_list = None, user = None, condition = None, autocomplete = Non... | from numpy import uint16
from numpy import bool_
from query_result_list import QueryResultList
from data_record import DataRecord
from has_actions import HasActions
class Query(DataRecord, HasActions):
def __init__(self, query_id, topic = None, user = None, condition = None, autocomplete = None, query_text = None... | Remove result list handling from Query constructor | Remove result list handling from Query constructor
| Python | mit | fire-uta/iiix-data-parser |
ded771f45dd8e196d53d892b40ac817912902746 | setup.py | setup.py | from distutils.core import setup
# Keeping all Python code for package in lib directory
NAME = 'cplate'
VERSION = '0.1'
AUTHOR = 'Alexander W Blocker'
AUTHOR_EMAIL = 'ablocker@gmail.com'
URL = 'http://www.awblocker.com'
DESCRIPTION = 'Probablistic deconvolution for chromatin-structure estimation.'
REQUIRES = ['numpy(... | from distutils.core import setup
# Keeping all Python code for package in lib directory
NAME = 'cplate'
VERSION = '0.1'
AUTHOR = 'Alexander W Blocker'
AUTHOR_EMAIL = 'ablocker@gmail.com'
URL = 'https://www.github.com/awblocker/cplate'
DESCRIPTION = 'Probabilistic deconvolution for chromatin-structure estimation.'
REQ... | Update URL and fix typo in description. | Update URL and fix typo in description.
| Python | apache-2.0 | awblocker/cplate,awblocker/cplate |
dcb9850c854733a9e3686548c8e397d4b86c5e3d | setup.py | setup.py | from distutils.core import setup
setup(
name = 'brazilnum',
packages = ['brazilnum'],
version = '0.6.1',
description = 'Validators for Brazilian CNPJ, CPF, and PIS/PASEP numbers.',
author = 'Chris Poliquin',
author_email = 'cpoliquin@hbs.edu',
url = 'https://gith... | from distutils.core import setup
setup(
name = 'brazilnum',
packages = ['brazilnum'],
version = '0.7.1',
description = 'Validators for Brazilian CNPJ, CEI, CPF, and PIS/PASEP',
author = 'Chris Poliquin',
author_email = 'cpoliquin@hbs.edu',
url = 'https://github.c... | Add CEI to package description and bump version | Add CEI to package description and bump version
| Python | mit | poliquin/brazilnum |
2202ecfafb085dbbaa1e2db1423b9d6f98f5f471 | stack.py | stack.py | class StackItem(object):
def __init__(self, data, next_item=None):
self.data = data
self.next_item = next_item
def __str__(self):
return self.data
class StackFrame(object):
def __init__(self, first_item=None):
self.first_item = first_item
def push(self, new_item):
... | class StackItem(object):
def __init__(self, data, next_item=None):
self.data = data
self.next_item = next_item
def __str__(self):
return self.data
class StackFrame(object):
def __init__(self, first_item=None):
self.first_item = first_item
def push(self, new_item):
... | Fix pop to raise ValueError when empty Stack is popped | Fix pop to raise ValueError when empty Stack is popped
| Python | mit | jwarren116/data-structures |
fd6572b9910e0c5a01cbe1376f15059d80cf5093 | all/templates/init.py | all/templates/init.py | from flask import Flask, url_for
import os
<%= appName %> = Flask(__name__)
# Determines the destination of the build. Only usefull if you're using Frozen-Flask
<%= appName %>.config['FREEZER_DESTINATION'] = os.path.dirname(os.path.abspath(__file__))+'/../build'
# Function to easily find your assets
# In your templa... | from flask import Flask, url_for
import os
<%= appName %> = Flask(__name__)
# Determines the destination of the build. Only usefull if you're using Frozen-Flask
<%= appName %>.config['FREEZER_DESTINATION'] = os.path.dirname(os.path.abspath(__file__))+'/../build'
# Function to easily find your assets
# In your templa... | Replace hardcoded "app" with parameter "appName" | Replace hardcoded "app" with parameter "appName"
| Python | mit | romainberger/yeoman-flask,romainberger/yeoman-flask |
47d950b882c01820db7fe99431526487d88622db | tasks.py | tasks.py | import os
from invocations.docs import docs, www, sites, watch_docs
from invocations.testing import test, coverage, integration, watch_tests
from invocations.packaging import vendorize, release
from invoke import Collection
from invoke.util import LOG_FORMAT
ns = Collection(
test, coverage, integration, vendori... | import os
from invocations.docs import docs, www, sites, watch_docs
from invocations.testing import test, coverage, integration, watch_tests
from invocations.packaging import vendorize, release
from invoke import Collection
from invoke.util import LOG_FORMAT
ns = Collection(
test, coverage, integration, vendori... | Check setup.py desc when packaging | Check setup.py desc when packaging
| Python | bsd-2-clause | pyinvoke/invoke,pyinvoke/invoke,mkusz/invoke,mkusz/invoke |
30709e0a8f5392260543b9d0fb168a3246d827ad | tasks.py | tasks.py |
import invoke
# Based on https://github.com/pyca/cryptography/blob/master/tasks.py
@invoke.task
def release(version):
invoke.run("git tag -a release-{0} -m \"Tagged {0} release\"".format(version))
invoke.run("git push --tags")
invoke.run("python setup.py sdist")
invoke.run("twine upload dist/pyuv-{... |
import invoke
# Based on https://github.com/pyca/cryptography/blob/master/tasks.py
@invoke.task
def release(version):
invoke.run("git tag -a pyuv-{0} -m \"pyuv {0} release\"".format(version))
invoke.run("git push --tags")
invoke.run("python setup.py sdist")
invoke.run("twine upload dist/pyuv-{0}*".... | Fix tag names so GitHub generates better filenames | Fix tag names so GitHub generates better filenames
| Python | mit | saghul/pyuv,fivejjs/pyuv,fivejjs/pyuv,fivejjs/pyuv,saghul/pyuv,saghul/pyuv |
fe033ea76c8dcc5a90b0ba28c2c851b4ebb3ed15 | src/clients/lib/python/xmmsclient/propdict.py | src/clients/lib/python/xmmsclient/propdict.py | class PropDict(dict):
def __init__(self, srcs):
dict.__init__(self)
self._sources = srcs
def set_source_preference(self, sources):
"""
Change list of source preference
This method has been deprecated and should no longer be used.
"""
raise DeprecationWarn... | class PropDict(dict):
def __init__(self, srcs):
dict.__init__(self)
self._sources = srcs
def set_source_preference(self, sources):
"""
Change list of source preference
This method has been deprecated and should no longer be used.
"""
raise DeprecationWarn... | Allow PropDict.sources in python bindings to be any sequence. | BUG(1900): Allow PropDict.sources in python bindings to be any sequence.
| Python | lgpl-2.1 | mantaraya36/xmms2-mantaraya36,theeternalsw0rd/xmms2,mantaraya36/xmms2-mantaraya36,dreamerc/xmms2,chrippa/xmms2,mantaraya36/xmms2-mantaraya36,krad-radio/xmms2-krad,krad-radio/xmms2-krad,chrippa/xmms2,oneman/xmms2-oneman-old,six600110/xmms2,krad-radio/xmms2-krad,six600110/xmms2,theeternalsw0rd/xmms2,chrippa/xmms2,oneman/... |
fd660a62bd142d4ef36bde44a02b28146498bfc6 | driver_code_test.py | driver_code_test.py | import SimpleCV as scv
from SimpleCV import Image
import cv2
import time
from start_camera import start_camera
import threading
# camera_thread = threading.Thread(target=start_camera)
# camera_thread.start()
# from get_images_from_pi import get_image, valid_image
# time.sleep(2)
# count = 0
# while (count < 50):
# g... | import SimpleCV as scv
from SimpleCV import Image
import cv2
import time
from start_camera import start_camera
import threading
def take_50_pictures():
camera_thread = threading.Thread(target=start_camera)
camera_thread.start()
from get_images_from_pi import get_image, valid_image
time.sleep(2)
count = 0
w... | Add simple logic to driver code test for easy testing | Add simple logic to driver code test for easy testing
| Python | mit | jwarshaw/RaspberryDrive |
83dce279fcf157f9ca4cc2e7dbdad55db9f1f857 | play.py | play.py | #!/usr/bin/python3
import readline
import random
import shelve
import sys
from src import parser
from src import locations
from src import classes
player = classes.Player(locations, locations.start)
previousNoun = ''
turns = 0
while True:
try:
command = parser.parseCommand(input('> '))
if command ... | #!/usr/bin/python3
import os
import readline
import random
import shelve
import sys
os.chdir(os.path.dirname(os.path.abspath(__file__)))
from src import parser
from src import locations
from src import classes
player = classes.Player(locations, locations.start)
previousNoun = ''
turns = 0
while True:
try:
... | Fix issue where game could be in wrong cwd | Fix issue where game could be in wrong cwd
| Python | mit | disorientedperson/python-adventure-game,allanburleson/python-adventure-game |
5278af1e7de42d4e881a0888074a02cce2831591 | utils.py | utils.py | from pylab import *
import rebound as re
def outer_solar_system():
sim = re.Simulation()
sim.add(['Sun', 'Jupiter', 'Saturn', 'Uranus', 'Neptune'])
sim.move_to_com()
sim.dt = 4
sim.integrator = 'whfast'
sim.integrator_whfast_safe_mode = 0
sim.integrator_whfast_corrector = 11
retur... | from pylab import *
import rebound as re
def outer_solar_system():
sim = re.Simulation()
sim.add(['Sun', 'Jupiter', 'Saturn', 'Uranus', 'Neptune'])
sim.move_to_com()
sim.dt = 4
sim.integrator = 'whfast'
sim.integrator_whfast_safe_mode = 0
sim.integrator_whfast_corrector = 11
retur... | Make planar perturber *really* planar. | Make planar perturber *really* planar.
| Python | mit | farr/PlanetIX |
e5f88d065601972bf1e7abebc69f9235b08d4c62 | easyium/__init__.py | easyium/__init__.py | __author__ = 'karl.gong'
try:
import appium
appium_installed = True
except ImportError:
appium_installed = False | from .webdriver import WebDriver, WebDriverType
from .staticelement import StaticElement
from .identifier import Identifier
from .waits.waiter import wait_for
__author__ = 'karl.gong'
try:
import appium
appium_installed = True
except ImportError:
appium_installed = False
| Add package "shortcuts" for classes&function | Add package "shortcuts" for classes&function
| Python | apache-2.0 | KarlGong/easyium-python,KarlGong/easyium |
fc23b7e6a330bd24d49edb60df3a7e8d948c6c32 | main.py | main.py | from kivy.app import App
from kivy.uix.widget import Widget
from kivy.clock import Clock
from kivy.graphics import Canvas, Color, Rectangle
from action_map import ActionMap
from camera import Camera
from graphics import Graphics
class ActionGame(Widget):
action_map = ActionMap()
graphics = Graphics()
def... | from kivy.app import App
from kivy.uix.widget import Widget
from kivy.clock import Clock
from kivy.graphics import Canvas, Color, Rectangle
from action_map import ActionMap
from camera import Camera
from graphics import Graphics
class ActionGame(Widget):
action_map = ActionMap()
graphics = Graphics()
def... | Simplify camera response to touch input | Simplify camera response to touch input
| Python | mit | Corrob/Action-Game |
6f8692d0345652acc5e4c858e0e2a3f688dc574f | project/views/twilioviews.py | project/views/twilioviews.py | from flask import request
import requests
from ..utils.status import get_status
from ..utils.reminders import create_reminder
import twilio.twiml
import json
import dateutil
def call():
resp = twilio.twiml.Response()
resp.record(timeout=10, transcribe=True,
transcribeCallback='http://queri.me/rec',... | from flask import request
import requests
from ..utils.status import get_status
from ..utils.reminders import create_reminder
import twilio.twiml
import json
import dateutil
def call():
resp = twilio.twiml.Response()
resp.record(timeout=10, transcribe=True,
transcribeCallback='http://queri.me/rec',... | Select the message text in twilio | Select the message text in twilio
| Python | apache-2.0 | tjcsl/mhacksiv |
506b3399fe20b0267e26a944b49d9ab16d927b31 | test.py | test.py | import parser, codegen, compile
import sys, os, unittest, subprocess
DIR = os.path.dirname(__file__)
TESTS_DIR = os.path.join(DIR, 'tests')
TESTS = [
'hello', 'print-int', 'multi-stmt', 'int-add', 'var-hello',
]
def run(self, key):
fullname = os.path.join(TESTS_DIR, key + '.lng')
base = fullname.rsplit('.lng', ... | import parser, codegen, compile
import sys, os, unittest, subprocess
DIR = os.path.dirname(__file__)
TESTS_DIR = os.path.join(DIR, 'tests')
TESTS = [
'hello', 'print-int', 'multi-stmt', 'int-add', 'var-hello', 'int-var',
]
def run(self, key):
fullname = os.path.join(TESTS_DIR, key + '.lng')
base = fullname.rspl... | Verify that integer variables also work. | Verify that integer variables also work.
| Python | mit | djc/runa,djc/runa,djc/runa,djc/runa |
a8ed783aff7a725260904d84e36e1f4ac7ed91b3 | example_slack.py | example_slack.py | #!/usr/bin/env python
"""Sets a luxafor flag based on status."""
import luxafor
import os
import time
from slackclient import SlackClient
slack_token = os.environ["SLACK_API_TOKEN"]
sc = SlackClient(slack_token)
API = luxafor.API()
while (True):
presence = sc.api_call("dnd.info")
if presence['snooze_enabl... | #!/usr/bin/env python
"""Sets a luxafor flag based on status."""
import luxafor
import os
import time
from slackclient import SlackClient
slack_token = os.environ["SLACK_API_TOKEN"]
slack_client = SlackClient(slack_token)
lux = luxafor.API()
snooze_remaining = -1 # Countdown timer
user_id = 'U024G0M2L'
if slack_cl... | Switch to use RTM protocol | Switch to use RTM protocol
There isn’t an RTM event for ‘stops being DND’ so I’ve added a simple countdown loop, it loses about a second or two, but it works.
Happy to have feedback on the loops / logic, feels like it could be sharper.
| Python | mit | blancltd/luxafor |
a452adfb297ff40ec3db71108681829769b1fba4 | pyface/tasks/enaml_editor.py | pyface/tasks/enaml_editor.py | # Enthought library imports.
from traits.api import Instance, on_trait_change
from enaml.components.constraints_widget import ConstraintsWidget
# local imports
from pyface.tasks.editor import Editor
class EnamlEditor(Editor):
""" Create an Editor for Enaml Components.
"""
#### EnamlEditor interface ####... | # Enthought library imports.
from traits.api import Instance, on_trait_change
from enaml.components.constraints_widget import ConstraintsWidget
# local imports
from pyface.tasks.editor import Editor
class EnamlEditor(Editor):
""" Create an Editor for Enaml Components.
"""
#### EnamlEditor interface ####... | Remove call of unimplemented method. | BUG: Remove call of unimplemented method.
| Python | bsd-3-clause | brett-patterson/pyface,pankajp/pyface,geggo/pyface,geggo/pyface |
f9cb73670966d7cb3ade12056c92c479404cbb07 | pythran/tests/test_cython.py | pythran/tests/test_cython.py | import os
import unittest
class TestCython(unittest.TestCase):
pass
def add_test(name, runner, target):
setattr(TestCython, "test_" + name, lambda s: runner(s, target))
try:
import Cython
import glob
import sys
targets = glob.glob(os.path.join(os.path.dirname(__file__), "cython", "setup_*.py"... | import os
import unittest
class TestCython(unittest.TestCase):
pass
# Needs to wait unil cython supports pythran new builtins naming
#def add_test(name, runner, target):
# setattr(TestCython, "test_" + name, lambda s: runner(s, target))
#
#try:
# import Cython
# import glob
# import sys
# targets = ... | Disable Cython test until Cython support new pythonic layout | Disable Cython test until Cython support new pythonic layout
| Python | bsd-3-clause | serge-sans-paille/pythran,serge-sans-paille/pythran,pombredanne/pythran,pombredanne/pythran,pombredanne/pythran |
fb1581dd11cfc74a5c3888430d1f288974e40c76 | giphy.py | giphy.py | # -*- coding: utf-8 -*-
#
# Insert a random giphy URL based on a search
#
# Usage: /giphy search
#
# History:
#
# Version 1.0.1: Auto post gif URL along with query string
# Version 1.0.0: initial release
#
import requests
import weechat
URL = "http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=%s"
def gi... | # -*- coding: utf-8 -*-
#
# Insert a random giphy URL based on a search
#
# Usage: /giphy search
#
# History:
#
# Version 1.0.2: Write text if no matches are found
# Version 1.0.1: Auto post gif URL along with query string
# Version 1.0.0: initial release
#
import requests
import weechat
URL = "http://api.giphy.com/v... | Write error if no matching gifs are found | Write error if no matching gifs are found
| Python | mit | keith/giphy-weechat |
1eb411a45f74819a039dfc1330decb212e1961a6 | rollbar/test/async_helper.py | rollbar/test/async_helper.py | import asyncio
import inspect
import sys
import rollbar
def run(coro):
if sys.version_info >= (3, 7):
return asyncio.run(coro)
assert inspect.iscoroutine(coro)
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
return loop.run_until_complete(coro)
finally:
... | import asyncio
import inspect
import sys
import rollbar
def run(coro):
if sys.version_info >= (3, 7):
return asyncio.run(coro)
assert inspect.iscoroutine(coro)
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
return loop.run_until_complete(coro)
finally:
... | Add BareMiddleware to test helpers | Add BareMiddleware to test helpers
| Python | mit | rollbar/pyrollbar |
a1be44dcc93a336232807f3ef79a03e73ca31f65 | froniusLogger.py | froniusLogger.py | """
Logs key data from a Fronius inverter to a CSV file for later analysis.
peter.marks@pobox.com
"""
import requests
import json
import datetime
import time
# Set this to the IP address of your inverter
host = "192.168.0.112"
sample_seconds = 60 # how many seconds between samples, set to zero to run once and exit
... | """
Logs key data from a Fronius inverter to a CSV file for later analysis.
peter.marks@pobox.com
"""
import requests
import json
import datetime
import time
# Set this to the IP address of your inverter
host = "192.168.0.112"
# number of seconds between samples, set to zero to run once and exit
sample_seconds = 60 *... | Set sample times to every 5 minutes. Show the time of a timeout. | Set sample times to every 5 minutes.
Show the time of a timeout.
| Python | apache-2.0 | peterbmarks/froniusLogger,peterbmarks/froniusLogger |
6aa3ed3634a22b89f7128883d20f28f65ed00152 | basic.py | basic.py | import os # needed for opening/compiling file
import time # needed for delay
def getPath(allowCancel = True):
"""Ask the user for lilypond file path and return it as string.
Takes one boolean argument as to whether message should say cancelling is allowed or not. Defaults to true, however this may not be suitabl... | import os; # needed for opening/compiling file
import time; # needed for delay
def getPath(allowCancel = True):
"""Ask the user for lilypond file path and return it as string.
Takes one boolean argument as to whether message should say cancelling is allowed or not. Defaults to true, however this may not be suita... | Add semicolons to end of program statements | Add semicolons to end of program statements
| Python | unlicense | RainCity471/lyCompiler |
47afbcf83280fdd4cf80119443524240ea8148ad | lms/djangoapps/grades/migrations/0005_multiple_course_flags.py | lms/djangoapps/grades/migrations/0005_multiple_course_flags.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from openedx.core.djangoapps.xmodule_django.models import CourseKeyField
class Migration(migrations.Migration):
dependencies = [
('grades', '0004_visibleblocks_course_id'),
]
operations = [
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from openedx.core.djangoapps.xmodule_django.models import CourseKeyField
class Migration(migrations.Migration):
dependencies = [
('grades', '0004_visibleblocks_course_id'),
]
operations = [
... | Allow grades app to be zero-migrated | Allow grades app to be zero-migrated
| Python | agpl-3.0 | jolyonb/edx-platform,ESOedX/edx-platform,ESOedX/edx-platform,synergeticsedx/deployment-wipro,angelapper/edx-platform,TeachAtTUM/edx-platform,Stanford-Online/edx-platform,jzoldak/edx-platform,proversity-org/edx-platform,philanthropy-u/edx-platform,mitocw/edx-platform,ahmedaljazzar/edx-platform,jzoldak/edx-platform,Stanf... |
c7e5306ede3415838c3cf0861c3a1be8caed38ba | mltsp/run_script_in_container.py | mltsp/run_script_in_container.py | #!/usr/bin/python
# run_script_in_container.py
# Will be run inside Docker container
if __name__ == "__main__":
# Run Cython setup script:
# from subprocess import call
# from mltsp import cfg
# call(["%s/make" % cfg.PROJECT_PATH])
import argparse
parser = argparse.ArgumentParser(description='... | #!/usr/bin/python
# run_script_in_container.py
# Will be run inside Docker container
if __name__ == "__main__":
# Run Cython setup script:
# from subprocess import call
# from mltsp import cfg
# call(["%s/make" % cfg.PROJECT_PATH])
import argparse
parser = argparse.ArgumentParser(description='... | Add comment explaining path append | Add comment explaining path append
| Python | bsd-3-clause | acrellin/mltsp,acrellin/mltsp,mltsp/mltsp,mltsp/mltsp,acrellin/mltsp,acrellin/mltsp,bnaul/mltsp,bnaul/mltsp,mltsp/mltsp,mltsp/mltsp,acrellin/mltsp,acrellin/mltsp,mltsp/mltsp,bnaul/mltsp,bnaul/mltsp,mltsp/mltsp,bnaul/mltsp,bnaul/mltsp |
5f332ba0d67607c99feae5af2fea177da588076f | addons/bestja_configuration_ucw/__openerp__.py | addons/bestja_configuration_ucw/__openerp__.py | # -*- coding: utf-8 -*-
{
'name': "Bestja: UCW",
'summary': "Installation configuration for UCW",
'description': "Installation configuration for Uniwersyteckie Centrum Wolontariatu",
'author': "Laboratorium EE",
'website': "http://www.laboratorium.ee",
'version': '0.1',
'category': 'Specific... | # -*- coding: utf-8 -*-
{
'name': "Bestja: UCW",
'summary': "Installation configuration for UCW",
'description': "Installation configuration for Uniwersyteckie Centrum Wolontariatu",
'author': "Laboratorium EE",
'website': "http://www.laboratorium.ee",
'version': '0.1',
'category': 'Specific... | Revert “Enable Odoo blog for UCW” | Revert “Enable Odoo blog for UCW”
This reverts commit 4922d53f95b3f7c055afe1d0af0088b505cbc0d2.
| Python | agpl-3.0 | KamilWo/bestja,KrzysiekJ/bestja,KrzysiekJ/bestja,EE/bestja,EE/bestja,ludwiktrammer/bestja,ludwiktrammer/bestja,EE/bestja,KamilWo/bestja,KamilWo/bestja,ludwiktrammer/bestja,KrzysiekJ/bestja |
fa991297168f216c208d53b880124a4f23250034 | setup.py | setup.py | import importlib
from cx_Freeze import setup, Executable
backend_path = importlib.import_module("bcrypt").__path__[0]
backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")
# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
"include_files": [
("... | import importlib
from cx_Freeze import setup, Executable
backend_path = importlib.import_module("bcrypt").__path__[0]
backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")
# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
"include_files": [
("... | Add gzip to cx-freeze packages | Add gzip to cx-freeze packages
| Python | mit | virtool/virtool,igboyes/virtool,virtool/virtool,igboyes/virtool |
a735cf90640899bc83a57f7b079b100f61f56e41 | setup.py | setup.py | from distutils.core import setup
from os.path import exists
setup(
name = "fsmonitor",
version = "0.1",
description = "Filesystem monitoring",
long_description=(open('README.rst').read() if exists('README.rst')
else ''),
author = "Luke McCarthy",
author_email = "luke@iogop... | from distutils.core import setup
from os.path import exists
from platform import system
requires = []
if system == "Windows":
requires = ["pypiwin32"]
setup(
name = "fsmonitor",
version = "0.1",
description = "Filesystem monitoring",
long_description=(open('README.rst').read() if exists('README.rs... | Add requires pywin32 only for Windows | Add requires pywin32 only for Windows
| Python | mit | shaurz/fsmonitor |
6ac11b95a10d8078774d3832aefb47ca3829d787 | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
setup(name='redis-dump-load',
version='0.4.0',
description='Dump and load redis databases',
author='Oleg Pudeyev',
author_email='oleg@bsdpower.com',
url='http://github.com/p/redis-dump-load',
py_modules=['redisdl'],
data_files=['LICENS... | #!/usr/bin/env python
import os.path
from distutils.core import setup
package_name = 'redis-dump-load'
package_version = '0.4.0'
doc_dir = os.path.join('share', 'doc', package_name)
data_files = ['LICENSE', 'README.rst']
setup(name=package_name,
version=package_version,
description='Dump and load redis dat... | Put data files in doc dir | Put data files in doc dir
| Python | bsd-2-clause | p/redis-dump-load,p/redis-dump-load |
b6d5f0551a53cc9d97a8b5f634ec54cd9b85bf00 | setup.py | setup.py | #!/usr/local/bin/python -u
__author__ = 'Oliver Ratzesberger <https://github.com/fxstein>'
__copyright__ = 'Copyright (C) 2015 Oliver Ratzesberger'
__license__ = 'Apache License, Version 2.0'
# Make sure we have access to SentientHome commons
import os
print 'Checking node.js presence:'
if 0 != os.system('node -... | #!/usr/local/bin/python -u
__author__ = 'Oliver Ratzesberger <https://github.com/fxstein>'
__copyright__ = 'Copyright (C) 2015 Oliver Ratzesberger'
__license__ = 'Apache License, Version 2.0'
# Make sure we have access to SentientHome commons
import os
print 'Checking node.js presence:'
if 0 != os.system('node -... | Add installation of some python 3 packages | Add installation of some python 3 packages
| Python | apache-2.0 | fxstein/SentientHome |
2e3e2dc66add761c228e0cc685dc808bddd1952e | spicedham/backend.py | spicedham/backend.py | from config import config
class BackendNotRecognizedException(Exception):
"""Possible backends are "sqlalchemy", "elasticsearch", and "djangoorm"""""
pass
if config['backend'] == 'sqlalchemy':
from sqlalchemywrapper.sqlalchemywrapper import SqlAlchemyWrapper as Backend
elif config['backend'] == 'elastics... | from spicedham.config import config
from sqlalchemywrapper import SqlAlchemyWrapper
#from elasticsearchwrapper import ElasticSearchWrapper
#from djangoormwrapper import DjangoOrmWrapper
class BackendNotRecognizedException(Exception):
"""Possible backends are "sqlalchemy", "elasticsearch", and "djangoorm"""""
... | Fix imports and duck typing | Fix imports and duck typing
* Always import all backends
* Only assign the right one to Backend based off the config
* Fix the config import
| Python | mpl-2.0 | mozilla/spicedham,mozilla/spicedham |
787fef7c74ca46b83557edaf3bb4d0189a586204 | build.py | build.py | from elixir.compilers import ModelCompiler
from elixir.processors import NevermoreProcessor
ModelCompiler("src/", "model.rbxmx", NevermoreProcessor).compile()
| from elixir.compilers import ModelCompiler
ModelCompiler("src/", "model.rbxmx").compile()
| Remove the use of the Nevermore processor | Remove the use of the Nevermore processor
| Python | mit | VoxelDavid/echo-ridge |
2d73c633f3d21f0b9ff5d80eebdfca9a48a478f5 | babyonboard/api/tests/test_models.py | babyonboard/api/tests/test_models.py | from django.test import TestCase
from ..models import Temperature
class TemperatureTest(TestCase):
"""Test class for temperature model"""
def setUp(self):
Temperature.objects.create(temperature=20.5)
def test_create_temperature(self):
temperature = Temperature.objects.get(temperature=20.... | from django.test import TestCase
from ..models import Temperature, HeartBeats
class TemperatureTest(TestCase):
"""Test class for temperature model"""
def setUp(self):
Temperature.objects.create(temperature=20.5)
def test_create_temperature(self):
temperature = Temperature.objects.get(tem... | Implement tests for heartbeats model | Implement tests for heartbeats model
| Python | mit | BabyOnBoard/BabyOnBoard-API,BabyOnBoard/BabyOnBoard-API |
4a0edb289a3a8a3195a339a1c89a444f414b8645 | tm/tm.py | tm/tm.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import os
import sys
import argparse
import tmux_wrapper as tmux
__version__ = 1.0
__description__ = "A tmux wrapper featuring shortcuts and session presets."
def load_session_presets():
try:
file_path = os.environ["TM_SESSIONS"]
except KeyError:... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import os
import sys
import argparse
import tmux_wrapper as tmux
__version__ = 1.0
__description__ = "A tmux wrapper featuring shortcuts and session presets."
def load_session_presets():
try:
file_path = os.environ["TM_SESSIONS"]
except KeyError:... | Check for all exceptions to main method | Check for all exceptions to main method
| Python | mit | ethanal/tm |
21e76ae7d9e7679007d90e842e28df46a8c0fc97 | itorch-runner.py | itorch-runner.py | # coding: utf-8
import sys, getopt
import os
import json
import datetime
from subprocess import call
current_date = str(datetime.datetime.now()).replace(' ', '!')
output_file_name = './tmp_itorch_exec-'+current_date+'.lua'
if __name__ == "__main__":
if len(sys.argv) > 0:
input_file = open(sys.argv[1], 'r')
wit... | # coding: utf-8
import sys, getopt
import os
import json
import datetime
from subprocess import call
current_date = str(datetime.datetime.now()).replace(' ', '!')
output_file_name = './tmp_itorch_exec-'+current_date+'.lua'
if __name__ == "__main__":
if len(sys.argv) > 0:
input_file = open(sys.argv[1], 'r')
wit... | Fix missing new line symbol for last line in notebook cell | Fix missing new line symbol for last line in notebook cell
| Python | mit | AlexMili/itorch-runner |
08c864a914b7996115f6b265cddb3c96c40e4fb5 | global_functions.py | global_functions.py | import random
import hashlib
def get_random_id():
# generate a random unique integer
random_id = random.randrange(1, 100000000)
return random_id
def get_attributes_from_class(instance_of_class):
members = [attr for attr in dir(instance_of_class) if
not callable(getattr(instance_of_cla... | import random
import hashlib
def get_random_id():
"""generates a random integer value between 1 and 100000000
:return
(int): randomly generated integer
"""
# generate a random unique integer
random_id = random.randrange(1, 100000000)
return random_id
def get_attributes_from_class(ins... | Add descriptive docstring comments global functions | [UPDATE] Add descriptive docstring comments global functions
| Python | mit | EinsteinCarrey/Shoppinglist,EinsteinCarrey/Shoppinglist,EinsteinCarrey/Shoppinglist |
e9bec1aeac09dcb00fd423350f83bab82ea80ffc | connection_example.py | connection_example.py | import socket
import threading
import SocketServer
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = self.request.recv(1024)
cur_thread = threading.current_thread()
response = "{}: {}".format(cur_thread.name, data)
self.request.sendall(respo... | import socket
import threading
import SocketServer
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = self.request.recv(1024)
cur_thread = threading.current_thread()
response = "{}: {}".format(cur_thread.name, data)
self.request.sendall(respo... | Update example with 8 servers. | Update example with 8 servers.
| Python | mit | Tribler/decentral-market |
defbf149afa47910742a588292507535b2679f54 | context_processors.py | context_processors.py | from django.conf import settings as django_settings
from django.core.urlresolvers import resolve, reverse
from django.utils.translation import activate, get_language
def settings(request):
return {'settings': django_settings}
def alternate_seo_url(request):
alternate_url = dict()
path = request.path
... | from django.conf import settings as django_settings
from django.core.urlresolvers import resolve, reverse
from django.utils.translation import activate, get_language
def settings(request):
return {'settings': django_settings}
def alternate_seo_url(request):
alternate_url = dict()
path = request.path
... | Exclude nonapp from contextprocessor of alternate_seo | Exclude nonapp from contextprocessor of alternate_seo
| Python | mit | lotrekagency/djlotrek,lotrekagency/djlotrek |
ab8b6ed75f27820ce2711d597838584fe68e62ef | setup.py | setup.py | #!python
import os
from distutils.core import setup
filepath = os.path.dirname(__file__)
readme_file = os.path.join(filepath, 'README.md')
try:
import pypandoc
long_description = pypandoc.convert(readme_file, 'rst')
except(IOError, ImportError):
long_description = open(readme_file).read()
def extract_ver... | #!python
import os
from distutils.core import setup
description = 'Cmdlet provides pipe-like mechanism to cascade functions and generators.'
filepath = os.path.dirname(__file__)
readme_file = os.path.join(filepath, 'README.md')
if not os.path.exist(readme_file):
long_description = description
else:
try:
... | Use short description if README.md not found. | Use short description if README.md not found.
| Python | mit | GaryLee/cmdlet |
cacbc6825be010f6b839c8d21392a43b8b7b938d | setup.py | setup.py | from distutils.core import setup
setup(name='pandocfilters',
version='1.0',
description='Utilities for writing pandoc filters in python',
author='John MacFarlane',
author_email='fiddlosopher@gmail.com',
url='http://github.com/jgm/pandocfilters',
py_modules=['pandocfilters'],
ke... | from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='pandocfilters',
version='1.0',
description='Utilities for writing pandoc filters in python',
long_description=read('README.rst'),
author='John MacFarlane',
... | INclude README as long description. | INclude README as long description.
| Python | bsd-3-clause | AugustH/pandocfilters,infotroph/pandocfilters,silvio/pandocfilters,alycosta/pandocfilters,timtylin/scholdoc-filters,jgm/pandocfilters |
a7c31950cc2ad737176ba2aa91c77c7c649aa8c7 | shell.py | shell.py | import sys, os, subprocess
def make_environment(env=None):
if env is None:
env = os.environ
env = env.copy()
env["PYTHONUNBUFFERED"] = "1"
env["PYTHONIOENCODING"] = "UTF-8"
return env
def run_shell_command(cmdline, pipe_output=True, env=None, **kwargs):
if sys.platform == "win32":
... | import sys, os, subprocess
remove_vars = ("PYTHONHOME", "PYTHONPATH", "VERSIONER_PYTHON_PREFER_32_BIT")
def make_environment(env=None):
if env is None:
env = os.environ
env = env.copy()
for var in remove_vars:
if var in env:
del env[var]
env["PYTHONUNBUFFERED"] = "1"
en... | Remove some Python environment variables from user subprocess environment. | Remove some Python environment variables from user subprocess environment.
| Python | mit | shaurz/devo |
bc25841219aa4811b8fb3ec19f5f75809a6e62c0 | tasks.py | tasks.py | # Project tasks (for use with invoke task runner)
import subprocess
from invoke import task
@task
def test(cover=False):
# Run tests using nose called with coverage
code = subprocess.call(['coverage', 'run', '-m', 'nose', '--rednose'])
# Also generate coverage reports when --cover flag is given
if co... | # Project tasks (for use with invoke task runner)
import subprocess
from invoke import task
@task
def test(cover=False):
if cover:
# Run tests via coverage and generate reports if --cover flag is given
code = subprocess.call(['coverage', 'run', '-m', 'nose', '--rednose'])
# Only show cove... | Improve performance of test task | Improve performance of test task
| Python | mit | caleb531/three-of-a-crime |
82099790938fefa3e844c908271471a8313356d0 | code_highlight/code_highlight.py | code_highlight/code_highlight.py | from django.utils.safestring import mark_safe
from pygments import highlight
from pygments.formatters import get_formatter_by_name
from pygments.lexers import get_lexer_by_name
from wagtail.wagtailcore import blocks
class CodeBlock(blocks.StructBlock):
"""
Code Highlighting Block
"""
LANGUAGE_CHOICES... | from django.utils.safestring import mark_safe
from pygments import highlight
from pygments.formatters import get_formatter_by_name
from pygments.lexers import get_lexer_by_name
from wagtail.wagtailcore import blocks
class CodeBlock(blocks.StructBlock):
"""
Code Highlighting Block
"""
LANGUAGE_CHOICES... | Add context=None to render as well. | Add context=None to render as well.
| Python | bsd-3-clause | FlipperPA/wagtail-components |
ceadd1355ef25282567030c180139886419543db | db/goalie_game.py | db/goalie_game.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from .common import Base
class GoalieGame(Base):
__tablename__ = 'goalie_games'
__autoload__ = True
STANDARD_ATTRS = [
"position", "no", "goals", "assists", "primary_assists",
"secondary_assists", "points", "plus_minus", "penalties", "pim",
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from sqlalchemy import and_
from .common import Base, session_scope
class GoalieGame(Base):
__tablename__ = 'goalie_games'
__autoload__ = True
STANDARD_ATTRS = [
"position", "no", "goals", "assists", "primary_assists",
"secondary_assists", "... | Add find and update functions to goalie game definition | Add find and update functions to goalie game definition
| Python | mit | leaffan/pynhldb |
f38f8765ba2b25437dddb5af13f68be3a6fdcffa | tap/tests/factory.py | tap/tests/factory.py | # Copyright (c) 2014, Matt Layman
import tempfile
from unittest.runner import TextTestResult
from tap.directive import Directive
from tap.line import Result
class Factory(object):
"""A factory to produce commonly needed objects"""
def make_ok(self, directive_text=''):
return Result(
Tru... | # Copyright (c) 2014, Matt Layman
import tempfile
try:
from unittest.runner import TextTestResult
except ImportError:
# Support Python 2.6.
from unittest import _TextTestResult as TextTestResult
from tap.directive import Directive
from tap.line import Result
class Factory(object):
"""A factory to pr... | Fix Python 2.6 and Python 3 tests. | Fix Python 2.6 and Python 3 tests.
| Python | bsd-2-clause | python-tap/tappy,blakev/tappy,Mark-E-Hamilton/tappy,mblayman/tappy |
4eb043cfb0f2535a1dca37927323155b7d3f363e | dynamic_rest/links.py | dynamic_rest/links.py | """This module contains utilities to support API links."""
from django.utils import six
from dynamic_rest.conf import settings
from .routers import DynamicRouter
def merge_link_object(serializer, data, instance):
"""Add a 'links' attribute to the data that maps field names to URLs.
NOTE: This is the format t... | """This module contains utilities to support API links."""
from django.utils import six
from dynamic_rest.conf import settings
from dynamic_rest.routers import DynamicRouter
def merge_link_object(serializer, data, instance):
"""Add a 'links' attribute to the data that maps field names to URLs.
NOTE: This is... | Fix some sorting thing for isort | Fix some sorting thing for isort
| Python | mit | sanoma/dynamic-rest,AltSchool/dynamic-rest,sanoma/dynamic-rest,AltSchool/dynamic-rest |
9f843b34ef5c85d781b7dd322641d5459cf6190d | linked_accounts/backends.py | linked_accounts/backends.py | from django.contrib.auth.models import User
from linked_accounts.utils import get_profile
class LinkedAccountsBackend(object):
def get_user(self, user_id):
return User.objects.get(id=user_id)
def authenticate(self, service=None, token=None):
profile = get_profile(service, token)
| from django.contrib.auth.models import User
from linked_accounts.utils import get_profile
class LinkedAccountsBackend(object):
def get_user(self, user_id):
return User.objects.get(id=user_id)
def authenticate(self, service=None, token=None):
profile = get_profile(service, token)
ret... | Return profile from authenticate method | Return profile from authenticate method
| Python | mit | zen4ever/django-linked-accounts,zen4ever/django-linked-accounts |
1fb1b1fa6ed40b593c00101967b86bf1f94de8ab | atlasseq/cmds/rowjoin.py | atlasseq/cmds/rowjoin.py | #! /usr/bin/env python
from __future__ import print_function
import shutil
import logging
logger = logging.getLogger(__name__)
from atlasseq.storage.base import BerkeleyDBStorage
def rowjoin(partitioned_data, out_db, N=25000000):
db_out = BerkeleyDBStorage(config={'filename': out_db})
for x in ["colour_to_sam... | #! /usr/bin/env python
from __future__ import print_function
import shutil
import logging
logger = logging.getLogger(__name__)
from atlasseq.storage.base import BerkeleyDBStorage
def rowjoin(partitioned_data, out_db, N=25000000):
N = int(N)
db_out = BerkeleyDBStorage(config={'filename': out_db})
for x in ... | Add row join command for merging berkeley DBs | Add row join command for merging berkeley DBs
| Python | mit | Phelimb/cbg,Phelimb/cbg,Phelimb/cbg,Phelimb/cbg |
c37e0b66b6f0cc57d7df94f62dd47e00dc91c544 | django_archive/archivers/__init__.py | django_archive/archivers/__init__.py | from .tarball import TarballArchiver
from .zipfile import ZipArchiver
TARBALL = TarballArchiver.UNCOMPRESSED
TARBALL_GZ = TarballArchiver.GZ
TARBALL_BZ2 = TarballArchiver.BZ2
TARBALL_XZ = TarballArchiver.XZ
ZIP = 'zip'
FORMATS = (
(TARBALL, "Tarball (.tar)"),
(TARBALL_GZ, "gzip-compressed Tarball (.tar.gz)")... | from .tarball import TarballArchiver
from .zipfile import ZipArchiver
TARBALL = TarballArchiver.UNCOMPRESSED
TARBALL_GZ = TarballArchiver.GZ
TARBALL_BZ2 = TarballArchiver.BZ2
TARBALL_XZ = TarballArchiver.XZ
ZIP = 'zip'
FORMATS = (
TARBALL,
TARBALL_GZ,
TARBALL_BZ2,
TARBALL_XZ,
ZIP,
)
FORMATS_DESC... | Make FORMATS a tuple and add FORMATS_DESC for textual format descriptions. | Make FORMATS a tuple and add FORMATS_DESC for textual format descriptions.
| Python | mit | nathan-osman/django-archive,nathan-osman/django-archive |
a05e9eff86ae43f83600842c5b9a840d22db6682 | pyinfra/api/__init__.py | pyinfra/api/__init__.py | from .command import ( # noqa: F401 # pragma: no cover
FileDownloadCommand,
FileUploadCommand,
FunctionCommand,
MaskString,
QuoteString,
StringCommand,
)
from .config import Config # noqa: F401 # pragma: no cover
from .deploy import deploy # noqa: F401 # pragma: no cover
from .exceptions impo... | from .command import ( # noqa: F401 # pragma: no cover
FileDownloadCommand,
FileUploadCommand,
FunctionCommand,
MaskString,
QuoteString,
StringCommand,
)
from .config import Config # noqa: F401 # pragma: no cover
from .deploy import deploy # noqa: F401 # pragma: no cover
from .exceptions impo... | Add `Host` to `pyinfra.api` imports. | Add `Host` to `pyinfra.api` imports.
| Python | mit | Fizzadar/pyinfra,Fizzadar/pyinfra |
ce82161dfcc1aa95febe601e331b8ba7044565ff | server/rest/twofishes.py | server/rest/twofishes.py | import requests
from girder.api import access
from girder.api.describe import Description
from girder.api.rest import Resource
class TwoFishes(Resource):
def __init__(self):
self.resourceName = 'minerva_geocoder'
self.route('GET', (), self.geocode)
@access.public
def geocode(self, params)... | import requests
from girder.api import access
from girder.api.describe import Description
from girder.api.rest import Resource
class TwoFishes(Resource):
def __init__(self):
self.resourceName = 'minerva_geocoder'
self.route('GET', (), self.geocode)
self.route('GET', ('autocomplete',), sel... | Add an endpoint which returns autocompleted results | Add an endpoint which returns autocompleted results
| Python | apache-2.0 | Kitware/minerva,Kitware/minerva,Kitware/minerva |
96d8431cd50a50a4ba25d63fbe1718a7c0ccba18 | wsgi/dapi/templatetags/deplink.py | wsgi/dapi/templatetags/deplink.py | from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe
from dapi import models
register = template.Library()
@register.filter(needs_autoescape=True)
@stringfilter
def deplink(value, autoescape=None):
'''Add links for required daps'''
... | from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe
from dapi import models
register = template.Library()
@register.filter(needs_autoescape=True)
@stringfilter
def deplink(value, autoescape=None):
'''Add links for required daps'''
... | Fix "UnboundLocalError: local variable 'dep' referenced before assignment" | Fix "UnboundLocalError: local variable 'dep' referenced before assignment"
| Python | agpl-3.0 | devassistant/dapi,devassistant/dapi,devassistant/dapi |
78d36a68e0d460f3ead713a82c7d23faf7e73b9b | Instanssi/tickets/views.py | Instanssi/tickets/views.py | # -*- coding: utf-8 -*-
from datetime import datetime
from django.conf import settings
from django.http import HttpResponse, Http404
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from Instanssi.tickets.models import Ticket
from Instanssi.store.models impo... | # -*- coding: utf-8 -*-
from datetime import datetime
from django.conf import settings
from django.http import HttpResponse, Http404
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from Instanssi.tickets.models import Ticket
from Instanssi.store.models impo... | Make sure ticket is paid before it can be viewed | tickets: Make sure ticket is paid before it can be viewed
| Python | mit | Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org |
f3cdd03f1e02f7fd0614d4421b831794c01de66d | tests/web_api/case_with_reform/reforms.py | tests/web_api/case_with_reform/reforms.py | from openfisca_core.model_api import Variable, Reform, MONTH
from openfisca_country_template.entities import Person
class goes_to_school(Variable):
value_type = bool
default_value = True
entity = Person
label = "The person goes to school (only relevant for children)"
definition_period = MONTH
cl... | from openfisca_core.model_api import Variable, Reform, MONTH
from openfisca_country_template.entities import Person
def test_dynamic_variable():
class NewDynamicClass(Variable):
value_type = bool
default_value = True
entity = Person
label = "The person goes to school (only relevant... | Update test reform to make it fail without a fix | Update test reform to make it fail without a fix
| Python | agpl-3.0 | openfisca/openfisca-core,openfisca/openfisca-core |
f9bf31e7cfdcbe8d9195b0f2ca9e159788193c50 | unjabberlib/cmdui.py | unjabberlib/cmdui.py | import cmd
from itertools import zip_longest
INDENT = 5 * ' '
class UnjabberCmd(cmd.Cmd):
def __init__(self, queries, **cmdargs):
super().__init__(**cmdargs)
self.queries = queries
def do_who(self, arg):
"""Show list of people. Add part of a name to narrow down."""
for name i... | import cmd
from functools import partial
from unjabberlib import formatters
trim_print = partial(print, sep='', end='')
class StdoutFormatter(formatters.Formatter):
def append(self, text, format=None):
if format is None or format == formatters.HOUR:
trim_print(text)
elif format == fo... | Use new formatter in cmd | Use new formatter in cmd
| Python | mit | adsr303/unjabber |
27758120f39c95d1040e7b6708808cc996363a3f | setup.py | setup.py | from distutils.core import setup
setup(
name='django-robots',
version=__import__('robots').__version__,
description='Robots exclusion application for Django, complementing Sitemaps.',
long_description=open('docs/overview.txt').read(),
author='Jannis Leidel',
author_email='jannis@leidel.info',
... | from distutils.core import setup
setup(
name='django-robots',
version=__import__('robots').__version__,
description='Robots exclusion application for Django, complementing Sitemaps.',
long_description=open('docs/overview.txt').read(),
author='Jannis Leidel',
author_email='jannis@leidel.info',
... | Remove download URL since Github doesn't get his act together. Damnit | Remove download URL since Github doesn't get his act together. Damnit
committer: Jannis Leidel <9b7c7d158dc2d8ee5ad777a516c517e4cfb54547@leidel.info>
| Python | bsd-3-clause | Jythoner/django-robots,Jythoner/django-robots |
952969952b835896e69f842aee711a58dc14a379 | setup.py | setup.py | from distutils.core import setup
# If sphinx is installed, enable the command
try:
from sphinx.setup_command import BuildDoc
cmdclass = {'build_sphinx': BuildDoc}
command_options = {
'build_sphinx': {
'version': ('setup.py', version),
'release': ('setup.py', version),
... | from distutils.core import setup
version = '1.0.2'
# If sphinx is installed, enable the command
try:
from sphinx.setup_command import BuildDoc
cmdclass = {'build_sphinx': BuildDoc}
command_options = {
'build_sphinx': {
'version': ('setup.py', version),
'release': ('setu... | Make sphinx building actually work | Make sphinx building actually work
| Python | lgpl-2.1 | ianweller/python-simplemediawiki,YSelfTool/python-simplemediawiki,lahwaacz/python-simplemediawiki |
c96b318166c19b644071386380e3b9b6b32deae6 | tests/test_config.py | tests/test_config.py | import unittest
import figgypy.config
import sys
import os
class TestConfig(unittest.TestCase):
def test_config_load(self):
os.environ['FIGGY_GPG_HOME']='tests/resources/test-keys'
c = figgypy.config.Config('tests/resources/test-config.yaml')
self.assertEqual(c.db, 'db.heck.ya')
se... | import unittest
import figgypy.config
import sys
import os
class TestConfig(unittest.TestCase):
def test_config_load(self):
os.environ['FIGGY_GPG_HOME']='tests/resources/test-keys'
c = figgypy.config.Config('tests/resources/test-config.yaml')
self.assertEqual(c.db['host'], 'db.heck.ya')
... | Modify to test with nesting | Modify to test with nesting
| Python | mit | theherk/figgypy |
5502a0be6f419990b95480c5d92d0bc594783c80 | tests/test_redgem.py | tests/test_redgem.py | from pytfa.redgem.redgem import RedGEM
from pytfa.io import import_matlab_model
from pytfa.io.base import load_thermoDB
from pytfa.thermo.tmodel import ThermoModel
from pytfa.io import read_compartment_data, apply_compartment_data, read_lexicon, annotate_from_lexicon
path_to_model = 'models/small_ecoli.mat'
thermo... | from pytfa.redgem.redgem import RedGEM
from pytfa.io import import_matlab_model
from pytfa.io.base import load_thermoDB
from pytfa.thermo.tmodel import ThermoModel
from pytfa.io import read_compartment_data, apply_compartment_data, read_lexicon, annotate_from_lexicon
path_to_model = 'models/small_ecoli.mat'
thermoD... | Remove unused parameters in test script | FIX: Remove unused parameters in test script
| Python | apache-2.0 | EPFL-LCSB/pytfa,EPFL-LCSB/pytfa |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.