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 |
|---|---|---|---|---|---|---|---|---|---|
03dc4f221aa9909c8a3074cbef9fd1816e0cc86c | stagecraft/libs/mass_update/data_set_mass_update.py | stagecraft/libs/mass_update/data_set_mass_update.py | from stagecraft.apps.datasets.models import DataGroup, DataSet, DataType
class DataSetMassUpdate():
@classmethod
def update_bearer_token_for_data_type_or_group_name(cls, query, new_token):
model_filter = DataSet.objects
if 'data_type' in query:
data_type = cls._get_model_instance_b... | from stagecraft.apps.datasets.models import DataGroup, DataSet, DataType
class DataSetMassUpdate(object):
@classmethod
def update_bearer_token_for_data_type_or_group_name(cls, query, new_token):
cls(query).update(bearer_token=new_token)
def __init__(self, query_dict):
self.model_filter =... | Refactor query out into instance with delegates the update | Refactor query out into instance with delegates the update
| Python | mit | alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft |
f78e20b05a5d7ede84f80a9be16a6a40a1a7abf8 | ifs/cli.py | ifs/cli.py | import click
import lib
@click.group()
def cli():
"""
Install From Source
When the version in the package manager has gone stale, get a fresh,
production-ready version from a source tarball or precompiled archive.
Send issues or improvements to https://github.com/cbednarski/ifs
"""
pass... | import click
import lib
@click.group()
def cli():
"""
Install From Source
When the version in the package manager has gone stale, get a fresh,
production-ready version from a source tarball or precompiled archive.
Send issues or improvements to https://github.com/cbednarski/ifs
"""
pass... | Exit with return code from called script | Exit with return code from called script
| Python | isc | cbednarski/ifs-python,cbednarski/ifs-python |
c8ef9e7271796239de2878bbf40a2c2d388427e4 | bayesian_methods_for_hackers/simulate_messages_ch02.py | bayesian_methods_for_hackers/simulate_messages_ch02.py | import json
import matplotlib
import numpy as np
import pymc as pm
from matplotlib import pyplot as plt
def main():
matplotlibrc_path = '/home/noel/repo/playground/matplotlibrc.json'
matplotlib.rcParams.update(json.load(open(matplotlibrc_path)))
tau = pm.rdiscrete_uniform(0, 80)
print tau
alpha ... | import json
import matplotlib
import numpy as np
import pymc as pm
from matplotlib import pyplot as plt
def main():
tau = pm.rdiscrete_uniform(0, 80)
print tau
alpha = 1. / 20.
lambda_1, lambda_2 = pm.rexponential(alpha, 2)
print lambda_1, lambda_2
data = np.r_[pm.rpoisson(lambda_1, tau), pm... | Change of repo name. Update effected paths | Change of repo name. Update effected paths
| Python | mit | noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit |
4f9ddcd07dbf5a84f183e7a84a8819bde062dbcf | example/_find_fuse_parts.py | example/_find_fuse_parts.py | import sys, os, glob
from os.path import realpath, dirname, join
from traceback import format_exception
PYTHON_MAJOR_MINOR = "%s.%s" % (sys.version_info[0], sys.version_info[1])
ddd = realpath(join(dirname(sys.argv[0]), '..'))
for d in [ddd, '.']:
for p in glob.glob(join(d, 'build', 'lib.*%s' % PYTHON_MAJOR_MIN... | import sys, os, glob
from os.path import realpath, dirname, join
from traceback import format_exception
PYTHON_MAJOR_MINOR = "%s.%s" % (sys.version_info[0], sys.version_info[1])
ddd = realpath(join(dirname(sys.argv[0]), '..'))
for d in [ddd, '.']:
for p in glob.glob(join(d, 'build', 'lib.*%s' % PYTHON_MAJOR_MIN... | Troubleshoot potential sys.path problem with python 3.x | Troubleshoot potential sys.path problem with python 3.x
| Python | lgpl-2.1 | libfuse/python-fuse,libfuse/python-fuse |
b22e96cc1e5daded4841b39d31ebefd1df86f26a | corehq/apps/hqadmin/migrations/0017_hqdeploy_commit.py | corehq/apps/hqadmin/migrations/0017_hqdeploy_commit.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-07-21 13:42
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hqadmin', '0016_hqdeploy_ordering'),
]
operations = [
migrations.AddField(... | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hqadmin', '0016_hqdeploy_ordering'),
]
operations = [
migrations.AddField(
model_name='hqdeploy',
name='commit',
field=models.CharField(max_length=255, n... | Remove unnecessary imports based on review | Remove unnecessary imports based on review
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq |
50c6e4a44a2451970c8e6286e1acb74dad78365c | example.py | example.py | import pyrc
import pyrc.utils.hooks as hooks
class GangstaBot(pyrc.Bot):
@hooks.command()
def bling(self, channel, sender):
"will print yo"
self.message(channel, "%s: yo" % sender)
@hooks.command("^repeat\s+(?P<msg>.+)$")
def repeat(self, channel, sender, **kwargs):
"will repeat whatever yo say"
... | import pyrc
import pyrc.utils.hooks as hooks
class GangstaBot(pyrc.Bot):
@hooks.command()
def bling(self, channel, sender):
"will print yo"
self.message(channel, "%s: yo" % sender)
@hooks.command("^repeat\s+(?P<msg>.+)$")
def repeat(self, channel, sender, **kwargs):
"will repeat whatever yo say"
... | Switch off debugging func that got through... | Switch off debugging func that got through...
| Python | mit | sarenji/pyrc |
4cad1d743f2c70c3ee046b59d98aecb6b5b301d6 | src/event_manager/views/base.py | src/event_manager/views/base.py | from django.shortcuts import render, redirect
from django.http import *
from django.contrib.auth import authenticate, login
def home(request):
return render(request, 'login.html', {})
def login_user(request):
logout(request)
username = ""
password = ""
if request.POST:
username = request.POST.get('username')
... | from django.shortcuts import render, redirect
from django.http import *
from django.contrib.auth import authenticate, login
def home(request):
return render(request, 'login.html', {})
def login_user(request):
logout(request)
username = ""
password = ""
if request.POST:
username = request.POST.get('username')
... | Create shell function for register_user | Create shell function for register_user | Python | agpl-3.0 | DavidJFelix/hatchit,DavidJFelix/hatchit,DavidJFelix/hatchit |
6abd349fa0392cd5518d3f01942289ae0527d8f4 | __init__.py | __init__.py | # Copyright 2017 Janos Czentye, Balazs Nemeth, Balazs Sonkoly
#
# 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... | # Copyright 2017 Janos Czentye, Balazs Nemeth, Balazs Sonkoly
#
# 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... | Add NetworkX version checking to nffg_lib package | Add NetworkX version checking to nffg_lib package
| Python | apache-2.0 | hsnlab/nffg,5GExchange/nffg |
7f7e606cc15e24190880d7388d07623be783a384 | src/address_extractor/__init__.py | src/address_extractor/__init__.py | from .__main__ import main
__version__ = '1.0.0'
__title__ = 'address_extractor'
__description__ = ''
__url__ = ''
__author__ = 'Scott Colby'
__email__ = ''
__license__ = 'MIT License'
__copyright__ = 'Copyright (c) 2015 Scott Colby'
__all__ = [
'address_extractor'
]
| from .__main__ import main
from .__main__ import parsed_address_to_human
__version__ = '1.0.0'
__title__ = 'address_extractor'
__description__ = ''
__url__ = ''
__author__ = 'Scott Colby'
__email__ = ''
__license__ = 'MIT License'
__copyright__ = 'Copyright (c) 2015 Scott Colby'
__all__ = [
'main',
'parsed... | Change importing structure in init | Change importing structure in init
| Python | mit | scolby33/address_extractor |
88776309a601e67c34747bd2eae49452006be017 | zsh/zsh_concat.py | zsh/zsh_concat.py | #!/usr/bin/env python3
from os import scandir
from sys import argv
from platform import uname
from pathlib import Path
filename_template = """
# -------------------------------------------------------------------------------
# filename: {filename}
# -------------------------------------------------------------------... | #!/usr/bin/env python3
from os import scandir
from sys import argv
from platform import uname
from pathlib import Path
filename_template = """
# -------------------------------------------------------------------------------
# filename: {filename}
# -------------------------------------------------------------------... | Read lib dir, before local dir. | Read lib dir, before local dir.
| Python | mit | skk/dotfiles,skk/dotfiles |
b0df06a29d4a235de86e51f4c6ff860fe5495d12 | run-tests.py | run-tests.py |
import os, sys
PROJECT_DIR = os.path.abspath(os.path.dirname( __file__ ))
SRC_DIR = os.path.join(PROJECT_DIR, "src")
TEST_DIR = os.path.join(PROJECT_DIR, "test")
def runtestdir(subdir):
entries = os.listdir(subdir)
total = 0
errs = 0
for f in entries:
if not f.endswith(".py"):
... |
import os, sys
PROJECT_DIR = os.path.abspath(os.path.dirname( __file__ ))
SRC_DIR = os.path.join(PROJECT_DIR, "src")
TEST_DIR = os.path.join(PROJECT_DIR, "test")
def runtestdir(subdir):
entries = os.listdir(subdir)
total = 0
errs = 0
for f in entries:
if not f.endswith(".py"):
con... | Test runner: fix line endings, print to stderr | Test runner: fix line endings, print to stderr | Python | mit | divtxt/binder |
f1da9bc9aae253779121f2b844e684c4ea4dd15f | seeker/migrations/0001_initial.py | seeker/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations ... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations ... | Add related_name to initial migration so it doesn't try to later | Add related_name to initial migration so it doesn't try to later | Python | bsd-2-clause | imsweb/django-seeker,imsweb/django-seeker |
d3b526c5079dc61d3bb8a80363c9448de07da331 | fabfile.py | fabfile.py | from fabric.api import *
env.runtime = 'production'
env.hosts = ['chimera.ericholscher.com']
env.user = 'docs'
env.code_dir = '/home/docs/sites/readthedocs.org/checkouts/readthedocs.org'
env.virtualenv = '/home/docs/sites/readthedocs.org'
env.rundir = '/home/docs/sites/readthedocs.org/run'
def update_requirements():
... | from fabric.api import *
env.runtime = 'production'
env.hosts = ['chimera.ericholscher.com']
env.user = 'docs'
env.code_dir = '/home/docs/sites/readthedocs.org/checkouts/readthedocs.org'
env.virtualenv = '/home/docs/sites/readthedocs.org'
env.rundir = '/home/docs/sites/readthedocs.org/run'
def push():
"Push new c... | Make it easy to do a full deploy with fab | Make it easy to do a full deploy with fab
| Python | mit | cgourlay/readthedocs.org,sunnyzwh/readthedocs.org,attakei/readthedocs-oauth,davidfischer/readthedocs.org,nikolas/readthedocs.org,fujita-shintaro/readthedocs.org,Tazer/readthedocs.org,techtonik/readthedocs.org,laplaceliu/readthedocs.org,jerel/readthedocs.org,johncosta/private-readthedocs.org,stevepiercy/readthedocs.org,... |
bed66179633a86751a938c13b98f5b56c3c1cfc7 | fabfile.py | fabfile.py | from fabric.api import local
vim_bundles = [
{
'git': 'git://github.com/fatih/vim-go.git',
'path': '~/.vim/bundle/vim-go'
}
]
def apt_get():
local('sudo apt-get update')
local('sudo apt-get upgrade')
# neovim instead of vim?
local('sudo apt-get install zsh vim wget curl kitty s... | from fabric.api import local
vim_bundles = [
{
'git': 'git://github.com/fatih/vim-go.git',
'path': '~/.vim/bundle/vim-go'
}
]
def apt_get():
local('sudo apt-get update')
local('sudo apt-get upgrade')
# neovim instead of vim?
local('sudo apt-get install zsh vim wget curl kitty s... | Add graphviz for converting dot to pdf | Add graphviz for converting dot to pdf
| Python | unlicense | spanners/dotfiles |
e98b9e1da819c571e165c55e222a3aa5a20e709b | mrbelvedereci/build/apps.py | mrbelvedereci/build/apps.py | from __future__ import unicode_literals
from django.apps import AppConfig
class BuildConfig(AppConfig):
name = 'mrbelvedereci.build'
| from __future__ import unicode_literals
from django.apps import AppConfig
class BuildConfig(AppConfig):
name = 'mrbelvedereci.build'
def ready(self):
import mrbelvedereci.build.handlers
| Include handlers in build app | Include handlers in build app
| Python | bsd-3-clause | SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci |
0ed4b5e2831c649bfb7c31a3fe0716bb02e4a02a | api/settings/staging.py | api/settings/staging.py | from .docker import *
INSTALLED_APPS.append('raven.contrib.django.raven_compat')
ADMINS = (
('[STAGING] HMCTS Reform Sustaining Support', 'sustainingteamsupport@HMCTS.NET'),
)
RAVEN_CONFIG = {
'dsn': os.environ["SENTRY_DSN"],
'release': os.environ.get("APP_GIT_COMMIT", "no-git-commit-available")
}
| from .docker import *
INSTALLED_APPS.append('raven.contrib.django.raven_compat')
ADMINS = (
('[STAGING] HMCTS Reform Sustaining Support', 'sustainingteamdev@hmcts.net'),
)
RAVEN_CONFIG = {
'dsn': os.environ["SENTRY_DSN"],
'release': os.environ.get("APP_GIT_COMMIT", "no-git-commit-available")
}
| Use dev email or non prod environments | Use dev email or non prod environments
| Python | mit | ministryofjustice/manchester_traffic_offences_pleas,ministryofjustice/manchester_traffic_offences_pleas,ministryofjustice/manchester_traffic_offences_pleas,ministryofjustice/manchester_traffic_offences_pleas |
2009a4ef78261fc8dfe96df00321d3fb612f697e | fireplace/cards/wog/hunter.py | fireplace/cards/wog/hunter.py | from ..utils import *
##
# Minions
class OG_179:
"Fiery Bat"
deathrattle = Hit(RANDOM_ENEMY_CHARACTER, 1)
class OG_292:
"Forlorn Stalker"
play = Buff(FRIENDLY_HAND + MINION + DEATHRATTLE, "OG_292e")
OG_292e = buff(+1, +1)
##
# Spells
class OG_045:
"Infest"
play = Buff(FRIENDLY_MINIONS, "OG_045a")
class ... | from ..utils import *
##
# Minions
class OG_179:
"Fiery Bat"
deathrattle = Hit(RANDOM_ENEMY_CHARACTER, 1)
class OG_292:
"Forlorn Stalker"
play = Buff(FRIENDLY_HAND + MINION + DEATHRATTLE, "OG_292e")
OG_292e = buff(+1, +1)
class OG_216:
"Infested Wolf"
deathrattle = Summon(CONTROLLER, "OG_216a") * 2
clas... | Implement Infested Wolf and Princess Huhuran | Implement Infested Wolf and Princess Huhuran
| Python | agpl-3.0 | beheh/fireplace,jleclanche/fireplace,NightKev/fireplace |
09c3c511687de8888180577fa66f4ca51f4bc237 | taggit_autosuggest_select2/views.py | taggit_autosuggest_select2/views.py | from django.conf import settings
from django.http import HttpResponse
from django.utils import simplejson as json
from taggit.models import Tag
MAX_SUGGESTIONS = getattr(settings, 'TAGGIT_AUTOSUGGEST_MAX_SUGGESTIONS', 20)
def list_tags(request):
"""
Returns a list of JSON objects with a `name` and a `value`... | from django.conf import settings
from django.http import HttpResponse
import json
from taggit.models import Tag
MAX_SUGGESTIONS = getattr(settings, 'TAGGIT_AUTOSUGGEST_MAX_SUGGESTIONS', 20)
def list_tags(request):
"""
Returns a list of JSON objects with a `name` and a `value` property that
all start lik... | Remove deprecated django json shim | Remove deprecated django json shim
| Python | mit | iris-edu/django-taggit-autosuggest-select2,iris-edu-int/django-taggit-autosuggest-select2,adam-iris/django-taggit-autosuggest-select2,adam-iris/django-taggit-autosuggest-select2,iris-edu/django-taggit-autosuggest-select2,iris-edu-int/django-taggit-autosuggest-select2,iris-edu-int/django-taggit-autosuggest-select2,iris-... |
a4264c610f33640ac773ca0b12912f3ad972d966 | feedback/admin.py | feedback/admin.py | from django.contrib import admin
# Register your models here.
from .models import Feedback
class FeedbackAdmin(admin.ModelAdmin):
list_display = ('name', 'email', 'note', 'archive', 'public')
list_filter = ['created']
search_fields = ['name', 'email', 'note', 'archive', 'public']
admin.site.register(Fee... | from django.contrib import admin
# Register your models here.
from .models import Feedback
class FeedbackAdmin(admin.ModelAdmin):
list_display = ('name', 'email', 'note', 'archive', 'public')
list_filter = ['created']
search_fields = ['name', 'email', 'note', 'archive', 'public']
actions = ['to_arch... | Add Admin action to feedbacks | Add Admin action to feedbacks
| Python | mit | n2o/dpb,n2o/dpb,n2o/dpb,n2o/dpb,n2o/dpb,n2o/dpb,n2o/dpb,n2o/dpb |
b824e4c4a106d73c842a38758addde52d94e976a | ngrams_feature_extractor.py | ngrams_feature_extractor.py | import sklearn
def make_train_pair(filename):
h5 = open_h5_file_read(filename)
title = get_title(h5)
pitches = get_segments_pitches(h5)[:11] # limit: only look at beginning
pitch_diffs = [pitches[i] - pitches[i - 1] for i in xrange(1, len(pitches))]
h5.close()
return {'title': title, 'pitch_di... | import sklearn
from hdf5_getters import *
import os
def make_train_pair(filename):
h5 = open_h5_file_read(filename)
title = get_title(h5)
pitches = get_segments_pitches(h5)[:11] # limit: only look at beginning
pitch_diffs = [pitches[i] - pitches[i - 1] for i in xrange(1, len(pitches))]
h5.close()
... | Add corresponding hdf5 parsing file | Add corresponding hdf5 parsing file
| Python | mit | ajnam12/MusicNLP |
444d97288c0fd80adf4077477336c98bfea140cc | node.py | node.py | class Node(object):
def __init__(self):
# Properties will go here!
| class Node(object):
def __init__(self):
# Node(s) from which this Node receives values
self.inbound_nodes = inbound_nodes
# Node(s) to which this Node passes values
self.outbound_nodes = []
# For each inbound Node here, add this Node as an outbound to that Node.
for n in self.inbound_nodes:
... | Initialize inbound and outbound Nodes of a Node | Initialize inbound and outbound Nodes of a Node
| Python | mit | YabinHu/miniflow |
cc06a15f734a6ed46561a99d1040a08582833a09 | src/puzzle/heuristics/acrostic.py | src/puzzle/heuristics/acrostic.py | from puzzle.heuristics.acrostics import _acrostic_iter
class Acrostic(_acrostic_iter.AcrosticIter):
"""Best available Acrostic solver."""
pass
| from puzzle.heuristics.acrostics import _acrostic_search
class Acrostic(_acrostic_search.AcrosticSearch):
"""Best available Acrostic solver."""
pass
| Use AccrosticSearch (~BFS) instead of AcrosticIter (~DFS). | Use AccrosticSearch (~BFS) instead of AcrosticIter (~DFS).
| Python | mit | PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge |
773064a61fcd4213196e44d347e304d746b28325 | syft/frameworks/torch/tensors/native.py | syft/frameworks/torch/tensors/native.py | import random
from syft.frameworks.torch.tensors import PointerTensor
class TorchTensor:
"""
This tensor is simply a more convenient way to add custom functions to
all Torch tensor types.
"""
def __init__(self):
self.id = None
self.owner = None
def create_pointer(
se... | import random
from syft.frameworks.torch.tensors import PointerTensor
import syft
class TorchTensor:
"""
This tensor is simply a more convenient way to add custom functions to
all Torch tensor types.
"""
def __init__(self):
self.id = None
self.owner = syft.local_worker
def ... | Set local worker as default for SyftTensor owner | Set local worker as default for SyftTensor owner
| Python | apache-2.0 | OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft |
debb03975e8b647f27980081371bd9fdad7b292f | solar/solar/system_log/operations.py | solar/solar/system_log/operations.py |
from solar.system_log import data
from dictdiffer import patch
def set_error(task_uuid, *args, **kwargs):
sl = data.SL()
item = sl.get(task_uuid)
if item:
item.state = data.STATES.error
sl.update(task_uuid, item)
def move_to_commited(task_uuid, *args, **kwargs):
sl = data.SL()
... |
from solar.system_log import data
from dictdiffer import patch
def set_error(task_uuid, *args, **kwargs):
sl = data.SL()
item = sl.get(task_uuid)
if item:
item.state = data.STATES.error
sl.update(item)
def move_to_commited(task_uuid, *args, **kwargs):
sl = data.SL()
item = sl.p... | Fix update of logitem bug in system_log | Fix update of logitem bug in system_log
| Python | apache-2.0 | loles/solar,openstack/solar,loles/solar,pigmej/solar,pigmej/solar,torgartor21/solar,torgartor21/solar,loles/solar,dshulyak/solar,zen/solar,zen/solar,dshulyak/solar,zen/solar,Mirantis/solar,Mirantis/solar,Mirantis/solar,pigmej/solar,Mirantis/solar,CGenie/solar,CGenie/solar,openstack/solar,zen/solar,loles/solar,openstack... |
e7e6274ee5fa16cb07e32bebe53532a6a16b7965 | dagrevis_lv/blog/templatetags/tags.py | dagrevis_lv/blog/templatetags/tags.py | from django import template
register = template.Library()
@register.filter
def get_style(tags, priority):
max_priority = max(tags, key=lambda tag: tag["priority"])["priority"]
size = (max_priority / 10.) * priority
return "font-size: {}em;".format(size)
| from django import template
register = template.Library()
@register.filter
def get_style(tags, priority):
max_priority = max(tags, key=lambda tag: tag["priority"])["priority"]
size = 100 / max_priority / priority / 2
return "font-size: {}em;".format(size)
| Fix tag cloud weird size | Fix tag cloud weird size
| Python | mit | daGrevis/daGrevis.lv,daGrevis/daGrevis.lv,daGrevis/daGrevis.lv |
968c73805e5beff502955ad3dbb8aa86ee8bc0b7 | freelancefinder/jobs/forms.py | freelancefinder/jobs/forms.py | """Forms for dealing with jobs/posts."""
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from taggit.models import Tag
class PostFilterForm(forms.Form):
"""Form for filtering the PostListView."""
title = forms.CharField(required=False)
is_job_p... | """Forms for dealing with jobs/posts."""
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from taggit.models import Tag
class PostFilterForm(forms.Form):
"""Form for filtering the PostListView."""
title = forms.CharField(required=False)
is_job_p... | Tag is not required, of course | Tag is not required, of course
| Python | bsd-3-clause | ScorpionResponse/freelancefinder,ScorpionResponse/freelancefinder,ScorpionResponse/freelancefinder |
99b96d2c0b82e186b9eaa13d2efe8b617c9cf3aa | registration/__init__.py | registration/__init__.py | VERSION = (0, 9, 0, 'beta', 1)
def get_version():
from django.utils.version import get_version as django_get_version
return django_get_version(VERSION) # pragma: no cover
| VERSION = (1, 0, 0, 'final', 0)
def get_version():
"Returns a PEP 386-compliant version number from VERSION."
assert len(VERSION) == 5
assert VERSION[3] in ('alpha', 'beta', 'rc', 'final')
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub = .devN - for pre-alpha releases... | Fix version number reporting so we can be installed before Django. | Fix version number reporting so we can be installed before Django.
| Python | bsd-3-clause | dinie/django-registration,dinie/django-registration,FundedByMe/django-registration,FundedByMe/django-registration,Avenza/django-registration |
7d88c98fcf6984b07a8b085f8272868b1c23b29e | app/status/views.py | app/status/views.py | from flask import jsonify, current_app
from . import status
from . import utils
from ..main.services.search_service import status_for_all_indexes
@status.route('/_status')
def status():
db_status = status_for_all_indexes()
if db_status['status_code'] == 200:
return jsonify(
status="ok",... | from flask import jsonify, current_app
from . import status
from . import utils
from ..main.services.search_service import status_for_all_indexes
@status.route('/_status')
def status():
db_status = status_for_all_indexes()
if db_status['status_code'] == 200:
return jsonify(
status="ok",... | Return correct message if elasticsearch fails to connect. | Return correct message if elasticsearch fails to connect.
| Python | mit | alphagov/digitalmarketplace-search-api,alphagov/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api |
155476e8feb584fb802b2aed4266aec32d617f2a | app/status/views.py | app/status/views.py | from flask import jsonify, current_app
from . import status
from . import utils
from .. import api_client
@status.route('/_status')
def status():
api_response = utils.return_response_from_api_status_call(
api_client.status
)
apis_wot_got_errors = []
if api_response is None or api_response.... | from flask import jsonify, current_app
from . import status
from . import utils
from .. import api_client
@status.route('/_status')
def status():
api_response = utils.return_response_from_api_status_call(
api_client.status
)
apis_with_errors = []
if api_response is None or api_response.sta... | Change variable name & int comparison. | Change variable name & int comparison.
| Python | mit | alphagov/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,alphag... |
829cccc630c26f2e9d89007c669308c6b1bb63cf | frigg/worker/fetcher.py | frigg/worker/fetcher.py | # -*- coding: utf8 -*-
import json
import threading
import time
import logging
from frigg.worker import config
from frigg.worker.jobs import Build
logger = logging.getLogger(__name__)
def fetcher():
redis = config.redis_client()
while redis:
task = redis.rpop('frigg:queue')
if task:
... | # -*- coding: utf8 -*-
import json
import threading
import time
import logging
from frigg.worker import config
from frigg.worker.jobs import Build
logger = logging.getLogger(__name__)
def fetcher():
redis = config.redis_client()
while redis:
task = redis.rpop('frigg:queue')
if task:
... | Add deletion of result after build | Add deletion of result after build
| Python | mit | frigg/frigg-worker |
cce8c4b40038a8b8ddccc76f7d13c7f5d0e5e566 | txircd/modules/rfc/cmd_links.py | txircd/modules/rfc/cmd_links.py | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from zope.interface import implements
class LinksCommand(ModuleData, Command):
implements(IPlugin, IModuleData, ICommand)
name = "LinksCommand"
core = True
d... | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from zope.interface import implements
class LinksCommand(ModuleData, Command):
implements(IPlugin, IModuleData, ICommand)
name = "LinksCommand"
core = True
d... | Make the order of LINKS output consistent | Make the order of LINKS output consistent
| Python | bsd-3-clause | ElementalAlchemist/txircd,Heufneutje/txircd |
0b2cf0a651d27af90a229d85f77ac9ebd2502905 | run_test_BMI_ku_model.py | run_test_BMI_ku_model.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 10 10:56:16 2017
@author: kangwang
"""
import os
import sys
from permamodel.components import bmi_Ku_component
from permamodel.tests import examples_directory
cfg_file = os.path.join(examples_directory, 'Ku_method.cfg')
x = bmi_Ku_component.BmiKu... | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 10 10:56:16 2017
@author: kangwang
"""
import os
import sys
from permamodel.components import bmi_Ku_component
from permamodel.tests import examples_directory
cfg_file = os.path.join(examples_directory, 'Ku_method.cfg')
x = bmi_Ku_component.BmiKu... | Use BMI method to get ALT value | Use BMI method to get ALT value
It looks like it may not give the correct answer, though.
| Python | mit | permamodel/permamodel,permamodel/permamodel |
c21318fa5c125e54160f67d410cf4572a2f9a47e | addons/web_calendar/contacts.py | addons/web_calendar/contacts.py | from openerp.osv import fields, osv
class web_calendar_contacts(osv.osv):
_name = 'web_calendar.contacts'
_columns = {
'user_id': fields.many2one('res.users','Me'),
'partner_id': fields.many2one('res.partner','Contact'),
'active':fields.boolean('active'),
}
_defaul... | from openerp.osv import fields, osv
class web_calendar_contacts(osv.osv):
_name = 'web_calendar.contacts'
_columns = {
'user_id': fields.many2one('res.users','Me'),
'partner_id': fields.many2one('res.partner','Contact',required=True),
'active':fields.boolean('active'),
... | Add required on field res.partner from model Contacts to avoid the creation of empty coworkers | [FIX] Add required on field res.partner from model Contacts to avoid the creation of empty coworkers
| Python | agpl-3.0 | havt/openerp-web,havt/openerp-web,havt/openerp-web,havt/openerp-web,havt/openerp-web |
31986c4c7d5781f0924289308d99754c81d29710 | pml/units.py | pml/units.py | import numpy as np
from scipy.interpolate import PchipInterpolator
class UcPoly(object):
def __init__(self, coef):
self.p = np.poly1d(coef)
def machine_to_physics(self, machine_value):
return self.p(machine_value)
def physics_to_machine(self, physics_value):
roots = (self.p - phy... | import numpy as np
from scipy.interpolate import PchipInterpolator
class UcPoly(object):
def __init__(self, coef):
self.p = np.poly1d(coef)
def machine_to_physics(self, machine_value):
return self.p(machine_value)
def physics_to_machine(self, physics_value):
roots = (self.p - phy... | Raise error when creating PChip object with not monotonely increasing y list | Raise error when creating PChip object with not monotonely increasing y list
| Python | apache-2.0 | willrogers/pml,willrogers/pml |
95d2036aab2e3d154f4f292ef8624d6d02d48ac0 | cleanpyc.py | cleanpyc.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'xilei'
import os
from os.path import join
import stat
def chmod(targetdir):
"""
remove *.pyc files
"""
for root, dirs, files in os.walk(targetdir):
for file in files:
prefix,ext = os.path.splitext(file)
if e... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'xilei'
import os
from os.path import join
import stat
def rmpyc(targetdir):
"""
remove *.pyc files
"""
for root, dirs, files in os.walk(targetdir):
for file in files:
prefix,ext = os.path.splitext(file)
if e... | Change function name chmod to rmpyc | Change function name chmod to rmpyc
| Python | apache-2.0 | xiilei/pytools,xiilei/pytools |
3a44dbeec871aa057c4d5b42c9089a8d2b649063 | django_agpl/urls.py | django_agpl/urls.py | # -*- coding: utf-8 -*-
#
# django-agpl -- tools to aid releasing Django projects under the AGPL
# Copyright (C) 2008, 2009, 2016 Chris Lamb <chris@chris-lamb.co.uk>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by t... | # -*- coding: utf-8 -*-
#
# django-agpl -- tools to aid releasing Django projects under the AGPL
# Copyright (C) 2008, 2009, 2016 Chris Lamb <chris@chris-lamb.co.uk>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by t... | Drop patterns import for Django 1.0 compatibility. | Drop patterns import for Django 1.0 compatibility.
| Python | agpl-3.0 | lamby/django-agpl,lamby/django-agpl |
99d1357c379b2df5219891da7f64e4584060f069 | app/celery/reporting_tasks.py | app/celery/reporting_tasks.py | from datetime import datetime, timedelta
from flask import current_app
from notifications_utils.statsd_decorators import statsd
from app import notify_celery
from app.dao.fact_billing_dao import (
fetch_billing_data_for_day,
update_fact_billing
)
@notify_celery.task(name="create-nightly-billing")
@statsd(na... | from datetime import datetime, timedelta
from flask import current_app
from notifications_utils.statsd_decorators import statsd
from app import notify_celery
from app.dao.fact_billing_dao import (
fetch_billing_data_for_day,
update_fact_billing
)
@notify_celery.task(name="create-nightly-billing")
@statsd(na... | Fix the logging message in the nightly task | Fix the logging message in the nightly task
| Python | mit | alphagov/notifications-api,alphagov/notifications-api |
987c54559cb52370fc459a30cdbdfd0e38c5ef62 | plata/context_processors.py | plata/context_processors.py | import plata
def plata_context(request):
"""
Adds a few variables from Plata to the context if they are available:
* ``plata.shop``: The current :class:`plata.shop.views.Shop` instance
* ``plata.order``: The current order
* ``plata.contact``: The current contact instance
"""
shop = plata.... | import plata
def plata_context(request):
"""
Adds a few variables from Plata to the context if they are available:
* ``plata.shop``: The current :class:`plata.shop.views.Shop` instance
* ``plata.order``: The current order
* ``plata.contact``: The current contact instance
* ``plata.price_includ... | Add the variable `plata.price_includes_tax` to the template context | Add the variable `plata.price_includes_tax` to the template context
| Python | bsd-3-clause | armicron/plata,armicron/plata,stefanklug/plata,armicron/plata |
ae4b4fe5fb5c5774720dd3a14549aa88bde91043 | tests/Epsilon_tests/ImportTest.py | tests/Epsilon_tests/ImportTest.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from unittest import TestCase, main
from grammpy import EPS
from grammpy import EPSILON
class ImportTest(TestCase):
def test_idSame(self):
self.assertEqual(id(EPS),id(EPSILON)... | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from unittest import TestCase, main
from grammpy import EPS
from grammpy import EPSILON
class ImportTest(TestCase):
def test_idSame(self):
self.assertEqual(id(EPS), id(EPSILON))... | Add tests to compare epsilon with another objects | Add tests to compare epsilon with another objects
| Python | mit | PatrikValkovic/grammpy |
d45fb029dc4bf0119062a07b962dbc7fff1f300a | skimage/measure/__init__.py | skimage/measure/__init__.py | from .find_contours import find_contours
from ._regionprops import regionprops, perimeter
from ._structural_similarity import structural_similarity
from ._polygon import approximate_polygon, subdivide_polygon
__all__ = ['find_contours',
'regionprops',
'perimeter',
'structural_similarit... | from .find_contours import find_contours
from ._regionprops import regionprops, perimeter
from ._structural_similarity import structural_similarity
from ._polygon import approximate_polygon, subdivide_polygon
from .fit import LineModel, CircleModel, EllipseModel, ransac
__all__ = ['find_contours',
'regionp... | Add imports of fit to subpackage | Add imports of fit to subpackage
| Python | bsd-3-clause | ajaybhat/scikit-image,vighneshbirodkar/scikit-image,almarklein/scikit-image,GaZ3ll3/scikit-image,keflavich/scikit-image,ofgulban/scikit-image,paalge/scikit-image,keflavich/scikit-image,chintak/scikit-image,chintak/scikit-image,chintak/scikit-image,Britefury/scikit-image,youprofit/scikit-image,dpshelio/scikit-image,Hiyo... |
3a6d76201104b928c1b9053317c9e61804814ff5 | pyresticd.py | pyresticd.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import getpass
import time
from twisted.internet import task
from twisted.internet import reactor
# Configuration
timeout = 3600*24*3 # Period
restic_command = "/home/mebus/restic" # your restic command here
# Program
def do_restic_backup():
print "\nStarti... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import getpass
import time
from twisted.internet import task
from twisted.internet import reactor
# Configuration
timeout = 3600*24*3 # Period
restic_command = "/home/mebus/restic" # your restic command here
# Program
def do_restic_backup():
print('Starting... | Use py3-style print and string-formatting | Use py3-style print and string-formatting
| Python | mit | Mebus/pyresticd,Mebus/pyresticd |
2c9d5a8b167f77a69995d55e2b2ef52c90807124 | pytest_vw.py | pytest_vw.py | # -*- coding: utf-8 -*-
import os
import pytest
# You didn't see that.
#
# I hope you don't understand this code.
_config = None
EXAMINATORS = [
'CI',
'CONTINUOUS_INTEGRATION',
'BUILD_ID',
'BUILD_NUMBER',
'TEAMCITY_VERSION',
'TRAVIS',
'CIRCLECI',
'JENKINS_URL',
'HUDSON_URL',
... | # -*- coding: utf-8 -*-
import os
import pytest
# You didn't see that.
#
# I hope you don't understand this code.
EXAMINATORS = [
'CI',
'CONTINUOUS_INTEGRATION',
'BUILD_ID',
'BUILD_NUMBER',
'TEAMCITY_VERSION',
'TRAVIS',
'CIRCLECI',
'JENKINS_URL',
'HUDSON_URL',
'bamboo.build... | Use item.config to access config. | Use item.config to access config.
Fixes #1.
| Python | mit | The-Compiler/pytest-vw |
e87490ea157f4882f644329e4b447f51c0a2acb3 | benchmarks/bench_vectorize.py | benchmarks/bench_vectorize.py | """
Benchmarks for ``@vectorize`` ufuncs.
"""
import numpy as np
from numba import vectorize
@vectorize(["float32(float32, float32)",
"float64(float64, float64)",
"complex64(complex64, complex64)",
"complex128(complex128, complex128)"])
def mul(x, y):
return x * y
class Tim... | """
Benchmarks for ``@vectorize`` ufuncs.
"""
import numpy as np
from numba import vectorize
@vectorize(["float32(float32, float32)",
"float64(float64, float64)",
"complex64(complex64, complex64)",
"complex128(complex128, complex128)"])
def mul(x, y):
return x * y
@vectoriz... | Add a relative difference vectorization benchmark | Add a relative difference vectorization benchmark
| Python | bsd-2-clause | gmarkall/numba-benchmark,numba/numba-benchmark |
f94c946d135aed30f4d9068844b563fa94e39ff1 | test.py | test.py | from unittest import TestCase
import lazydict
class TestLazyDictionary(TestCase):
def test_circular_reference_error(self):
d = lazydict.LazyDictionary()
d['foo'] = lambda s: s['foo']
self.assertRaises(lazydict.CircularReferenceError, d.__getitem__, 'foo')
def test_constant_redefinitio... | from unittest import TestCase
import lazydict
class TestLazyDictionary(TestCase):
def test_circular_reference_error(self):
d = lazydict.LazyDictionary()
d['foo'] = lambda s: s['foo']
self.assertRaises(lazydict.CircularReferenceError, d.__getitem__, 'foo')
def test_constant_redefinitio... | Check recursion in str() and repr() | Check recursion in str() and repr()
| Python | mit | janrain/lazydict |
1469da25fec3e3e966d5a0b5fab11dd279bbe05a | blogsite/models.py | blogsite/models.py | """Collection of Models used in blogsite."""
from . import db
class Post(db.Model):
"""Model representing a blog post.
Attributes
----------
id : db.Column
Autogenerated primary key
title : db.Column
body : db.Column
"""
# Columns
id = db.Column(db.Integer, primary_key=Tr... | """Collection of Models used in blogsite."""
from . import db
class Post(db.Model):
"""Model representing a blog post.
Attributes
----------
id : SQLAlchemy.Column
Autogenerated primary key
title : SQLAlchemy.Column
body : SQLAlchemy.Column
"""
# Columns
id = db.Column(db... | Correct type comment for table columns | Correct type comment for table columns
| Python | mit | paulaylingdev/blogsite,paulaylingdev/blogsite |
0cda764617dcbf52c36d4a63e240b6f849b06640 | tests/app/test_application.py | tests/app/test_application.py | from .helpers import BaseApplicationTest
class TestApplication(BaseApplicationTest):
def test_index(self):
response = self.client.get('/')
assert 200 == response.status_code
| from .helpers import BaseApplicationTest
class TestApplication(BaseApplicationTest):
def test_index(self):
response = self.client.get('/')
assert 200 == response.status_code
def test_404(self):
response = self.client.get('/not-found')
assert 404 == response.status_code
| Add test for not found URLs | Add test for not found URLs
| Python | mit | alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace... |
18cd9a1db083db1ce0822bab2f502357eeec97b5 | blog/tests/test_templatetags.py | blog/tests/test_templatetags.py | from django.test import TestCase
from django.template import Context, Template
class BlogTemplatetagsTestCase(TestCase):
def test_md_as_html5(self):
body = """# H1 heading
**Paragraph** text
## H2 heading
~~~~{.python}
if True:
print("Some Python code in markdown")
~~~~
1 First
2. Second
* sub
3.... | from django.test import TestCase
from django.template import Context, Template
class BlogTemplatetagsTestCase(TestCase):
def test_md_as_html5(self):
body = """# H1 heading
**Paragraph** text
<strong>html markup works</strong>
## H2 heading
~~~~{.python}
if True:
print("Some <b>Python</b> code in mark... | Test HTML handling in markdown | Test HTML handling in markdown
| Python | agpl-3.0 | node13h/droll,node13h/droll |
726370913332fd5e27bb04446b75ef59fb711a9c | broadgauge/main.py | broadgauge/main.py | import os
import sys
import web
import yaml
from . import default_settings
def load_default_config():
# take all vars defined in default_config
config = dict((k, v) for k, v in default_settings.__dict__.items()
if not k.startswith("_"))
web.config.update(config)
def load_config_from_en... | import os
import sys
import web
import yaml
from . import default_settings
def load_default_config():
# take all vars defined in default_config
config = dict((k, v) for k, v in default_settings.__dict__.items()
if not k.startswith("_"))
web.config.update(config)
def load_config_from_en... | Read mail settings from config. | Read mail settings from config.
| Python | bsd-3-clause | fsmk/fsmkschool,anandology/broadgauge |
4a32838db7cbfa1962f3cd61f46caa308e4ea645 | src/rgrep.py | src/rgrep.py | def display_usage():
return 'Usage: python rgrep [options] pattern files\nThe options are the '\
'same as grep\n'
def rgrep(pattern='', text='', case='', count=False, version=False):
if pattern == '' or text == '':
return display_usage()
elif not count:
if case == 'i':
... | def display_usage():
return 'Usage: python rgrep [options] pattern files\nThe options are the '\
'same as grep\n'
class RGrep(object):
def __init__(self):
self.version = 'RGrep (BSD) 0.0.1'
self.count = False
self.pattern = ''
self.text = ''
self.case = ''
... | Add match and case insensitive methods | Add match and case insensitive methods
| Python | bsd-2-clause | ambidextrousTx/RGrep-Python |
bd8c5628a6af96a68f1ed6022a983af7a5495529 | tartpy/rt.py | tartpy/rt.py | import os
import multiprocessing
import threading
class Sponsor(object):
def __init__(self):
print('Sponsor pid: {}'.format(os.getpid()))
def create(self, behavior):
return Actor(behavior, self)
class Actor(object):
def __init__(self, behavior, sponsor):
self.behavior = behavior... | import os
import multiprocessing
import threading
class Sponsor(object):
def __init__(self):
print('Sponsor pid: {}'.format(os.getpid()))
def create(self, behavior):
return Actor(behavior, self)
class Actor(object):
def __init__(self, behavior, sponsor):
self.behavior = behavior... | Allow arg to specify spawning type | Allow arg to specify spawning type | Python | mit | waltermoreira/tartpy |
4df20c02934e431568105467ee44374bedddf4a5 | fabfile/dbengine.py | fabfile/dbengine.py | ###################################################################
#
# Copyright (c) 2013 Miing.org <samuel.miing@gmail.com>
#
# This software is licensed under the GNU Affero General Public
# License version 3 (AGPLv3), as published by the Free Software
# Foundation, and may be copied, distributed, and modified un... | ###################################################################
#
# Copyright (c) 2013 Miing.org <samuel.miing@gmail.com>
#
# This software is licensed under the GNU Affero General Public
# License version 3 (AGPLv3), as published by the Free Software
# Foundation, and may be copied, distributed, and modified un... | Fix 'cant import from .postgresql' | Fix 'cant import from .postgresql'
| Python | agpl-3.0 | miing/mci_migo,miing/mci_migo,miing/mci_migo |
2201aaeffb93713adcdf20f5868b5a90b562efda | pages/models.py | pages/models.py | from django.db import models
class Page(models.Model):
def __str__(self):
return self.name
name = models.CharField(max_length=64, blank=False)
name.help_text='Internal name of page'
title = models.CharField(max_length=64, blank=True)
title.help_text='Page title to display in titlebar of browser/tab'
body = ... | from django.db import models
class Page(models.Model):
def __str__(self):
return self.name
name = models.CharField(max_length=64, blank=False)
name.help_text='Internal name of page'
title = models.CharField(max_length=64, blank=True)
title.help_text='Page title to display in titlebar of browser/tab'
body = ... | Increase character limit for pages | Increase character limit for pages
Closes #70. | Python | isc | ashbc/tgrsite,ashbc/tgrsite,ashbc/tgrsite |
42918ef774625643220c182ca0eb5601841db595 | dvox/app.py | dvox/app.py | config = {
"CREATE_RETRIES": 5,
"CHUNK_LOCK_TIMEOUT_SECONDS": 10,
"WORKER_TIMEOUT_SECONDS": 15
}
| config = {
"CREATE_RETRIES": 5,
"CHUNK_LOCK_TIMEOUT_SECONDS": 10,
"WORKER_TIMEOUT_SECONDS": 15,
"CHUNK_SIZE": 25,
"BLOCK_BYTE_SIZE": 8
}
| Add controls for storage size | Add controls for storage size
| Python | mit | numberoverzero/dvox |
510063159145cd3fdc7bdd0c8b93dc46d98a88c8 | obj_sys/models.py | obj_sys/models.py | # Create your models here.
from models_obj_rel import *
from models_ufs_obj import *
try:
# apps.py
from django.apps import AppConfig
try:
import tagging
tagging.register(UfsObj)
except ImportError:
pass
except ImportError:
try:
import tagging
tagging.regi... | # Create your models here.
from models_obj_rel import *
from models_ufs_obj import *
try:
import tagging
tagging.register(UfsObj)
except ImportError:
pass
| Remove not used app config. | Remove not used app config.
| Python | bsd-3-clause | weijia/obj_sys,weijia/obj_sys |
33a9bd5cf465a56c2eb156dcbc0d4e61a0f590a4 | osmABTS/places.py | osmABTS/places.py | """
Places of interest generation
=============================
"""
| """
Places of interest generation
=============================
This module defines a class for places of interest and the functions for
generating the data structure for all of them from the OSM raw data.
Each place of interest will basically just carry the information about its
location in the **network** as the id... | Implement place class and homes generation | Implement place class and homes generation
The Place class for places of interest has been implemented, as well as
the generation of homes, which is different from the generation of other
places of interest.
| Python | mit | tschijnmo/osmABTS |
306cf5987c90d54d72037c19dd02f07be37cbb6f | make_mozilla/base/tests/decorators.py | make_mozilla/base/tests/decorators.py | from functools import wraps
from nose.plugins.attrib import attr
from nose.plugins.skip import SkipTest
__all__ = ['wip']
def fail(message):
raise AssertionError(message)
def wip(f):
@wraps(f)
def run_test(*args, **kwargs):
try:
f(*args, **kwargs)
except Exception as e:
... | from functools import wraps
from nose.plugins.attrib import attr
from nose.plugins.skip import SkipTest
import os
__all__ = ['wip']
def fail(message):
raise AssertionError(message)
def wip(f):
@wraps(f)
def run_test(*args, **kwargs):
try:
f(*args, **kwargs)
except Exception as... | Add integration test decorator to prevent certain tests running unless we really want them to. | Add integration test decorator to prevent certain tests running unless we really want them to.
| Python | bsd-3-clause | mozilla/make.mozilla.org,mozilla/make.mozilla.org,mozilla/make.mozilla.org,mozilla/make.mozilla.org |
aeae640c34b7f68870304fb2a6a163d852440b7a | test/buildbot/buildbot_config/master/schedulers.py | test/buildbot/buildbot_config/master/schedulers.py | """
This module contains the logic which returns the set of
schedulers to use for the build master.
"""
def get_schedulers():
return []
| """
This module contains the logic which returns the set of
schedulers to use for the build master.
"""
from buildbot.changes.filter import ChangeFilter
from buildbot.schedulers.basic import SingleBranchScheduler
def get_schedulers():
full = SingleBranchScheduler(name="full",
chan... | Add a scheduler for the master branch to run | Buildbot: Add a scheduler for the master branch to run
| Python | mit | mkuzmin/vagrant,zsjohny/vagrant,ferventcoder/vagrant,sni/vagrant,patrys/vagrant,ArloL/vagrant,tomfanning/vagrant,channui/vagrant,wangfakang/vagrant,muhanadra/vagrant,jkburges/vagrant,rivy/vagrant,muhanadra/vagrant,krig/vagrant,Ninir/vagrant,tbarrongh/vagrant,johntron/vagrant,petems/vagrant,signed8bit/vagrant,carlosefr/... |
9e6621ac7e4f07b9272ddb144aebbb75826d2405 | src/flock.py | src/flock.py | #!/usr/bin/env python
import cherrypy
from jinja2 import Environment, FileSystemLoader
j2_env = Environment(loader = FileSystemLoader('templates'))
class Root(object):
@cherrypy.expose
def index(self):
template = j2_env.get_template('base.html')
return template.render()
cherrypy.config.update('app.config')
ch... | #!/usr/bin/env python
from flask import Flask, redirect, render_template, request, session, url_for
from flask_oauthlib.client import OAuth, OAuthException
app = Flask(__name__)
app.config['FACEBOKK_APP_ID'] = ''
app.config['FACEBOOK_APP_SECRET'] = ''
app.config['GOOGLE_APP_ID'] = ''
app.config['GOOGLE_APP_SECRET'] =... | Switch to Flask, add oauth | Switch to Flask, add oauth
| Python | agpl-3.0 | DavidJFelix/hatchit,DavidJFelix/hatchit,DavidJFelix/hatchit |
5f63a4cddc1157e1b0cb085562ee16e55f1c88b5 | cesium/celery_app.py | cesium/celery_app.py | from celery import Celery
from cesium import _patch_celery
celery_config = {
'CELERY_ACCEPT_CONTENT': ['pickle'],
'CELERY_IMPORTS': ['cesium', 'cesium._patch_celery', 'cesium.celery_tasks'],
'CELERY_RESULT_BACKEND': 'amqp',
'CELERY_RESULT_SERIALIZER': 'pickle',
'CELERY_TASK_SERIALIZER': 'pickle',
... | from celery import Celery
from cesium import _patch_celery
import os
celery_config = {
'CELERY_ACCEPT_CONTENT': ['pickle'],
'CELERY_IMPORTS': ['cesium', 'cesium._patch_celery', 'cesium.celery_tasks'],
'CELERY_RESULT_BACKEND': 'amqp',
'CELERY_RESULT_SERIALIZER': 'pickle',
'CELERY_TASK_SERIALIZER':... | Allow broker to be overridden | Allow broker to be overridden
| Python | bsd-3-clause | mltsp/mltsp,acrellin/mltsp,bnaul/mltsp,bnaul/mltsp,bnaul/mltsp,acrellin/mltsp,mltsp/mltsp,mltsp/mltsp,acrellin/mltsp,acrellin/mltsp,mltsp/mltsp,bnaul/mltsp,mltsp/mltsp,bnaul/mltsp,bnaul/mltsp,acrellin/mltsp,acrellin/mltsp,mltsp/mltsp |
a17aade30c5925ba40eacfa2ab2a067a9141aa84 | tests/__init__.py | tests/__init__.py | #
# For the license of this file, please consult the LICENSE file in the
# root directory of this distribution.
#
# All tests in the test suite.
__all__ = ( "bitfield_tests", "zscii_tests" )
| #
# For the license of this file, please consult the LICENSE file in the
# root directory of this distribution.
#
# All tests in the test suite.
__all__ = ( "bitfield_tests", "zscii_tests", "lexer_tests", "glk_tests" )
| Make run_tests run all tests if no arguments are provided. | Make run_tests run all tests if no arguments are provided.
| Python | bsd-3-clause | BGCX262/zvm-hg-to-git,BGCX262/zvm-hg-to-git |
5ee94e9a74bc4128ed8e7e10a2106ea422f22757 | sandbox/sandbox/polls/serialiser.py | sandbox/sandbox/polls/serialiser.py |
from nap import models, fields, api, serialiser, publisher
from .models import Choice, Poll
class ChoiceSerialiser(models.ModelSerialiser):
class Meta:
model = Choice
exclude = ('poll,')
class PollSerialiser(serialiser.Serialiser):
api_name = 'poll'
question = fields.Field()
publ... |
from nap import models, fields, api, serialiser, publisher
from .models import Choice, Poll
class ChoiceSerialiser(models.ModelSerialiser):
class Meta:
model = Choice
exclude = ('poll,')
class PollSerialiser(serialiser.Serialiser):
api_name = 'poll'
question = fields.Field()
publ... | Add attribute to choices field declaration | Add attribute to choices field declaration
| Python | bsd-3-clause | MarkusH/django-nap,limbera/django-nap |
a3c49c490ffe103f759b935bae31c37c05d26e81 | tests/settings.py | tests/settings.py | # -*- coding: utf-8 -*-
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'formtools',
'tests.wizard.wizardtests',
]
SECRET_KEY = 'sp... | # -*- coding: utf-8 -*-
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/tmp/django-formtools-tests.db',
}
}
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'formtools',
... | Use a filesystem db and add the sites app to fix a test failure. | Use a filesystem db and add the sites app to fix a test failure.
| Python | bsd-3-clause | gchp/django-formtools,thenewguy/django-formtools,lastfm/django-formtools,barseghyanartur/django-formtools,thenewguy/django-formtools,barseghyanartur/django-formtools,gchp/django-formtools,lastfm/django-formtools |
36b10d57a812b393c73fe3b4117cc133d0f9d110 | templatemailer/mailer.py | templatemailer/mailer.py | import logging
from django.core import mail
from .tasks import task_email_user
logger = logging.getLogger(__name__)
def send_email(user, template, context, attachments=None, delete_attachments_after_send=False,
language_code=None):
'''
Send email to user
:param user: User instance or re... | import logging
from django.core import mail
from .tasks import task_email_user
logger = logging.getLogger(__name__)
def send_email(user, template, context, attachments=None, delete_attachments_after_send=False,
language_code=None):
'''
Send email to user
:param user: User instance or re... | Fix AttributeError when supplying email address as user | Fix AttributeError when supplying email address as user
| Python | mit | tuomasjaanu/django-templatemailer |
359cab09d0cf7de375b43f82f9a9507f3c84cd34 | distutilazy/__init__.py | distutilazy/__init__.py | """
distutilazy
-----------
Extra distutils command classes.
:license: MIT, see LICENSE for more details.
"""
__version__ = "0.4.0"
__all__ = ("clean", "pyinstaller", "command")
| """
distutilazy
-----------
Extra distutils command classes.
:license: MIT, see LICENSE for more details.
"""
__version__ = "0.4.1"
__all__ = ("clean", "command", "pyinstaller", "test")
| Add test to __all__ in package, bump version to 0.4.1 | Add test to __all__ in package, bump version to 0.4.1
| Python | mit | farzadghanei/distutilazy |
698ab729f60bdb1a4b280bf6f93e9faa0e1b63f9 | run-hooks.py | run-hooks.py | # -*- coding: utf-8 -*-
"""
Eve Demo
~~~~~~~~
A demostration of a simple API powered by Eve REST API.
The live demo is available at eve-demo.herokuapp.com. Please keep in mind
that the it is running on Heroku's free tier using a free MongoHQ
sandbox, which means that the first request to the ... | # -*- coding: utf-8 -*-
"""
Eve Demo
~~~~~~~~
A demostration of a simple API powered by Eve REST API.
The live demo is available at eve-demo.herokuapp.com. Please keep in mind
that the it is running on Heroku's free tier using a free MongoHQ
sandbox, which means that the first request to the ... | Prepare for PyCon Belarus 2018 | Prepare for PyCon Belarus 2018
| Python | bsd-3-clause | nicolaiarocci/eve-demo |
8d56fe74b373efe2dd3bbaffbde9eddd6fae6da7 | piot/sensor/sumppump.py | piot/sensor/sumppump.py | import time
from periphery import GPIO
from piot.sensor.base import BaseAnalogSensor
class SumpPump(BaseAnalogSensor):
def __init__(self):
self.min_normal=30
self.max_normal=200
self.unit='cm'
self.error_sentinel=None
def read_analog_sensor(self):
trig=GPIO(23, 'out... | import time
from periphery import GPIO
from piot.sensor.base import BaseAnalogSensor
class SumpPump(BaseAnalogSensor):
def __init__(self):
self.min_normal=30
self.max_normal=200
self.unit='cm'
self.error_sentinel=None
def read_analog_sensor(self):
trig=GPIO(23, 'out... | Return distance from sump pump sensor | Return distance from sump pump sensor
| Python | mit | tnewman/PIoT,tnewman/PIoT,tnewman/PIoT |
3d439d81766f354de9ab257d5ed690efd4aeb508 | nap/extras/actions.py | nap/extras/actions.py |
from django.http import StreamingHttpResponse
from django.utils.encoding import force_text
from .models import modelserialiser_factory
from .simplecsv import CSV
class ExportCsv(object):
def __init__(self, serialiser=None, label=None, **opts):
self.serialiser = serialiser
self.opts = opts
... |
from django.http import StreamingHttpResponse
from django.utils.encoding import force_text
from .models import modelserialiser_factory
from .simplecsv import Writer
class ExportCsv(object):
def __init__(self, serialiser=None, label=None, **opts):
self.serialiser = serialiser
self.opts = opts
... | Adjust for renamed CSV class | Adjust for renamed CSV class
| Python | bsd-3-clause | limbera/django-nap,MarkusH/django-nap |
dc47a724525186fe99d79e62447efc3dbc9d95b0 | app/groups/utils.py | app/groups/utils.py | from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
from django.contrib.sites.models import Site
def send_group_email(request, to_email, subject, email_text_template, email_html_template):
"""Sends ... | from django.conf import settings
from django.core.mail import EmailMultiAlternatives, get_connection
from django.template.loader import get_template
from django.template import Context
from django.contrib.sites.models import Site
def send_group_email(request, to_email, subject, email_text_template, email_html_template... | Send individual mails, to avoid showing the whole to list, BCC and spamholing from Google | Send individual mails, to avoid showing the whole to list, BCC and spamholing from Google
| Python | bsd-3-clause | nikdoof/test-auth |
cfcce6d4002657f72afdd780af06b3bfa4d9e10d | neo/test/iotest/test_axonaio.py | neo/test/iotest/test_axonaio.py | """
Tests of neo.io.axonaio
"""
import unittest
from neo.io.axonaio import AxonaIO
from neo.test.iotest.common_io_test import BaseTestIO
from neo.io.proxyobjects import (AnalogSignalProxy,
SpikeTrainProxy, EventProxy, EpochProxy)
from neo import (AnalogSignal, SpikeTrain)
import quantities as pq
impo... | """
Tests of neo.io.axonaio
"""
import unittest
from neo.io.axonaio import AxonaIO
from neo.test.iotest.common_io_test import BaseTestIO
from neo.io.proxyobjects import (AnalogSignalProxy,
SpikeTrainProxy, EventProxy, EpochProxy)
from neo import (AnalogSignal, SpikeTrain)
import quantities as pq
impo... | Add new files to common io tests | Add new files to common io tests
| Python | bsd-3-clause | apdavison/python-neo,NeuralEnsemble/python-neo,JuliaSprenger/python-neo,samuelgarcia/python-neo,INM-6/python-neo |
474f213cf2cc4851f9cfcd17652a29ad74ab1f0d | write_csv.py | write_csv.py | import sqlite3
import csv
from datetime import datetime
current_date = datetime.now().strftime('%Y-%m-%d')
destination_file = 'srvy' + current_date + '.csv'
sqlite_file = 'srvy.db'
table_name = 'responses'
date_column = 'date'
time_column = 'time'
score_column = 'score'
question_column = 'question'
conn = sqlite3... | import sqlite3
import csv
from datetime import datetime
current_date = str(datetime.now().strftime('%Y-%m-%d'))
destination_file = 'srvy' + current_date + '.csv'
sqlite_file = 'srvy.db'
table_name = 'responses'
date_column = 'date'
time_column = 'time'
score_column = 'score'
question_column = 'question'
conn = sq... | Change current date in SQLite query to tuple | Change current date in SQLite query to tuple
| Python | mit | andrewlrogers/srvy |
1c9540879d8761d9252c3fb3f749ae0b6d5be2b9 | wqflask/utility/elasticsearch_tools.py | wqflask/utility/elasticsearch_tools.py | es = None
try:
from elasticsearch import Elasticsearch, TransportError
from utility.tools import ELASTICSEARCH_HOST, ELASTICSEARCH_PORT
es = Elasticsearch([{
"host": ELASTICSEARCH_HOST
, "port": ELASTICSEARCH_PORT
}]) if (ELASTICSEARCH_HOST and ELASTICSEARCH_PORT) else None
except:
... | es = None
try:
from elasticsearch import Elasticsearch, TransportError
from utility.tools import ELASTICSEARCH_HOST, ELASTICSEARCH_PORT
es = Elasticsearch([{
"host": ELASTICSEARCH_HOST
, "port": ELASTICSEARCH_PORT
}]) if (ELASTICSEARCH_HOST and ELASTICSEARCH_PORT) else None
except:
... | Refactor common items to more generic methods. | Refactor common items to more generic methods.
* Refactor code that can be used in more than one place to a more
generic method/function that's called by other methods
| Python | agpl-3.0 | pjotrp/genenetwork2,zsloan/genenetwork2,DannyArends/genenetwork2,genenetwork/genenetwork2,DannyArends/genenetwork2,zsloan/genenetwork2,pjotrp/genenetwork2,DannyArends/genenetwork2,pjotrp/genenetwork2,zsloan/genenetwork2,DannyArends/genenetwork2,DannyArends/genenetwork2,zsloan/genenetwork2,pjotrp/genenetwork2,DannyArend... |
2438efb99b85fbc76cd285792c1511e7e2813a05 | zeus/api/resources/repository_tests.py | zeus/api/resources/repository_tests.py | from datetime import timedelta
from sqlalchemy.sql import func
from zeus.config import db
from zeus.constants import Result, Status
from zeus.models import Repository, TestCase, Job
from zeus.utils import timezone
from .base_repository import BaseRepositoryResource
from ..schemas import TestCaseStatisticsSchema
test... | from datetime import timedelta
from sqlalchemy.sql import func
from zeus.config import db
from zeus.constants import Result, Status
from zeus.models import Repository, TestCase, Job
from zeus.utils import timezone
from .base_repository import BaseRepositoryResource
from ..schemas import TestCaseStatisticsSchema
test... | Simplify query plan for repo tests | ref: Simplify query plan for repo tests
| Python | apache-2.0 | getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus |
08c2e38f9c87926476e7ad346001bf2a8271ab47 | wikichatter/TalkPageParser.py | wikichatter/TalkPageParser.py | import mwparserfromhell as mwp
from . import IndentTree
from . import WikiComments as wc
class Page:
def __init__(self):
self.indent = -2
def __str__(self):
return "Talk_Page"
class Section:
def __init__(self, heading):
self.heading = heading
self.indent = -1
def __st... | import mwparserfromhell as mwp
from . import IndentTree
from . import WikiComments as wc
class Page:
def __init__(self):
self.indent = -2
def __str__(self):
return "Talk_Page"
class Section:
def __init__(self, heading):
self.heading = heading
self.indent = -1
def __... | Switch to flat sections to avoid double including subsections | Switch to flat sections to avoid double including subsections
| Python | mit | kjschiroo/WikiChatter |
f35c6f989129d6298eb2f419ccb6fe8d4c734fd6 | taskq/run.py | taskq/run.py | import time
import transaction
from taskq import models
from daemon import runner
class TaskRunner():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = '/dev/tty'
self.stderr_path = '/dev/tty'
self.pidfile_path = '/tmp/task-runner.pid'
self.pidfile_timeo... | import time
import transaction
from daemon import runner
from taskq import models
class TaskDaemonRunner(runner.DaemonRunner):
def _status(self):
pid = self.pidfile.read_pid()
message = []
if pid:
message += ['Daemon started with pid %s' % pid]
else:
messag... | Add status to the daemon | Add status to the daemon
| Python | mit | LeResKP/sqla-taskq |
76abc1d6043a509418027c618d16c5a38502f2f2 | findaconf/tests/test_site_routes.py | findaconf/tests/test_site_routes.py | # coding: utf-8
from findaconf import app, db
from findaconf.tests.config import set_app, unset_app
from unittest import TestCase
class TestSiteRoutes(TestCase):
def setUp(self):
self.app = set_app(app, db)
def tearDown(self):
unset_app(db)
# test routes from blueprint/site.py
def ... | # coding: utf-8
from findaconf import app, db
from findaconf.tests.config import set_app, unset_app
from unittest import TestCase
class TestSiteRoutes(TestCase):
def setUp(self):
self.app = set_app(app, db)
def tearDown(self):
unset_app(db)
# test routes from blueprint/site.py
def ... | Add tests for login oauth links | Add tests for login oauth links
| Python | mit | cuducos/findaconf,cuducos/findaconf,koorukuroo/findaconf,koorukuroo/findaconf,koorukuroo/findaconf,cuducos/findaconf |
3e2746de9aae541880fe4cf643520a2577a3a0d5 | tof_server/views.py | tof_server/views.py | """This module provides views for application."""
from tof_server import app, versioning, mysql
from flask import jsonify, make_response
import string, random
@app.route('/')
def index():
"""Server information"""
return jsonify({
'server-version' : versioning.SERVER_VERSION,
'client-versions' :... | """This module provides views for application."""
from tof_server import app, versioning, mysql
from flask import jsonify, make_response
import string, random
@app.route('/')
def index():
"""Server information"""
return jsonify({
'server-version' : versioning.SERVER_VERSION,
'client-versions' :... | Add stub methods for map handling | Add stub methods for map handling
| Python | mit | P1X-in/Tanks-of-Freedom-Server |
757f984f37d6b3f989c7d9109a09834c2834197f | pipeline/compute_rpp/compute_rpp.py | pipeline/compute_rpp/compute_rpp.py | import sys
import os
import numpy as np
from skcycling.utils import load_power_from_fit
from skcycling.power_profile import Rpp
# The first input argument corresponding to the data path
data_path = sys.argv[1]
# The second input argument is the storage directory
storage_path = sys.argv[2]
# We can create a list of ... | import sys
import os
import numpy as np
from skcycling.utils import load_power_from_fit
from skcycling.restoration import denoise
from skcycling.power_profile import Rpp
# The first input argument corresponding to the data path
data_path = sys.argv[1]
# The second input argument is the storage directory
storage_path... | Update the pipeline to take into account the outlier rejection method to compute the RPP | Update the pipeline to take into account the outlier rejection method to compute the RPP
| Python | mit | clemaitre58/power-profile,clemaitre58/power-profile,glemaitre/power-profile,glemaitre/power-profile |
d6536696f322beba321384ec58c1576b56d3eec2 | clio/utils.py | clio/utils.py |
import json
from bson import json_util
from flask.wrappers import Request, cached_property
def getBoolean(string):
if string is None:
return False
return {
'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False, '': False, None: False
... |
import json
from bson import json_util, BSON
from flask.wrappers import Request, cached_property
def getBoolean(string):
if string is None:
return False
return {
'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False, '': False, None: F... | Add support for decoding data serialized as BSON. | Add support for decoding data serialized as BSON.
| Python | apache-2.0 | geodelic/clio,geodelic/clio |
aa359661c31df53885e19f5acb2e0171b6f87398 | recipe_scrapers/innit.py | recipe_scrapers/innit.py | from ._abstract import AbstractScraper
"""
Note that innit hosts recipes for several companies. I found it while looking at centralmarket.com
"""
class Innit(AbstractScraper):
@classmethod
def host(self, domain="com"):
return f"innit.{domain}"
| from ._abstract import AbstractScraper
"""
Note that innit hosts recipes for several companies. I found it while looking at centralmarket.com
"""
class Innit(AbstractScraper):
@classmethod
def host(self, domain="com"):
return f"innit.{domain}"
def title(self):
return self.schema.tit... | Add wrapper methods for clarity. | Add wrapper methods for clarity.
| Python | mit | hhursev/recipe-scraper |
af42088008ec2592885005e1a6e2b0ae52fd15a8 | File.py | File.py | import scipy.io.wavfile as wav
import numpy
import warnings
def wavread(filename):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
fs,x = wav.read(filename)
maxv = numpy.iinfo(x.dtype).max
x = x.astype('float')
x = x / maxv
return (fs,x)
def wavwrite(filename, fs, x):
maxv = numpy.iinfo(nump... | import scipy.io.wavfile as wav
import numpy
import warnings
def wavread(filename):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
fs,x = wav.read(filename)
maxv = numpy.iinfo(x.dtype).max
return (fs,x.astype('float') / maxv)
def wavwrite(filename, fs, x):
maxv = numpy.iinfo(numpy.int16).max
... | Test fuer WAV write und read gleichheit | Test fuer WAV write und read gleichheit
| Python | mit | antiface/dspy,nils-werner/dspy |
93d066f464a048881010a9d468a727a48e78c69d | books/CrackingCodesWithPython/Chapter20/vigenereDictionaryHacker.py | books/CrackingCodesWithPython/Chapter20/vigenereDictionaryHacker.py | # Vigenère Cipher Dictionary Hacker
# https://www.nostarch.com/crackingcodes/ (BSD Licensed)
from books.CrackingCodesWithPython.pyperclip import copy
from books.CrackingCodesWithPython.Chapter11.detectEnglish import isEnglish
from books.CrackingCodesWithPython.Chapter18.vigenereCipher import decryptMessage
def main(... | # Vigenère Cipher Dictionary Hacker
# https://www.nostarch.com/crackingcodes/ (BSD Licensed)
from books.CrackingCodesWithPython.pyperclip import copy
from books.CrackingCodesWithPython.Chapter11.detectEnglish import isEnglish
from books.CrackingCodesWithPython.Chapter18.vigenereCipher import decryptMessage
DICTIONARY... | Update vigenereDicitonaryHacker: added full path to dictionary file | Update vigenereDicitonaryHacker: added full path to dictionary file
| Python | mit | JoseALermaIII/python-tutorials,JoseALermaIII/python-tutorials |
4b54a8a038d5f9f2ead224b030f87f393d57d40b | tests/__init__.py | tests/__init__.py | """Test suite for distutils.
This test suite consists of a collection of test modules in the
distutils.tests package. Each test module has a name starting with
'test' and contains a function test_suite(). The function is expected
to return an initialized unittest.TestSuite instance.
Tests for the command classes in... | """Test suite for distutils.
This test suite consists of a collection of test modules in the
distutils.tests package. Each test module has a name starting with
'test' and contains a function test_suite(). The function is expected
to return an initialized unittest.TestSuite instance.
Tests for the command classes in... | Fix test_copyreg when numpy is installed (GH-20935) | bpo-41003: Fix test_copyreg when numpy is installed (GH-20935)
Fix test_copyreg when numpy is installed: test.pickletester now
saves/restores warnings.filters when importing numpy, to ignore
filters installed by numpy.
Add the save_restore_warnings_filters() function to the
test.support.warnings_helper module. | Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools |
19656decb756db364d012cbfb13d0ddf30e15bae | py/tests/test_runner.py | py/tests/test_runner.py | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | Fix running python tests by changing the env directly | [SW-1610][FollowUp] Fix running python tests by changing the env directly
(cherry picked from commit 0d808a100cd14fce9d4fba4f9cde6ad5315fbc12)
| Python | apache-2.0 | h2oai/sparkling-water,h2oai/sparkling-water,h2oai/sparkling-water,h2oai/sparkling-water |
bc6999e5e587a5e4dfd8b65f168de8ebce8bc93b | webnotes/website/doctype/blog_category/blog_category.py | webnotes/website/doctype/blog_category/blog_category.py | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import webnotes
from webnotes.webutils import WebsiteGenerator, cleanup_page_name, clear_cache
class DocType(WebsiteGenerator):
def __init__(self, d, dl):
self.doc, self.do... | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import webnotes
from webnotes.webutils import WebsiteGenerator, cleanup_page_name, clear_cache
class DocType(WebsiteGenerator):
def __init__(self, d, dl):
self.doc, self.do... | Fix in Blog Category Naming | Fix in Blog Category Naming
| Python | mit | aboganas/frappe,RicardoJohann/frappe,gangadharkadam/letzfrappe,mbauskar/omnitech-demo-frappe,mhbu50/frappe,BhupeshGupta/frappe,gangadhar-kadam/laganfrappe,mbauskar/omnitech-frappe,shitolepriya/test-frappe,shitolepriya/test-frappe,mbauskar/tele-frappe,gangadharkadam/letzfrappe,gangadharkadam/frappecontribution,sbktechno... |
37bedf8495834f0773f8a082c3f358321ebb8f77 | src/utils.py | src/utils.py | import os
vowels = ['a e i o u']
constanents = ['b c d f g h j k l m n p q r s t v w x y z 1 2 3 4 \
5 6 7 8 9 0']
def inInventory(itemClass, player):
for item in player.inventory:
if isinstance(item, itemClass):
return True
break
return False
def getItemFrom... | import os
vowels = ['a e i o u'].split(' ')
consonants = ['b c d f g h j k l m n p q r s t v w x y z 1 2 3 4 \
5 6 7 8 9 0'].split(' ')
def inInventory(itemClass, player):
for item in player.inventory:
if isinstance(item, itemClass):
return True
break
return Fa... | Fix @DaVinci789's crappy spelling >:) | Fix @DaVinci789's crappy spelling >:)
| Python | mit | allanburleson/python-adventure-game,disorientedperson/python-adventure-game |
b57a2e184e3861617c12801529295b0095257cd9 | petition/resources.py | petition/resources.py | from import_export import resources
from .models import Signature
class SignatureResource(resources.ModelResource):
class Meta:
exclude = ('created_on', 'modified_on')
model = Signature
| from import_export import resources
import swapper
Signature = swapper.load_model("petition", "Signature")
class SignatureResource(resources.ModelResource):
class Meta:
model = Signature
| Fix swappable model in signature export | Fix swappable model in signature export
| Python | mit | watchdogpolska/django-one-petition,watchdogpolska/django-one-petition,watchdogpolska/django-one-petition |
8851223a1576a4e164449b589f68c0420966d622 | PythonScript/GenerateBook.py | PythonScript/GenerateBook.py | #Set Cover=Cover
#Set BookCover=%BookName%%Cover%
#Set BookCoverHTML=%BookCover%%HTMLExt%
#Call pandoc ..\source\%BookCover%%BookExt% -o %BookCoverHTML% --standalone %CSS_%%Cover%%CSSExt% --verbose
def GenerateCover():
pass
if __name__ == '__main__':
GenerateCover()
| import subprocess
def GenerateCover():
Cover = "Cover"
BookName = "BookName"
BookCover = BookName + Cover
BookExt = "BookExt"
HTMLExt = "HTMLExt"
BookCoverHTML = BookCover + HTMLExt
CSS = "CSS_"
CSSExt = "CSSExt"
pandocCommand = "pandoc ..\\source\\" + BookCover + BookExt + " -o "
+ BookCoverHTML + " -standa... | Implement GenerateCover using fake vars | Implement GenerateCover using fake vars
| Python | mit | fan-jiang/Dujing |
2b7a703aab3e07cee82a0b1cc494dab71d7c22df | bin/build-scripts/write_build_time.py | bin/build-scripts/write_build_time.py | #!/usr/bin/env python
import time
now = time.time()
formatted = time.strftime("%B %d, %Y %H:%M:%S UTC", time.gmtime())
print 'exports.string = %r' % formatted
# Note Javascript uses milliseconds:
print 'exports.timestamp = %i' % int(now * 1000)
import subprocess
print 'exports.gitrevision = %r' % subprocess.check_ou... | #!/usr/bin/env python
import time
now = time.time()
formatted = time.strftime("%B %d, %Y %H:%M:%S UTC", time.gmtime())
print 'exports.string = %r' % formatted
# Note Javascript uses milliseconds:
print 'exports.timestamp = %i' % int(now * 1000)
import subprocess
print 'exports.gitrevision = %r' % subprocess.check_ou... | Use correct latest commit in __version__ endpoint | Use correct latest commit in __version__ endpoint
| Python | mpl-2.0 | mozilla-services/pageshot,mozilla-services/screenshots,mozilla-services/pageshot,mozilla-services/pageshot,mozilla-services/screenshots,mozilla-services/screenshots,mozilla-services/screenshots,mozilla-services/pageshot |
3a57d826a957b864753895d8769dcf747d489e1b | administrator/serializers.py | administrator/serializers.py | from categories.models import Category, Keyword, Subcategory
from rest_framework import serializers
class SubcategoryListSerializer(serializers.ModelSerializer):
class Meta:
model = Subcategory
fields = ('pk', 'name')
class CategorySerializer(serializers.ModelSerializer):
subcategories = Sub... | from categories.models import Category, Keyword, Subcategory
from rest_framework import serializers
class SubcategoryListSerializer(serializers.ModelSerializer):
class Meta:
model = Subcategory
fields = ('pk', 'name')
class CategorySerializer(serializers.ModelSerializer):
subcategories = Sub... | Remove category serializer from subcategory serializer | Remove category serializer from subcategory serializer
| Python | apache-2.0 | belatrix/BackendAllStars |
2ce08224bc87ae34f546211c80d2b89a38acd0ec | chromepass.py | chromepass.py | from os import getenv
import sqlite3
import win32crypt
csv_file = open("chromepass.csv",'wb')
csv_file.write("link,username,password\n".encode('utf-8'))
appdata = getenv("APPDATA")
if appdata[-7:] == "Roaming": #Some WINDOWS Installations point to Roaming.
appdata = appdata[:-8]
connection = sqlite3.connect(appdata +... | from os import getenv
import sqlite3
import win32crypt
import argparse
def args_parser():
parser = argparse.ArgumentParser(description="Retrieve Google Chrome Passwords")
parser.add_argument("--output", help="Output to csv file", action="store_true")
args = parser.parse_args()
if args.output:
... | Complete Overhaul. Argeparse used. Outputs to csv | Complete Overhaul. Argeparse used. Outputs to csv
| Python | mit | hassaanaliw/chromepass |
7a2e6723a925626b1d8ee6f70c656a9fd5befd5d | airflow/utils/__init__.py | airflow/utils/__init__.py | # -*- coding: utf-8 -*-
#
# 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
... | # -*- coding: utf-8 -*-
#
# 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
... | Fix airflow.utils deprecation warning code being Python 3 incompatible | Fix airflow.utils deprecation warning code being Python 3 incompatible
See https://docs.python.org/3.0/whatsnew/3.0.html#operators-and-special-methods
| Python | apache-2.0 | wooga/airflow,AllisonWang/incubator-airflow,sid88in/incubator-airflow,nathanielvarona/airflow,gritlogic/incubator-airflow,hgrif/incubator-airflow,gilt/incubator-airflow,sdiazb/airflow,andyxhadji/incubator-airflow,vijaysbhat/incubator-airflow,dmitry-r/incubator-airflow,mtagle/airflow,gritlogic/incubator-airflow,mrares/i... |
fb03522237afdd56059fb0146e1609b85606286f | l10n_ch_import_cresus/__openerp__.py | l10n_ch_import_cresus/__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Author Vincent Renaville
# Copyright 2015 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pu... | # -*- coding: utf-8 -*-
##############################################################################
#
# Author Vincent Renaville
# Copyright 2015 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pu... | Add Odoo Community Association (OCA) as author | Add Odoo Community Association (OCA) as author | Python | agpl-3.0 | open-net-sarl/l10n-switzerland,BT-ojossen/l10n-switzerland,cgaspoz/l10n-switzerland,CompassionCH/l10n-switzerland,BT-fgarbely/l10n-switzerland,BT-csanchez/l10n-switzerland,cyp-opennet/ons_cyp_github,BT-fgarbely/l10n-switzerland,ndtran/l10n-switzerland,CompassionCH/l10n-switzerland,cyp-opennet/ons_cyp_github,open-net-sa... |
53ff13fa0822dbabf554360bf000f8b3bfe41f40 | imagersite/imager_profile/models.py | imagersite/imager_profile/models.py | from django.db import models
# Create your models here.
| """Establish models for the imager site's User Profile."""
from django.db import models
from django.contrib.auth.models import User
class ImagerProfile(models.Model):
"""Profile attached to User models by one-to-one relationship."""
user = models.OneToOneField(User, related_name='profile')
is_active = mo... | Set up basic imagerprofile and made first migration | Set up basic imagerprofile and made first migration
| Python | mpl-2.0 | WillWeatherford/django-imager,WillWeatherford/django-imager |
48d0dc98fd859ea1d8cf25370fe0be9ac1350448 | selftest/subdir/proc.py | selftest/subdir/proc.py | # Copyright 2012 Dietrich Epp <depp@zdome.net>
# See LICENSE.txt for details.
@test
def nostdin_1():
check_output(['./nostdin'], 'Test', '')
@test(fail=True)
def nostdin_2_fail():
check_output(['./nostdin'], 'Test', 'Bogus')
@test
def nostdout_1():
check_output(['./nostdout'], 'Test', '')
@test(fail=Tru... | # Copyright 2012 Dietrich Epp <depp@zdome.net>
# See LICENSE.txt for details.
@test(fail=True)
def nostdin_1():
check_output(['./nostdin'], 'Test', '')
fail("The pipe didn't break, but that's okay")
@test(fail=True)
def nostdin_2_fail():
check_output(['./nostdin'], 'Test', 'Bogus')
@test
def nostdout_1()... | Mark broken pipe test with expected failure | Mark broken pipe test with expected failure
| Python | bsd-2-clause | depp/idiotest,depp/idiotest |
39708edfad5698b34771eba941ac822cbf84baa7 | readthedocs/oauth/migrations/0004_drop_github_and_bitbucket_models.py | readthedocs/oauth/migrations/0004_drop_github_and_bitbucket_models.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('oauth', '0003_move_github'),
]
operations = [
migrations.RemoveField(
model_name='bitbucketproject',
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def forwards_remove_content_types(apps, schema_editor):
db = schema_editor.connection.alias
ContentType = apps.get_model('contenttypes', 'ContentType')
ContentType.objects.using(db).filter(
ap... | Drop content type in migration as well | Drop content type in migration as well
| Python | mit | stevepiercy/readthedocs.org,techtonik/readthedocs.org,pombredanne/readthedocs.org,rtfd/readthedocs.org,stevepiercy/readthedocs.org,istresearch/readthedocs.org,techtonik/readthedocs.org,pombredanne/readthedocs.org,tddv/readthedocs.org,espdev/readthedocs.org,istresearch/readthedocs.org,rtfd/readthedocs.org,davidfischer/r... |
056b4ae938ab1aacf5e3f48a1e17919a79ff29b7 | scripts/sbatch_cancel.py | scripts/sbatch_cancel.py | import subprocess
import sys
import getpass
### Kill a job and its chain of dependents (as created by sbatch_submit).
### Usage: python sbatch_cancel.py [Name of first running job in chain] ... | import subprocess
import sys
import getpass
### Kill a job and its chain of dependents (as created by sbatch_submit).
### Usage: python sbatch_cancel.py [Name of first running job in chain] [Name of fi... | Kill multiple chains at once. | Kill multiple chains at once.
| Python | mit | nyu-mll/spinn,nyu-mll/spinn,nyu-mll/spinn |
cef6f3cce4a942bea53d6bae639dcd48d680d05a | gpytorch/means/linear_mean.py | gpytorch/means/linear_mean.py | #!/usr/bin/env python3
import torch
from .mean import Mean
class LinearMean(Mean):
def __init__(self, input_size, batch_shape=torch.Size(), bias=True):
super().__init__()
self.register_parameter(name='weights',
parameter=torch.nn.Parameter(torch.randn(*batch_shape,... | #!/usr/bin/env python3
import torch
from .mean import Mean
class LinearMean(Mean):
def __init__(self, input_size, batch_shape=torch.Size(), bias=True):
super().__init__()
self.register_parameter(name='weights',
parameter=torch.nn.Parameter(torch.randn(*batch_shape,... | Fix LinearMean bias when bias=False | Fix LinearMean bias when bias=False
| Python | mit | jrg365/gpytorch,jrg365/gpytorch,jrg365/gpytorch |
f00fd0fde81a340cf00030bbe2562b8c878edd41 | src/yawf/signals.py | src/yawf/signals.py | from django.dispatch import Signal
message_handled = Signal(providing_args=['message', 'instance', 'new_revision'])
| from django.dispatch import Signal
message_handled = Signal(
providing_args=['message', 'instance', 'new_revision', 'transition_result']
)
| Add new arg in message_handled signal definition | Add new arg in message_handled signal definition
| Python | mit | freevoid/yawf |
5a76457e2b9596ad3497b0145410a2f4090a5c54 | tests/mixins.py | tests/mixins.py | class RedisCleanupMixin(object):
client = None
prefix = None
def setUp(self):
super(RedisCleanupMixin, self).setUp()
self.assertIsNotNone(self.client, "Need a redis client to be provided")
def tearDown(self):
root = '*'
if self.prefix is not None:
root = '{}... | class RedisCleanupMixin(object):
client = None
prefix = NotImplemented # type: str
def setUp(self):
super(RedisCleanupMixin, self).setUp()
self.assertIsNotNone(self.client, "Need a redis client to be provided")
def tearDown(self):
root = '*'
if self.prefix is not None:... | Add annotation required for mypy | Add annotation required for mypy
| Python | bsd-3-clause | thread/django-lightweight-queue,thread/django-lightweight-queue |
e281c9ab30acdbc60439a143557efdeaf4757e1b | tests/integration/test_kcm_install.py | tests/integration/test_kcm_install.py | from . import integration
import os
import tempfile
def test_kcm_install():
# Install kcm to a temporary directory.
install_dir = tempfile.mkdtemp()
integration.execute(integration.kcm(),
["install",
"--install-dir={}".format(install_dir)])
installed_kc... | from . import integration
import os
import tempfile
def test_kcm_install():
# Install kcm to a temporary directory.
install_dir = tempfile.mkdtemp()
integration.execute(integration.kcm(),
["install",
"--install-dir={}".format(install_dir)])
installed_kc... | Remove the installed kcm binary after int tests. | Remove the installed kcm binary after int tests.
| Python | apache-2.0 | Intel-Corp/CPU-Manager-for-Kubernetes,Intel-Corp/CPU-Manager-for-Kubernetes,Intel-Corp/CPU-Manager-for-Kubernetes |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.