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 |
|---|---|---|---|---|---|---|---|---|---|
66ae5304c81d74e8f30e9274c90d0f83766744d7 | datamodel/nodes/printer.py | datamodel/nodes/printer.py | import sys
from datamodel.base import node
class ConsolePrinter(node.Node):
"""
This node prints on stdout its context and then returns it as output.
"""
def input(self, context):
self._context = context
def output(self):
sys.stdout.write(self._context)
return self._conte... | import sys
import os
from datamodel.base import node
class ConsolePrinter(node.Node):
"""
This node prints on stdout its context and then returns it as output.
"""
def input(self, context):
self._context = context
def output(self):
try:
sys.stdout.write(str(self._cont... | Make sure we only write chars to stdout | Make sure we only write chars to stdout
| Python | apache-2.0 | csparpa/robograph,csparpa/robograph |
f7153fd88f07f99181f790a93559efd585272f18 | nuxeo-drive-client/tests/test_copy.py | nuxeo-drive-client/tests/test_copy.py | from tests.common_unit_test import UnitTestCase
class TestCopy(UnitTestCase):
def test_synchronize_remote_copy(self):
local = self.local_client_1
remote = self.remote_document_client_1
# Create a file and a folder in the remote root workspace
remote.make_file('/', 'test.odt', 'So... | from tests.common_unit_test import RandomBug, UnitTestCase
class TestCopy(UnitTestCase):
@RandomBug('NXDRIVE-808', target='linux', repeat=5)
def test_synchronize_remote_copy(self):
local = self.local_client_1
remote = self.remote_document_client_1
# Create a file and a folder in the ... | Add RandomBug for Linux on test_synchronize_remote_copy | NXDRIVE-808: Add RandomBug for Linux on test_synchronize_remote_copy
| Python | lgpl-2.1 | ssdi-drive/nuxeo-drive,ssdi-drive/nuxeo-drive,ssdi-drive/nuxeo-drive |
0dc72761a3b4b17098633df27fdbb70058afe311 | geotrek/signage/migrations/0013_auto_20200423_1255.py | geotrek/signage/migrations/0013_auto_20200423_1255.py | # Generated by Django 2.0.13 on 2020-04-23 12:55
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('signage', '0012_auto_20200406_1411'),
]
operations = [
migrations.RunSQL(sql=[("DELETE FROM geotrek.signag... | # Generated by Django 2.0.13 on 2020-04-23 12:55
from django.db import migrations, models
import django.db.models.deletion
def delete_force(apps, schema_editor):
# We can't import Infrastructure models directly as it may be a newer
# version than this migration expects. We use the historical version.
Bla... | Change order migration, user runpython instead | Change order migration, user runpython instead
| Python | bsd-2-clause | makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin |
b6d4baa9d30362a291567f078c1f93df7a63aeaa | waterbutler/providers/osfstorage/metadata.py | waterbutler/providers/osfstorage/metadata.py | from waterbutler.core import metadata
class BaseOsfStorageMetadata:
@property
def provider(self):
return 'osfstorage'
class OsfStorageFileMetadata(BaseOsfStorageMetadata, metadata.BaseFileMetadata):
@property
def name(self):
return self.raw['name']
@property
def path(self):
... | from waterbutler.core import metadata
class BaseOsfStorageMetadata:
@property
def provider(self):
return 'osfstorage'
class OsfStorageFileMetadata(BaseOsfStorageMetadata, metadata.BaseFileMetadata):
@property
def name(self):
return self.raw['name']
@property
def path(self):
... | Return full path if it exists for OSF | Return full path if it exists for OSF
| Python | apache-2.0 | cosenal/waterbutler,Ghalko/waterbutler,CenterForOpenScience/waterbutler,icereval/waterbutler,Johnetordoff/waterbutler,TomBaxter/waterbutler,rdhyee/waterbutler,felliott/waterbutler,RCOSDP/waterbutler,rafaeldelucena/waterbutler,chrisseto/waterbutler,hmoco/waterbutler,kwierman/waterbutler |
f2fd526e08cc5576c651a7677c781c0c0bb7c94c | tests/test_jg.py | tests/test_jg.py | from jg.__main__ import main, generate_template_graph
from mock import patch
FIXTURE_GRAPH = (
'digraph {\n'
'\t"snippets/sub/analytics.html"\n'
'\t"snippets/ga.html"\n'
'\t\t"snippets/ga.html" -> "snippets/sub/analytics.html"\n'
'\t"header.html"\n'
'\t"analytics.html"\... | from jg.__main__ import main, generate_template_graph
from mock import patch
FIXTURE_GRAPH = (
'digraph {\n'
'\t"snippets/sub/analytics.html"\n'
'\t"snippets/ga.html"\n'
'\t\t"snippets/ga.html" -> "snippets/sub/analytics.html"\n'
'\t"header.html"\n'
'\t"analytics.html"\... | Fix test generating graph file | Fix test generating graph file
| Python | bsd-2-clause | abele/jinja-graph |
fe9a47f480b8db8de3b2b572f333e56497462ea2 | Python/item15.py | Python/item15.py | # -*- coding: utf-8 -*-
def sort_priority(num,pro):
res=num[:]
def helper(x):
if x in pro:
return (0,x)
return (1,x)
res.sort(key=helper)
return res
def sort_priority3(num,pro):
found=False
def helper(x):
nonlocal found
if x in pro:
found=True
return (0,x)
return (1,x... | # -*- coding: utf-8 -*-
def sort_priority(num,pro):
res=num[:]
def helper(x):
if x in pro:
return (0,x)
return (1,x)
res.sort(key=helper)
return res
def sort_priority2(num,pro):
found=[False]
def helper(x):
nonlocal found
if x in pro:
found[0]=True
return (0,x)
return... | Add the sort_priority2 for python2. | Add the sort_priority2 for python2.
| Python | mit | Vayne-Lover/Effective |
0599e76db6c1eef495a608d7386601bbee3cfbc5 | test/authinfo.py | test/authinfo.py | import unittest
from testbase import MQWebTest
'''
Test for AuthenticationInformationController
'''
class TestAuthInfoActions(MQWebTest):
'''
Test Inquire with HTTP GET
'''
def testInquire(self):
json = self.getJSON('/api/authinfo/inquire/' + self.qmgr)
'''
Test Inquire with HTTP POST
'''
def testInquire... | import unittest
from testbase import MQWebTest
'''
Test for AuthenticationInformationController
'''
class TestAuthInfoActions(MQWebTest):
'''
Test Inquire with HTTP GET
'''
def testInquire(self):
json = self.getJSON('/api/authinfo/inquire/' + self.qmgr)
'''
Test Empty Result with HTTP GET
'''
def testEmpt... | Add test for empty responses | Add test for empty responses
| Python | mit | fbraem/mqweb,fbraem/mqweb,fbraem/mqweb |
d4a0a85673b5d61b82c65e77efcd6518da719952 | pmxbot/__init__.py | pmxbot/__init__.py | # vim:ts=4:sw=4:noexpandtab
import socket
import logging as _logging
from .dictlib import ConfigDict
config = ConfigDict(
bot_nickname='pmxbot',
database='sqlite:pmxbot.sqlite',
server_host='localhost',
server_port=6667,
use_ssl=False,
password=None,
nickserv_password=None,
silent_bot=False,
log_channels=[]... | # vim:ts=4:sw=4:noexpandtab
import socket
import logging as _logging
from .dictlib import ConfigDict
config = ConfigDict(
bot_nickname='pmxbot',
database='sqlite:pmxbot.sqlite',
server_host='localhost',
server_port=6667,
use_ssl=False,
password=None,
nickserv_password=None,
silent_bot=False,
log_channels=[]... | Remove places default config. It doesn't appear to be used anywhere. | Remove places default config. It doesn't appear to be used anywhere.
| Python | mit | yougov/pmxbot,yougov/pmxbot,yougov/pmxbot |
525cbab46570342098613ae591749b4cf5026453 | tests/terrain.py | tests/terrain.py | from lettuce import world
import os
"""
Set world.basedir relative to this terrain.py file,
when running lettuce from this directory,
and add the directory it to the import path
"""
world.basedir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
os.sys.path.insert(0,world.basedir)
world.bas... | from lettuce import world
import os
"""
Set world.basedir relative to this terrain.py file,
when running lettuce from this directory,
and add the directory it to the import path
"""
world.basedir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
os.sys.path.insert(0,world.basedir)
world.bas... | Create the tests output directory automatically. | Create the tests output directory automatically.
| Python | mit | gnott/elife-poa-xml-generation,gnott/elife-poa-xml-generation |
8d09a8557433d95015010465b62f31ffe7b6fe2c | usb/shortener.py | usb/shortener.py | from hashids import Hashids
class Shortener(object):
def __init__(self, secret, min_length, short_url_domain):
self.secret = secret
self.min_length = min_length
self.short_url_domain = short_url_domain
self._hasher = None
def get_short_id(self, number):
if self._hashe... | from hashids import Hashids
class Shortener(object):
def __init__(self, secret, min_length, short_url_domain):
self.secret = secret
self.min_length = min_length
self.short_url_domain = short_url_domain
self._hasher = Hashids(self.secret, self.min_length)
def get_short_id(self... | Move hasher creation to constructor | Move hasher creation to constructor
| Python | mit | dizpers/usb |
b5ae6290382ef69f9d76c0494aee90f85bdf2c16 | plugins/Views/SimpleView/__init__.py | plugins/Views/SimpleView/__init__.py | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import SimpleView
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
def getMetaData():
return {
"plugin": {
"name": i18n_catalog.i18nc("@label", "Simple View"),
... | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import SimpleView
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
def getMetaData():
return {
"type": "view",
"plugin": {
"name": i18n_catalog.i18nc("@label"... | Fix plug-in type and description key | Fix plug-in type and description key
't Was a typo.
Contributes to issue CURA-1190.
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium |
35c7d7816c3c441286519658a3426a5f03aca284 | plugins/check_pinned/check_pinned.py | plugins/check_pinned/check_pinned.py | from __future__ import unicode_literals
# don't convert to ascii in py2.7 when creating string to return
crontable = []
outputs = []
# Catch all the events
def catch_all(data):
print(data)
# Only handles when a user becomes active
def process_presence_change(data):
print("PRESENCE CHANGE")
# While we ca... | from __future__ import unicode_literals
# don't convert to ascii in py2.7 when creating string to return
crontable = []
outputs = []
# Catch all the events
def catch_all(data):
print(data)
# Only handles when a user becomes active
def process_presence_change(data):
print("PRESENCE CHANGE")
# While we ca... | Add note about potential work around | Add note about potential work around
The bot itself cannot send a message only on presence_change actions
We may be able to contact the slack bot to send a message in our stead instead.
| Python | mit | pyamanak/oithdbot |
e4ee7034291fbeda48efa0d1c617be8a20eb49bd | algorithms/python/496_next_greater_element.py | algorithms/python/496_next_greater_element.py | class Solution(object):
def nextGreaterElement(self, findNums, nums):
"""
:type findNums: List[int]
:type nums: List[int]
:rtype: List[int]
"""
results = []
for findNum in findNums:
index = nums.index(findNum)
result = index + 1
... | class Solution(object):
def nextGreaterElement(self, findNums, nums):
"""
:type findNums: List[int]
:type nums: List[int]
:rtype: List[int]
"""
results = []
for findNum in findNums:
index = nums.index(findNum)
result = index + 1
... | Add another solution for 496 next greater element | Add another solution for 496 next greater element
| Python | mit | ruichao-factual/leetcode |
e5daa53aab94360c2e06a6cb608c4992b25becc6 | test/helpers.py | test/helpers.py | # -*- coding: utf-8 -*-
"""
helpers
~~~~~~~
This module contains helpers for the h2 tests.
"""
from hyperframe.frame import HeadersFrame, DataFrame
from hpack.hpack import Encoder
class FrameFactory(object):
"""
A class containing lots of helper methods and state to build frames. This
allows test cases t... | # -*- coding: utf-8 -*-
"""
helpers
~~~~~~~
This module contains helpers for the h2 tests.
"""
from hyperframe.frame import HeadersFrame, DataFrame
from hpack.hpack import Encoder
class FrameFactory(object):
"""
A class containing lots of helper methods and state to build frames. This
allows test cases t... | Allow stream ids != 1 in frame factory. | Allow stream ids != 1 in frame factory.
| Python | mit | Kriechi/hyper-h2,mhils/hyper-h2,bhavishyagopesh/hyper-h2,Kriechi/hyper-h2,vladmunteanu/hyper-h2,python-hyper/hyper-h2,python-hyper/hyper-h2,vladmunteanu/hyper-h2 |
1509336a27d80eae68e56cfa776bd8342221297f | tests/scoring_engine/engine/test_basic_check.py | tests/scoring_engine/engine/test_basic_check.py | from scoring_engine.engine.basic_check import BasicCheck
from scoring_engine.models.service import Service
from scoring_engine.models.environment import Environment
from scoring_engine.models.account import Account
from tests.scoring_engine.unit_test import UnitTest
class TestBasicCheck(UnitTest):
def setup(sel... | import pytest
from scoring_engine.engine.basic_check import BasicCheck
from scoring_engine.models.service import Service
from scoring_engine.models.environment import Environment
from scoring_engine.models.account import Account
from tests.scoring_engine.unit_test import UnitTest
class TestBasicCheck(UnitTest):
... | Add test for incorrect check properties | Add test for incorrect check properties
| Python | mit | pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine |
8b5ccf93fbac8929ecfc185d7407a79b1e890bde | project_template/project_settings.py | project_template/project_settings.py | # Do not commit secrets to VCS.
# Local environment variables will be loaded from `.env.local`.
# Additional environment variables will be loaded from `.env.$DOTENV`.
# Local settings will be imported from `icekit_settings_local.py`
from icekit.project.settings.icekit import * # icekit, glamkit
# Override the defau... | # Do not commit secrets to VCS.
# Local environment variables will be loaded from `.env.local`.
# Additional environment variables will be loaded from `.env.$DOTENV`.
# Local settings will be imported from `icekit_settings_local.py`
from icekit.project.settings.glamkit import * # glamkit, icekit
# Override the defa... | Use GLAMkit settings in default project template. | Use GLAMkit settings in default project template.
| Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit |
6cfc784ce3136cbec8c88948f4d6b45f9070b91b | pyqode/__init__.py | pyqode/__init__.py | # -*- coding: utf-8 -*-
"""
pyQode is a code editor framework for python qt applications.
"""
import pkg_resources
pkg_resources.declare_namespace(__name__)
| # -*- coding: utf-8 -*-
"""
pyQode is a source code editor widget for Python Qt (PyQt5/PyQt4/PySide)
pyQode is a **namespace package**.
"""
import pkg_resources
pkg_resources.declare_namespace(__name__) | Fix pyqode main docstring (uniformised with other pyqode namespace packages) | Fix pyqode main docstring (uniformised with other pyqode namespace packages)
| Python | mit | mmolero/pyqode.python,pyQode/pyqode.python,zwadar/pyqode.python,pyQode/pyqode.python |
226e8c322670a310fcfb9eb95d9d59838bbac3d3 | refcollections/admin_custom.py | refcollections/admin_custom.py | from django.contrib.admin.sites import AdminSite
from django.conf.urls.defaults import patterns, url
from shells.admin_views import ShellsImagesUploader, upload_species_spreadsheet
class ShellsAdmin(AdminSite):
def get_urls(self):
urls = super(ShellsAdmin, self).get_urls()
my_urls = patterns('',
... | from django.contrib.admin.sites import AdminSite
from django.conf.urls.defaults import patterns, url
from shells.admin_views import ShellsImagesUploader, upload_species_spreadsheet
class ShellsAdmin(AdminSite):
def get_urls(self):
urls = super(ShellsAdmin, self).get_urls()
my_urls = patterns('',
... | Add User back into admin | Add User back into admin
| Python | bsd-3-clause | uq-eresearch/archaeology-reference-collections,uq-eresearch/archaeology-reference-collections,uq-eresearch/archaeology-reference-collections,uq-eresearch/archaeology-reference-collections |
52d38e360b14fcfad01f87ff1e9ca5db27004877 | src/comms/admin.py | src/comms/admin.py | #
# This sets up how models are displayed
# in the web admin interface.
#
from django.contrib import admin
from src.comms.models import ChannelDB
class MsgAdmin(admin.ModelAdmin):
list_display = ('id', 'db_date_sent', 'db_sender', 'db_receivers',
'db_channels', 'db_message', 'db_lock_storage'... | #
# This sets up how models are displayed
# in the web admin interface.
#
from django.contrib import admin
from src.comms.models import ChannelDB
class MsgAdmin(admin.ModelAdmin):
list_display = ('id', 'db_date_sent', 'db_sender', 'db_receivers',
'db_channels', 'db_message', 'db_lock_storage'... | Remove unsupport M2M field in channelAdmin handler. Removes traceback when DEBUG=True. | Remove unsupport M2M field in channelAdmin handler. Removes traceback when DEBUG=True.
| Python | bsd-3-clause | ypwalter/evennia,TheTypoMaster/evennia,TheTypoMaster/evennia,mrkulk/text-world,mrkulk/text-world,titeuf87/evennia,ergodicbreak/evennia,mrkulk/text-world,feend78/evennia,shollen/evennia,jamesbeebop/evennia,shollen/evennia,feend78/evennia,ergodicbreak/evennia,feend78/evennia,titeuf87/evennia,mrkulk/text-world,jamesbeebop... |
21b6a5573190848b93de930b9d41e1ac766c18bc | src/epiweb/urls.py | src/epiweb/urls.py | from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
import epiweb.apps.survey.urls
urlpatterns = patterns('',
# Example:
# (r'^epiweb/', include('epiweb.foo.urls')),
# Uncomment the admin/doc line below and add... | from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
import epiweb.apps.survey.urls
urlpatterns = patterns('',
# Example:
# (r'^epiweb/', include('epiweb.foo.urls')),
# Uncomment the admin/doc line below and add... | Add user registration URLs. Use what django-registration provides for the moment. | Add user registration URLs. Use what django-registration provides for the moment.
| Python | agpl-3.0 | ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website |
017de01e8a1ec8f49069cf546e89652b4ddb8e39 | tests/test_create_template.py | tests/test_create_template.py | # -*- coding: utf-8 -*-
"""
test_create_template
--------------------
"""
import os
import pytest
import subprocess
@pytest.fixture
def output_dir(tmpdir):
return str(tmpdir.mkdir('output'))
def run_tox(plugin):
"""Run the tox suite of the newly created plugin."""
try:
subprocess.check_call([... | # -*- coding: utf-8 -*-
"""
test_create_template
--------------------
"""
import os
import pytest
import subprocess
def run_tox(plugin):
"""Run the tox suite of the newly created plugin."""
try:
subprocess.check_call([
'tox',
plugin,
'-c', os.path.join(plugin, 't... | Remove output_dir fixture from test | Remove output_dir fixture from test
| Python | mit | pytest-dev/cookiecutter-pytest-plugin |
18b0ddbbca429778a70f1e9b7f7d5140eb88d68f | tests/test_fs.py | tests/test_fs.py | from farmfs.fs import normpath as _normalize
from farmfs.fs import userPath2Path as up2p
from farmfs.fs import Path
def test_normalize_abs():
assert _normalize("/") == "/"
assert _normalize("/a") == "/a"
assert _normalize("/a/") == "/a"
assert _normalize("/a/b") == "/a/b"
assert _normalize(... | from farmfs.fs import normpath as _normalize
from farmfs.fs import userPath2Path as up2p
from farmfs.fs import Path
def test_normalize_abs():
assert _normalize("/") == "/"
assert _normalize("/a") == "/a"
assert _normalize("/a/") == "/a"
assert _normalize("/a/b") == "/a/b"
assert _normalize(... | Add test to Path compare. | Add test to Path compare. | Python | mit | andrewguy9/farmfs,andrewguy9/farmfs |
c41d0a9f03e66fdc20fb093aaad87cdd6f60461e | studies/helpers.py | studies/helpers.py | from django.core.mail.message import EmailMultiAlternatives
from django.template.loader import get_template
from project.settings import EMAIL_FROM_ADDRESS, BASE_URL
# TODO: celery taskify
def send_mail(template_name, subject, to_addresses, cc=None, bcc=None, from_email=None, **context):
"""
Helper for sendi... | from django.core.mail.message import EmailMultiAlternatives
from django.template.loader import get_template
from project.celery import app
from project.settings import EMAIL_FROM_ADDRESS, BASE_URL
@app.task
def send_mail(template_name, subject, to_addresses, cc=None, bcc=None, from_email=None, **context):
"""
... | Add decorator to send_mail function to celery taskify. | Add decorator to send_mail function to celery taskify.
| Python | apache-2.0 | pattisdr/lookit-api,pattisdr/lookit-api,CenterForOpenScience/lookit-api,CenterForOpenScience/lookit-api,pattisdr/lookit-api,CenterForOpenScience/lookit-api |
49a1548399fa822515920d910ec6ea6a6c813bca | threadpool.py | threadpool.py | from __future__ import with_statement
import threado
import threading
import Queue
class ThreadPool(object):
def __init__(self, idle_time=5.0):
self.lock = threading.Lock()
self.threads = list()
self.idle_time = idle_time
@threado.stream
def run(inner, self, func, *args, **keys):
... | from __future__ import with_statement
import sys
import threado
import threading
import Queue
class ThreadPool(object):
def __init__(self, idle_time=5.0):
self.lock = threading.Lock()
self.threads = list()
self.idle_time = idle_time
def run(self, func, *args, **keys):
with self... | Fix a weird situation when a function run in a thread raises StopIteration, which was erroneusly interpreted that the thread returned None. | Fix a weird situation when a function run in a thread raises StopIteration, which was erroneusly interpreted that the thread returned None.
| Python | mit | abusesa/idiokit |
b252592eb40263994317d88ced43ddc4669a4975 | tests/run_tests.py | tests/run_tests.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Test runner for sqlparse."""
import optparse
import os
import sys
import unittest
test_mod = os.path.abspath(os.path.join(os.path.dirname(__file__), '../'))
if test_mod not in sys.path:
sys.path.insert(1, test_mod)
parser = optparse.OptionParser()
parser.add_opt... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Test runner for sqlparse."""
import optparse
import os
import sys
import unittest
test_mod = os.path.abspath(os.path.join(os.path.dirname(__file__), '../'))
if test_mod not in sys.path:
sys.path.insert(1, test_mod)
parser = optparse.OptionParser()
parser.add_opt... | Fix return code when running unittests. | Fix return code when running unittests.
| Python | bsd-3-clause | AndiDog/sqlparse,actsasgeek/sqlparse,zhongdai/sqlparse,tailhook/sqlparse,AndiDog/sqlparse,Yelp/sqlparse,Yelp/sqlparse,benekastah/sqlparse,actsasgeek/sqlparse,tailhook/sqlparse,Yelp/sqlparse,MariaPet/sqlparse,payne/sqlparse,adamgreenhall/sqlparse,andialbrecht/sqlparse,tailhook/sqlparse,adamgreenhall/sqlparse,payne/sqlpa... |
12ec1cf9084789b9e2022eb0d1d55b553db06cb5 | tests/test_util.py | tests/test_util.py | import util
from nose.tools import assert_equal
class TestPick():
def check(self, filenames, expected, k, randomized):
result = util.pick(filenames, k, randomized)
assert_equal(result, expected)
def test_all_sequential(self):
filenames = ['a-4.txt', 'b-2.txt', 'c-3.txt', 'd-1.txt', '... | import util
from nose.tools import assert_equal, assert_true, raises
class TestPick():
def test_all_sequential(self):
filenames = ['a-4.txt', 'b-2.txt', 'c-3.txt', 'd-1.txt', 'e-0.txt']
expected = ['e-0.txt', 'd-1.txt', 'b-2.txt', 'c-3.txt', 'a-4.txt']
result = util.pick(filenames, random... | Fix unit test for util.py | Fix unit test for util.py
| Python | mit | kemskems/otdet |
0bf00b40e84a5c5fbcdbeb7b81911998e3f1081a | src/idea/tests/smoke_tests.py | src/idea/tests/smoke_tests.py | import os
from django.utils import timezone
from django_webtest import WebTest
from exam.decorators import fixture
from exam.cases import Exam
from django.core.urlresolvers import reverse
class SmokeTest(Exam, WebTest):
csrf_checks = False
fixtures = ['state']
@fixture
def user(self):
try:
... | import os
from django.utils import timezone
from django_webtest import WebTest
from exam.decorators import fixture
from exam.cases import Exam
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
class SmokeTest(Exam, WebTest):
csrf_checks = False
fixtures = ['state', 'core... | Use fixtures for smoke tests | Use fixtures for smoke tests
| Python | cc0-1.0 | cmc333333/idea-box,m3brown/idea-box,18F/idea-box,cmc333333/idea-box,CapeSepias/idea-box,geomapdev/idea-box,CapeSepias/idea-box,cmc333333/idea-box,18F/idea-box,geomapdev/idea-box,geomapdev/idea-box,18F/idea-box,CapeSepias/idea-box,m3brown/idea-box |
b77a3f47876d824d2e0f1c009a6d580fc5d41ec6 | accelerator/migrations/0019_add_deferred_user_role.py | accelerator/migrations/0019_add_deferred_user_role.py | # Generated by Django 2.2.10 on 2020-04-09 21:24
from django.db import migrations
def add_deferred_user_role(apps, schema_editor):
DEFERRED_MENTOR = 'Deferred Mentor'
UserRole = apps.get_model('accelerator', 'UserRole')
Program = apps.get_model('accelerator', 'Program')
ProgramRole = apps.get_model('... | # Generated by Django 2.2.10 on 2020-04-09 21:24
from django.db import migrations
def add_deferred_user_role(apps, schema_editor):
DEFERRED_MENTOR = 'Deferred Mentor'
UserRole = apps.get_model('accelerator', 'UserRole')
Program = apps.get_model('accelerator', 'Program')
ProgramRole = apps.get_model('... | Make changes to the migration file | [AC-7594] Make changes to the migration file
| Python | mit | masschallenge/django-accelerator,masschallenge/django-accelerator |
4574d25ade5c18d6c15ac6d427f4fbd4cb2f0f04 | braid/info.py | braid/info.py | from fabric.api import run, quiet
from braid import succeeds, cacheInEnvironment
@cacheInEnvironment
def distroName():
"""
Get the name of the distro.
"""
with quiet():
lsb = run('/usr/bin/lsb_release --id --short', warn_only=True)
if lsb.succeeded:
return lsb.lower()
... | from fabric.api import run, quiet
from braid import succeeds, cacheInEnvironment
@cacheInEnvironment
def distroName():
"""
Get the name of the distro.
"""
with quiet():
lsb = run('/usr/bin/lsb_release --id --short', warn_only=True)
if lsb.succeeded:
return lsb.lower()
... | Add debian-squeeze support for os detection. | Add debian-squeeze support for os detection.
| Python | mit | alex/braid,alex/braid |
ee7ced467a7b87e71aa5a1df4c828e672d0b9870 | Utils/py/BallDetection/RegressionNetwork/evaluate.py | Utils/py/BallDetection/RegressionNetwork/evaluate.py | #!/usr/bin/env python3
import argparse
import pickle
import tensorflow.keras as keras
import numpy as np
import sys
import cv2
parser = argparse.ArgumentParser(description='Train the network given ')
parser.add_argument('-b', '--database-path', dest='imgdb_path',
help='Path to the image database ... | #!/usr/bin/env python3
import argparse
import pickle
import tensorflow.keras as keras
import numpy as np
import sys
import cv2
parser = argparse.ArgumentParser(description='Train the network given ')
parser.add_argument('-b', '--database-path', dest='imgdb_path',
help='Path to the image database ... | Print all evaluation metrics associated with the model | Print all evaluation metrics associated with the model
| Python | apache-2.0 | BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH |
d25603818e6af0b99ee1a6add0a7e182037d7a12 | tests/test_set_pref.py | tests/test_set_pref.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import nose.tools as nose
import yv_suggest.set_pref as yvs
import context_managers as ctx
def test_set_language():
"""should set preferred language"""
with ctx.preserve_prefs() as prefs:
with ctx.preserve_recent_re... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import nose.tools as nose
import yv_suggest.set_pref as yvs
import context_managers as ctx
def test_set_language():
"""should set preferred language"""
with ctx.preserve_prefs() as prefs:
with ctx.preserve_recent_re... | Verify that recent list is cleared when language is changed | Verify that recent list is cleared when language is changed
| Python | mit | caleb531/youversion-suggest,caleb531/youversion-suggest |
88098475358aaee18d32a1ad2c4a4301672bca0e | account_move_fiscal_month/models/account_move_line.py | account_move_fiscal_month/models/account_move_line.py | # Copyright 2017 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class AccountMoveLine(models.Model):
_inherit = 'account.move.line'
date_range_fm_id = fields.Many2one(
related='move_id.date_range_fm_id',
store=True, copy=False)
| # Copyright 2017 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class AccountMoveLine(models.Model):
_inherit = 'account.move.line'
date_range_fm_id = fields.Many2one(
related='move_id.date_range_fm_id',
)
| Remove unneeded and inefficient "store=True" | [FIX] Remove unneeded and inefficient "store=True"
| Python | agpl-3.0 | OCA/account-financial-tools,OCA/account-financial-tools |
68a7fd8a444a8c568d716db11849f58ad7a9dee5 | django_pesapal/views.py | django_pesapal/views.py | # Create your views here.
from django.core.urlresolvers import reverse_lazy
from django.contrib.auth.decorators import login_required
from django.views.generic.base import RedirectView
from django.db.models.loading import get_model
from .models import Transaction
import conf
class TransactionCompletedView(Redirect... | # Create your views here.
from django.core.urlresolvers import reverse_lazy, reverse
from django.views.generic.base import RedirectView
from django.core.urlresolvers import NoReverseMatch
from .models import Transaction
import conf
class TransactionCompletedView(RedirectView):
permanent = False
url = None
... | Add support for further processing of the payment while maintaining compatibility | Add support for further processing of the payment while maintaining compatibility
| Python | bsd-3-clause | odero/django-pesapal,odero/django-pesapal |
b7106307baf97ba32cb29fe2a4bb9ed925c194ca | custom/onse/management/commands/update_onse_facility_cases.py | custom/onse/management/commands/update_onse_facility_cases.py | from django.core.management import BaseCommand
from custom.onse.tasks import update_facility_cases_from_dhis2_data_elements
class Command(BaseCommand):
help = ('Update facility_supervision cases with indicators collected '
'in DHIS2 over the last quarter.')
def handle(self, *args, **options):
... | from django.core.management import BaseCommand
from custom.onse.tasks import update_facility_cases_from_dhis2_data_elements
class Command(BaseCommand):
help = ('Update facility_supervision cases with indicators collected '
'in DHIS2 over the last quarter.')
def handle(self, *args, **options):
... | Fix passing keyword arg to task | Fix passing keyword arg to task
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq |
e5eff6f7f92b2946ca17e59c70b81df6f2e7a12d | opps/core/models/publisher.py | opps/core/models/publisher.py | #!/usr/bin/env python
from django.db import models
from django.utils.translation import ugettext_lazy as _
from datetime import datetime
class PublisherMnager(models.Manager):
def all_published(self):
return super(PublisherMnager, self).get_query_set().filter(
date_available__lte=datetim... | #!/usr/bin/env python
from django.db import models
from django.utils.translation import ugettext_lazy as _
from datetime import datetime
class PublisherMnager(models.Manager):
def all_published(self):
return super(PublisherMnager, self).get_query_set().filter(
date_available__lte=datetim... | Remove date field (insert and update) | Remove date field (insert and update)
| Python | mit | jeanmask/opps,jeanmask/opps,jeanmask/opps,YACOWS/opps,opps/opps,williamroot/opps,williamroot/opps,YACOWS/opps,opps/opps,YACOWS/opps,jeanmask/opps,opps/opps,williamroot/opps,opps/opps,YACOWS/opps,williamroot/opps |
1dd58c6717fb8c3c23bce8cecf205c04cc03a134 | comrade/views/simple.py | comrade/views/simple.py | from django.http import HttpResponse, HttpResponseServerError
from django.template import Context, loader
from django.conf import settings
import logging
logger = logging.getLogger('comrade.views.simple')
def status(request):
logger.info("Responding to status check")
return HttpResponse()
def server_error(re... | from django.http import HttpResponse, HttpResponseServerError
from django.template import RequestContext, loader
from django.conf import settings
from maintenancemode.http import HttpResponseTemporaryUnavailable
import logging
logger = logging.getLogger('comrade.views.simple')
def status(request):
logger.info("R... | Use requestcontext in error views. | Use requestcontext in error views.
| Python | mit | bueda/django-comrade |
0ba671698bf4e268ae3f17e11078a5eb669a174c | indico/modules/events/roles/__init__.py | indico/modules/events/roles/__init__.py | # This file is part of Indico.
# Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | # This file is part of Indico.
# Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | Move roles menu item into a submenu | Move roles menu item into a submenu
- 'organization' for conferences
- 'advanced' for other event types
| Python | mit | mic4ael/indico,indico/indico,mic4ael/indico,pferreir/indico,DirkHoffmann/indico,OmeGak/indico,pferreir/indico,OmeGak/indico,DirkHoffmann/indico,indico/indico,mvidalgarcia/indico,ThiefMaster/indico,indico/indico,OmeGak/indico,ThiefMaster/indico,DirkHoffmann/indico,DirkHoffmann/indico,mvidalgarcia/indico,ThiefMaster/indi... |
5a785f725d68733561a7e5e82c57655e25439ec8 | indra/tests/test_grounding_resources.py | indra/tests/test_grounding_resources.py | import os
import csv
from indra.statements.validate import validate_db_refs, validate_ns
from indra.preassembler.grounding_mapper import default_grounding_map
from indra.preassembler.grounding_mapper import default_misgrounding_map
# Namespaces that are not currently handled but still appear in statements
exceptions ... | import os
import csv
from indra.statements.validate import validate_db_refs, validate_ns
from indra.preassembler.grounding_mapper import default_grounding_map
from indra.preassembler.grounding_mapper import default_misgrounding_map
def test_misgrounding_map_entries():
bad_entries = []
for text, db_refs in def... | Remove exceptional namespaces from test | Remove exceptional namespaces from test
| Python | bsd-2-clause | johnbachman/indra,sorgerlab/indra,sorgerlab/belpy,sorgerlab/indra,bgyori/indra,sorgerlab/indra,bgyori/indra,bgyori/indra,johnbachman/indra,johnbachman/indra,sorgerlab/belpy,sorgerlab/belpy |
1e42bc1ef04ff3f52ce3f5db75d781be7d450a25 | etl_framework/etl_class.py | etl_framework/etl_class.py | """Base EtlClass that all EtlClasses should inherit"""
class EtlClass(object):
def __init__(self, config):
self.config = config
def __setattr__(self, key, value):
"""Set attribute on config if not in EtlClass object"""
if key == "config":
self.__dict__[key] = value
... | """Base EtlClass that all EtlClasses should inherit"""
class EtlClass(object):
def __init__(self, config):
self.config = config
def __setattr__(self, key, value):
"""Set attribute on config if not in EtlClass object"""
if key == "config":
self.__dict__[key] = value
... | Make EtlClass attribute access more robust | Make EtlClass attribute access more robust
| Python | mit | pantheon-systems/etl-framework |
1f83113e748963cda9688d88a5d36dd7f9a54c1f | tests/app/test_cloudfoundry_config.py | tests/app/test_cloudfoundry_config.py | import json
import os
import pytest
from app.cloudfoundry_config import (
extract_cloudfoundry_config,
set_config_env_vars,
)
@pytest.fixture
def cloudfoundry_config():
return {
'postgres': [{
'credentials': {
'uri': 'postgres uri'
}
}],
'u... | import json
import os
import pytest
from app.cloudfoundry_config import (
extract_cloudfoundry_config,
set_config_env_vars,
)
@pytest.fixture
def cloudfoundry_config():
return {
'postgres': [{
'credentials': {
'uri': 'postgres uri'
}
}],
'u... | Move setting VCAP_SERVICES out of fixture | Move setting VCAP_SERVICES out of fixture
This was inconsistent with the source data for the fixture being
overidden in some of the tests. We only need to set it in the env
once, so it makes sense to just put the code there.
| Python | mit | alphagov/notifications-api,alphagov/notifications-api |
7cbe2351c2ad93def98005597a24e21d878ea492 | flask_velox/mixins/http.py | flask_velox/mixins/http.py | # -*- coding: utf-8 -*-
""" Module provides mixins for issuing HTTP Status codes using the
Flask ``View``.
"""
from flask import url_for
from flask.views import View
from werkzeug.utils import redirect
class RedirectMixin(View):
""" Raise a HTTP Redirect, by default a 302 HTTP Status Code will be used
howev... | # -*- coding: utf-8 -*-
""" Module provides mixins for issuing HTTP Status codes using the
Flask ``View``.
"""
from flask import url_for
from flask.views import View
from werkzeug.utils import redirect
class RedirectMixin(View):
""" Raise a HTTP Redirect, by default a 302 HTTP Status Code will be used
howev... | Allow RedirectMixin to work within flask-admin | Allow RedirectMixin to work within flask-admin
| Python | mit | thisissoon/Flask-Velox,thisissoon/Flask-Velox,jstacoder/Flask-Velox,jstacoder/Flask-Velox |
bdda5e565981ac26a7e5e1ab8d1486eb91b09e4c | views/base.py | views/base.py | from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from feincms.models import Page
def handler(request, path):
page = Page.objects.page_for_path_or_404(path)
if page.override_url:
return HttpResponseRedirect(page.ov... | from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from feincms.models import Page
def handler(request, path=None):
if path is None:
path = request.path
page = Page.objects.page_for_path_or_404(path)
if page.ov... | Use request.path if no path was passed to the default view | Use request.path if no path was passed to the default view
| Python | bsd-3-clause | mjl/feincms,nickburlett/feincms,nickburlett/feincms,pjdelport/feincms,matthiask/django-content-editor,michaelkuty/feincms,matthiask/feincms2-content,mjl/feincms,matthiask/django-content-editor,matthiask/django-content-editor,mjl/feincms,hgrimelid/feincms,hgrimelid/feincms,joshuajonah/feincms,nickburlett/feincms,matthia... |
31bfe8fb498ea2e528da6463c9045b397992e028 | python/caffe/test/test_draw.py | python/caffe/test/test_draw.py | import os
import unittest
from google import protobuf
import caffe.draw
from caffe.proto import caffe_pb2
def getFilenames():
"""Yields files in the source tree which are Net prototxts."""
result = []
root_dir = os.path.abspath(os.path.join(
os.path.dirname(__file__), '..', '..', '..'))
asse... | import os
import unittest
from google.protobuf import text_format
import caffe.draw
from caffe.proto import caffe_pb2
def getFilenames():
"""Yields files in the source tree which are Net prototxts."""
result = []
root_dir = os.path.abspath(os.path.join(
os.path.dirname(__file__), '..', '..', '..... | Add main() for draw_net unittest, fix import errors | Add main() for draw_net unittest, fix import errors
| Python | apache-2.0 | gnina/gnina,gnina/gnina,gnina/gnina,gnina/gnina,gnina/gnina,gnina/gnina |
d1e1f63062eff158b9bce8b9c3cbcaef1abed8ba | flask_gzip.py | flask_gzip.py | import gzip
import StringIO
from flask import request
class Gzip(object):
def __init__(self, app, compress_level=6, minimum_size=500):
self.app = app
self.compress_level = compress_level
self.minimum_size = minimum_size
self.app.after_request(self.after_request)
def after_requ... | import gzip
import StringIO
from flask import request
class Gzip(object):
def __init__(self, app, compress_level=6, minimum_size=500):
self.app = app
self.compress_level = compress_level
self.minimum_size = minimum_size
self.app.after_request(self.after_request)
def after_requ... | Fix a runtime error when direct_passthrough is used. | Fix a runtime error when direct_passthrough is used.
| Python | mit | wichitacode/flask-compress,wichitacode/flask-compress,libwilliam/flask-compress,saymedia/flask-compress,saymedia/flask-compress,libwilliam/flask-compress,libwilliam/flask-compress |
23ad531d932b6c042c3bd0161b74a6088d02524f | myfedora/lib/app_globals.py | myfedora/lib/app_globals.py | """The application's Globals object"""
from app_factory import AppFactoryDict
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self):
"""One instance of Globals is created during application
initializat... | """The application's Globals object"""
from app_factory import AppFactoryDict
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self):
"""One instance of Globals is created during application
initializat... | Add a feed_storage and feed_cache to our Globals object. | Add a feed_storage and feed_cache to our Globals object.
| Python | agpl-3.0 | fedora-infra/fedora-packages,fedora-infra/fedora-packages,Fale/fedora-packages,Fale/fedora-packages,fedora-infra/fedora-packages,fedora-infra/fedora-packages,Fale/fedora-packages |
e9f3b6f9eb59ef7290498e8ceaf81c2bc66c8f59 | ichnaea/gunicorn_config.py | ichnaea/gunicorn_config.py | # This file contains gunicorn configuration setttings, as described at
# http://docs.gunicorn.org/en/latest/settings.html
# The file is loaded via the -c ichnaea.gunicorn_config command line option
# Be explicit about the worker class
worker_class = "sync"
# Set timeout to the same value as the default one from Amazo... | # This file contains gunicorn configuration setttings, as described at
# http://docs.gunicorn.org/en/latest/settings.html
# The file is loaded via the -c ichnaea.gunicorn_config command line option
# Be explicit about the worker class
worker_class = "sync"
# Set timeout to the same value as the default one from Amazo... | Update gunicorn timeout after gunicorn issue was answered. | Update gunicorn timeout after gunicorn issue was answered.
| Python | apache-2.0 | mozilla/ichnaea,therewillbecode/ichnaea,mozilla/ichnaea,therewillbecode/ichnaea,mozilla/ichnaea,therewillbecode/ichnaea,mozilla/ichnaea |
1c8f29d78d6409ba58df36d439f1ffd436c9dd10 | gaphas/picklers.py | gaphas/picklers.py | """
Some extra picklers needed to gracefully dump and load a canvas.
"""
from future import standard_library
standard_library.install_aliases()
import copyreg
# Allow instancemethod to be pickled:
import new
def construct_instancemethod(funcname, self, clazz):
func = getattr(clazz, funcname)
return new.ins... | """
Some extra picklers needed to gracefully dump and load a canvas.
"""
from future import standard_library
standard_library.install_aliases()
import copyreg
# Allow instancemethod to be pickled:
import types
def construct_instancemethod(funcname, self, clazz):
func = getattr(clazz, funcname)
return types... | Fix no module 'new', replaced new.instancemethod with types.MethodType | Fix no module 'new', replaced new.instancemethod with types.MethodType
Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me>
| Python | lgpl-2.1 | amolenaar/gaphas |
48c9b0fc46da538633e7597bb919ac15e4accf7c | zeus/db/func.py | zeus/db/func.py | import re
from sqlalchemy.sql import func
from sqlalchemy.types import String, TypeDecorator
# https://bitbucket.org/zzzeek/sqlalchemy/issues/3729/using-array_agg-around-row-function-does
class ArrayOfRecord(TypeDecorator):
_array_regexp = re.compile(r"^\{(\".+?\")*\}$")
_chunk_regexp = re.compile(r'"(.*?)"... | import re
from sqlalchemy.sql import func
from sqlalchemy.types import String, TypeDecorator
# https://bitbucket.org/zzzeek/sqlalchemy/issues/3729/using-array_agg-around-row-function-does
class ArrayOfRecord(TypeDecorator):
_array_regexp = re.compile(r"^\{(\".+?\")*\}$")
_chunk_regexp = re.compile(r'"(.*?)"... | Correct padding on array aggregations | fix: Correct padding on array aggregations
This was incorrectly building padding based on a single row.
| Python | apache-2.0 | getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus |
83042027fe74ffe200d0bdaa79b0529af54ae6dc | addons/website/__openerp__.py | addons/website/__openerp__.py | # -*- encoding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Website Builder',
'category': 'Website',
'sequence': 50,
'summary': 'Build Your Enterprise Website',
'website': 'https://www.odoo.com/page/website-builder',
'version': '1.0',
'des... | # -*- encoding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Website Builder',
'category': 'Website',
'sequence': 50,
'summary': 'Build Your Enterprise Website',
'website': 'https://www.odoo.com/page/website-builder',
'version': '1.0',
'des... | Revert "[FIX] website: add missing module dependency `base_setup`" | Revert "[FIX] website: add missing module dependency `base_setup`"
This reverts commit d269eb0eb62d88e02c4fa33b84178d0e73d82ef1.
The issue has been fixed in 61f2c90d507645492e1904c1005e8da6253788ea.
| Python | agpl-3.0 | ygol/odoo,dfang/odoo,hip-odoo/odoo,hip-odoo/odoo,ygol/odoo,ygol/odoo,dfang/odoo,dfang/odoo,ygol/odoo,hip-odoo/odoo,hip-odoo/odoo,ygol/odoo,ygol/odoo,ygol/odoo,dfang/odoo,hip-odoo/odoo,hip-odoo/odoo,dfang/odoo,dfang/odoo |
c138adaf69f5029209f03cafe72f1082cdb78f30 | ppp_nlp_ml_standalone/requesthandler.py | ppp_nlp_ml_standalone/requesthandler.py | """Request handler of the module."""
import ppp_datamodel
from ppp_datamodel import Sentence
from ppp_datamodel.communication import TraceItem, Response
from ppp_nlp_ml_standalone import ExtractTriplet
class RequestHandler:
def __init__(self, request):
self.request = request
def answer(self):
... | """Request handler of the module."""
import ppp_datamodel
from ppp_datamodel import Sentence, Missing, Resource
from ppp_datamodel.communication import TraceItem, Response
from ppp_nlp_ml_standalone import ExtractTriplet
def missing_or_resource(x):
return Missing() if x == '?' else Resource(value=x)
class Reques... | Make RequestHandler's code less redundant. | Make RequestHandler's code less redundant.
| Python | mit | ProjetPP/PPP-QuestionParsing-ML-Standalone,ProjetPP/PPP-QuestionParsing-ML-Standalone |
b4473d45ba5925551334762bc02708fcb373c957 | config.py | config.py | CONFIG = {
'database': './ida_info.sqlite3',
'out_dir': './code_gen/',
'verbose': False
}
| CONFIG = {
'database': './ida_info.sqlite3',
'out_dir': './code_gen/',
'verbose': False,
'page_size': 100
}
| Add page size for sql query | Add page size for sql query
| Python | mit | goodwinxp/ATFGenerator,goodwinxp/ATFGenerator,goodwinxp/ATFGenerator |
cc19d0af1c22c9677960f406ced425aa48da54c1 | src/sentry/migrations/0063_remove_bad_groupedmessage_index.py | src/sentry/migrations/0063_remove_bad_groupedmessage_index.py | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Removing unique constraint on 'GroupedMessage', fields ['logger', 'view', 'checksum']
try:
db.delete_... | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Removing unique constraint on 'GroupedMessage', fields ['logger', 'view', 'checksum']
db.delete_unique('sentry_gr... | Revert "Dont error if 0063 index was already cleaned up" | Revert "Dont error if 0063 index was already cleaned up"
This reverts commit b3a51fa482fc949de75d962ddd9fe3464fa70e58.
| Python | bsd-3-clause | felixbuenemann/sentry,JackDanger/sentry,zenefits/sentry,korealerts1/sentry,fuziontech/sentry,daevaorn/sentry,argonemyth/sentry,beeftornado/sentry,vperron/sentry,mvaled/sentry,rdio/sentry,gg7/sentry,hongliang5623/sentry,felixbuenemann/sentry,jokey2k/sentry,pauloschilling/sentry,beni55/sentry,rdio/sentry,BayanGroup/sentr... |
1daeedde2cd8597e047b6a6d7fc737f103fa4ac8 | example/handler/my_handler.py | example/handler/my_handler.py | from base_handler import BaseHandler
from utils import truncated_stdout, with_payload
class MyHandler(BaseHandler):
@truncated_stdout
@with_payload
def hello(self, who=None):
print("Hello there, {}!".format(who))
| from base_handler import BaseHandler
from utils import truncated_stdout, with_payload, with_member_info
class MyHandler(BaseHandler):
@truncated_stdout
@with_payload
def hello(self, who=None):
"""A custom user event."""
print("Hello there, {}!".format(who))
@with_payload
def sup... | Add example of supervisor event and member join | Add example of supervisor event and member join
| Python | mit | waltermoreira/serfnode,waltermoreira/serfnode,waltermoreira/serfnode |
54d4551ce8efb16d4a8d02e38b9f223f8f1cd816 | ab_game.py | ab_game.py | #!/usr/bin/python
import board
import pente_exceptions
from ab_state import *
CAPTURE_SCORE_BASE = 120 ** 3
class ABGame():
""" This class acts as a bridge between the AlphaBeta code and my code """
def __init__(self, base_game):
s = self.current_state = ABState()
s.set_state(base_game.curre... | #!/usr/bin/python
import board
import pente_exceptions
from ab_state import *
class ABGame():
""" This class acts as a bridge between the AlphaBeta code and my code """
def __init__(self, base_game):
s = self.current_state = ABState()
s.set_state(base_game.current_state)
self.base_gam... | Disable min_priority filter for now | Disable min_priority filter for now
| Python | mit | cropleyb/pentai,cropleyb/pentai,cropleyb/pentai |
06d9171b2244e4dd9d5e1883101d7ec3e05be4b2 | bitfield/apps.py | bitfield/apps.py | from django.apps import AppConfig
class BitFieldAppConfig(AppConfig):
name = 'bitfield'
verbose_name = "Bit Field"
| import django
from django.apps import AppConfig
django.setup()
class BitFieldAppConfig(AppConfig):
name = 'bitfield'
verbose_name = "Bit Field"
| Add django.setup to the AppConfig | Add django.setup to the AppConfig
| Python | apache-2.0 | Elec/django-bitfield,disqus/django-bitfield,joshowen/django-bitfield |
0db43d894bfb419a7f4b538f755af47fc0b653cb | tests/unit/test_sharpspring.py | tests/unit/test_sharpspring.py | from unittest.mock import patch
from pmg.sharpspring import Sharpspring
from tests import PMGTestCase
class TestSharpspring(PMGTestCase):
@patch("pmg.sharpspring.requests.post")
def test_make_sharpsrping_request(self, post_mock):
sharpspring = Sharpspring()
details = {
"emailAddre... | from unittest.mock import patch
from pmg.sharpspring import Sharpspring
from tests import PMGTestCase
class MockResponse:
def __init__(self, json_data, status_code):
self.json_data = json_data
self.status_code = status_code
def raise_for_status(self):
pass
def json(self):
... | Add mock response to sharpspring test | Add mock response to sharpspring test
| Python | apache-2.0 | Code4SA/pmg-cms-2,Code4SA/pmg-cms-2,Code4SA/pmg-cms-2 |
0cb807470ee56207251f36ad78d35c48f6e9361b | example_project/urls.py | example_project/urls.py | from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^selectable/', include('selectable.urls')),
url(r'', include('timepiece.urls')),
# authentication views
url(r'^accounts/login/$', 'django.contrib.auth.views.... | from django.conf.urls import include, url
from django.contrib import admin
admin.autodiscover() # For Django 1.6
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^selectable/', include('selectable.urls')),
url(r'', include('timepiece.urls')),
# authentication views
url(r'^accou... | Update Python/Django: Restore admin.autodiscover() for Django 1.6 compatibility | Update Python/Django: Restore admin.autodiscover() for Django 1.6 compatibility
| Python | mit | BocuStudio/django-timepiece,caktus/django-timepiece,arbitrahj/django-timepiece,BocuStudio/django-timepiece,caktus/django-timepiece,arbitrahj/django-timepiece,caktus/django-timepiece,arbitrahj/django-timepiece,BocuStudio/django-timepiece |
23343eb3316a3d304a3b021519b9a470f9c2446b | django_bcrypt/models.py | django_bcrypt/models.py | import bcrypt
from django.contrib.auth.models import User
from django.conf import settings
try:
rounds = settings.BCRYPT_ROUNDS
except AttributeError:
rounds = 12
_check_password = User.check_password
def bcrypt_check_password(self, raw_password):
if self.password.startswith('bc$'):
salt_and_has... | import bcrypt
from django.contrib.auth.models import User
from django.conf import settings
try:
rounds = settings.BCRYPT_ROUNDS
except AttributeError:
rounds = 12
_check_password = User.check_password
def bcrypt_check_password(self, raw_password):
if self.password.startswith('bc$'):
salt_and_has... | Allow users to be created with blank (unusable) passwords. | Allow users to be created with blank (unusable) passwords.
| Python | mit | dwaiter/django-bcrypt |
f5e4a8000e23e279192834d03e4b5b9ecca6b2b0 | linguist/utils/__init__.py | linguist/utils/__init__.py | # -*- coding: utf-8 -*-
from .i18n import (get_language_name,
get_language,
get_fallback_language,
build_localized_field_name,
build_localized_verbose_name)
from .models import load_class, get_model_string
from .template import select_template... | # -*- coding: utf-8 -*-
from .i18n import (get_language_name,
get_language,
get_fallback_language,
get_real_field_name,
get_fallback_field_name,
build_localized_field_name,
build_localized_verbose_name)
fr... | Fix new i18n utils imports. | Fix new i18n utils imports.
| Python | mit | ulule/django-linguist |
986b9227fe66d95a7e42253395c89de5c2385b2d | scuole/campuses/management/commands/dedupecampusslugs.py | scuole/campuses/management/commands/dedupecampusslugs.py | from django.core.management.base import BaseCommand
from django.db.models import Count
from django.utils.text import slugify
from scuole.campuses.models import Campus
class Command(BaseCommand):
help = "Dedupe Campus slugs by adding the county name to the end."
def handle(self, *args, **options):
dup... | from django.core.management.base import BaseCommand
from django.db.models import Count
from django.utils.text import slugify
from scuole.campuses.models import Campus
class Command(BaseCommand):
help = "Dedupe Campus slugs by adding the county name to the end."
def handle(self, *args, **options):
dup... | Edit dedupe campus slugs code | Edit dedupe campus slugs code
| Python | mit | texastribune/scuole,texastribune/scuole,texastribune/scuole,texastribune/scuole |
de0bb4886b9a6ecd2fb4e5c4272167911141c71c | apic_ml2/neutron/plugins/ml2/drivers/cisco/apic/nova_client.py | apic_ml2/neutron/plugins/ml2/drivers/cisco/apic/nova_client.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
# d... | # 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
# d... | Load Nova Client only once to avoid reconnecting | Load Nova Client only once to avoid reconnecting
| Python | apache-2.0 | noironetworks/apic-ml2-driver,noironetworks/apic-ml2-driver |
79c5a3b12fbe0ccde4bf8ec8694d42696241621d | products/bika/browser/clientfolder.py | products/bika/browser/clientfolder.py | from Products.CMFCore.utils import getToolByName
from Products.bika import logger
from Products.bika.browser.bika_folder_contents import BikaFolderContentsView
from plone.app.content.browser.interfaces import IFolderContentsView
from zope.interface import implements
class ClientFolderContentsView(BikaFolderContentsVie... | from Products.CMFCore.utils import getToolByName
from Products.bika import logger
from Products.bika.browser.bika_folder_contents import BikaFolderContentsView
from plone.app.content.browser.interfaces import IFolderContentsView
from zope.interface import implements
class ClientFolderContentsView(BikaFolderContentsVie... | Remove 'field' and 'icon' from column list | Remove 'field' and 'icon' from column list
| Python | agpl-3.0 | veroc/Bika-LIMS,veroc/Bika-LIMS,veroc/Bika-LIMS,DeBortoliWines/Bika-LIMS,labsanmartin/Bika-LIMS,rockfruit/bika.lims,labsanmartin/Bika-LIMS,DeBortoliWines/Bika-LIMS,labsanmartin/Bika-LIMS,anneline/Bika-LIMS,anneline/Bika-LIMS,DeBortoliWines/Bika-LIMS,anneline/Bika-LIMS,rockfruit/bika.lims |
2f57fd6422c68657b10b0b26118b9598f30cb27a | dash/orgs/migrations/0019_resctructure_org_config.py | dash/orgs/migrations/0019_resctructure_org_config.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-03-07 08:24
from __future__ import unicode_literals
import json
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('orgs', '0018_auto_20170301_0914'),
]
def migrate_api_token_and_common_org_conf... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-03-07 08:24
from __future__ import unicode_literals
import json
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('orgs', '0018_auto_20170301_0914'),
]
def migrate_api_token_and_common_org_conf... | Check config if not null in migrations | Check config if not null in migrations
| Python | bsd-3-clause | rapidpro/dash,rapidpro/dash |
47c6c9b4c7d0b86bc47ac0177d8f91e7bf4c72fe | akwriters/urls.py | akwriters/urls.py | from django.urls import include, path
from django.contrib import admin
from django.views.generic import TemplateView
urlpatterns = [
# Examples:
# url(r'^$', 'akwriters.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
path('', TemplateView.as_view(template_name='index.html'), name='i... | from django.urls import include, path
from django.contrib import admin
from django.views.generic import TemplateView,RedirectView
urlpatterns = [
# Examples:
# url(r'^$', 'akwriters.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
path('', RedirectView.as_view(pattern_name='forum:ind... | Bring the forum to the foreground | Bring the forum to the foreground
The default landing page is now the forum, to hopefully encourage people to use it
| Python | mit | Kromey/fbxnano,Kromey/akwriters,Kromey/fbxnano,Kromey/akwriters,Kromey/fbxnano,Kromey/akwriters,Kromey/fbxnano,Kromey/akwriters |
9fd4c69ac1dc4644c35687423dd4fe3e2f73fe63 | mistral/tests/unit/engine/actions/test_fake_action.py | mistral/tests/unit/engine/actions/test_fake_action.py | # -*- coding: utf-8 -*-
#
# Copyright 2013 - StackStorm, Inc.
#
# 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 requ... | # -*- coding: utf-8 -*-
#
# Copyright 2013 - StackStorm, Inc.
#
# 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 requ... | Correct fake action test name | Correct fake action test name
Change-Id: Ibb2322139fd8d7f3365d3522afde622def910fe9
| Python | apache-2.0 | openstack/mistral,StackStorm/mistral,TimurNurlygayanov/mistral,dennybaa/mistral,openstack/mistral,StackStorm/mistral,dennybaa/mistral |
784136c8e04c67ae5a6f4b027096ee94b4c57ee9 | py_naca0020_3d_openfoam/processing.py | py_naca0020_3d_openfoam/processing.py | """
This module contains processing functions.
"""
import numpy as np
import pandas as pd
import os
def load_force_coeffs(steady=False):
"""
Load force coefficients from file. If steady, the file from the `0`
directory is used, and the last values are returned. Otherwise, arrays are
loaded from the la... | """
This module contains processing functions.
"""
import numpy as np
import pandas as pd
import os
def load_force_coeffs(steady=False):
"""
Load force coefficients from file. If steady, the file from the `0`
directory is used, and the last values are returned. Otherwise, arrays are
loaded from the la... | Add function for loading sampled set | Add function for loading sampled set
| Python | mit | petebachant/actuatorLine-3D-turbinesFoam,petebachant/NACA0020-3D-OpenFOAM,petebachant/NACA0020-3D-OpenFOAM,petebachant/NACA0020-3D-OpenFOAM,petebachant/actuatorLine-3D-turbinesFoam,petebachant/actuatorLine-3D-turbinesFoam |
6d23f3bd1ccd45a6e739264e8d041282e6baaf0b | hassio/dock/util.py | hassio/dock/util.py | """HassIO docker utilitys."""
import re
from ..const import ARCH_AARCH64, ARCH_ARMHF, ARCH_I386, ARCH_AMD64
RESIN_BASE_IMAGE = {
ARCH_ARMHF: "resin/armhf-alpine:3.5",
ARCH_AARCH64: "resin/aarch64-alpine:3.5",
ARCH_I386: "resin/i386-alpine:3.5",
ARCH_AMD64: "resin/amd64-alpine:3.5",
}
TMPL_IMAGE = re... | """HassIO docker utilitys."""
import re
from ..const import ARCH_AARCH64, ARCH_ARMHF, ARCH_I386, ARCH_AMD64
RESIN_BASE_IMAGE = {
ARCH_ARMHF: "homeassistant/armhf-base:latest",
ARCH_AARCH64: "homeassistant/aarch64-base:latest",
ARCH_I386: "homeassistant/i386-base:latest",
ARCH_AMD64: "homeassistant/am... | Use our new base image | Use our new base image | Python | bsd-3-clause | pvizeli/hassio,pvizeli/hassio |
21d062ef148b75d00dba6c2873a627e87723e93b | PyFVCOM/__init__.py | PyFVCOM/__init__.py | """
The FVCOM Python toolbox (PyFVCOM)
"""
__version__ = '2.1.3'
__author__ = 'Pierre Cazenave'
__credits__ = ['Pierre Cazenave', 'Michael Bedington', 'Ricardo Torres']
__license__ = 'MIT'
__maintainer__ = 'Pierre Cazenave'
__email__ = 'pica@pml.ac.uk'
import inspect
import sys
from warnings import warn
# Import ev... | """
The FVCOM Python toolbox (PyFVCOM)
"""
__version__ = '2.1.3'
__author__ = 'Pierre Cazenave'
__credits__ = ['Pierre Cazenave', 'Michael Bedington', 'Ricardo Torres']
__license__ = 'MIT'
__maintainer__ = 'Pierre Cazenave'
__email__ = 'pica@pml.ac.uk'
import inspect
import sys
from warnings import warn
# Import ev... | Remove the old coast import. | Remove the old coast import.
| Python | mit | pwcazenave/PyFVCOM |
d1c18841d8a028f76283b9779da61d482df75973 | plumeria/plugins/youtube.py | plumeria/plugins/youtube.py | from plumeria.api.youtube import YouTube
from plumeria.command import commands, CommandError, channel_only
from plumeria.message import Response
from plumeria.util.ratelimit import rate_limit
youtube = YouTube()
@commands.register('youtube', 'yt', 'ytsearch', cost=2, category='Search')
@channel_only
@rate_limit()
as... | from plumeria.api.youtube import YouTube
from plumeria.command import commands, CommandError, channel_only
from plumeria.message import Response
from plumeria.util.ratelimit import rate_limit
youtube = YouTube()
@commands.register('youtube', 'yt', 'ytsearch', cost=2, category='Search')
@rate_limit()
async def yt(mes... | Allow YouTube plugin to be used in PMs. | Allow YouTube plugin to be used in PMs.
| Python | mit | sk89q/Plumeria,sk89q/Plumeria,sk89q/Plumeria |
96b4040e3508d55abf1857209e9820cff7ab3478 | geotrek/feedback/management/commands/erase_emails.py | geotrek/feedback/management/commands/erase_emails.py | import logging
from datetime import timedelta
from django.core.management.base import BaseCommand
from django.utils import timezone
from geotrek.feedback.models import Report
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Erase emails older than 1 year from feedbacks."
# def add_... | import logging
from datetime import timedelta
from django.core.management.base import BaseCommand
from django.utils import timezone
from geotrek.feedback.models import Report
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Erase emails older than 1 year from feedbacks."
def add_ar... | Add options dry-run mode and days | Add options dry-run mode and days
| Python | bsd-2-clause | makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin |
94cd1300a4ccf66488120092dfe880eabc7f06df | tests/test_dump.py | tests/test_dump.py | """ Testing gitwash dumper
"""
from os.path import join as pjoin, dirname, split as psplit
import shutil
from tempfile import mkdtemp
from subprocess import call
from nose.tools import assert_true, assert_equal, assert_raises
def test_dumper():
downpath, _ = psplit(dirname(__file__))
exe_pth = pjoin(downpat... | """ Testing gitwash dumper
"""
from os.path import join as pjoin, dirname, split as psplit
import shutil
from tempfile import mkdtemp
from subprocess import call
from nose.tools import assert_true, assert_equal, assert_raises
_downpath, _ = psplit(dirname(__file__))
EXE_PTH = pjoin(_downpath, 'gitwash_dumper.py')
TM... | TEST - setup teardown for test | TEST - setup teardown for test
| Python | bsd-2-clause | QuLogic/gitwash,QuLogic/gitwash |
8c9cc7f3e8d39007eab076c1bb34715d37716fc9 | tests/test_rmap.py | tests/test_rmap.py | from skrt.utils import rmap
def test_list():
list_ = [1, 2, 3, 4, 5]
assert rmap(list_, lambda x: x**2, int) == [1, 4, 9, 16, 25]
def test_tuple():
tuple_ = (1, 2, 3, 4, 5)
assert rmap(tuple_, lambda x: x**2, int) == (1, 4, 9, 16, 25)
def test_set():
set_ = {1, 2, 3, 4, 5}
assert rmap(set_... | from skrt.utils import rmap
def square(x):
return x ** 2
def test_list():
list_ = [1, 2, 3, 4, 5]
assert rmap(list_, square, int) == [1, 4, 9, 16, 25]
def test_tuple():
tuple_ = (1, 2, 3, 4, 5)
assert rmap(tuple_, square, int) == (1, 4, 9, 16, 25)
def test_set():
set_ = {1, 2, 3, 4, 5}
... | Add complex test for rmap | Add complex test for rmap
| Python | mit | nvander1/skrt |
00fe6161c7c26d25f52fa6cf374c3fd767cf7cf7 | conllu/compat.py | conllu/compat.py | from io import StringIO
try:
from contextlib import redirect_stdout
except ImportError:
import contextlib
import sys
@contextlib.contextmanager
def redirect_stdout(target):
original = sys.stdout
sys.stdout = target
yield
sys.stdout = original
def string_to_file(str... | from io import StringIO
from contextlib import redirect_stdout
def string_to_file(string):
return StringIO(text(string) if string else None)
def capture_print(func, args=None):
f = StringIO()
with redirect_stdout(f):
if args:
func(args)
else:
func()
return f.g... | Remove special case for redirect_stdout. | Remove special case for redirect_stdout.
| Python | mit | EmilStenstrom/conllu |
dc755e07516e1cbbcd01f01e8be59abf8f1a6329 | humfrey/update/management/commands/update_dataset.py | humfrey/update/management/commands/update_dataset.py | import base64
import datetime
import os
import pickle
from lxml import etree
import redis
from django.core.management.base import BaseCommand
from django.conf import settings
from humfrey.update.longliving.updater import Updater
class Command(BaseCommand):
def handle(self, *args, **options):
config_file... | import base64
import datetime
import os
import pickle
from lxml import etree
import redis
from django.core.management.base import BaseCommand
from django.conf import settings
from humfrey.update.longliving.updater import Updater
class Command(BaseCommand):
def handle(self, *args, **options):
config_file... | Update trigger can now be specified on the command line as the second argument, and the module can now be run as a script. | Update trigger can now be specified on the command line as the second argument, and the module can now be run as a script.
| Python | bsd-3-clause | ox-it/humfrey,ox-it/humfrey,ox-it/humfrey |
0c42fdc90e3d4dfcf0a1b353be1abbe34e820f85 | bills/tests.py | bills/tests.py | from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from opencivicdata.models import Bill, LegislativeSession, Person
from tot import settings
from preferences.models import Preferences
BILL_FULL_FIELDS = ('a... | from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from preferences.models import Preferences
class BillViewTests(StaticLiveServerTestCase):
fixtures = ['fl_testdata.json']
def setUp(self):
... | Remove failing test for now | Remove failing test for now
| Python | mit | jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot |
e4ea9426a75828c6fce924b895ee3e4603595dc7 | tests/templates/components/test_radios_with_images.py | tests/templates/components/test_radios_with_images.py | import json
from importlib import metadata
from packaging.version import Version
def test_govuk_frontend_jinja_overrides_on_design_system_v3():
with open("package.json") as package_file:
package_json = json.load(package_file)
govuk_frontend_version = Version(package_json["dependencies"]["govuk-fr... | import json
from importlib import metadata
from packaging.version import Version
def test_govuk_frontend_jinja_overrides_on_design_system_v3():
with open("package.json") as package_file:
package_json = json.load(package_file)
govuk_frontend_version = Version(package_json["dependencies"]["govuk-fr... | Update test for GOVUK Frontend libraries parity | Update test for GOVUK Frontend libraries parity
| Python | mit | alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin |
8fdd6f8c2eb463b4d7bf9bb7372d141b97af8f1f | tviserrys/views.py | tviserrys/views.py | from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic import View
from django.utils.decorators import method_decorator
from django.template import RequestContext, loader
from django.core.exceptions import PermissionDenied
from django.contrib.auth.decorators import login_required
from djan... | from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic import View
from django.utils.decorators import method_decorator
from django.template import RequestContext, loader
from django.core.exceptions import PermissionDenied
from django.contrib.auth.decorators import login_required
from djan... | Add TviitForm into main View | Add TviitForm into main View
| Python | mit | DeWaster/Tviserrys,DeWaster/Tviserrys |
31b7ad0eaf4f74503a970e0cee303eb3bc5ea460 | charity_server.py | charity_server.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 30 01:14:12 2017
@author: colm
"""
from flask import Flask, jsonify
from parse_likecharity import refresh_charities
import threading
refresh_rate = 24 * 60 * 60 #Seconds
# variables that are accessible from anywhere
payload = {}
# lock to control... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 30 01:14:12 2017
@author: colm
"""
from flask import Flask, jsonify
from parse_likecharity import refresh_charities
import threading
from datetime import datetime
refresh_rate = 24 * 60 * 60 #Seconds
start_time = datetime.now()
# variables that a... | Switch to datetime based on calls for updates. | Switch to datetime based on calls for updates.
| Python | mit | colmcoughlan/alchemy-server |
f5ba363de4777e2d594261214913f5d480cb04b6 | Heuristics/AbstactHeuristic.py | Heuristics/AbstactHeuristic.py | from abc import ABC, abstractmethod
import random as random
class AbstractHeuristic(ABC):
@abstractmethod
def calculate(self, solution):
pass
def calculateCost(self, dataset, solution):
cost = 0
i = 0
cost += dataset.getValueXY(0, solution[0])
for i in range(0, ... | from abc import ABC, abstractmethod
import random as random
class AbstractHeuristic(ABC):
@abstractmethod
def calculate(self, solution):
pass
def calculateCost(self, dataset, solution):
cost = 0
i = 0
cost += dataset.getValueXY(0, solution[0])
for i in range(0, ... | Fix on function generate random solution | Fix on function generate random solution
| Python | mit | DiegoReiriz/MetaHeuristics,DiegoReiriz/MetaHeuristics |
703b67c2ac1753133c00d5cd4a859752830b578a | kokekunster/urls.py | kokekunster/urls.py | """kokekunster URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class... | """kokekunster URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class... | Set homepage to first semester fysmat | Set homepage to first semester fysmat
| Python | mit | afriestad/WikiLinks,afriestad/WikiLinks,afriestad/WikiLinks |
9de5a1935ceb3f39b17807096c800cdf01b219bf | Scripts/multi_process_files.py | Scripts/multi_process_files.py | #!/usr/bin/python
from joblib import Parallel, delayed
import multiprocessing
import os
from subprocess import call
inputpath = '/data/amnh/darwin/images'
segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
def handle_file(filename):
call([segment_exe, filename])... | #!/usr/bin/python
from joblib import Parallel, delayed
import multiprocessing
import os
from subprocess import call
# inputpath = '/data/amnh/darwin/images'
# segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
inputpath = '/home/ibanez/data/amnh/darwin_notes/images'
... | Fix paths for local execution different from cloud server. | Fix paths for local execution different from cloud server.
| Python | apache-2.0 | HackTheStacks/darwin-notes-image-processing,HackTheStacks/darwin-notes-image-processing |
8e58b413801a0dbbcd3e48a5ef94201a24af7e8e | are_there_spiders/are_there_spiders/custom_storages.py | are_there_spiders/are_there_spiders/custom_storages.py | from django.contrib.staticfiles.storage import CachedFilesMixin
from pipeline.storage import PipelineMixin
from storages.backends.s3boto import S3BotoStorage
class S3PipelineStorage(PipelineMixin, CachedFilesMixin, S3BotoStorage):
pass
| import urllib
import urlparse
from django.contrib.staticfiles.storage import CachedFilesMixin
from pipeline.storage import PipelineMixin
from storages.backends.s3boto import S3BotoStorage
# CachedFilesMixin doesn't play well with Boto and S3. It over-quotes things,
# causing erratic failures. So we subclass.
# (Se... | Revert "Improvement to custom storage." | Revert "Improvement to custom storage."
This reverts commit 6f185ac7398f30653dff9403d5ebf5539d222f4c.
| Python | mit | wlonk/are_there_spiders,wlonk/are_there_spiders,wlonk/are_there_spiders |
7c09368b3322144c9cb2b0e18f0b4264acb88eb7 | blaze/__init__.py | blaze/__init__.py |
# build the blaze namespace with selected functions
from constructors import array, open
from datashape import dshape
|
# build the blaze namespace with selected functions
from constructors import array, open
from datashape import dshape
def test(verbosity=1, xunitfile=None, exit=False):
"""
Runs the full Blaze test suite, outputting
the results of the tests to sys.stdout.
This uses nose tests to discover which tests... | Add a nose-based blaze.test() function as a placeholder | Add a nose-based blaze.test() function as a placeholder
Hopefully we find something better, but this at least gives
us behavior similar to NumPy as a start.
| Python | bsd-3-clause | AbhiAgarwal/blaze,dwillmer/blaze,mrocklin/blaze,jdmcbr/blaze,mwiebe/blaze,mwiebe/blaze,ChinaQuants/blaze,xlhtc007/blaze,markflorisson/blaze-core,ContinuumIO/blaze,dwillmer/blaze,cpcloud/blaze,FrancescAlted/blaze,cowlicks/blaze,maxalbert/blaze,caseyclements/blaze,aterrel/blaze,cowlicks/blaze,ChinaQuants/blaze,FrancescAl... |
018172a47450eb5500d330803a2e5a7429891016 | migrations/versions/177_add_run_state_eas_folderstatus.py | migrations/versions/177_add_run_state_eas_folderstatus.py | """add run state to eas folders
Revision ID: 2b9dd6f7593a
Revises: 48a1991e5dbd
Create Date: 2015-05-28 00:47:47.636511
"""
# revision identifiers, used by Alembic.
revision = '2b9dd6f7593a'
down_revision = '48a1991e5dbd'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('easfoldersy... | """add run state to eas folders
Revision ID: 2b9dd6f7593a
Revises: 48a1991e5dbd
Create Date: 2015-05-28 00:47:47.636511
"""
# revision identifiers, used by Alembic.
revision = '2b9dd6f7593a'
down_revision = '48a1991e5dbd'
from alembic import op
import sqlalchemy as sa
def upgrade():
from inbox.ignition import... | Update migration 177 to check for table existence first | Update migration 177 to check for table existence first
| Python | agpl-3.0 | ErinCall/sync-engine,wakermahmud/sync-engine,Eagles2F/sync-engine,closeio/nylas,gale320/sync-engine,nylas/sync-engine,Eagles2F/sync-engine,nylas/sync-engine,jobscore/sync-engine,jobscore/sync-engine,ErinCall/sync-engine,wakermahmud/sync-engine,wakermahmud/sync-engine,closeio/nylas,wakermahmud/sync-engine,jobscore/sync-... |
4597935c29ec9cd2679254dbb8ee648ab5b2d75e | busshaming/api.py | busshaming/api.py | from rest_framework import mixins, serializers, viewsets
from .models import Route, Trip
class TripSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Trip
fields = ('id', 'gtfs_trip_id', 'version', 'route', 'trip_headsign', 'trip_short_name', 'direction', 'wheelchair_accessib... | from rest_framework import filters, mixins, serializers, viewsets
from .models import Route, Trip
class TripSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Trip
fields = ('id', 'gtfs_trip_id', 'version', 'route', 'trip_headsign', 'trip_short_name', 'direction', 'wheelchair... | Add search feature to the Route API. | Add search feature to the Route API.
| Python | mit | katharosada/bus-shaming,katharosada/bus-shaming,katharosada/bus-shaming,katharosada/bus-shaming,katharosada/bus-shaming |
7d59df357c34f910914baa0bb030e1ec3793f980 | capnp/__init__.py | capnp/__init__.py | """A python library wrapping the Cap'n Proto C++ library
Example Usage::
import capnp
addressbook = capnp.load('addressbook.capnp')
# Building
message = capnp.MallocMessageBuilder()
addressBook = message.initRoot(addressbook.AddressBook)
people = addressBook.init('people', 2)
alice ... | """A python library wrapping the Cap'n Proto C++ library
Example Usage::
import capnp
addressbook = capnp.load('addressbook.capnp')
# Building
message = capnp.MallocMessageBuilder()
addressBook = message.initRoot(addressbook.AddressBook)
people = addressBook.init('people', 2)
alice ... | Add _capnp for original Cython module. Meant for testing. | Add _capnp for original Cython module. Meant for testing.
| Python | bsd-2-clause | SymbiFlow/pycapnp,rcrowder/pycapnp,rcrowder/pycapnp,rcrowder/pycapnp,SymbiFlow/pycapnp,jparyani/pycapnp,tempbottle/pycapnp,jparyani/pycapnp,tempbottle/pycapnp,SymbiFlow/pycapnp,rcrowder/pycapnp,tempbottle/pycapnp,jparyani/pycapnp,tempbottle/pycapnp,jparyani/pycapnp,SymbiFlow/pycapnp |
d61714022eb191294373519e41d6c1ec3252ed39 | organizer/forms.py | organizer/forms.py | from django import forms
from django.core.exceptions import ValidationError
from .models import Tag
class TagForm(forms.Form):
name = forms.CharField(max_length=31)
slug = forms.SlugField(
max_length=31,
help_text='A label for URL config')
def clean_name(self):
return self.cleane... | from django import forms
from django.core.exceptions import ValidationError
from .models import Tag
class TagForm(forms.ModelForm):
class Meta:
model = Tag
fields = '__all__'
def clean_name(self):
return self.cleaned_data['name'].lower()
def clean_slug(self):
new_slug = ... | Refactor TagForm to inherit ModelForm. | Ch07: Refactor TagForm to inherit ModelForm.
| Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 |
1c05408187b0a93407be5500381c654ea5c3af11 | pyluos/modules/l0_servo.py | pyluos/modules/l0_servo.py | from .module import Module, interact
from .gpio import Pwm
class L0Servo(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'L0Servo', id, alias, robot)
self.pwm_1 = Pwm('p1', self, max=180.0)
self.pwm_2 = Pwm('p2', self, max=180.0)
self.pwm_3 = Pwm('p3', self, m... | from .module import Module, interact
from .gpio import Pwm
class PositionServo(object):
def __init__(self, alias, delegate, default= 0.0, min=0.0, max=180.0):
self._pos = None
self._pwm = Pwm(alias, delegate, default, min, max)
@property
def target_position(self):
return self._pos... | Improve l0 servo api with target_position accessor. | Improve l0 servo api with target_position accessor.
| Python | mit | pollen/pyrobus |
ae21001fea38e9b8e4af34654c48b415e419f319 | core/utils.py | core/utils.py | from django.utils.duration import _get_duration_components
from datetime import timedelta
def duration_string_from_delta(delta):
seconds = delta.total_seconds()
split = str(seconds/3600).split('.')
print split
hours = int(split[0])
minutes = int(float('.'+split[1])*60)
string = '{}:{:02d}'.... | from django.utils.duration import _get_duration_components
from datetime import timedelta
def duration_string_from_delta(delta):
seconds = delta.total_seconds()
split = str(seconds/3600).split('.')
hours = int(split[0])
minutes = int(float('.'+split[1])*60)
string = '{}:{:02d}'.format(hours, mi... | Remove debugging print statement, opps | Remove debugging print statement, opps
| Python | bsd-2-clause | muhleder/timestrap,muhleder/timestrap,overshard/timestrap,cdubz/timestrap,Leahelisabeth/timestrap,Leahelisabeth/timestrap,Leahelisabeth/timestrap,cdubz/timestrap,Leahelisabeth/timestrap,overshard/timestrap,muhleder/timestrap,cdubz/timestrap,overshard/timestrap |
34bf8d82580b83b1e0409db8636877a22203996b | cryptex/trade.py | cryptex/trade.py | class Trade(object):
BUY = 0
SELL = 1
def __init__(self, trade_id, trade_type, base_currency, counter_currency,
time, order_id, amount, price, fee=None):
self.trade_id = trade_id
self.trade_type = trade_type
self.base_currency = base_currency
self.counter_currency = c... | class Trade(object):
BUY = 0
SELL = 1
def __init__(self, trade_id, trade_type, base_currency, counter_currency,
time, order_id, amount, price, fee=None):
self.trade_id = trade_id
self.trade_type = trade_type
self.base_currency = base_currency
self.counter_currency = c... | Remove magic number check in Trade str method | Remove magic number check in Trade str method
| Python | mit | coink/cryptex |
c1de3bddb7e440064f15fd2a340cfea41f9e7be4 | heltour/tournament/management/commands/cleanupcomments.py | heltour/tournament/management/commands/cleanupcomments.py | import random
import string
from django.core.management import BaseCommand
from django.utils import timezone
from heltour.tournament.models import *
from django_comments.models import Comment
from django.contrib.contenttypes.models import ContentType
class Command(BaseCommand):
help = "Removes ALL emails from the... | import random
import string
from datetime import datetime
from django.core.management import BaseCommand
from django.utils import timezone
from heltour.tournament.models import *
from django_comments.models import Comment
from django.contrib.contenttypes.models import ContentType
class Command(BaseCommand):
help ... | Remove all moderator made comments before 2021/01/01 | Remove all moderator made comments before 2021/01/01
| Python | mit | cyanfish/heltour,cyanfish/heltour,cyanfish/heltour,cyanfish/heltour |
eaa907d5d8e4bb4e8514c719b3c11a4a30442694 | vpr/muxes/logic/mux2/tests/test_mux2.py | vpr/muxes/logic/mux2/tests/test_mux2.py | # Simple tests for an adder module
import cocotb
from cocotb.triggers import Timer
from cocotb.result import TestFailure
#from adder_model import adder_model
#import random
@cocotb.test()
def mux2_test(dut):
"""Test for MUX2 options"""
opts = [(x,y,z, x&~z | y&z) for x in [0,1] for y in [0,1] for z in [0,1]]
... | import cocotb
from cocotb.triggers import Timer
from cocotb.result import TestFailure
from cocotb.regression import TestFactory
@cocotb.coroutine
def mux2_basic_test(dut, inputs=(1,0,0)):
"""Test for MUX2 options"""
yield Timer(2)
I0, I1, S0 = inputs
dut.I0 = I0
dut.I1 = I1
dut.S0 = S0
if ... | Use factory to iterate over permutations | Use factory to iterate over permutations
Signed-off-by: Jeffrey Elms <23ce84ca7a7de9dc17ad8e8b0bbd717d4f9f9884@freshred.net>
| Python | isc | SymbiFlow/symbiflow-arch-defs,SymbiFlow/symbiflow-arch-defs |
ea2bf30629dd7986d0e20041c8633897b2b1a324 | main.py | main.py | import argparse
import io
#Define commmand line arguments which can be passed to main.py
#Currently irrelevant, but could be useful later
def initialize_argument_parser():
parser = argparse.ArgumentParser(description='Simulate Indian health solutions')
parser.add_argument('-s', '--solution', dest='solution',
... | import argparse
import io
#Define commmand line arguments which can be passed to main.py
#Currently irrelevant, but could be useful later
def initialize_argument_parser():
parser = argparse.ArgumentParser(description='Simulate Indian health solutions')
parser.add_argument('-s', '--solution', dest='solution',
... | Put many demos in demonstrate_queries() | Put many demos in demonstrate_queries()
| Python | bsd-3-clause | rkawauchi/IHK,rkawauchi/IHK |
7c1623513151a3c1d81cd42f00efbb8a1b7d09fc | board/signals.py | board/signals.py | from django.contrib.sessions.models import Session
from django.dispatch import receiver
from django.utils.translation import ugettext as _
from account.signals import email_confirmation_sent, user_signed_up
from board.models import Board, Notification
from board.utils import treedict
@receiver(email_confirmation_sen... | from django.contrib.sessions.models import Session
from django.dispatch import receiver
from django.utils.translation import ugettext as _
from account.models import EmailAddress
from account.signals import email_confirmation_sent, password_changed, user_signed_up
from board.models import Board, Notification
from boar... | Set user.email_address.verified as true when user changed his password | Set user.email_address.verified as true when user changed his password
| Python | mit | devunt/hydrocarbon,devunt/hydrocarbon,devunt/hydrocarbon |
2f27a175ffa777d4fe2aad41396e9da3f2c70216 | nbs/utils/validators.py | nbs/utils/validators.py | # -*- coding: utf-8-*-
def validate_cuit(cuit):
"from: http://python.org.ar/pyar/Recetario/ValidarCuit by Mariano Reingart"
# validaciones minimas
if len(cuit) != 13 or cuit[2] != "-" or cuit [11] != "-":
return False
base = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2]
cuit = cuit.replace("-", "")
... | # -*- coding: utf-8-*-
import re
def validate_cuit(cuit):
"""
Validates CUIT (Argentina) - Clave Única de Identificación Triebutaria
from: http://python.org.ar/pyar/Recetario/ValidarCuit by Mariano Reingart
"""
cuit = str(cuit).replace("-", "") # normalize
# validaciones minimas
if not re.m... | Add cbu validator to utils module | Add cbu validator to utils module
| Python | mit | coyotevz/nobix-app |
228b53836e9569fa901de341d7486f85152e67f9 | txircd/modules/rfc/cmode_t.py | txircd/modules/rfc/cmode_t.py | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class TopicLockMode(ModuleData, Mode):
implements(IPlugin, IModuleData, IMode)
name = "TopicLoc... | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class TopicLockMode(ModuleData, Mode):
implements(IPlugin, IModuleData, IMode)
name = "TopicLoc... | Fix non-chanops not being able to query the topic | Fix non-chanops not being able to query the topic
| Python | bsd-3-clause | Heufneutje/txircd,ElementalAlchemist/txircd |
46b5b03385d26589a97b6ab156fffd3b1b10fa5b | secretstorage/exceptions.py | secretstorage/exceptions.py | # SecretStorage module for Python
# Access passwords using the SecretService DBus API
# Author: Dmitry Shachnev, 2012
# License: BSD
"""All secretstorage functions may raise various exceptions when
something goes wrong. All exceptions derive from base
:exc:`SecretStorageException` class."""
class SecretStorageExcepti... | # SecretStorage module for Python
# Access passwords using the SecretService DBus API
# Author: Dmitry Shachnev, 2012
# License: BSD
"""All secretstorage functions may raise various exceptions when
something goes wrong. All exceptions derive from base
:exc:`SecretStorageException` class."""
class SecretStorageExcepti... | Make SecretServiceNotAvailableException a subclass of SecretStorageException | Make SecretServiceNotAvailableException a subclass of SecretStorageException
| Python | bsd-3-clause | mitya57/secretstorage |
72af62bdf9339c880b0cc0f1e1002cf1961e962b | rule.py | rule.py | class PriceRule:
"""PriceRule is a rule that triggers when a stock price satisfies a condition.
The condition is usually greater, equal or lesser than a given value.
"""
def __init__(self, symbol, condition):
self.symbol = symbol
self.condition = condition
def matches(self, exchan... | class PriceRule:
"""PriceRule is a rule that triggers when a stock price satisfies a condition.
The condition is usually greater, equal or lesser than a given value.
"""
def __init__(self, symbol, condition):
self.symbol = symbol
self.condition = condition
def matches(self, exchan... | Add matches method to AndRule class. | Add matches method to AndRule class.
| Python | mit | bsmukasa/stock_alerter |
7198133cf9d24f3d29d300366951b7eac8b2547f | alburnum/maas/viscera/users.py | alburnum/maas/viscera/users.py | """Objects for users."""
__all__ = [
"User",
"Users",
]
from . import (
check,
Object,
ObjectField,
ObjectSet,
ObjectType,
)
class UsersType(ObjectType):
"""Metaclass for `Users`."""
def __iter__(cls):
return map(cls._object, cls._handler.read())
def create(cls, use... | """Objects for users."""
__all__ = [
"User",
"Users",
]
from . import (
check,
Object,
ObjectField,
ObjectSet,
ObjectType,
)
class UsersType(ObjectType):
"""Metaclass for `Users`."""
def __iter__(cls):
return map(cls._object, cls._handler.read())
def create(cls, use... | Change to is_superuser and make email optional. | Change to is_superuser and make email optional.
| Python | agpl-3.0 | blakerouse/python-libmaas,alburnum/alburnum-maas-client |
ef03459429ba878f7c8f0e1d75f716d829250628 | flaggen.py | flaggen.py | import random
def random_color():
colors = ['white', 'black',
'#cc0033', #red
'#ffcc00', #yellow
'#009933', #green
'#003399', #blue
]
return random.choice(colors)
class Flag:
def __init__(self, **kwargs):
self.mode = kwargs.get(... | import random
class Flag:
def __init__(self, **kwargs):
self.mode = kwargs.get('mode', self.random_mode())
self.bg = kwargs.get('bg', self.random_color())
if self.mode == 'plain':
pass
elif self.mode == 'quarters':
self.quarterpanels = kwargs.get('quarterpan... | Refactor Random Color as Flag Method | Refactor Random Color as Flag Method
| Python | mit | Eylrid/flaggen |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.