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 |
|---|---|---|---|---|---|---|---|---|---|
f7a9f65e68b2fe78a0180acb1b2bef552e9633f3 | media/collector.py | media/collector.py | import feedparser
import pickle
import requests
hub = "http://feeds.feedburner.com/ampparit-politiikka" ## collect from ampparit all politics related sites
feed = feedparser.parse( hub )
stored = []
try:
stored = pickle.load( open( '.history' , 'r' ) )
except:
pass
stored = []
out = open( 'urls.txt' , 'a'... | import feedparser
import pickle
import requests
import sys
hub = "http://feeds.feedburner.com/ampparit-politiikka" ## collect from ampparit all politics related sites
feed = feedparser.parse( hub )
stored = []
path = sys.argv[0]
try:
stored = pickle.load( open( path + '/.history' , 'r' ) )
except:
pass
... | Make path variable working for server side | Make path variable working for server side
| Python | mit | HIIT/digivaalit-2015,HIIT/digivaalit-2015,HIIT/digivaalit-2015 |
19a8a0e2f85b7ab01cbd3e2dd283e8e1e9b97373 | example/example/tasksapp/run_tasks.py | example/example/tasksapp/run_tasks.py | import time
from dj_experiment.tasks.tasks import longtime_add
if __name__ == '__main__':
result = longtime_add.delay(1, 2)
# at this time, our task is not finished, so it will return False
print 'Task finished? ', result.ready()
print 'Task result: ', result.result
# sleep 10 seconds to ensure th... | import time
from dj_experiment.tasks.tasks import longtime_add, netcdf_save
if __name__ == '__main__':
result = longtime_add.delay(1, 2)
# at this time, our task is not finished, so it will return False
print 'Task finished? ', result.ready()
print 'Task result: ', result.result
# sleep 10 seconds... | Add the use of task to the example app | Add the use of task to the example app
| Python | mit | francbartoli/dj-experiment,francbartoli/dj-experiment |
332f275b3ac4b93c523b474c94268bac834c180c | memorize/models.py | memorize/models.py | from datetime import datetime, timedelta
import datetime
from django.utils.timezone import utc
from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from .algorithm import interval
class Pra... | from datetime import datetime, timedelta
from django.utils.timezone import utc
from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from .algorithm import interval
class Practice(models.Mo... | Fix datetime usage in memorize model | Fix datetime usage in memorize model
| Python | mit | DummyDivision/Tsune,DummyDivision/Tsune,DummyDivision/Tsune |
8c7daf1c0e140cb68c425b34eb60d9b001fd7063 | fiduswriter/base/management/commands/jest.py | fiduswriter/base/management/commands/jest.py | from pathlib import Path
import shutil
from subprocess import call
from django.core.management.base import BaseCommand
from django.core.management import call_command
from django.conf import settings
BABEL_CONF = '''
module.exports = {
presets: [
[
'@babel/preset-env',
{
... | from pathlib import Path
import shutil
from subprocess import call
from django.core.management.base import BaseCommand
from django.core.management import call_command
from django.conf import settings
BABEL_CONF = '''
module.exports = {
presets: [
[
'@babel/preset-env',
{
... | Make test suite pass when there are no tests | Make test suite pass when there are no tests
| Python | agpl-3.0 | fiduswriter/fiduswriter,fiduswriter/fiduswriter,fiduswriter/fiduswriter,fiduswriter/fiduswriter |
d6500b3d9af37fb2cd0fa14c82f78b165f9d221b | test_framework/test_settings.py | test_framework/test_settings.py | from .settings import * # NOQA
# Django 1.8 still has INSTALLED_APPS as a tuple
INSTALLED_APPS = list(INSTALLED_APPS)
INSTALLED_APPS.append('djoyapp')
| from .settings import * # NOQA
INSTALLED_APPS.append('djoyapp')
| Remove handling of apps tuple, it is always list now | Remove handling of apps tuple, it is always list now
Since Django 1.11, app settings are lists by default
| Python | mit | jamescooke/factory_djoy |
46af8faf699d893a95ecec402030ef74e07e77ed | recharges/tasks.py | recharges/tasks.py | import requests
from django.conf import settings
from celery.task import Task
from celery.utils.log import get_task_logger
from .models import Account
logger = get_task_logger(__name__)
class Hotsocket_Login(Task):
"""
Task to get the username and password varified then produce a token
"""
name = ... | import requests
from django.conf import settings
from celery.task import Task
from celery.utils.log import get_task_logger
from .models import Account
logger = get_task_logger(__name__)
class Hotsocket_Login(Task):
"""
Task to get the username and password varified then produce a token
"""
name = ... | Update login task to get username from settings | Update login task to get username from settings
| Python | bsd-3-clause | westerncapelabs/gopherairtime,westerncapelabs/gopherairtime |
aeefef1f80ba92c7900c95c436b61b019d8ffb6a | src/waldur_mastermind/marketplace_openstack/migrations/0011_limit_components.py | src/waldur_mastermind/marketplace_openstack/migrations/0011_limit_components.py | from django.db import migrations
TENANT_TYPE = 'Packages.Template'
LIMIT = 'limit'
def process_components(apps, schema_editor):
OfferingComponent = apps.get_model('marketplace', 'OfferingComponent')
OfferingComponent.objects.filter(offering__type=TENANT_TYPE).update(
billing_type=LIMIT
)
class ... | from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('marketplace_openstack', '0010_split_invoice_items'),
]
| Remove invalid migration script: it has been superceded by 0052_limit_components | Remove invalid migration script: it has been superceded by 0052_limit_components
| Python | mit | opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur |
353ad2e4d03d5ad5a8c5a1e949e8cd3251c7d85b | holviapi/tests/test_api_idempotent.py | holviapi/tests/test_api_idempotent.py | # -*- coding: utf-8 -*-
import os
import pytest
import holviapi
@pytest.fixture
def connection():
pool = os.environ.get('HOLVI_POOL', None)
key = os.environ.get('HOLVI_KEY', None)
if not pool or not key:
raise RuntimeError("HOLVI_POOL and HOLVI_KEY must be in ENV for these tests")
cnc = holviap... | # -*- coding: utf-8 -*-
import os
import pytest
import holviapi
@pytest.fixture
def connection():
pool = os.environ.get('HOLVI_POOL', None)
key = os.environ.get('HOLVI_KEY', None)
if not pool or not key:
raise RuntimeError("HOLVI_POOL and HOLVI_KEY must be in ENV for these tests")
cnc = holviap... | Test getting invoice by code | Test getting invoice by code
| Python | mit | rambo/python-holviapi,rambo/python-holviapi |
745c03d3cc5ae31fb852ba7bfc9d0ad6a9ac4716 | unittests.py | unittests.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import const
import uniformdh
import obfsproxy.network.buffer as obfs_buf
class UniformDHTest( unittest.TestCase ):
def setUp( self ):
weAreServer = True
self.udh = uniformdh.new("A" * const.SHARED_SECRET_LENGTH, weAreServer)
de... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import const
import uniformdh
import obfsproxy.network.buffer as obfs_buf
class UniformDHTest( unittest.TestCase ):
def setUp( self ):
weAreServer = True
self.udh = uniformdh.new("A" * const.SHARED_SECRET_LENGTH, weAreServer)
de... | Add UniformDH unit test to test for invalid HMACs. | Add UniformDH unit test to test for invalid HMACs.
| Python | bsd-3-clause | isislovecruft/scramblesuit,isislovecruft/scramblesuit |
da47bca1bbdffff536d240cafe780533ee79809e | mesh.py | mesh.py | #!/usr/bin/env python3
import os
import shutil
import sys
import readline
import traceback
readline.parse_and_bind('tab: complete')
readline.parse_and_bind('set editing-mode vi')
builtin_cmds = {'cd', 'pwd', 'exit',}
def prompt():
return '%s$ ' % os.getcwd()
def read_command():
line = input(prompt())
re... | #!/usr/bin/env python3
import os
import shutil
import sys
import readline
import traceback
readline.parse_and_bind('tab: complete')
readline.parse_and_bind('set editing-mode vi')
builtin_cmds = {'cd', 'pwd', 'exit',}
def prompt():
return '%s$ ' % os.getcwd()
def read_command():
line = input(prompt())
re... | Handle ctrl-c and ctrl-d properly | Handle ctrl-c and ctrl-d properly
| Python | mit | mmichie/mesh |
6c932dc133ca2e6608297a93489e5c57ad73d5c2 | models/fallahi_eval/evidence_sources.py | models/fallahi_eval/evidence_sources.py | from util import pklload
from collections import defaultdict
import indra.tools.assemble_corpus as ac
if __name__ == '__main__':
# Load cached Statements just before going into the model
stmts = pklload('pysb_stmts')
# Start a dictionary for source counts
sources_count = defaultdict(int)
# Count ... | from util import pklload
from collections import defaultdict
import indra.tools.assemble_corpus as ac
if __name__ == '__main__':
# Load cached Statements just before going into the model
stmts = pklload('pysb_stmts')
# Start a dictionary for source counts
sources_count = defaultdict(int)
# Count ... | Fix some things in evidence sources | Fix some things in evidence sources
| Python | bsd-2-clause | johnbachman/belpy,sorgerlab/indra,johnbachman/indra,johnbachman/belpy,sorgerlab/belpy,pvtodorov/indra,bgyori/indra,pvtodorov/indra,pvtodorov/indra,sorgerlab/indra,sorgerlab/belpy,johnbachman/belpy,sorgerlab/belpy,pvtodorov/indra,johnbachman/indra,sorgerlab/indra,bgyori/indra,johnbachman/indra,bgyori/indra |
ee485b086e66f6c423e6c9b728d43a6ace071d55 | Lib/test/test_frozen.py | Lib/test/test_frozen.py | # Test the frozen module defined in frozen.c.
from __future__ import with_statement
from test.test_support import captured_stdout, run_unittest
import unittest
import sys, os
class FrozenTests(unittest.TestCase):
def test_frozen(self):
with captured_stdout() as stdout:
try:
im... | # Test the frozen module defined in frozen.c.
from __future__ import with_statement
from test.test_support import captured_stdout, run_unittest
import unittest
import sys, os
class FrozenTests(unittest.TestCase):
def test_frozen(self):
with captured_stdout() as stdout:
try:
im... | Make it possible to run this test stand-alone. | Make it possible to run this test stand-alone.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator |
61f710b64f32da26bd36c7c95a3f46e4d21c991a | modules/output_statistics.py | modules/output_statistics.py | from pysqlite2 import dbapi2 as sqlite
import sys, os.path
class Statistics:
def __init__(self):
self.total = 0
self.passed = 0
self.failed = 0
def register(self, manager, parser):
manager.register(instance=self, event='input', keyword='stats', callback=self.input, order=65535)... | import sys, os.path
has_sqlite = True
try:
from pysqlite2 import dbapi2 as sqlite
except:
has_sqlite = False
class Statistics:
def __init__(self):
self.total = 0
self.passed = 0
self.failed = 0
def register(self, manager, parser):
manager.register(instance=self, event=... | Check that python-sqlite2 is installed | Check that python-sqlite2 is installed
git-svn-id: ad91b9aa7ba7638d69f912c9f5d012e3326e9f74@147 3942dd89-8c5d-46d7-aeed-044bccf3e60c
| Python | mit | asm0dey/Flexget,gazpachoking/Flexget,vfrc2/Flexget,X-dark/Flexget,ianstalk/Flexget,patsissons/Flexget,tvcsantos/Flexget,ibrahimkarahan/Flexget,Flexget/Flexget,ibrahimkarahan/Flexget,lildadou/Flexget,LynxyssCZ/Flexget,antivirtel/Flexget,drwyrm/Flexget,jawilson/Flexget,offbyone/Flexget,ZefQ/Flexget,thalamus/Flexget,malka... |
62c5e911689555c62931692e0d6ff87ed7340559 | src/models/split.py | src/models/split.py | # Third-party modules
import numpy as np
import pandas as pd
from sklearn.model_selection import KFold
# Hand-made modules
from .base import BloscpackMixin
KWARGS_READ_CSV = {
"sep": "\t",
"header": 0,
"parse_dates": [0],
"index_col": 0
}
class ValidationSplitHandler(BloscpackMixin):
def __init__... | # Third-party modules
import numpy as np
import pandas as pd
from sklearn.model_selection import KFold
# Hand-made modules
from .base import PathHandlerBase, BloscpackMixin
KWARGS_READ_CSV = {
"sep": "\t",
"header": 0,
"parse_dates": [0],
"index_col": 0
}
KWARGS_TO_CSV = {
"sep": "\t"
}
OBJECTIVE_L... | Adjust to current serialization conditions | Adjust to current serialization conditions
+ blp -> tsv
| Python | mit | gciteam6/xgboost,gciteam6/xgboost |
f081906482bf080363dd494a6ab0ca6ed63b49f5 | loremipsum/tests/plugs_testpackage/plugin.py | loremipsum/tests/plugs_testpackage/plugin.py | """Test plugin."""
def load(*args, **kwargs):
pass
def dump(*args, **kwargs):
pass
def plugin():
import sys
return (__name__.split('.')[-1], sys.modules.get(__name__))
| """Test plugin.
def load(*args, **kwargs): pass
def dump(*args, **kwargs): pass
def plugin():
return (__name__.split('.')[-1], sys.modules.get(__name__))
"""
| Put useless module function into docstring | Put useless module function into docstring
| Python | bsd-3-clause | monkeython/loremipsum |
2551eb35f2d5c5b95952b40c2583468a8deb5565 | pylib/djangoproj/binalerts/tests.py | pylib/djangoproj/binalerts/tests.py | """
Integration-style tests for binalerts. These tests think of things from the web
frontend point of view. They are designed to make sure the application behaves
as required to the user.
"""
# Various tips on testing forms:
# http://stackoverflow.com/questions/2257958/django-unit-testing-for-form-edit
from django.te... | """
Integration-style tests for binalerts. These tests think of things from the web
frontend point of view. They are designed to make sure the application behaves
as required to the user.
"""
# Various tips on testing forms:
# http://stackoverflow.com/questions/2257958/django-unit-testing-for-form-edit
from django.te... | Test for error if not a postcode. | Test for error if not a postcode.
| Python | agpl-3.0 | mysociety/binalerts,mysociety/binalerts,mysociety/binalerts |
b740490e49b775809cb99b4cf30e3b7cf259d8f6 | superdesk/io/__init__.py | superdesk/io/__init__.py | """Superdesk IO"""
from abc import ABCMeta, abstractmethod
import superdesk
import logging
from superdesk.celery_app import celery
providers = {}
allowed_providers = []
logger = logging.getLogger(__name__)
from .commands.update_ingest import UpdateIngest
from .commands.add_provider import AddProvider # NOQA
def ... | """Superdesk IO"""
from abc import ABCMeta, abstractmethod
import superdesk
import logging
from superdesk.celery_app import celery
providers = {}
allowed_providers = []
logger = logging.getLogger(__name__)
from .commands.remove_expired_content import RemoveExpiredContent
from .commands.update_ingest import UpdateIn... | Revert "fix(ingest) - disable expired content removal" | Revert "fix(ingest) - disable expired content removal"
This reverts commit 281e051344c9fe8e835941117e2d2068ecdabd87.
| Python | agpl-3.0 | mdhaman/superdesk,akintolga/superdesk-aap,ioanpocol/superdesk-ntb,marwoodandrew/superdesk,marwoodandrew/superdesk-aap,marwoodandrew/superdesk-aap,plamut/superdesk,darconny/superdesk,darconny/superdesk,superdesk/superdesk,amagdas/superdesk,hlmnrmr/superdesk,mdhaman/superdesk-aap,sivakuna-aap/superdesk,liveblog/superdesk... |
23075e994d081a90a1b3ed48b7e30b82c4614854 | tests/test_acf.py | tests/test_acf.py | import pytest
from steamfiles import acf
@pytest.yield_fixture
def acf_data():
with open('tests/test_data/appmanifest_202970.acf', 'rt') as f:
yield f.read()
@pytest.mark.usefixtures('acf_data')
def test_loads_dumps(acf_data):
assert acf.dumps(acf.loads(acf_data)) == acf_data
| import io
import pytest
from steamfiles import acf
test_file_name = 'tests/test_data/appmanifest_202970.acf'
@pytest.yield_fixture
def acf_data():
with open(test_file_name, 'rt') as f:
yield f.read()
@pytest.mark.usefixtures('acf_data')
def test_loads_dumps(acf_data):
assert acf.dumps(acf.loads(acf... | Add more tests for ACF format | Add more tests for ACF format
| Python | mit | leovp/steamfiles |
3f57221af38a25dceb9d1024c225481ec2f49328 | parchment/views.py | parchment/views.py | from django.conf import settings
from django.views.generic import FormView
from .crypto import Parchment
from .forms import ParchmentForm
class ParchmentView(FormView):
form_class = ParchmentForm
template_name = 'parchment/login.html'
def get_initial(self):
sso_key = getattr(settings, 'PARCHMENT... | from urllib import urlencode
from django.conf import settings
from django.views.generic import FormView
from .crypto import Parchment
from .forms import ParchmentForm
class ParchmentView(FormView):
form_class = ParchmentForm
template_name = 'parchment/login.html'
connect_variables = {}
def get(self... | Encrypt all provided GET parameters | Encrypt all provided GET parameters
| Python | bsd-3-clause | jbittel/django-parchment,jbittel/django-parchment |
0f2ccc881e8d2b8b0f4064e3e1fae39b14875821 | tortilla/utils.py | tortilla/utils.py | # -*- coding: utf-8 -*-
import six
from formats import FormatBank, discover_json, discover_yaml
formats = FormatBank()
discover_json(formats, content_type='application/json')
discover_yaml(formats, content_type='application/x-yaml')
def run_from_ipython():
try:
__IPYTHON__
return True
exc... | # -*- coding: utf-8 -*-
import six
from formats import FormatBank, discover_json, discover_yaml
formats = FormatBank()
discover_json(formats, content_type='application/json')
discover_yaml(formats, content_type='application/x-yaml')
def run_from_ipython():
return getattr(__builtins__, "__IPYTHON__", False)
... | Refactor run_from_ipython() implementation to make it pass static code analysis test | Refactor run_from_ipython() implementation to make it pass static code analysis test
| Python | mit | redodo/tortilla |
45d442cfe9c737332ca75e68e1488667937015ed | src/repository/models.py | src/repository/models.py | from django.db import models
import git, os
class Github (models.Model):
username = models.CharField(max_length=39)
repository = models.CharField(max_length=100)
def __str__(self):
return self.repository
def clone_repository(self):
DIR_NAME = self.repository
REMOTE_URL = "http... | from django.db import models
from django.conf import settings
import git, os
class Github (models.Model):
username = models.CharField(max_length=39)
repository = models.CharField(max_length=100)
def __str__(self):
return self.repository
def clone_repository(self):
DIR_NAME = os.path.j... | Clone repository to playbooks directory | Clone repository to playbooks directory
| Python | bsd-3-clause | lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin |
ca43660869bbd390979a928dc219e016c1a0607a | api/route_settings.py | api/route_settings.py | import json
import falcon
import models
import schemas
import api_util
settings_schema = schemas.SettingSchema(many=True)
setting_schema = schemas.SettingSchema()
class SettingsResource:
def on_get(self, req, resp):
settings = models.Setting.select()
settings_dict = {}
for setting in... | import json
import falcon
import models
import schemas
import api_util
class SettingsResource:
def on_get(self, req, resp):
settings = models.Setting.select()
settings_dict = {}
for setting in settings:
settings_dict[setting.key] = setting.value
resp.body = api_uti... | Remove reference to now-deleted SettingSchema | Remove reference to now-deleted SettingSchema
| Python | mit | thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline |
b86bcfd1f1762cbb956b3eb42b515107249cb66e | production_settings.py | production_settings.py | from default_settings import *
import dj_database_url
DATABASES = {
'default': dj_database_url.config(),
}
SECRET_KEY = os.environ['SECRET_KEY']
STATICFILES_STORAGE = 's3storage.S3HashedFilesStorage'
AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY', '')
AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_KEY... | from default_settings import *
import dj_database_url
DATABASES = {
'default': dj_database_url.config(),
}
SECRET_KEY = os.environ['SECRET_KEY']
STATICFILES_STORAGE = 's3storage.S3HashedFilesStorage'
AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY', '')
AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_KEY... | Disable querystring auth for s3 | Disable querystring auth for s3
| Python | mit | brutasse/djangopeople,brutasse/djangopeople,django/djangopeople,django/djangopeople,django/djangopeople,brutasse/djangopeople,polinom/djangopeople,polinom/djangopeople,brutasse/djangopeople,polinom/djangopeople,polinom/djangopeople |
51a2ac2d66d4245626f3d8830bb47f596b3d9879 | app/minify.py | app/minify.py | # Python 3
import glob
import os
uglifyjs = os.path.abspath("../lib/uglifyjs")
input_dir = os.path.abspath("./Resources/Tracker/scripts")
output_dir = os.path.abspath("./Resources/Tracker/scripts.min")
for file in glob.glob(input_dir + "/*.js"):
name = os.path.basename(file)
print("Minifying {0}...".format(n... | #!/usr/bin/env python3
import glob
import os
import shutil
import sys
if os.name == "nt":
uglifyjs = os.path.abspath("../lib/uglifyjs.cmd")
else:
uglifyjs = "uglifyjs"
if shutil.which(uglifyjs) is None:
print("Cannot find executable: {0}".format(uglifyjs))
sys.exit(1)
input_dir = os.path.abspath("./... | Fix app minification script on non-Windows systems | Fix app minification script on non-Windows systems
| Python | mit | chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker |
c3c8c566c8294715b07614c1d18a2c6de3a7c212 | app/models.py | app/models.py | from app import db
class User(db.Model):
__tablename__ = 'users'
username = db.Column(db.String(64), nullable=False, unique=True, primary_key=True)
password = db.Column(db.String(192), nullable=False)
def __init__(self, username, password):
self.username = username
self.email = pass... | from app import db
class User(db.Model):
__tablename__ = 'users'
username = db.Column(db.String(64), nullable=False, unique=True, primary_key=True)
password = db.Column(db.String(192), nullable=False)
def __init__(self, username, password):
self.username = username
self.password = p... | Fix variable names in model. | Fix variable names in model.
| Python | mit | jawrainey/atc,jawrainey/atc |
105d46937babb7a43901d8238fb9cc0a7b00c8c9 | lyman/tools/commandline.py | lyman/tools/commandline.py | import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-subjects", nargs="*", dest="subjects",
help=("list of subject ids, name of file in lyman "
"directory, or full path to text file with "
"subject ids"))
parser.add_argument("... | import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-subjects", nargs="*", dest="subjects",
help=("list of subject ids, name of file in lyman "
"directory, or full path to text file with "
"subject ids"))
parser.add_argument("... | Add slurm to command line plugin choices | Add slurm to command line plugin choices
| Python | bsd-3-clause | mwaskom/lyman,tuqc/lyman,kastman/lyman |
ac95449e6774538756d7813d73c8b113f9dcb6e6 | axis/configuration.py | axis/configuration.py | """Python library to enable Axis devices to integrate with Home Assistant."""
import requests
from requests.auth import HTTPDigestAuth
class Configuration(object):
"""Device configuration."""
def __init__(self, *,
loop, host, username, password,
port=80, web_proto='http', ve... | """Python library to enable Axis devices to integrate with Home Assistant."""
import requests
from requests.auth import HTTPDigestAuth
class Configuration(object):
"""Device configuration."""
def __init__(self, *,
loop, host, username, password,
port=80, web_proto='http', v... | Allow to properly disable verification of SSL | Allow to properly disable verification of SSL
| Python | mit | Kane610/axis |
0e30e73ffa928b11fd6ee6c0ea12709100623e5f | pltpreview/view.py | pltpreview/view.py | """Convenience functions for matplotlib plotting and image viewing."""
import numpy as np
from matplotlib import pyplot as plt
def show(image, blocking=False, title='', **kwargs):
"""Show *image*. If *blocking* is False the call is nonblocking. *title*
is the image title. *kwargs* are passed to matplotlib's ... | """Convenience functions for matplotlib plotting and image viewing."""
import numpy as np
from matplotlib import pyplot as plt
def show(image, blocking=False, title='', **kwargs):
"""Show *image*. If *blocking* is False the call is nonblocking. *title*
is the image title. *kwargs* are passed to matplotlib's ... | Use pop for getting blocking parameter | Use pop for getting blocking parameter
| Python | mit | tfarago/pltpreview |
f8b83fc7976768c2b9d92ab35297aa17637eeb92 | firefed/feature/addons.py | firefed/feature/addons.py | import json
from feature import Feature
from output import good, bad, info
from tabulate import tabulate
class Addons(Feature):
def run(self, args):
with open(self.profile_path('extensions.json')) as f:
addons = json.load(f)['addons']
info(('%d addons found. (%d active)\n' %
... | import json
from feature import Feature
from output import good, bad, info
from tabulate import tabulate
def signed_state(num):
# See constants defined in [1]
states = {
-2: 'broken',
-1: 'unknown',
0: 'missing',
1: 'preliminary',
2: 'signed',
3: 'system',
... | Add signature and visibility status to addon feature | Add signature and visibility status to addon feature
| Python | mit | numirias/firefed |
314b8cf14eb3bed9b116b78ce0199e73399a4dab | businesstime/test/holidays/aus_test.py | businesstime/test/holidays/aus_test.py | from datetime import datetime, date, timedelta
import unittest
from businesstime.holidays.aus import QueenslandPublicHolidays, BrisbanePublicHolidays
class QueenslandPublicHolidaysTest(unittest.TestCase):
def test_2016_08(self):
holidays_gen = QueenslandPublicHolidays()
self.assertEqual(
... | from datetime import datetime, date, timedelta
import unittest
from businesstime.holidays.aus import QueenslandPublicHolidays, BrisbanePublicHolidays
class QueenslandPublicHolidaysTest(unittest.TestCase):
def test_2016_08(self):
holidays_gen = QueenslandPublicHolidays()
self.assertEqual(
... | Fix tests in python 2.6 | Fix tests in python 2.6
| Python | bsd-2-clause | seatgeek/businesstime |
f3cdd316f9e0859f77389c68b073134a6076374b | ppp_datamodel_notation_parser/requesthandler.py | ppp_datamodel_notation_parser/requesthandler.py | """Request handler of the module."""
from functools import partial
from ppp_datamodel import Sentence, TraceItem, Response
from ppp_datamodel.parsers import parse_triples, ParseError
def tree_to_response(measures, trace, tree):
trace = trace + [TraceItem('DatamodelNotationParser',
... | """Request handler of the module."""
from functools import partial
from ppp_datamodel import Sentence, TraceItem, Response
from ppp_datamodel.parsers import parse_triples, ParseError
def tree_to_response(tree, measures, trace):
trace = trace + [TraceItem('DatamodelNotationParser',
... | Fix compatibility with new parser. | Fix compatibility with new parser.
| Python | mit | ProjetPP/PPP-DatamodelNotationParser,ProjetPP/PPP-DatamodelNotationParser |
e64b0544b146cb810424e0e243835a34aa977f40 | boxoffice/__init__.py | boxoffice/__init__.py | # -*- coding: utf-8 -*-
# imports in this file are order-sensitive
from pytz import timezone
from flask import Flask
from flask.ext.mail import Mail
from flask.ext.lastuser import Lastuser
from flask.ext.lastuser.sqlalchemy import UserManager
from baseframe import baseframe, assets, Version
from ._version import __vers... | # -*- coding: utf-8 -*-
# imports in this file are order-sensitive
from pytz import timezone
from flask import Flask
from flask.ext.mail import Mail
from flask.ext.lastuser import Lastuser
from flask.ext.lastuser.sqlalchemy import UserManager
from baseframe import baseframe, assets, Version
from ._version import __vers... | Add assests ractive-transitions-fly and validate | Add assests ractive-transitions-fly and validate
| Python | agpl-3.0 | hasgeek/boxoffice,hasgeek/boxoffice,hasgeek/boxoffice,hasgeek/boxoffice |
5736e8314d5af3346a15224b27448f1c795f665c | bin/coverage_check.py | bin/coverage_check.py | #!/usr/bin/env python
import os
import subprocess
from lib import functional
from util import find_all
def coverage_module(package, module):
command = (
'coverage run --branch'
' --source=%s.%s tests/%s/%s_test.py')
print subprocess.check_output(
command % (package, module, package,... | #!/usr/bin/env python
import os
import subprocess
from lib import functional
from util import find_all
def coverage_module(package, module):
command = (
'coverage run --branch'
' --source=%s.%s tests/%s/%s_test.py')
print subprocess.check_output(
command % (package, module, package,... | Remove hard coded 'engine' and 'lib' in coverage testing | Remove hard coded 'engine' and 'lib' in coverage testing
| Python | mit | Tactique/game_engine,Tactique/game_engine |
4dd5dbf6c1f693c54b31a84756350cb9588921d1 | pybinding/model.py | pybinding/model.py | from scipy.sparse import csr_matrix
from . import _cpp
from .system import System
from .lattice import Lattice
from .support.sparse import SparseMatrix
class Model(_cpp.Model):
def __init__(self, *params):
super().__init__()
self.add(*params)
def add(self, *params):
for param in para... | import numpy as np
from scipy.sparse import csr_matrix
from . import _cpp
from . import results
from .system import System
from .lattice import Lattice
from .support.sparse import SparseMatrix
class Model(_cpp.Model):
def __init__(self, *params):
super().__init__()
self.add(*params)
def add(... | Add onsite energy map to Model | Add onsite energy map to Model
| Python | bsd-2-clause | dean0x7d/pybinding,MAndelkovic/pybinding,MAndelkovic/pybinding,dean0x7d/pybinding,dean0x7d/pybinding,MAndelkovic/pybinding |
517c0f2b1f8e6616cc63ec0c3990dcff2922f0e6 | pinax/invitations/admin.py | pinax/invitations/admin.py | from django.contrib import admin
from django.contrib.auth import get_user_model
from .models import InvitationStat, JoinInvitation
User = get_user_model()
class InvitationStatAdmin(admin.ModelAdmin):
raw_id_fields = ["user"]
readonly_fields = ["invites_sent", "invites_accepted"]
list_display = [
... | from django.contrib import admin
from django.contrib.auth import get_user_model
from .models import InvitationStat, JoinInvitation
User = get_user_model()
class InvitationStatAdmin(admin.ModelAdmin):
raw_id_fields = ["user"]
readonly_fields = ["invites_sent", "invites_accepted"]
list_display = [
... | Use f-strings in place of `str.format()` | Use f-strings in place of `str.format()`
| Python | unknown | pinax/pinax-invitations,eldarion/kaleo |
6749c5a4541836fcf25abbc571082b4c909b0bbb | corehq/apps/app_manager/migrations/0019_exchangeapplication_required_privileges.py | corehq/apps/app_manager/migrations/0019_exchangeapplication_required_privileges.py | # Generated by Django 2.2.24 on 2021-09-14 17:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app_manager', '0018_migrate_case_search_labels'),
]
operations = [
migrations.AddField(
model_name='exchangeapplication',
... | # Generated by Django 2.2.24 on 2021-09-14 17:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app_manager', '0018_migrate_case_search_labels'),
]
operations = [
migrations.AddField(
model_name='exchangeapplication',
... | Fix migration with help text | Fix migration with help text
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq |
3291b015a5f3d311c72980913756a08d87b1ac1a | scripts/blacklisted.py | scripts/blacklisted.py | import os
import platform
# If you are adding a new entry, please include a short comment
# explaining why the specific test is blacklisted.
_unix_black_list = set([name.lower() for name in [
'blackparrot',
'blackucode',
'blackunicore',
'earlgrey_nexysvideo', # ram size in ci machines
'lpddr',
'simplepa... | import os
import platform
# If you are adding a new entry, please include a short comment
# explaining why the specific test is blacklisted.
_unix_black_list = set([name.lower() for name in [
'blackparrot',
'blackucode',
'blackunicore',
'earlgrey_nexysvideo', # ram size in ci machines
'lpddr',
'rsd', ... | Exclude a few failing tests | Exclude a few failing tests
Rsd - failing on linux due to running out of memory
Verilator - failing on Windows clang due to stack overflow caused by
expression evaluation
| Python | apache-2.0 | chipsalliance/Surelog,alainmarcel/Surelog,alainmarcel/Surelog,chipsalliance/Surelog,alainmarcel/Surelog,chipsalliance/Surelog,alainmarcel/Surelog,chipsalliance/Surelog |
77fc06c0ee8ca2c8669ca1cd7f45babb21d75ba5 | opps/__init__.py | opps/__init__.py | import pkg_resources
pkg_resources.declare_namespace(__name__) | # See http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages
try:
__import__('pkg_resources').declare_namespace(__name__)
except ImportError:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__) | Remove opps package on opps-polls | Remove opps package on opps-polls
| Python | mit | opps/opps-polls,opps/opps-polls |
fb427a72bf3d8fb3802689bf89a9d71dee47108c | semillas_backend/users/serializers.py | semillas_backend/users/serializers.py | #from phonenumber_field.serializerfields import PhoneNumberField
from rest_framework import serializers
from drf_extra_fields.geo_fields import PointField
from .models import User
class UserSerializer(serializers.ModelSerializer):
""" Usage:
from rest_framework.renderers import JSONRenderer
from ... | #from phonenumber_field.serializerfields import PhoneNumberField
from rest_framework import serializers
from drf_extra_fields.geo_fields import PointField
from .models import User
class UserSerializer(serializers.ModelSerializer):
""" Usage:
from rest_framework.renderers import JSONRenderer
from ... | Add location to user profile post | Add location to user profile post
| Python | mit | Semillas/semillas_backend,Semillas/semillas_backend,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_platform,Semillas/semillas_platform |
e913ed7d5643c4acc85ed7ec82a70c235053360f | tests/test_token.py | tests/test_token.py | """
NOTE: There are no tests that check for data validation at this point since
the interpreter doesn't have any data validation as a feature.
"""
import pytest
from calc import INTEGER, Token
def test_no_defaults():
# There's no valid defaults at the moment.
with pytest.raises(TypeError):
Token()
... | import pytest
from calc import INTEGER, Token
def test_token_cannot_be_instantiated_with_no_defaults():
"""
Test that there are currently no valid defaults for a :class:`Token`. More
simply, ensure that a :class:`Token` cannot be instantiated without any
arguments.
"""
with pytest.raises(Type... | Improve documentation in token tests. Rename functions to be more clear | Improve documentation in token tests. Rename functions to be more clear
| Python | isc | bike-barn/red-green-refactor |
9b043b0bd31f35e140831f61a4484513922f8712 | stop_words/__init__.py | stop_words/__init__.py | import os
__VERSION__ = (2014, 5, 26)
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
STOP_WORDS_DIR = os.path.join(CURRENT_DIR, 'stop-words/')
def get_version():
"""
:rtype: basestring
"""
return ".".join(str(v) for v in __VERSION__)
def get_stop_words(language):
"""
:type langua... | import os
__VERSION__ = (2014, 5, 26)
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
STOP_WORDS_DIR = os.path.join(CURRENT_DIR, 'stop-words/')
LANGUAGE_MAPPING = {
'ar': 'arabic',
'da': 'danish',
'nl': 'dutch',
'en': 'english',
'fi': 'finnish',
'fr': 'french',
'de': 'german',
... | Implement language code mapping and check availability of the language | Implement language code mapping and check availability of the language
| Python | bsd-3-clause | Alir3z4/python-stop-words |
c30bd67d4fc1773ce8b0752d8e4a7cc00e2a7ae4 | app/forms.py | app/forms.py | from flask.ext.wtf import Form
from wtforms import StringField, BooleanField
from wtforms.validators import DataRequired
class LoginForm(Form):
openid = StringField('openid', validators=[DataRequired()])
remember_me = BooleanField('remember_me', default=False)
| from flask.ext.wtf import Form
from wtforms import StringField, BooleanField, TextAreaField
from wtforms.validators import DataRequired, Length
class LoginForm(Form):
openid = StringField('openid', validators=[DataRequired()])
remember_me = BooleanField('remember_me', default=False)
class EditForm(Form):
... | Define the edit profile form | Define the edit profile form
| Python | mit | ddayguerrero/blogme,ddayguerrero/blogme,ddayguerrero/blogme,ddayguerrero/blogme,ddayguerrero/blogme |
1d0dd7856d1c1e80f24a94af4fc323530383b009 | readthedocs/gold/models.py | readthedocs/gold/models.py | from django.db import models
from django.utils.translation import ugettext_lazy as _
LEVEL_CHOICES = (
('v1-org-patron', '$5'),
('v1-org-supporter', '$10'),
)
class GoldUser(models.Model):
pub_date = models.DateTimeField(_('Publication date'), auto_now_add=True)
modified_date = models.DateTimeField(_... | from django.db import models
from django.utils.translation import ugettext_lazy as _
LEVEL_CHOICES = (
('v1-org-5', '$5/mo'),
('v1-org-10', '$10/mo'),
('v1-org-15', '$15/mo'),
('v1-org-20', '$20/mo'),
('v1-org-50', '$50/mo'),
('v1-org-100', '$100/mo'),
)
class GoldUser(models.Model):
pub_... | Update plan names and levels | Update plan names and levels
| Python | mit | hach-que/readthedocs.org,istresearch/readthedocs.org,VishvajitP/readthedocs.org,laplaceliu/readthedocs.org,stevepiercy/readthedocs.org,VishvajitP/readthedocs.org,davidfischer/readthedocs.org,jerel/readthedocs.org,clarkperkins/readthedocs.org,soulshake/readthedocs.org,sunnyzwh/readthedocs.org,michaelmcandrew/readthedocs... |
e8aca80abcf8c309c13360c386b9505a595e1998 | app/oauth.py | app/oauth.py | # -*- coding: utf-8 -*-
import logging
import httplib2
import json
import time
import random
from apiclient import errors
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
class OAuth():
__services = dict()
@staticmethod
def getCredentials(email, scopes, ... | # -*- coding: utf-8 -*-
import logging
import httplib2
import json
import time
import random
from apiclient import errors
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
class OAuth():
__services = dict()
@staticmethod
def getCredentials(email, scopes, ... | Revert "Do not cache discovery" | Revert "Do not cache discovery"
This reverts commit fcd37e8228d66230008963008a24e9a8afc669e7.
| Python | mit | lumapps/lumRest |
eb2f19a95175d68c5ac5345d38c8ce8db3b3ba9c | packs/linux/actions/get_open_ports.py | packs/linux/actions/get_open_ports.py | import nmap
from st2actions.runners.pythonrunner import Action
"""
Note: This action requires nmap binary to be available and needs to run as root.
"""
class PortScanner(Action):
def run(self, host):
result = []
port_details = {}
ps = nmap.PortScanner()
scan_res = ps.scan(host, arguments='--min-pa... | import nmap
from st2actions.runners.pythonrunner import Action
"""
Note: This action requires nmap binary to be available and needs to run as root.
"""
class PortScanner(Action):
def run(self, host):
result = []
port_details = {}
ps = nmap.PortScanner()
scan_res = ps.scan(host, arguments='--min-pa... | Remove unused main entry point. | Remove unused main entry point.
| Python | apache-2.0 | pinterb/st2contrib,psychopenguin/st2contrib,tonybaloney/st2contrib,jtopjian/st2contrib,StackStorm/st2contrib,pearsontechnology/st2contrib,psychopenguin/st2contrib,lmEshoo/st2contrib,lmEshoo/st2contrib,meirwah/st2contrib,pidah/st2contrib,armab/st2contrib,tonybaloney/st2contrib,pearsontechnology/st2contrib,digideskio/st2... |
0024b8b921d788a0539bc242bd1600c0da666bd6 | panoptes/state_machine/states/core.py | panoptes/state_machine/states/core.py | import time
import transitions
from panoptes.utils.logger import has_logger
@has_logger
class PanState(transitions.State):
""" Base class for PANOPTES transitions """
def __init__(self, *args, **kwargs):
name = kwargs.get('name', self.__class__)
self.panoptes = kwargs.get('panoptes', None)... | import time
import transitions
from panoptes.utils.logger import has_logger
@has_logger
class PanState(transitions.State):
""" Base class for PANOPTES transitions """
def __init__(self, *args, **kwargs):
name = kwargs.get('name', self.__class__)
self.panoptes = kwargs.get('panoptes', None)... | Remove return state from main `main` | Remove return state from main `main`
| Python | mit | panoptes/POCS,panoptes/POCS,joshwalawender/POCS,AstroHuntsman/POCS,joshwalawender/POCS,joshwalawender/POCS,panoptes/POCS,panoptes/POCS,AstroHuntsman/POCS,AstroHuntsman/POCS,AstroHuntsman/POCS |
b529ef8eb6985103e8b0a0cf81399a50a26c05f5 | app/views.py | app/views.py | from app import mulungwishi_app as url
from flask import render_template
@url.route('/')
def index():
return render_template('index.html')
@url.route('/<query>')
def print_user_input(query):
if '=' in query:
query_container, query_value = query.split('=')
return 'Your query is {} which is eq... | from app import mulungwishi_app as url
from flask import render_template
@url.route('/')
def index():
return render_template('index.html')
@url.route('/<query>')
def print_user_input(query):
if '=' in query:
query_container, query_value = query.split('=')
return 'Your query is {} which is eq... | Replace 404 redirection for incorrect query | Replace 404 redirection for incorrect query
| Python | mit | admiral96/mulungwishi-webhook,engagespark/mulungwishi-webhook,engagespark/public-webhooks,engagespark/public-webhooks,admiral96/public-webhooks,admiral96/mulungwishi-webhook,engagespark/mulungwishi-webhook,admiral96/public-webhooks |
e45b3d3a2428d3703260c25b4275359bf6786a37 | launcher.py | launcher.py | from pract2d.game import gamemanager
if __name__ == '__main__':
game = gamemanager.GameManager()
game.run()
| from pract2d.game import gamemanager
from pract2d.core import files
from platform import system
import os
if __name__ == '__main__':
try:
if system() == 'Windows' or not os.environ["PYSDL2_DLL_PATH"]:
os.environ["PYSDL2_DLL_PATH"] = files.get_path()
except KeyError:
pass
game = ... | Set the default sdl2 library locations. | Set the default sdl2 library locations.
| Python | bsd-2-clause | mdsitton/pract2d |
5c90e74139f2735d0b4d62f524eb624780c48847 | scripts/migration/projectorganizer/migrate_projectorganizer.py | scripts/migration/projectorganizer/migrate_projectorganizer.py | """Fixes nodes without is_folder set.
This script must be run from the OSF root directory for the imports to work.
"""
from framework.mongo import database
def main():
database['node'].update({"is_folder": {'$exists': False}}, {'$set': {'is_folder': False}}, multi=True)
print('-----\nDone.')
if __name__ ... | """Fixes nodes without is_folder set.
This script must be run from the OSF root directory for the imports to work.
"""
from framework.mongo import database
def main():
database['node'].update({"is_folder": {'$exists': False}}, {'$set': {'is_folder': False}}, multi=True)
database['node'].update({"is_dashboa... | Update migration to ensure node's have is_dashboard and expanded fields | Update migration to ensure node's have is_dashboard and expanded fields
| Python | apache-2.0 | kushG/osf.io,cwisecarver/osf.io,cldershem/osf.io,caseyrygt/osf.io,ticklemepierce/osf.io,brandonPurvis/osf.io,danielneis/osf.io,rdhyee/osf.io,pattisdr/osf.io,barbour-em/osf.io,Johnetordoff/osf.io,felliott/osf.io,samchrisinger/osf.io,Johnetordoff/osf.io,mfraezz/osf.io,DanielSBrown/osf.io,crcresearch/osf.io,mluke93/osf.io... |
42465957542fe232739d58c2a46098d13fb9c995 | tests/parser_db.py | tests/parser_db.py | from compiler import error, parse
class ParserDB():
"""A class for parsing with memoized parsers."""
parsers = {}
@classmethod
def _parse(cls, data, start='program'):
mock = error.LoggerMock()
try:
parser = cls.parsers[start]
except KeyError:
parser =... | from compiler import error, parse
class ParserDB():
"""A class for parsing with memoized parsers."""
parsers = {}
@classmethod
def _parse(cls, data, start='program'):
mock = error.LoggerMock()
try:
parser = cls.parsers[start]
except KeyError:
parser =... | Clear previous logger state on each call. | ParserDB: Clear previous logger state on each call.
| Python | mit | Renelvon/llama,dionyziz/llama,dionyziz/llama,Renelvon/llama |
c01cef9340a3d55884fe38b60b209dbad5f97ea6 | nova/db/sqlalchemy/migrate_repo/versions/080_add_hypervisor_hostname_to_compute_nodes.py | nova/db/sqlalchemy/migrate_repo/versions/080_add_hypervisor_hostname_to_compute_nodes.py | # Copyright 2012 OpenStack, LLC
#
# 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 by applicable law or agreed ... | # Copyright 2012 OpenStack, LLC
#
# 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 by applicable law or agreed ... | Use sqlalchemy reflection in migration 080 | Use sqlalchemy reflection in migration 080
Change-Id: If2a0e59461d108d59c6e9907d3db053ba2b44f57
| Python | apache-2.0 | petrutlucian94/nova,adelina-t/nova,DirectXMan12/nova-hacking,sridevikoushik31/nova,gooddata/openstack-nova,alvarolopez/nova,whitepages/nova,thomasem/nova,affo/nova,berrange/nova,eayunstack/nova,mahak/nova,cernops/nova,felixma/nova,apporc/nova,cyx1231st/nova,openstack/nova,klmitch/nova,JianyuWang/nova,CiscoSystems/nova,... |
452955ca8b7ba2ef01fc97800e5f350fee3e3a6e | tvnamer/renamer.py | tvnamer/renamer.py | import re
import os
import pytvdbapi.api as tvdb
class Renamer:
def __init__(self, api_key):
self.tvdb = tvdb.TVDB(api_key)
@staticmethod
def flat_file_list(directory):
directory = os.path.normpath(directory)
for dirpath, dirnames, filenames in os.walk(directory):
fo... | import re
import os
import pytvdbapi.api as tvdb
class Renamer:
def __init__(self, api_key):
self.tvdb = tvdb.TVDB(api_key)
@staticmethod
def flat_file_list(directory):
directory = os.path.normpath(directory)
for dirpath, dirnames, filenames in os.walk(directory):
fo... | Add normalising params from the regex input | Add normalising params from the regex input
| Python | mit | tomleese/tvnamer,thomasleese/tvnamer |
39086b074dbac8d6d743ede09ce3556e4861e5a4 | wdim/client/blob.py | wdim/client/blob.py | import json
import hashlib
from wdim.client.storable import Storable
class Blob(Storable):
HASH_METHOD = 'sha1'
@classmethod
def _create(cls, data):
sha = hashlib(cls.HASH_METHOD, json.dumps(data))
return cls(sha, data)
@classmethod
def _from_document(cls, document):
re... | import json
import hashlib
from wdim import exceptions
from wdim.client import fields
from wdim.client.storable import Storable
class Blob(Storable):
HASH_METHOD = 'sha256'
_id = fields.StringField(unique=True)
data = fields.DictField()
@classmethod
async def create(cls, data):
sha = h... | Reimplement Blob, switch to sha256 | Reimplement Blob, switch to sha256
| Python | mit | chrisseto/Still |
ca7580c12ffefafce1705d60ab74fcb22af18eb4 | examples/python_interop/python_interop.py | examples/python_interop/python_interop.py | #!/usr/bin/env python
# Copyright 2017 Stanford University
#
# 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 by applicabl... | #!/usr/bin/env python
# Copyright 2017 Stanford University
#
# 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 by applicabl... | Update Python example with a task call. | examples: Update Python example with a task call.
| Python | apache-2.0 | StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion |
a839dcaa51cde0bf191cc87ff2cf54bbc483d61e | main.py | main.py | #!/usr/bin/env python
import sys
import json
from pprint import pprint
try:
import requests
except ImportError:
print(
'Script requires requests package. \n'
'You can install it by running "pip install requests"'
)
exit()
API_URL = 'http://jsonplaceholder.typicode.com/posts/'
def get_... | #!/usr/bin/env python
import sys
import json
from pprint import pprint
try:
import requests
except ImportError:
print(
'Script requires requests package. \n'
'You can install it by running "pip install requests"'
)
exit()
API_URL = 'http://jsonplaceholder.typicode.com/posts/'
def get_... | Print all data from posts | Print all data from posts
| Python | mit | sevazhidkov/rest-wrapper |
032bd078b7650905148ceb3adf653d1f78f7e73f | srtm.py | srtm.py | import os
import json
import numpy as np
SAMPLES = 1201 # For SRTM3, use 3601 for SRTM1
def get_elevation(lat, lon):
file = get_file_name(lat, lon)
if file:
return read_elevation_from_file(file, lat, lon)
# Treat it as data void as in SRTM documentation
return -32768
def read_elevation_from... | import os
import json
import numpy as np
SAMPLES = 1201 # For SRTM3, use 3601 for SRTM1
HGTDIR = 'hgt' # All 'hgt' files will be kept here uncompressed
def get_elevation(lat, lon):
file = get_file_name(lat, lon)
if file:
return read_elevation_from_file(file, lat, lon)
# Treat it as data void as in... | Add HGTDIR to store hgt files inside a directory | Add HGTDIR to store hgt files inside a directory
| Python | mit | aatishnn/srtm-python |
1bf15bca7a492bf874dccab08e24df053b7a859f | mesh.py | mesh.py | import os
import sys
import traceback
builtin_cmds = {'cd', 'pwd',}
def prompt():
print '%s $ ' % os.getcwd(),
def read_command():
return sys.stdin.readline()
def parse_command(cmd_text):
return (cmd_text, cmd_text.strip().split())
def record_command(command):
return True
def run_builtin(cmd):
... | #!/usr/bin/env python3
import os
import shutil
import sys
import traceback
builtin_cmds = {'cd', 'pwd', 'exit',}
def prompt():
print('%s $ ' % os.getcwd(), end='', flush=True)
def read_command():
return sys.stdin.readline()
def parse_command(cmd_text):
return (cmd_text, cmd_text.strip().split())
def r... | Switch to Python 3, add exit built_in | Switch to Python 3, add exit built_in
| Python | mit | mmichie/mesh |
35d5ca76a0c7f63545d2e8bc6b877c78ba9eab1d | tests/adapter/_path.py | tests/adapter/_path.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
def fix():
p = os.path.join(os.path.dirname(__file__), '../../src/')
if p not in sys.path:
sys.path.insert(0, p)
if "__main__" == __name__:
fix()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from unittest import mock
except ImportError:
import mock
def fix():
p = os.path.join(os.path.dirname(__file__), '../../src/')
if p not in sys.path:
sys.path.insert(0, p)
if "__main__" == __name__:
fix()
| Make 'mock' mocking library available for test cases stored under 'tests/adapter' | Make 'mock' mocking library available for test cases stored under 'tests/adapter'
| Python | bsd-3-clause | michalbachowski/pygrapes,michalbachowski/pygrapes,michalbachowski/pygrapes |
3e843b9d0474657eeefc896b06e50968defb2514 | wsgi.py | wsgi.py | # Yith Library Server is a password storage server.
# Copyright (C) 2015 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# This file is part of Yith Library Server.
#
# Yith Library Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as publ... | # Yith Library Web Client is a client for Yith Library Server.
# Copyright (C) 2015 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# This file is part of Yith Library Web Client.
#
# Yith Library Web Client is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Pub... | Fix project name in license section | Fix project name in license section
| Python | agpl-3.0 | lorenzogil/yith-library-web-client,ablanco/yith-library-web-client,ablanco/yith-library-web-client,lorenzogil/yith-library-web-client,ablanco/yith-library-web-client,ablanco/yith-library-web-client,lorenzogil/yith-library-web-client,lorenzogil/yith-library-web-client |
cadab3fef1e95c0b186dc28860ac4797243fdf22 | tests/test_visualization.py | tests/test_visualization.py | from tornado.httpclient import HTTPRequest
import json
import os.path
import json
import shutil
from xml.etree import ElementTree as ET
from util import generate_filename
from util import make_trace_folder
from tests.base import BaseRecorderTestCase
class VisualizationTestCase(BaseRecorderTestCase):
def test_no... | from tornado.httpclient import HTTPRequest
import json
import os.path
import json
import shutil
from xml.etree import ElementTree as ET
from util import generate_filename
from util import make_trace_folder
from tests.base import BaseRecorderTestCase
class VisualizationTestCase(BaseRecorderTestCase):
def test_no... | Update test case for visualization page. | Update test case for visualization page.
| Python | bsd-3-clause | openxc/web-logging-example,openxc/web-logging-example |
28cdad6e8ab6bd400ef50331a2f93af93620cc7f | app/models.py | app/models.py | from django.db import models
class Event(models.Model):
when = models.DateTimeField(auto_now=True)
what = models.TextField()
| from django.db import models
class Event(models.Model):
when = models.DateTimeField(auto_now=True)
what = models.TextField()
def time(self):
return '{:%H:%M}'.format(self.when)
| Return human-sensible time in Event | Return human-sensible time in Event
| Python | mit | schatten/logan |
4184d968668ebd590d927aea7ecbaf7088473cb5 | bot/action/util/reply_markup/inline_keyboard/button.py | bot/action/util/reply_markup/inline_keyboard/button.py | class InlineKeyboardButton:
def __init__(self, data: dict):
self.data = data
@staticmethod
def switch_inline_query(text: str, query: str = "", current_chat: bool = True):
switch_inline_query_key = "switch_inline_query_current_chat" if current_chat else "switch_inline_query"
return I... | class InlineKeyboardButton:
def __init__(self, data: dict):
self.data = data
@staticmethod
def create(text: str,
url: str = None,
callback_data: str = None,
switch_inline_query: str = None,
switch_inline_query_current_chat: str = None):
... | Add create static method to InlineKeyboardButton with all possible parameters | Add create static method to InlineKeyboardButton with all possible parameters
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot |
9c281ff44d6a28962897f4ca8013a539d7f08040 | src/libcask/network.py | src/libcask/network.py | import subprocess
class SetupNetworkMixin(object):
def _setup_hostname(self):
with self.get_attachment(['uts']).attach():
subprocess.check_call(['hostname', self.hostname])
def _setup_virtual_ethernet(self):
veth_name = 'veth-{hostname}'.format(hostname=self.hostname)
veth... | import subprocess
class SetupNetworkMixin(object):
def _setup_hostname(self):
with self.get_attachment(['uts']).attach():
subprocess.check_call(['hostname', self.hostname])
def _setup_virtual_ethernet(self):
veth_name = 'veth-{name}'.format(name=self.name)
veth_host_name =... | Use container names, rather than hostnames, for virtual ethernet interface names | Use container names, rather than hostnames, for virtual ethernet interface names
Container names are guaranteed to be unique, but hostnames are not
| Python | mit | ianpreston/cask,ianpreston/cask |
edd21fc76068894de1001a163885291c3b2cfadb | tests/factories.py | tests/factories.py | from django.conf import settings
from django.contrib.auth.models import User
import factory
from website.models import Db, Query
class TagsFactory(factory.DjangoModelFactory):
class Meta:
abstract = True
@factory.post_generation
def tags(self, create, extracted):
if create and extracted:... | from django.conf import settings
from django.contrib.auth.models import User
import factory
from website.models import Db, Query
class TagsFactory(factory.DjangoModelFactory):
class Meta:
abstract = True
@factory.post_generation
def tags(self, create, extracted):
if create and extracted:... | Make default QueryFactory return data (fixes test) | Make default QueryFactory return data (fixes test)
| Python | mit | sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz |
3fc45407eaba1452092a364eeb676bdaab6d5edc | polling_stations/apps/councils/migrations/0005_geom_not_geog.py | polling_stations/apps/councils/migrations/0005_geom_not_geog.py | # Generated by Django 2.2.10 on 2020-02-14 14:41
import django.contrib.gis.db.models.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("councils", "0004_auto_20200203_1040"),
]
operations = [
migrations.AlterField(
model_name="c... | # Generated by Django 2.2.10 on 2020-02-14 14:41
# Amended by Will on 2021-04-11
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("councils", "0004_auto_20200203_1040"),
]
operations = [
migrations.RunSQL(
'ALTER TABLE "councils_counc... | Fix council migration using explicit type cast | Fix council migration using explicit type cast
The generated SQL for this doesn't include the 'USING' section. It seems
like this is now needed.
| Python | bsd-3-clause | DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations |
653832ebc7b18599b9aab2f230b190b14e71cd3d | models.py | models.py | from google.appengine.ext import db
class User(db.Model):
name = db.UserProperty(auto_current_user = True, auto_current_user_add = True)
date = db.DateTimeProperty(auto_now = True, auto_now_add = True)
#token = db.StringProperty()
services = db.StringListProperty()
| class User(db.Model):
name = db.UserProperty(auto_current_user = True, auto_current_user_add = True)
date = db.DateTimeProperty(auto_now = True, auto_now_add = True)
#token = db.StringProperty()
services = db.StringListProperty()
| Clean import modules hey hey. | Clean import modules hey hey.
| Python | mpl-2.0 | BYK/fb2goog,BYK/fb2goog,BYK/fb2goog |
97b6894671c0906393aea5aa43e632a35bd2aa27 | penchy/tests/test_util.py | penchy/tests/test_util.py | import os
import unittest2
from penchy import util
class ClasspathTest(unittest2.TestCase):
def test_valid_options(self):
expected = 'foo:bar:baz'
options = ['-cp', expected]
self.assertEquals(util.extract_classpath(options), expected)
expected = 'foo:bar:baz'
options = [... | import os
import unittest2
from penchy import util
class ClasspathTest(unittest2.TestCase):
def test_valid_options(self):
expected = 'foo:bar:baz'
options = ['-cp', expected]
self.assertEquals(util.extract_classpath(options), expected)
expected = 'foo:bar:baz'
options = [... | Check if tempdir returns to former cwd. | tests: Check if tempdir returns to former cwd.
Signed-off-by: Michael Markert <5eb998b7ac86da375651a4cd767b88c9dad25896@googlemail.com>
| Python | mit | fhirschmann/penchy,fhirschmann/penchy |
754f5c968ad1dff3ae7f602d23baac1299731062 | update_filelist.py | update_filelist.py | #!/usr/bin/python3
import os
import re
import subprocess
dir_path = os.path.dirname(os.path.realpath(__file__))
filename = 'chatterino.pro'
data = ""
with open(filename, 'r') as project:
data = project.read()
sources = subprocess.getoutput("find ./src -type f -regex '.*\.cpp' | sed 's_\./_ _g'")
sourc... | #!/usr/bin/python3
import os
import re
import subprocess
dir_path = os.path.dirname(os.path.realpath(__file__))
filename = 'chatterino.pro'
data = ""
with open(filename, 'r') as project:
data = project.read()
sources_list = subprocess.getoutput("find ./src -type f -regex '.*\.cpp' | sed 's_\./_ _g'").spli... | Sort file list before writing to project file | Sort file list before writing to project file
Now using the built-in Python `list.sort` method to sort files.
This should ensure consistent behavior on all systems and prevent
unnecessary merge conflicts.
| Python | mit | Cranken/chatterino2,hemirt/chatterino2,fourtf/chatterino2,Cranken/chatterino2,hemirt/chatterino2,Cranken/chatterino2,fourtf/chatterino2,Cranken/chatterino2,fourtf/chatterino2,hemirt/chatterino2,hemirt/chatterino2 |
28cb04ae75a42e6b3ce10972e12166a6cbd84267 | astroquery/sha/tests/test_sha.py | astroquery/sha/tests/test_sha.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from ... import sha
def test_query():
# Example queries for SHA API help page
sha.query(ra=163.6136, dec=-11.784, size=0.5)
sha.query(naifid=2003226)
sha.query(pid=30080)
sha.query(reqkey=21641216)
| # Licensed under a 3-clause BSD style license - see LICENSE.rst
from ... import sha
def test_query():
# Example queries for SHA API help page
pos_t = sha.query(ra=163.6136, dec=-11.784, size=0.5)
nid_t = sha.query(naifid=2003226)
pid_t = sha.query(pid=30080)
rqk_t = sha.query(reqkey=21641216)
#... | Update test for get file | Update test for get file
Commented out the actual get_img calls because they would create a
directoy and download files if run, potentially in parts of the file
system where the user/process does not have the right permissions.
| Python | bsd-3-clause | imbasimba/astroquery,ceb8/astroquery,imbasimba/astroquery,ceb8/astroquery |
b41ce2be52bc3aebf5ad9a737700da0753602670 | parser.py | parser.py | import requests
API_URL = 'https://api.github.com/users/{}/repos'
def main(user):
return parse(request(user))
def request(user):
return requests.get(url=API_URL.format(user))
def parse(response):
repos = response.json()
data = []
if repos is None:
return None
for repo in repos:
... | import requests
import collections
API_URL = 'https://api.github.com/users/{}/repos'
def main(user):
return parse(request(user))
def request(user):
return requests.get(url=API_URL.format(user))
def parse(response):
repos = response.json()
data = []
if repos is None:
return None
fo... | Use OrderedDict for repo data | Use OrderedDict for repo data
| Python | mit | kshvmdn/github-list,kshvmdn/github-list,kshvmdn/github-list |
52a90e320355de503624edf714ff7999aafba062 | blitz/io/signals.py | blitz/io/signals.py | __author__ = 'Will Hart'
from blinker import signal
# fired when a new web client device connects
web_client_connected = signal('client_connected')
# fired when a web client disconnects
web_client_disconnected = signal('client_disconnected')
# fired when a new TCP client device connects
tcp_client_connected = signa... | __author__ = 'Will Hart'
from blinker import signal
# fired when a new web client device connects
web_client_connected = signal('client_connected')
# fired when a web client disconnects
web_client_disconnected = signal('client_disconnected')
# fired when a new TCP client device connects
tcp_client_connected = signa... | Add a boards registering signal to allow the board manager to gather connected boards | Add a boards registering signal to allow the board manager to gather connected boards
| Python | agpl-3.0 | will-hart/blitz,will-hart/blitz |
8292c4afe43ac636ebf23a0740eb06a25fbbb04d | backend/post_handler/__init__.py | backend/post_handler/__init__.py | from flask import Flask
app = Flask(__name__)
@app.route("/", methods=["GET", "POST"])
def hello():
from flask import request
# print dir(request)
# print request.values
sdp_headers = request.form.get('sdp')
with open('./stream.sdp', 'w') as f:
f.write(sdp_headers)
cmd = "ffmpeg -i s... | from flask import Flask
app = Flask(__name__)
@app.route("/", methods=["GET", "POST"])
def hello():
from flask import request
# print dir(request)
# print request.values
sdp_headers = request.form.get('sdp')
with open('./stream.sdp', 'w') as f:
f.write(sdp_headers)
import time
t... | Add uniq filenames for videos | Add uniq filenames for videos
| Python | mit | optimus-team/optimus-video,optimus-team/optimus-video,optimus-team/optimus-video,optimus-team/optimus-video |
07e825b31912a821d116b2a2b394bd041321cd6d | molly/utils/management/commands/deploy.py | molly/utils/management/commands/deploy.py | import os
from optparse import make_option
from django.core.management import call_command
from django.core.management.base import NoArgsCommand
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option('--develop',
action='store_true',
dest='develo... | import os
from optparse import make_option
from django.core.management import call_command
from django.core.management.base import NoArgsCommand
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option('--develop',
action='store_true',
dest='develo... | Deploy should remember to generate markers | Deploy should remember to generate markers
| Python | apache-2.0 | mollyproject/mollyproject,mollyproject/mollyproject,mollyproject/mollyproject |
9c6cb0943381271052e11d35df7c35c677c52cdf | vtimshow/vtimageviewer.py | vtimshow/vtimageviewer.py | #!/usr/bin/env python3
class VtImageViewer:
def __init__(self):
print("Woot!")
| #!/usr/bin/env python3
from . import defaults
from . import __version__
from PyQt4 import QtGui
class VtImageViewer:
"""
"""
UID = defaults.UID
NAME = defaults.PLUGIN_NAME
COMMENT = defaults.COMMENT
def __init__(self, parent=None):
#super(VtImageViewer, self).__init__(parent)
d... | Add initial corrections to class | Add initial corrections to class
Now the class loads and does not crash. I added the help information;
however, it does not do anything yet.
| Python | mit | kprussing/vtimshow |
53204208c30780092f1e21ff0d4d66d7a12930ff | automat/_introspection.py | automat/_introspection.py | """
Python introspection helpers.
"""
from types import CodeType as code, FunctionType as function
def copycode(template, changes):
names = [
"argcount", "nlocals", "stacksize", "flags", "code", "consts",
"names", "varnames", "filename", "name", "firstlineno", "lnotab",
"freevars", "cellv... | """
Python introspection helpers.
"""
from types import CodeType as code, FunctionType as function
def copycode(template, changes):
names = [
"argcount", "nlocals", "stacksize", "flags", "code", "consts",
"names", "varnames", "filename", "name", "firstlineno", "lnotab",
"freevars", "cellv... | Add support for positional only arguments | Add support for positional only arguments
PEP 570 adds "positional only" arguments to Python, which changes the
code object constructor. This adds support for Python 3.8.
Signed-off-by: Robert-André Mauchin <aa2d2b4191fcc92df7813016d4b511c37a1b9a82@gmail.com>
| Python | mit | glyph/automat,glyph/Automat |
4e15bc71205cf308c8338b2608213f439a48d5d6 | swiftclient/version.py | swiftclient/version.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack LLC
#
# 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
... | # Copyright 2012 OpenStack LLC
#
# 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 by applicable law or a... | Remove extraneous vim configuration comments | Remove extraneous vim configuration comments
Remove line containing
comment - # vim: tabstop=4 shiftwidth=4 softtabstop=4
Change-Id: I31e4ee4112285f0daa5f2dd50db0344f4876820d
Closes-Bug:#1229324
| Python | apache-2.0 | ironsmile/python-swiftclient,varunarya10/python-swiftclient,pratikmallya/python-swiftclient,ironsmile/python-swiftclient,JioCloud/python-swiftclient,jeseem/python-swiftclient,krnflake/python-hubicclient,varunarya10/python-swiftclient,openstack/python-swiftclient,VyacheslavHashov/python-swiftclient,VyacheslavHashov/pyth... |
52922fd4117640cc2a9ce6abd72079d43d5641f7 | connected_components.py | connected_components.py | def get_connected_components(g):
"""
Return an array of arrays, each representing a connected component.
:param dict g: graph represented as an adjacency list where all nodes are labeled 1 to n.
:returns: array of arrays, each representing a connected component.
"""
connected_components = []
... | from collections import deque
def get_connected_components(g):
"""
Return an array of arrays, each representing a connected component.
:param dict g: graph represented as an adjacency list where all nodes are labeled 1 to n.
:returns: array of arrays, each representing a connected component.
"""
... | Implement bfs for connected components | Implement bfs for connected components
| Python | mit | stephtzhang/algorithms |
dd1aa173c8d158f45af9eeff8d3cc58c0e272f12 | solcast/radiation_estimated_actuals.py | solcast/radiation_estimated_actuals.py | from datetime import datetime, timedelta
from urllib.parse import urljoin
from isodate import parse_datetime, parse_duration
import requests
from solcast.base import Base
class RadiationEstimatedActuals(Base):
end_point = 'radiation/estimated_actuals'
def __init__(self, latitude, longitude, *args, **kwargs... | from datetime import datetime, timedelta
from urllib.parse import urljoin
from isodate import parse_datetime, parse_duration
import requests
from solcast.base import Base
class RadiationEstimatedActuals(Base):
end_point = 'radiation/estimated_actuals'
def __init__(self, latitude, longitude, *args, **kwargs... | Remove parameters that aren't required for an estimate actuals request | Remove parameters that aren't required for an estimate actuals request
| Python | mit | cjtapper/solcast-py |
7d14d51d138081c4f53ed185f54e975e0a074955 | bookmarks/forms.py | bookmarks/forms.py | from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import DataRequired, Length, EqualTo, Email, URL
class BookmarkForm(FlaskForm):
b_id = StringField('Bookmark ID', [
Length(min=6,
max=6,
message='Bookmark ID m... | from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import (DataRequired, Length, EqualTo, Email, Regexp,
URL)
class BookmarkForm(FlaskForm):
b_id = StringField('Bookmark ID', [
Length(min=6,
ma... | Add regex validation check on bookmark form | Add regex validation check on bookmark form
Checks that entry is only lowercase letters and numbers
| Python | apache-2.0 | byanofsky/bookmarks,byanofsky/bookmarks,byanofsky/bookmarks |
c4e0cc76e6051e59078e58e55647671f4acd75a3 | neutron/conf/policies/floatingip_pools.py | neutron/conf/policies/floatingip_pools.py | # 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 by applicable law or agreed to in writing, software
# distributed u... | # 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 by applicable law or agreed to in writing, software
# distributed u... | Implement secure RBAC for floating IP pools API | Implement secure RBAC for floating IP pools API
This commit updates the policies for floating IP pools API
to understand scope checking and account for a read-only role.
This is part of a broader series of changes across OpenStack to
provide a consistent RBAC experience and improve security.
Partially-Implements blu... | Python | apache-2.0 | mahak/neutron,openstack/neutron,openstack/neutron,mahak/neutron,mahak/neutron,openstack/neutron |
cb4eae7b76982c500817859b393cb9d4ea086685 | gcframe/tests/urls.py | gcframe/tests/urls.py | # -*- coding: utf-8 -*-
""" Simple urls for use in testing the gcframe app. """
from __future__ import unicode_literals
from django.conf.urls.defaults import patterns, url
from .views import normal, framed, exempt
urlpatterns = patterns('',
url(r'normal/$', normal, name='gcframe-test-normal'),
url(r'frame... | # -*- coding: utf-8 -*-
""" Simple urls for use in testing the gcframe app. """
from __future__ import unicode_literals
# The defaults module is deprecated in Django 1.5, but necessary to
# support Django 1.3. drop ``.defaults`` when dropping 1.3 support.
from django.conf.urls.defaults import patterns, url
from .vi... | Add note regarding URLs defaults module deprecation. | Add note regarding URLs defaults module deprecation.
| Python | bsd-3-clause | benspaulding/django-gcframe |
fbb9824e019b5211abd80ade9445afebc036bb27 | reporting/shellReporter.py | reporting/shellReporter.py | #!/usr/bin/env python3
import json
class ShellReporter:
def report_categories(self, categories):
to_dict = lambda x: { '{#TOOL}}': '{:s}'.format(x.tool), '{#TYPE}': '{:s}'.format(x.context) }
category_dict_list = list(map(to_dict, categories))
print(json.dumps(category_dict_list))
def... | #!/usr/bin/env python3
import json
class ShellReporter:
def report_categories(self, categories):
to_dict = lambda x: { 'TOOL': '{:s}'.format(x.tool), 'CONTEXT': '{:s}'.format(x.context) }
category_dict_list = list(map(to_dict, categories))
print(json.dumps(category_dict_list))
def rep... | Rename category fields in shell reporter | Rename category fields in shell reporter
| Python | mit | luigiberrettini/build-deploy-stats |
0a7104680d1aeaa7096f9bb7603cd63d46efb480 | wikitables/util.py | wikitables/util.py | import sys
import json
def ftag(t):
return lambda node: node.tag == t
def ustr(s):
if sys.version_info < (3, 0):
#py2
return unicode(s).encode('utf-8')
else:
return str(s)
class TableJSONEncoder(json.JSONEncoder):
def default(self, obj):
if hasattr(obj, '__json__'):
... | import sys
import json
def ftag(t):
return lambda node: node.tag == t
def ustr(s):
if sys.version_info < (3, 0):
#py2
try:
return unicode(s).encode('utf-8')
except UnicodeDecodeError:
return str(s)
else:
return str(s)
class TableJSONEncoder(json.JSO... | Add try catch to avoid unicode decode exception in python 2.7.10 | Add try catch to avoid unicode decode exception in python 2.7.10
| Python | mit | bcicen/wikitables |
560e441c64943500a032da8c4f81aef1c3354f84 | hado/auth_backends.py | hado/auth_backends.py | from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from django.core.exceptions import ImproperlyConfigured
from django.db.models import get_model
class UserModelBackend(ModelBackend):
def authenticate(self, username=None, password=None):
try:
user = self.user_class.objects.get... | from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from django.core.exceptions import ImproperlyConfigured
from django.db.models import get_model
from django.contrib.auth.models import User as oUser
from hado.models import User as cUser
class UserModelBackend(ModelBackend):
def au... | Fix for createsuperuser not creating a custom User model, and hence breaking AdminSite logins on setup | Fix for createsuperuser not creating a custom User model, and hence breaking AdminSite logins on setup
Since we're using a custom Auth Backend as well, we trap the authenticate() call.
If we can't find the requested user in our custom User, we fall back to checking the vanilla Django Users.
If we find one there, and i... | Python | mit | hackerspacesg/hackdo |
c97339e3a121c48ec3eed38e1bf901e2bf1d323c | src/proposals/resources.py | src/proposals/resources.py | from import_export import fields, resources
from .models import TalkProposal
class TalkProposalResource(resources.ModelResource):
name = fields.Field(attribute='submitter__speaker_name')
email = fields.Field(attribute='submitter__email')
class Meta:
model = TalkProposal
fields = [
... | from import_export import fields, resources
from .models import TalkProposal
class TalkProposalResource(resources.ModelResource):
name = fields.Field(attribute='submitter__speaker_name')
email = fields.Field(attribute='submitter__email')
class Meta:
model = TalkProposal
fields = [
... | Add language field to proposal export | Add language field to proposal export
| Python | mit | pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016 |
be7fded7f6c9fbc5d370849cc22113c30ab20fe7 | astrobin_apps_premium/templatetags/astrobin_apps_premium_tags.py | astrobin_apps_premium/templatetags/astrobin_apps_premium_tags.py | # Python
import urllib
# Django
from django.conf import settings
from django.db.models import Q
from django.template import Library, Node
# Third party
from subscription.models import Subscription, UserSubscription
# This app
from astrobin_apps_premium.utils import premium_get_valid_usersubscription
register = Libr... | # Python
import urllib
# Django
from django.conf import settings
from django.db.models import Q
from django.template import Library, Node
# Third party
from subscription.models import Subscription, UserSubscription
# This app
from astrobin_apps_premium.utils import premium_get_valid_usersubscription
register = Libr... | Remove stray debug log message | Remove stray debug log message
| Python | agpl-3.0 | astrobin/astrobin,astrobin/astrobin,astrobin/astrobin,astrobin/astrobin |
b40e1f42af2d392f821ec0da41717d9d14457f8d | src/serializer/__init__.py | src/serializer/__init__.py | from htmlserializer import HTMLSerializer
from xhtmlserializer import XHTMLSerializer
|
import os.path
__path__.append(os.path.dirname(__path__[0]))
from htmlserializer import HTMLSerializer
from xhtmlserializer import XHTMLSerializer
| Fix imports now that the serializer is in its own sub-package. | Fix imports now that the serializer is in its own sub-package.
--HG--
extra : convert_revision : svn%3Aacbfec75-9323-0410-a652-858a13e371e0/trunk%40800
| Python | mit | mgilson/html5lib-python,mgilson/html5lib-python,ordbogen/html5lib-python,html5lib/html5lib-python,alex/html5lib-python,alex/html5lib-python,dstufft/html5lib-python,dstufft/html5lib-python,mindw/html5lib-python,gsnedders/html5lib-python,mgilson/html5lib-python,ordbogen/html5lib-python,mindw/html5lib-python,gsnedders/htm... |
4c4b5a99e2fd02eff3451bf6c3a761163794a8ce | imageofmodel/admin.py | imageofmodel/admin.py | # -*- coding: utf-8 -*-
from django.contrib import admin
from django import forms
from django.contrib.contenttypes.generic import GenericTabularInline, BaseGenericInlineFormSet
from models import ImageOfModel
class ImageFormset(BaseGenericInlineFormSet):
def clean(self):
if not self.files.values() a... | # -*- coding: utf-8 -*-
from django.contrib import admin
from django import forms
from django.contrib.contenttypes.generic import GenericTabularInline, BaseGenericInlineFormSet
from models import ImageOfModel
class ImageFormset(BaseGenericInlineFormSet):
def clean(self):
if not self.files.values() a... | Add class OptionalImageOfModelInline for optional images | [+] Add class OptionalImageOfModelInline for optional images
| Python | bsd-3-clause | vixh/django-imageofmodel |
7e80f197d6cd914b9d43f0bc1d9f84e3d226a480 | fuse_util.py | fuse_util.py | import sublime
import os
def getSetting(key,default=None):
s = sublime.load_settings("Fuse.sublime-settings")
return s.get(key, default)
def getFusePathFromSettings():
path = getSetting("fuse_path_override")
if path == "" or path == None:
return "fuse"
else:
return path+"/fuse"
def setSetting(key,value):
s... | import sublime
import os
def getSetting(key,default=None):
s = sublime.load_settings("Fuse.sublime-settings")
return s.get(key, default)
def getFusePathFromSettings():
path = getSetting("fuse_path_override")
if path == "" or path == None:
return "fuse"
else:
return path+"/fuse"
def setSetting(key,value):
s... | Fix case where there are no extension. | Fix case where there are no extension.
| Python | mit | fusetools/Fuse.SublimePlugin,fusetools/Fuse.SublimePlugin |
a8a088828eee6938c56ce6f2aaecc7e776a8cb23 | swift/obj/dedupe/fp_index.py | swift/obj/dedupe/fp_index.py | __author__ = 'mjwtom'
import sqlite3
import unittest
class fp_index:
def __init__(self, name):
if name.endswith('.db'):
self.name = name
else:
self.name = name + '.db'
self.conn = sqlite3.connect(name)
self.c = self.conn.cursor()
self.c.execute('''C... | __author__ = 'mjwtom'
import sqlite3
import unittest
class Fp_Index(object):
def __init__(self, name):
if name.endswith('.db'):
self.name = name
else:
self.name = name + '.db'
self.conn = sqlite3.connect(name)
self.c = self.conn.cursor()
self.c.exec... | Use database to detect the duplication. But the md5 value does not match. Need to add some code here | Use database to detect the duplication. But the md5 value does not match. Need to add some code here
| Python | apache-2.0 | mjwtom/swift,mjwtom/swift |
8925c3a827659e1983827368948e95e764a40585 | utf9/__init__.py | utf9/__init__.py | # -*- coding: utf-8 -*-
from bitarray import bitarray as _bitarray
def utf9encode(string):
bits = _bitarray()
for char in string:
for idx, byte in enumerate(char.encode('utf-8')):
bits.append(idx)
bits.extend('{0:b}'.format(ord(byte)).zfill(8))
return bits.tobytes()
def ut... | # -*- coding: utf-8 -*-
"""Encode and decode text with UTF-9.
On April 1st 2005, IEEE released the RFC4042 "UTF-9 and UTF-18 Efficient
Transformation Formats of Unicode" (https://www.ietf.org/rfc/rfc4042.txt)
> The current representation formats for Unicode (UTF-7, UTF-8, UTF-16)
> are not storage and computation eff... | Add module and functions docstring | Add module and functions docstring
| Python | mit | enricobacis/utf9 |
15d2f98980b5a2baea5e6c55cc2d42c848a19e63 | axes/tests/test_models.py | axes/tests/test_models.py | from django.test import TestCase
class MigrationsCheck(TestCase):
def setUp(self):
from django.utils import translation
self.saved_locale = translation.get_language()
translation.deactivate_all()
def tearDown(self):
if self.saved_locale is not None:
from django.uti... | from django.apps.registry import apps
from django.db import connection
from django.db.migrations.autodetector import MigrationAutodetector
from django.db.migrations.executor import MigrationExecutor
from django.db.migrations.state import ProjectState
from django.test import TestCase
from django.utils import translation... | Clean up database test case imports | Clean up database test case imports
Signed-off-by: Aleksi Häkli <44cb6a94c0d20644d531e2be44779b52833cdcd2@iki.fi>
| Python | mit | django-pci/django-axes,jazzband/django-axes |
e0ffee5d5d6057a6dd776b02fea33c6509eb945c | signac/contrib/formats.py | signac/contrib/formats.py | # Copyright (c) 2016 The Regents of the University of Michigan
# All rights reserved.
# This software is licensed under the BSD 3-Clause License.
import logging
logger = logging.getLogger(__name__)
class BasicFormat(object):
pass
class FileFormat(BasicFormat):
def __init__(self, file_object):
self... | # Copyright (c) 2016 The Regents of the University of Michigan
# All rights reserved.
# This software is licensed under the BSD 3-Clause License.
TextFile = 'TextFile'
| Replace TextFile class definition with str constant. | Replace TextFile class definition with str constant.
| Python | bsd-3-clause | csadorf/signac,csadorf/signac |
3d3319b96475f40de6dd4e4cf39cdae323fd3b3d | arcutils/templatetags/arc.py | arcutils/templatetags/arc.py | from bootstrapform.templatetags.bootstrap import *
from django.template import Template, Context, Library
from django.template.loader import get_template
from django.utils.safestring import mark_safe
register = Library()
| from django import template
from django.template.defaulttags import url
from django.core.urlresolvers import reverse
from django.conf import settings
from django.template import Node, Variable, VariableDoesNotExist
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
register ... | Add a bunch of template tags | Add a bunch of template tags
| Python | mit | PSU-OIT-ARC/django-arcutils,wylee/django-arcutils,PSU-OIT-ARC/django-arcutils,kfarr2/django-arcutils,wylee/django-arcutils,mdj2/django-arcutils,mdj2/django-arcutils |
89a95df295036a9fc55ae061eac8e5921f85e095 | lib/py/src/metrics.py | lib/py/src/metrics.py | import os
import datetime
import tornado.gen
import statsd
if os.environ.get("STATSD_URL", None):
ip, port = os.environ.get("STATSD_URL").split(':')
statsd_client = statsd.Client(ip, int(port))
else:
statsd_client = None
def instrument(name):
def instrument_wrapper(fn):
@tornado.gen.coroutine... | import os
import datetime
import tornado.gen
import statsd
if os.environ.get("STATSD_URL", None):
ip, port = os.environ.get("STATSD_URL").split(':')
statsd_client = statsd.Client(ip, int(port))
else:
statsd_client = None
def instrument(name):
def instrument_wrapper(fn):
@tornado.gen.coroutine... | FIx issue with oneway methods | FIx issue with oneway methods
| Python | apache-2.0 | upfluence/thrift,upfluence/thrift,upfluence/thrift,upfluence/thrift,upfluence/thrift,upfluence/thrift,upfluence/thrift,upfluence/thrift,upfluence/thrift,upfluence/thrift,upfluence/thrift,upfluence/thrift |
55d9da44e71985e8fa81ffa60ea07f6db8c5e81e | ircu/util.py | ircu/util.py | from ircu import consts
def int_to_base64(n, count):
buf = ''
while count > 0:
count -= 1
buf = consts.BASE64_INT_TO_NUM[n & consts.BASE64_NUMNICKMASK] + buf
n >>= consts.BASE64_NUMNICKLOG
return buf
def base64_to_int(s):
n = 0
for ii in range(0, len(s)):
n = n <<... | from ircu import consts
def int_to_base64(n, count):
buf = ''
while count:
count -= 1
buf = consts.BASE64_INT_TO_NUM[n & consts.BASE64_NUMNICKMASK] + buf
n >>= consts.BASE64_NUMNICKLOG
return buf
def base64_to_int(s):
n = 0
for ii in range(0, len(s)):
n = n << 6
... | Add server/user numeric conversion methods | Add server/user numeric conversion methods
| Python | mit | briancline/ircu-python |
5df86afa64aafb4aee1adb066307910e0fb64256 | jd2chm_utils.py | jd2chm_utils.py | import os
import sys
import jd2chm_log
import jd2chm_conf
logging = None
config = None
def getAppDir():
if hasattr(sys, "frozen"): # py2exe
return os.path.dirname(sys.executable)
return os.path.dirname(sys.argv[0])
def getLogging(level=2):
global logging
if not logging:
logging = jd2chm_log.Jd2chmLo... | import os
import sys
import shutil
import jd2chm_log as log
import jd2chm_conf as conf
import jd2chm_const as const
logging = None
config = None
def get_app_dir():
if hasattr(sys, "frozen"): # py2exe
return os.path.dirname(sys.executable)
return os.path.dirname(sys.argv[0])
def get_logging(level=... | Reformat code. Added methods to pretty print messages. | Reformat code. Added methods to pretty print messages.
| Python | mit | andreburgaud/jd2chm,andreburgaud/jd2chm |
814782f5ef291728ecad6ce6bf430ce1fd82e5c4 | core/tests/views.py | core/tests/views.py | from django.conf import settings
from django.core.urlresolvers import reverse
from django.template import TemplateDoesNotExist
from django.test import TestCase
from core.models import Image
from core.tests import create_user
from users.models import User
__all__ = ['CreateImageTest']
class CreateImageTest(TestCase... | from django.conf import settings
from django.core.urlresolvers import reverse
from django.template import TemplateDoesNotExist
from django.test import TestCase
from core.models import Image
from core.tests import create_user
from users.models import User
__all__ = ['CreateImageTest']
class CreateImageTest(TestCase... | Use rsponse.json() to fix test-failure on json-3.5 | Fix: Use rsponse.json() to fix test-failure on json-3.5
| Python | bsd-2-clause | pinry/pinry,pinry/pinry,pinry/pinry,lapo-luchini/pinry,pinry/pinry,lapo-luchini/pinry,lapo-luchini/pinry,lapo-luchini/pinry |
49570c1b7dd5c62495a01db07fe070c34db18383 | tests/test_BaseDataSet_uri_property.py | tests/test_BaseDataSet_uri_property.py | import os
from . import tmp_dir_fixture # NOQA
def test_uri_property(tmp_dir_fixture): # NOQA
from dtoolcore import _BaseDataSet
admin_metadata = {
"name": os.path.basename(tmp_dir_fixture),
"uuid": "1234",
}
base_ds = _BaseDataSet(tmp_dir_fixture, admin_metadata, None)
expec... | import os
from . import tmp_uri_fixture # NOQA
def test_uri_property(tmp_uri_fixture): # NOQA
from dtoolcore import _BaseDataSet
admin_metadata = {
"name": os.path.basename(tmp_uri_fixture),
"uuid": "1234",
}
base_ds = _BaseDataSet(tmp_uri_fixture, admin_metadata, None)
asser... | Fix windows issue with test_uri_property | Fix windows issue with test_uri_property
| Python | mit | JIC-CSB/dtoolcore |
a0a93d1ccd2a2e339da59f6864c63b0fc9857886 | mailchimp3/baseapi.py | mailchimp3/baseapi.py | from os import path
class BaseApi(object):
"""
Simple class to buid path for entities
"""
def __init__(self, mc_client):
"""
Initialize the class with you user_id and secret_key
"""
super(BaseApi, self).__init__()
self._mc_client = mc_client
def _build_pa... | from os import path
class BaseApi(object):
"""
Simple class to buid path for entities
"""
def __init__(self, mc_client):
"""
Initialize the class with you user_id and secret_key
"""
super(BaseApi, self).__init__()
self._mc_client = mc_client
def _build_pa... | Update path build function to work on Windows | Update path build function to work on Windows | Python | mit | s0x90/python-mailchimp,charlesthk/python-mailchimp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.