commit stringlengths 40 40 | old_file stringlengths 5 117 | new_file stringlengths 5 117 | old_contents stringlengths 0 1.93k | new_contents stringlengths 19 3.3k | subject stringlengths 17 320 | message stringlengths 18 3.28k | lang stringclasses 1
value | license stringclasses 13
values | repos stringlengths 7 42.4k | completion stringlengths 19 3.3k | prompt stringlengths 21 3.65k |
|---|---|---|---|---|---|---|---|---|---|---|---|
2ac066511fb7febe0a0dd2f54845e945c639f810 | py/maximum-width-of-binary-tree.py | py/maximum-width-of-binary-tree.py | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def widthOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
start... | Add py solution for 662. Maximum Width of Binary Tree | Add py solution for 662. Maximum Width of Binary Tree
662. Maximum Width of Binary Tree: https://leetcode.com/problems/maximum-width-of-binary-tree/
| Python | apache-2.0 | ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def widthOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
start... | Add py solution for 662. Maximum Width of Binary Tree
662. Maximum Width of Binary Tree: https://leetcode.com/problems/maximum-width-of-binary-tree/
| |
a73a4b3373ad032ac2ad02426fef8a23314d5826 | test/test_external_libs.py | test/test_external_libs.py | import unittest
from test.util import ykman_cli
class TestExternalLibraries(unittest.TestCase):
def test_ykman_version(self):
output = ykman_cli('-v')
# Test that major version is 1 on all libs
self.assertIn('libykpers 1', output)
self.assertIn('libu2f-host 1', output)
sel... | import unittest
import os
from test.util import ykman_cli
@unittest.skipIf(
os.environ.get('INTEGRATION_TESTS') != 'TRUE', 'INTEGRATION_TESTS != TRUE')
class TestExternalLibraries(unittest.TestCase):
def test_ykman_version(self):
output = ykman_cli('-v')
# Test that major version is 1 on all ... | Revert "Don't check INTEGRATION_TESTS env var in external libs test" | Revert "Don't check INTEGRATION_TESTS env var in external libs test"
This reverts commit 648d02fbfca79241a65902f6dd9a7a767a0f633d.
| Python | bsd-2-clause | Yubico/yubikey-manager,Yubico/yubikey-manager | import unittest
import os
from test.util import ykman_cli
@unittest.skipIf(
os.environ.get('INTEGRATION_TESTS') != 'TRUE', 'INTEGRATION_TESTS != TRUE')
class TestExternalLibraries(unittest.TestCase):
def test_ykman_version(self):
output = ykman_cli('-v')
# Test that major version is 1 on all ... | Revert "Don't check INTEGRATION_TESTS env var in external libs test"
This reverts commit 648d02fbfca79241a65902f6dd9a7a767a0f633d.
import unittest
from test.util import ykman_cli
class TestExternalLibraries(unittest.TestCase):
def test_ykman_version(self):
output = ykman_cli('-v')
# Test that m... |
b4ce1a023bf047524f40ac63f40d46a70c8f6f77 | src/dirtyfields/dirtyfields.py | src/dirtyfields/dirtyfields.py | # Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django
from django.db.models.signals import post_save
class DirtyFieldsMixin(object):
def __init__(self, *args, **kwargs):
super(DirtyFieldsMixin, self).__init__(*args, **kwargs)
post_save.connect(reset_state, sender=self.__cl... | # Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django
from django.db.models.signals import post_save
class DirtyFieldsMixin(object):
def __init__(self, *args, **kwargs):
super(DirtyFieldsMixin, self).__init__(*args, **kwargs)
post_save.connect(reset_state, sender=self.__cl... | Check primary keys for foreign key and one-to-one fields | Check primary keys for foreign key and one-to-one fields
| Python | bsd-3-clause | stanhu/django-dirtyfields | # Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django
from django.db.models.signals import post_save
class DirtyFieldsMixin(object):
def __init__(self, *args, **kwargs):
super(DirtyFieldsMixin, self).__init__(*args, **kwargs)
post_save.connect(reset_state, sender=self.__cl... | Check primary keys for foreign key and one-to-one fields
# Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django
from django.db.models.signals import post_save
class DirtyFieldsMixin(object):
def __init__(self, *args, **kwargs):
super(DirtyFieldsMixin, self).__init__(*args, **kwarg... |
ae1696364f078d7813076c7e0a937ad30a19e84f | receiver/receive.py | receiver/receive.py | #!/usr/bin/env/python
import socket, fcntl, sys
#Lock to only allow one instance of this program to run
pid_file = '/tmp/send.pid'
fp = open(pid_file, 'w')
try:
fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
print 'An instance of this program is already running'
sys.exit(0)
import Adafruit_C... | #!/usr/bin/env python
import socket, fcntl, sys
#Lock to only allow one instance of this program to run
pid_file = '/tmp/send.pid'
fp = open(pid_file, 'w')
try:
fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
print 'An instance of this program is already running'
sys.exit(0)
import Adafruit_C... | Fix header of Python file | Fix header of Python file
Now correctly points to the Python interpretor
| Python | mit | sapientsalamander/Pi_Packet_Project,sapientsalamander/Pi_Packet_Project,sapientsalamander/Pi_Packet_Project,sapientsalamander/Pi_Packet_Project,sapientsalamander/Pi_Packet_Project | #!/usr/bin/env python
import socket, fcntl, sys
#Lock to only allow one instance of this program to run
pid_file = '/tmp/send.pid'
fp = open(pid_file, 'w')
try:
fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
print 'An instance of this program is already running'
sys.exit(0)
import Adafruit_C... | Fix header of Python file
Now correctly points to the Python interpretor
#!/usr/bin/env/python
import socket, fcntl, sys
#Lock to only allow one instance of this program to run
pid_file = '/tmp/send.pid'
fp = open(pid_file, 'w')
try:
fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
print 'An ins... |
066833caebddb9a6e0735e635ff214448e078405 | check_env.py | check_env.py | """ Run this file to check your python installation.
"""
def test_import_pandas():
import pandas
def test_pandas_version():
import pandas
version_found = pandas.__version__.split(".")
version_found = tuple(int(num) for num in version_found)
assert version_found > (0, 15)
def test_import_numpy()... | """ Run this file to check your python installation.
"""
from os.path import dirname, join
HERE = dirname(__file__)
def test_import_pandas():
import pandas
def test_pandas_version():
import pandas
version_found = pandas.__version__.split(".")
version_found = tuple(int(num) for num in version_found)
... | Add some more content in tests including with statsmodels. | Add some more content in tests including with statsmodels.
| Python | mit | wateryhcho/pandas_tutorial,linan7788626/pandas_tutorial,jonathanrocher/pandas_tutorial,wateryhcho/pandas_tutorial,Sandor-PRA/pandas_tutorial,Sandor-PRA/pandas_tutorial,ajaykliyara/pandas_tutorial,ajaykliyara/pandas_tutorial,jonathanrocher/pandas_tutorial,jonathanrocher/pandas_tutorial,ajaykliyara/pandas_tutorial,linan7... | """ Run this file to check your python installation.
"""
from os.path import dirname, join
HERE = dirname(__file__)
def test_import_pandas():
import pandas
def test_pandas_version():
import pandas
version_found = pandas.__version__.split(".")
version_found = tuple(int(num) for num in version_found)
... | Add some more content in tests including with statsmodels.
""" Run this file to check your python installation.
"""
def test_import_pandas():
import pandas
def test_pandas_version():
import pandas
version_found = pandas.__version__.split(".")
version_found = tuple(int(num) for num in version_found)
... |
fba553b19585c26ba6eed73c71519b882a57add5 | test_hash.py | test_hash.py | from hash import HashTable
import io
words = []
with io.open('/usr/share/dict/words', 'r') as word_file:
words = word_file.readlines()
def test_hash():
t = HashTable()
t.set('coffee', 'coffee')
assert t.get('coffee') == 'coffee'
def test_duplicate_hash_val():
t = HashTable()
t.set('bob', ... | Add tests for hash table | Add tests for hash table
| Python | mit | nbeck90/data_structures_2 | from hash import HashTable
import io
words = []
with io.open('/usr/share/dict/words', 'r') as word_file:
words = word_file.readlines()
def test_hash():
t = HashTable()
t.set('coffee', 'coffee')
assert t.get('coffee') == 'coffee'
def test_duplicate_hash_val():
t = HashTable()
t.set('bob', ... | Add tests for hash table
| |
1c32b17bd4c85165f91fbb188b22471a296c6176 | kajiki/i18n.py | kajiki/i18n.py | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from .ir import TranslatableTextNode
def gettext(s):
return s
def extract(fileobj, keywords, comment_tags, options):
'''Babel entry point that extracts translation strings fr... | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from .ir import TranslatableTextNode
def gettext(s):
return s
def extract(fileobj, keywords, comment_tags, options):
'''Babel entry point that extracts translation strings fr... | Fix issue with message extractor on Py2 | Fix issue with message extractor on Py2
| Python | mit | ollyc/kajiki,ollyc/kajiki,ollyc/kajiki | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from .ir import TranslatableTextNode
def gettext(s):
return s
def extract(fileobj, keywords, comment_tags, options):
'''Babel entry point that extracts translation strings fr... | Fix issue with message extractor on Py2
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from .ir import TranslatableTextNode
def gettext(s):
return s
def extract(fileobj, keywords, comment_tags, options):
'''Babel entry p... |
daca2bb7810b4c8eaf9f6a0598d8c6b41e0f2e10 | froide_theme/settings.py | froide_theme/settings.py | # -*- coding: utf-8 -*-
from froide.settings import Base, ThemeBase, HerokuPostmark, HerokuPostmarkS3 # noqa
class CustomThemeBase(ThemeBase):
FROIDE_THEME = 'froide_theme.theme'
SITE_NAME = "My Froide"
SITE_EMAIL = "info@example.com"
SITE_URL = 'http://localhost:8000'
SECRET_URLS = {
"... | # -*- coding: utf-8 -*-
import os
from froide.settings import Base, ThemeBase, HerokuPostmark, HerokuPostmarkS3 # noqa
class CustomThemeBase(ThemeBase):
FROIDE_THEME = 'froide_theme.theme'
SITE_NAME = "My Froide"
SITE_EMAIL = "info@example.com"
SITE_URL = 'http://localhost:8000'
SECRET_URLS = ... | Add own locale directory to LOCALE_PATHS | Add own locale directory to LOCALE_PATHS | Python | mit | CodeforHawaii/uipa_org,CodeforHawaii/uipa_org,CodeforHawaii/uipa_org,okfde/froide-theme | # -*- coding: utf-8 -*-
import os
from froide.settings import Base, ThemeBase, HerokuPostmark, HerokuPostmarkS3 # noqa
class CustomThemeBase(ThemeBase):
FROIDE_THEME = 'froide_theme.theme'
SITE_NAME = "My Froide"
SITE_EMAIL = "info@example.com"
SITE_URL = 'http://localhost:8000'
SECRET_URLS = ... | Add own locale directory to LOCALE_PATHS
# -*- coding: utf-8 -*-
from froide.settings import Base, ThemeBase, HerokuPostmark, HerokuPostmarkS3 # noqa
class CustomThemeBase(ThemeBase):
FROIDE_THEME = 'froide_theme.theme'
SITE_NAME = "My Froide"
SITE_EMAIL = "info@example.com"
SITE_URL = 'http://local... |
98acdc9262cfa8c5da092e0c3b1264afdcbde66a | locations/spiders/speedway.py | locations/spiders/speedway.py | # -*- coding: utf-8 -*-
import scrapy
import json
from locations.items import GeojsonPointItem
class SuperAmericaSpider(scrapy.Spider):
name = "superamerica"
allowed_domains = ["superamerica.com"]
start_urls = (
'https://www.speedway.com/GasPriceSearch',
)
def parse(self, response):
... | # -*- coding: utf-8 -*-
import scrapy
import json
from locations.items import GeojsonPointItem
class SuperAmericaSpider(scrapy.Spider):
name = "speedway"
allowed_domains = ["www.speedway.com"]
start_urls = (
'https://www.speedway.com/GasPriceSearch',
)
def parse(self, response):
... | Correct the name of the spider | Correct the name of the spider
| Python | mit | iandees/all-the-places,iandees/all-the-places,iandees/all-the-places | # -*- coding: utf-8 -*-
import scrapy
import json
from locations.items import GeojsonPointItem
class SuperAmericaSpider(scrapy.Spider):
name = "speedway"
allowed_domains = ["www.speedway.com"]
start_urls = (
'https://www.speedway.com/GasPriceSearch',
)
def parse(self, response):
... | Correct the name of the spider
# -*- coding: utf-8 -*-
import scrapy
import json
from locations.items import GeojsonPointItem
class SuperAmericaSpider(scrapy.Spider):
name = "superamerica"
allowed_domains = ["superamerica.com"]
start_urls = (
'https://www.speedway.com/GasPriceSearch',
)
... |
86446c6d1b0b8583562e0fccf1745e95ce7003c2 | util/__init__.py | util/__init__.py | #!/usr/bin/env python
#
# dials.util.__init__.py
#
# Copyright (C) 2013 Diamond Light Source
#
# Author: James Parkhurst
#
# This code is distributed under the BSD license, a copy of which is
# included in the root directory of this package.
from __future__ import division
class HalError(RuntimeError):
def _... | #!/usr/bin/env python
#
# dials.util.__init__.py
#
# Copyright (C) 2013 Diamond Light Source
#
# Author: James Parkhurst
#
# This code is distributed under the BSD license, a copy of which is
# included in the root directory of this package.
from __future__ import division
class HalError(RuntimeError):
def _... | Print out errors to log. | Print out errors to log. | Python | bsd-3-clause | dials/dials,dials/dials,dials/dials,dials/dials,dials/dials | #!/usr/bin/env python
#
# dials.util.__init__.py
#
# Copyright (C) 2013 Diamond Light Source
#
# Author: James Parkhurst
#
# This code is distributed under the BSD license, a copy of which is
# included in the root directory of this package.
from __future__ import division
class HalError(RuntimeError):
def _... | Print out errors to log.
#!/usr/bin/env python
#
# dials.util.__init__.py
#
# Copyright (C) 2013 Diamond Light Source
#
# Author: James Parkhurst
#
# This code is distributed under the BSD license, a copy of which is
# included in the root directory of this package.
from __future__ import division
class HalError... |
4fde76e19df9cb7ac0d7c3b763dc43b9af85a022 | tsne/tests/test_iris.py | tsne/tests/test_iris.py |
def test_iris():
from tsne import bh_sne
from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data
y = iris.target
X_2d = bh_sne(X)
| Add test for iris, same as example notebook | Add test for iris, same as example notebook
| Python | bsd-3-clause | pryvkin10x/tsne,pryvkin10x/tsne,pryvkin10x/tsne |
def test_iris():
from tsne import bh_sne
from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data
y = iris.target
X_2d = bh_sne(X)
| Add test for iris, same as example notebook
| |
90a024186928d98dfbd3db29d02d5eeba4a55415 | sql/src/test/BugTracker-2009/Tests/create_on_ro_db_crash.SF-2830238.py | sql/src/test/BugTracker-2009/Tests/create_on_ro_db_crash.SF-2830238.py | import sys
import os
import time
try:
import subprocess
except ImportError:
# use private copy for old Python versions
import MonetDBtesting.subprocess26 as subprocess
def server():
s = subprocess.Popen("%s --dbinit='include sql;' --set gdk_readonly=yes" % os.getenv('MSERVER'),
... | import sys
import os
import time
try:
import subprocess
except ImportError:
# use private copy for old Python versions
import MonetDBtesting.subprocess26 as subprocess
def server():
s = subprocess.Popen('%s "--dbinit=include sql;" --set gdk_readonly=yes' % os.getenv('MSERVER'),
... | Use double quotes to quote command arguments. The Windows command parser doesn't recognize single quotes. | Use double quotes to quote command arguments. The Windows command
parser doesn't recognize single quotes.
| Python | mpl-2.0 | zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb | import sys
import os
import time
try:
import subprocess
except ImportError:
# use private copy for old Python versions
import MonetDBtesting.subprocess26 as subprocess
def server():
s = subprocess.Popen('%s "--dbinit=include sql;" --set gdk_readonly=yes' % os.getenv('MSERVER'),
... | Use double quotes to quote command arguments. The Windows command
parser doesn't recognize single quotes.
import sys
import os
import time
try:
import subprocess
except ImportError:
# use private copy for old Python versions
import MonetDBtesting.subprocess26 as subprocess
def server():
s = subproces... |
1bc4507234d87b1ed246501165fa1d8138bf5ca6 | cheddar/exceptions.py | cheddar/exceptions.py | """
Shared exception.
"""
class BadRequestError(Exception):
pass
class ConflictError(Exception):
pass
class NotFoundError(Exception):
def __init__(self, status_code=None):
self.status_code = status_code
| """
Shared exception.
"""
class BadRequestError(Exception):
pass
class ConflictError(Exception):
pass
class NotFoundError(Exception):
def __init__(self, status_code=None):
super(NotFoundError, self).__init__()
self.status_code = status_code
| Fix for pypy compatibility: must super's __init__ | Fix for pypy compatibility: must super's __init__
| Python | apache-2.0 | jessemyers/cheddar,jessemyers/cheddar | """
Shared exception.
"""
class BadRequestError(Exception):
pass
class ConflictError(Exception):
pass
class NotFoundError(Exception):
def __init__(self, status_code=None):
super(NotFoundError, self).__init__()
self.status_code = status_code
| Fix for pypy compatibility: must super's __init__
"""
Shared exception.
"""
class BadRequestError(Exception):
pass
class ConflictError(Exception):
pass
class NotFoundError(Exception):
def __init__(self, status_code=None):
self.status_code = status_code
|
53f98ee4f0f5922bc154e109aac0e4447f4ed062 | setup.py | setup.py | # -*- coding: utf-8 -*-
from distutils.core import setup
with open('requirements.txt') as reqs:
requirements = reqs.read().split()
setup(
name='pybrdst',
packages=['pybrdst'], # this must be the same as the name above
version='0.1',
description='Brazilian daylight saving time',
author='João ... | # -*- coding: utf-8 -*-
from distutils.core import setup
with open('README.md') as f:
long_description = f.read()
setup(
name='pybrdst',
packages=['pybrdst'], # this must be the same as the name above
version='0.1',
description='Brazilian daylight saving time',
long_description=long_descript... | Remove parâmetros inutilizados e adiciona a descrição longa | Remove parâmetros inutilizados e adiciona a descrição longa
| Python | mit | joaocarlosmendes/pybrdst | # -*- coding: utf-8 -*-
from distutils.core import setup
with open('README.md') as f:
long_description = f.read()
setup(
name='pybrdst',
packages=['pybrdst'], # this must be the same as the name above
version='0.1',
description='Brazilian daylight saving time',
long_description=long_descript... | Remove parâmetros inutilizados e adiciona a descrição longa
# -*- coding: utf-8 -*-
from distutils.core import setup
with open('requirements.txt') as reqs:
requirements = reqs.read().split()
setup(
name='pybrdst',
packages=['pybrdst'], # this must be the same as the name above
version='0.1',
de... |
9c6532aad52f8eb950aeae97dd43f1d921006b6b | tasks.py | tasks.py | from invoke import run, task
TESTPYPI = "https://testpypi.python.org/pypi"
@task
def lint(ctx):
"""Run flake8 to lint code"""
run("flake8")
@task(lint)
def test(ctx):
"""Lint, unit test, and check setup.py"""
cmd = "{} {}".format(
"nosetests",
"--with-coverage --cover-erase --cover-... | from invoke import run, task
TESTPYPI = "https://testpypi.python.org/pypi"
@task
def lint(ctx):
"""Run flake8 to lint code"""
run("flake8")
@task
def freeze(ctx):
"""Freeze the pip requirements"""
run("pip freeze -l > requirements.txt")
@task(lint)
def test(ctx):
"""Lint, unit test, and check... | Add freeze task to invoke | Add freeze task to invoke
| Python | mit | questrail/keysight | from invoke import run, task
TESTPYPI = "https://testpypi.python.org/pypi"
@task
def lint(ctx):
"""Run flake8 to lint code"""
run("flake8")
@task
def freeze(ctx):
"""Freeze the pip requirements"""
run("pip freeze -l > requirements.txt")
@task(lint)
def test(ctx):
"""Lint, unit test, and check... | Add freeze task to invoke
from invoke import run, task
TESTPYPI = "https://testpypi.python.org/pypi"
@task
def lint(ctx):
"""Run flake8 to lint code"""
run("flake8")
@task(lint)
def test(ctx):
"""Lint, unit test, and check setup.py"""
cmd = "{} {}".format(
"nosetests",
"--with-cove... |
fe7e841c166ebc227e00baca4c8a72fb04ce0693 | src/mcedit2/util/directories.py | src/mcedit2/util/directories.py | import os
import sys
def getUserFilesDirectory():
exe = sys.executable
if hasattr(sys, 'frozen'):
folder = os.path.dirname(exe)
else:
script = sys.argv[0]
if exe.endswith("python") or exe.endswith("python.exe"):
folder = os.path.dirname(script)
else:
... | import os
import sys
def getUserFilesDirectory():
exe = sys.executable
if hasattr(sys, 'frozen'):
folder = os.path.dirname(exe)
else:
script = sys.argv[0]
if exe.endswith("python") or exe.endswith("python.exe"):
folder = os.path.dirname(os.path.dirname(os.path.dirname(sc... | Put data folder in ./ instead of ./src/mcedit when running from source (xxx work on this) | Put data folder in ./ instead of ./src/mcedit when running from source (xxx work on this)
| Python | bsd-3-clause | Rubisk/mcedit2,vorburger/mcedit2,vorburger/mcedit2,Rubisk/mcedit2 | import os
import sys
def getUserFilesDirectory():
exe = sys.executable
if hasattr(sys, 'frozen'):
folder = os.path.dirname(exe)
else:
script = sys.argv[0]
if exe.endswith("python") or exe.endswith("python.exe"):
folder = os.path.dirname(os.path.dirname(os.path.dirname(sc... | Put data folder in ./ instead of ./src/mcedit when running from source (xxx work on this)
import os
import sys
def getUserFilesDirectory():
exe = sys.executable
if hasattr(sys, 'frozen'):
folder = os.path.dirname(exe)
else:
script = sys.argv[0]
if exe.endswith("python") or exe.ends... |
44a7c59d798d9a20d4d54b9cce7e56b8f88595cc | ch14/caesar.py | ch14/caesar.py | # Caesar Cipher
MAX_KEY_SIZE = 26
def getMode():
while True:
print('Do you wish to encrypt or decrypt a message?')
mode = input().lower()
if mode in 'encrypt e decrypt d'.split():
return mode
else:
print('Enter either "encrypt" or "e" or "decrypt" or "d".')
... | # Caesar Cipher
MAX_KEY_SIZE = 26
def getMode():
while True:
print('Do you wish to encrypt or decrypt a message?')
mode = input().lower()
if mode in 'encrypt e decrypt d'.split():
return mode
else:
print('Enter either "encrypt" or "e" or "decrypt" or "d".')
... | Modify the code in the getKey() function so that it gracefully ignores non-integer input. | Modify the code in the getKey() function so that it gracefully ignores non-integer input.
| Python | bsd-2-clause | aclogreco/InventGamesWP | # Caesar Cipher
MAX_KEY_SIZE = 26
def getMode():
while True:
print('Do you wish to encrypt or decrypt a message?')
mode = input().lower()
if mode in 'encrypt e decrypt d'.split():
return mode
else:
print('Enter either "encrypt" or "e" or "decrypt" or "d".')
... | Modify the code in the getKey() function so that it gracefully ignores non-integer input.
# Caesar Cipher
MAX_KEY_SIZE = 26
def getMode():
while True:
print('Do you wish to encrypt or decrypt a message?')
mode = input().lower()
if mode in 'encrypt e decrypt d'.split():
return ... |
f7dd603d4e24134affda6430736838ecaaab9938 | jungle/cli.py | jungle/cli.py | # -*- coding: utf-8 -*-
import click
from . import __version__
class JungleCLI(click.MultiCommand):
"""Jangle CLI main class"""
def list_commands(self, ctx):
"""return available modules"""
return ['ec2', 'elb', 'emr', 'asg']
def get_command(self, ctx, name):
"""get command"""
... | # -*- coding: utf-8 -*-
import click
from . import __version__
class JungleCLI(click.MultiCommand):
"""Jangle CLI main class"""
def list_commands(self, ctx):
"""return available modules"""
return ['ec2', 'elb', 'emr', 'asg']
def get_command(self, ctx, name):
"""get command"""
... | Fix unintended ImportError for wrong subcommnad | Fix unintended ImportError for wrong subcommnad
| Python | mit | achiku/jungle | # -*- coding: utf-8 -*-
import click
from . import __version__
class JungleCLI(click.MultiCommand):
"""Jangle CLI main class"""
def list_commands(self, ctx):
"""return available modules"""
return ['ec2', 'elb', 'emr', 'asg']
def get_command(self, ctx, name):
"""get command"""
... | Fix unintended ImportError for wrong subcommnad
# -*- coding: utf-8 -*-
import click
from . import __version__
class JungleCLI(click.MultiCommand):
"""Jangle CLI main class"""
def list_commands(self, ctx):
"""return available modules"""
return ['ec2', 'elb', 'emr', 'asg']
def get_comm... |
dba22abf151ddee20aeb886e2bca6401a17d7cea | properties/spatial.py | properties/spatial.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import six
from .base import Property
from . import vmath
class Vector(Property):
"""class properties.Vector
Vector property, using properties.vmath.Vector
... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import six
from .base import Property
from . import vmath
class Vector(Property):
"""class properties.Vector
Vector property, using properties.vmath.Vector
... | Improve vector property error message | Improve vector property error message
| Python | mit | aranzgeo/properties,3ptscience/properties | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import six
from .base import Property
from . import vmath
class Vector(Property):
"""class properties.Vector
Vector property, using properties.vmath.Vector
... | Improve vector property error message
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import six
from .base import Property
from . import vmath
class Vector(Property):
"""class properties.Vector
Vector pro... |
9cd3bb79126fa2431ba4ae03811ac30fb77b9b46 | netcat.py | netcat.py | #!/usr/bin/python2
import argparse
import socket
import sys
parser = argparse.ArgumentParser(description='Simple netcat in pure python.')
parser.add_argument('-z', '--scan', action='store_true')
parser.add_argument('-w', '--timeout', metavar='SECONDS', type=int)
parser.add_argument('-v', '--verbose', action='store_tru... | #!/usr/bin/python
import argparse
import socket
import sys
parser = argparse.ArgumentParser(description='Simple netcat in pure python.')
parser.add_argument('-s', '--source', metavar='ADDRESS')
parser.add_argument('-v', '--verbose', action='store_true')
parser.add_argument('-w', '--wait', metavar='SECONDS', type=int)
... | Support python 2 and 3 | Support python 2 and 3
Add source argument.
Update arguments to use long names from GNU netcat.
| Python | unlicense | benformosa/Toolbox,benformosa/Toolbox | #!/usr/bin/python
import argparse
import socket
import sys
parser = argparse.ArgumentParser(description='Simple netcat in pure python.')
parser.add_argument('-s', '--source', metavar='ADDRESS')
parser.add_argument('-v', '--verbose', action='store_true')
parser.add_argument('-w', '--wait', metavar='SECONDS', type=int)
... | Support python 2 and 3
Add source argument.
Update arguments to use long names from GNU netcat.
#!/usr/bin/python2
import argparse
import socket
import sys
parser = argparse.ArgumentParser(description='Simple netcat in pure python.')
parser.add_argument('-z', '--scan', action='store_true')
parser.add_argument('-w', ... |
207871f4f057d88f67bad0c371f880664dcee062 | pydirections/route_requester.py | pydirections/route_requester.py | """
This class holds all the necessary information required for a proposed route
"""
ACCEPTABLE_MODES = set(["driving", "walking", "bicycling", "transit"])
class DirectionsRequest(object):
def __init__(self, mode="driving", **kwargs):
self.mode = mode
self.origin = kwargs['origin']
self.destination = kwarg... | """
This class holds all the necessary information required for a proposed route
"""
ACCEPTABLE_MODES = set(["driving", "walking", "bicycling", "transit"])
class DirectionsRequest(object):
def __init__(self, **kwargs):
self.mode = "driving"
self.origin = kwargs['origin']
self.destination = kwargs['destinat... | Build custom route requester class | Build custom route requester class
| Python | apache-2.0 | apranav19/pydirections | """
This class holds all the necessary information required for a proposed route
"""
ACCEPTABLE_MODES = set(["driving", "walking", "bicycling", "transit"])
class DirectionsRequest(object):
def __init__(self, **kwargs):
self.mode = "driving"
self.origin = kwargs['origin']
self.destination = kwargs['destinat... | Build custom route requester class
"""
This class holds all the necessary information required for a proposed route
"""
ACCEPTABLE_MODES = set(["driving", "walking", "bicycling", "transit"])
class DirectionsRequest(object):
def __init__(self, mode="driving", **kwargs):
self.mode = mode
self.origin = kwargs[... |
8fc274021a8c0813f3fc3568d1d7984112952b9c | pytilemap/qtsupport.py | pytilemap/qtsupport.py |
import sys
import sip
import qtpy
__all__ = [
'getQVariantValue',
'wheelAngleDelta',
]
try:
if qtpy.PYQT5:
QVARIANT_API = 2
else:
QVARIANT_API = sip.getapi('QVariant')
except ValueError:
QVARIANT_API = 1
if QVARIANT_API == 1:
def getQVariantValue(variant):
return ... |
import sys
import sip
import qtpy
__all__ = [
'getQVariantValue',
'wheelAngleDelta',
]
try:
if qtpy.PYQT5:
QVARIANT_API = 2
else:
QVARIANT_API = sip.getapi('QVariant')
except ValueError:
QVARIANT_API = 1
if QVARIANT_API == 1:
def getQVariantValue(variant):
return ... | Use Cache location instead of temp folder | Use Cache location instead of temp folder
| Python | mit | allebacco/PyTileMap |
import sys
import sip
import qtpy
__all__ = [
'getQVariantValue',
'wheelAngleDelta',
]
try:
if qtpy.PYQT5:
QVARIANT_API = 2
else:
QVARIANT_API = sip.getapi('QVariant')
except ValueError:
QVARIANT_API = 1
if QVARIANT_API == 1:
def getQVariantValue(variant):
return ... | Use Cache location instead of temp folder
import sys
import sip
import qtpy
__all__ = [
'getQVariantValue',
'wheelAngleDelta',
]
try:
if qtpy.PYQT5:
QVARIANT_API = 2
else:
QVARIANT_API = sip.getapi('QVariant')
except ValueError:
QVARIANT_API = 1
if QVARIANT_API == 1:
def... |
c4f1a3dd38e83c799dcd505f81b9b14308331cb6 | gpi/BNI2BART_Traj_GPI.py | gpi/BNI2BART_Traj_GPI.py | # Author: Ashley Anderson III <aganders3@gmail.com>
# Date: 2016-01-25 13:58
import numpy as np
import gpi
class ExternalNode(gpi.NodeAPI):
"""Transform coordinates from BNI conventions to BART conventions.
INPUT:
in - a numpy arrary of k-space coordinates in the BNI convention
i.e. (-0.5... | Add node to convert BNI trajectories (e.g. from SpiralCoords) to BART trajectories. | Add node to convert BNI trajectories (e.g. from SpiralCoords) to BART trajectories.
| Python | bsd-3-clause | nckz/bart,nckz/bart,nckz/bart,nckz/bart,nckz/bart | # Author: Ashley Anderson III <aganders3@gmail.com>
# Date: 2016-01-25 13:58
import numpy as np
import gpi
class ExternalNode(gpi.NodeAPI):
"""Transform coordinates from BNI conventions to BART conventions.
INPUT:
in - a numpy arrary of k-space coordinates in the BNI convention
i.e. (-0.5... | Add node to convert BNI trajectories (e.g. from SpiralCoords) to BART trajectories.
| |
697d30430fa908c6e2baf88285f0a464993d6636 | formapi/compat.py | formapi/compat.py | # coding=utf-8
# flake8: noqa
import sys
if sys.version_info[0] == 3:
from django.utils.encoding import smart_bytes as smart_b, force_str as force_u, smart_text as smart_u
# noinspection PyUnresolvedReferences
from urllib.parse import quote
ifilter = filter
b_str = bytes
u_str = str
iterite... | # coding=utf-8
# flake8: noqa
import sys
if sys.version_info[0] == 3:
from django.utils.encoding import smart_bytes as smart_b, force_str as force_u, smart_text as smart_u
# noinspection PyUnresolvedReferences
from urllib.parse import quote
ifilter = filter
b_str = bytes
u_str = str
iterite... | Fix smart_u for Django 1.3 | Fix smart_u for Django 1.3 | Python | mit | 5monkeys/django-formapi,andreif/django-formapi,5monkeys/django-formapi,andreif/django-formapi | # coding=utf-8
# flake8: noqa
import sys
if sys.version_info[0] == 3:
from django.utils.encoding import smart_bytes as smart_b, force_str as force_u, smart_text as smart_u
# noinspection PyUnresolvedReferences
from urllib.parse import quote
ifilter = filter
b_str = bytes
u_str = str
iterite... | Fix smart_u for Django 1.3
# coding=utf-8
# flake8: noqa
import sys
if sys.version_info[0] == 3:
from django.utils.encoding import smart_bytes as smart_b, force_str as force_u, smart_text as smart_u
# noinspection PyUnresolvedReferences
from urllib.parse import quote
ifilter = filter
b_str = bytes
... |
e593306092292f72009e13bafe1cbb83f85d7937 | indra/bel/ndex_client.py | indra/bel/ndex_client.py | import requests
import json
import time
ndex_base_url = 'http://services.bigmech.ndexbio.org'
def send_request(url_suffix, params):
res = requests.post(ndex_base_url + url_suffix, data=json.dumps(params))
res_json = get_result(res)
return res_json
def get_result(res):
status = res.status_code
if ... | import requests
import json
import time
ndex_base_url = 'http://services.bigmech.ndexbio.org'
def send_request(url_suffix, params):
res = requests.post(ndex_base_url + url_suffix, data=json.dumps(params))
res_json = get_result(res)
return res_json
def get_result(res):
status = res.status_code
if ... | Fix messages in NDEx client | Fix messages in NDEx client
| Python | bsd-2-clause | jmuhlich/indra,pvtodorov/indra,pvtodorov/indra,bgyori/indra,sorgerlab/belpy,bgyori/indra,johnbachman/belpy,johnbachman/belpy,johnbachman/indra,sorgerlab/indra,johnbachman/indra,bgyori/indra,johnbachman/belpy,sorgerlab/indra,pvtodorov/indra,sorgerlab/indra,johnbachman/indra,jmuhlich/indra,jmuhlich/indra,sorgerlab/belpy,... | import requests
import json
import time
ndex_base_url = 'http://services.bigmech.ndexbio.org'
def send_request(url_suffix, params):
res = requests.post(ndex_base_url + url_suffix, data=json.dumps(params))
res_json = get_result(res)
return res_json
def get_result(res):
status = res.status_code
if ... | Fix messages in NDEx client
import requests
import json
import time
ndex_base_url = 'http://services.bigmech.ndexbio.org'
def send_request(url_suffix, params):
res = requests.post(ndex_base_url + url_suffix, data=json.dumps(params))
res_json = get_result(res)
return res_json
def get_result(res):
sta... |
6a889eea6953e8ecb89c0cbac0656f5d7e274669 | project/creditor/management/commands/update_membershipfees.py | project/creditor/management/commands/update_membershipfees.py | # -*- coding: utf-8 -*-
import datetime
import dateutil.parser
from creditor.models import RecurringTransaction, TransactionTag
from creditor.tests.fixtures.recurring import MembershipfeeFactory
from django.core.management.base import BaseCommand, CommandError
from members.models import Member
class Command(BaseComm... | Add initial version of membership fee updater | Add initial version of membership fee updater
| Python | mit | jautero/asylum,hacklab-fi/asylum,HelsinkiHacklab/asylum,jautero/asylum,HelsinkiHacklab/asylum,hacklab-fi/asylum,hacklab-fi/asylum,rambo/asylum,HelsinkiHacklab/asylum,jautero/asylum,jautero/asylum,HelsinkiHacklab/asylum,rambo/asylum,rambo/asylum,rambo/asylum,hacklab-fi/asylum | # -*- coding: utf-8 -*-
import datetime
import dateutil.parser
from creditor.models import RecurringTransaction, TransactionTag
from creditor.tests.fixtures.recurring import MembershipfeeFactory
from django.core.management.base import BaseCommand, CommandError
from members.models import Member
class Command(BaseComm... | Add initial version of membership fee updater
| |
a715821c75521e25172805c98d204fc4e24a4641 | CodeFights/circleOfNumbers.py | CodeFights/circleOfNumbers.py | #!/usr/local/bin/python
# Code Fights Circle of Numbers Problem
def circleOfNumbers(n, firstNumber):
pass
def main():
tests = [
["crazy", "dsbaz"],
["z", "a"]
]
for t in tests:
res = circleOfNumbers(t[0], t[1])
if t[2] == res:
print("PASSED: circleOfNumbe... | #!/usr/local/bin/python
# Code Fights Circle of Numbers Problem
def circleOfNumbers(n, firstNumber):
mid = n / 2
return (mid + firstNumber if firstNumber < mid else firstNumber - mid)
def main():
tests = [
[10, 2, 7],
[10, 7, 2],
[4, 1, 3],
[6, 3, 0]
]
for t in t... | Solve Code Fights circle of numbers problem | Solve Code Fights circle of numbers problem
| Python | mit | HKuz/Test_Code | #!/usr/local/bin/python
# Code Fights Circle of Numbers Problem
def circleOfNumbers(n, firstNumber):
mid = n / 2
return (mid + firstNumber if firstNumber < mid else firstNumber - mid)
def main():
tests = [
[10, 2, 7],
[10, 7, 2],
[4, 1, 3],
[6, 3, 0]
]
for t in t... | Solve Code Fights circle of numbers problem
#!/usr/local/bin/python
# Code Fights Circle of Numbers Problem
def circleOfNumbers(n, firstNumber):
pass
def main():
tests = [
["crazy", "dsbaz"],
["z", "a"]
]
for t in tests:
res = circleOfNumbers(t[0], t[1])
if t[2] == ... |
8b9730dce9ed50d764b86804609c17235044bbfd | heapsort.py | heapsort.py | __author__ = 'harsh'
LT = 0
GT = 1
def compare_ele(comp_type, ele1, ele2):
if comp_type == LT:
return ele1 < ele2
elif comp_type == GT:
return ele1 > ele2
raise Exception("Compare type Undefined")
def heapsort(lst, comp_type=LT):
"""
:param lst:
"""
#heapify
for sta... | Add min and max heap sort | Add min and max heap sort
| Python | mit | hs634/algorithms,hs634/algorithms | __author__ = 'harsh'
LT = 0
GT = 1
def compare_ele(comp_type, ele1, ele2):
if comp_type == LT:
return ele1 < ele2
elif comp_type == GT:
return ele1 > ele2
raise Exception("Compare type Undefined")
def heapsort(lst, comp_type=LT):
"""
:param lst:
"""
#heapify
for sta... | Add min and max heap sort
| |
2bd62c4b241340ca79292c3b9ef3ad87715e64c8 | setup.py | setup.py | import os
from setuptools import find_packages, setup
from asgiref import __version__
# We use the README as the long_description
readme_path = os.path.join(os.path.dirname(__file__), "README.rst")
setup(
name='asgiref',
version=__version__,
url='http://github.com/django/asgiref/',
author='Django So... | import os
from setuptools import find_packages, setup
from asgiref import __version__
# We use the README as the long_description
readme_path = os.path.join(os.path.dirname(__file__), "README.rst")
setup(
name='asgiref',
version=__version__,
url='http://github.com/django/asgiref/',
author='Django So... | Fix version to include 2.0 for now (3.0 appears unfindable) | Fix version to include 2.0 for now (3.0 appears unfindable)
| Python | bsd-3-clause | django/asgiref | import os
from setuptools import find_packages, setup
from asgiref import __version__
# We use the README as the long_description
readme_path = os.path.join(os.path.dirname(__file__), "README.rst")
setup(
name='asgiref',
version=__version__,
url='http://github.com/django/asgiref/',
author='Django So... | Fix version to include 2.0 for now (3.0 appears unfindable)
import os
from setuptools import find_packages, setup
from asgiref import __version__
# We use the README as the long_description
readme_path = os.path.join(os.path.dirname(__file__), "README.rst")
setup(
name='asgiref',
version=__version__,
u... |
dfbff1c8e1e9acdf66da4caf7ace35fd0b2ce161 | RPxVideoConverter.py | RPxVideoConverter.py | #!/usr/bin/env python
import time
import os
import glob
import sys
import shutil
def RPxLog(severity, message):
print time.time(), severity, message
def RPxErrLog(message):
RPxLog("E", message)
def RPxInfoLog(message):
RPxLog("I", message)
def RPxDevLog(message):
RPxLog("D", message)
scriptDir = os.path.abspa... | Convert video files captured with raspivid | Convert video files captured with raspivid
| Python | apache-2.0 | RPxDrones/RPxCamera,RPxCopter/RPxCamera,RPxCopter/RPxCamera,RPxDrones/RPxCamera | #!/usr/bin/env python
import time
import os
import glob
import sys
import shutil
def RPxLog(severity, message):
print time.time(), severity, message
def RPxErrLog(message):
RPxLog("E", message)
def RPxInfoLog(message):
RPxLog("I", message)
def RPxDevLog(message):
RPxLog("D", message)
scriptDir = os.path.abspa... | Convert video files captured with raspivid
| |
4c6f40f3d1394fff9ed9a4c6fe3ffd0ae5cb6230 | jsondb/file_writer.py | jsondb/file_writer.py | from .compat import decode, encode
def read_data(path):
"""
Reads a file and returns a json encoded representation of the file.
"""
db = open(path, "r+")
content = db.read()
obj = decode(content)
db.close()
return obj
def write_data(path, obj):
"""
Writes to a file and retu... | from .compat import decode, encode
def read_data(file_path):
"""
Reads a file and returns a json encoded representation of the file.
"""
if not is_valid(file_path):
write_data(file_path, {})
db = open(file_path, "r+")
content = db.read()
obj = decode(content)
db.close()
... | Create a new file if the path is invalid. | Create a new file if the path is invalid.
| Python | bsd-3-clause | gunthercox/jsondb | from .compat import decode, encode
def read_data(file_path):
"""
Reads a file and returns a json encoded representation of the file.
"""
if not is_valid(file_path):
write_data(file_path, {})
db = open(file_path, "r+")
content = db.read()
obj = decode(content)
db.close()
... | Create a new file if the path is invalid.
from .compat import decode, encode
def read_data(path):
"""
Reads a file and returns a json encoded representation of the file.
"""
db = open(path, "r+")
content = db.read()
obj = decode(content)
db.close()
return obj
def write_data(path, ... |
860e23b6c854ea5a5babb774328e5359d346c80a | contact_form/forms.py | contact_form/forms.py |
from django import forms
from django.conf import settings
from django.template import loader
from django.core.mail import send_mail
class BaseEmailFormMixin(object):
from_email = settings.DEFAULT_FROM_EMAIL
recipient_list = [email for email, _ in settings.MANAGERS]
subject_template_name = 'contact_form/e... |
from django import forms
from django.conf import settings
from django.template import loader
from django.core.mail import send_mail
class BaseEmailFormMixin(object):
from_email = settings.DEFAULT_FROM_EMAIL
recipient_list = [email for _, email in settings.MANAGERS]
subject_template_name = 'contact_form/e... | Make email and name order fit to the default django settings file | Make email and name order fit to the default django settings file
| Python | bsd-3-clause | alainivars/django-contact-form,alainivars/django-contact-form,madisona/django-contact-form,madisona/django-contact-form |
from django import forms
from django.conf import settings
from django.template import loader
from django.core.mail import send_mail
class BaseEmailFormMixin(object):
from_email = settings.DEFAULT_FROM_EMAIL
recipient_list = [email for _, email in settings.MANAGERS]
subject_template_name = 'contact_form/e... | Make email and name order fit to the default django settings file
from django import forms
from django.conf import settings
from django.template import loader
from django.core.mail import send_mail
class BaseEmailFormMixin(object):
from_email = settings.DEFAULT_FROM_EMAIL
recipient_list = [email for email, _... |
a4e4a67b631083535a413d56aaa1afff3b88a67f | pymt/framework/bmi_plot.py | pymt/framework/bmi_plot.py | #! /usr/bin/env python
import matplotlib.pyplot as plt
def quick_plot(bmi, name, **kwds):
gid = bmi.get_var_grid(name)
gtype = bmi.get_grid_type(gid)
grid = bmi.grid[gid]
x, y = grid.node_x.values, grid.node_y.values
z = bmi.get_value(name)
x_label = '{name} ({units})'.format(name=grid.node_... | Add module for quick plotting of bmi values. | Add module for quick plotting of bmi values.
| Python | mit | csdms/coupling,csdms/coupling,csdms/pymt | #! /usr/bin/env python
import matplotlib.pyplot as plt
def quick_plot(bmi, name, **kwds):
gid = bmi.get_var_grid(name)
gtype = bmi.get_grid_type(gid)
grid = bmi.grid[gid]
x, y = grid.node_x.values, grid.node_y.values
z = bmi.get_value(name)
x_label = '{name} ({units})'.format(name=grid.node_... | Add module for quick plotting of bmi values.
| |
554ef995f8c4ba42d00482480bf291bac2fd96e1 | utils/database.py | utils/database.py | import json
class Database(dict):
"""Holds a dict that contains all the information about the users in a channel"""
def __init__(self, irc):
super(Database, self).__init__(json.load(open("userdb.json")))
self.irc = irc
def remove_entry(self, event, nick):
try:
del self... | import json
class Database(dict):
"""Holds a dict that contains all the information about the users in a channel"""
def __init__(self, irc):
super(Database, self).__init__(json.load(open("userdb.json")))
self.irc = irc
def remove_entry(self, event, nick):
try:
del self... | Reduce code to a simpler form that checks if a user is already in the DB | Reduce code to a simpler form that checks if a user is already in the DB
| Python | mit | wolfy1339/Python-IRC-Bot | import json
class Database(dict):
"""Holds a dict that contains all the information about the users in a channel"""
def __init__(self, irc):
super(Database, self).__init__(json.load(open("userdb.json")))
self.irc = irc
def remove_entry(self, event, nick):
try:
del self... | Reduce code to a simpler form that checks if a user is already in the DB
import json
class Database(dict):
"""Holds a dict that contains all the information about the users in a channel"""
def __init__(self, irc):
super(Database, self).__init__(json.load(open("userdb.json")))
self.irc = irc
... |
02181601597e203777412b9377af47525eee77f4 | custom/enikshay/management/commands/update_enikshay_custom_data.py | custom/enikshay/management/commands/update_enikshay_custom_data.py | from django.core.management.base import BaseCommand
from corehq.apps.custom_data_fields.models import CustomDataFieldsDefinition, CustomDataField
from corehq.apps.locations.views import LocationFieldsView
from corehq.apps.users.views.mobile.custom_data_fields import UserFieldsView
# pcp -> MBBS
# pac -> AYUSH/other
# ... | Add mgmt command to auto-add new fields | Add mgmt command to auto-add new fields
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | from django.core.management.base import BaseCommand
from corehq.apps.custom_data_fields.models import CustomDataFieldsDefinition, CustomDataField
from corehq.apps.locations.views import LocationFieldsView
from corehq.apps.users.views.mobile.custom_data_fields import UserFieldsView
# pcp -> MBBS
# pac -> AYUSH/other
# ... | Add mgmt command to auto-add new fields
| |
d2eb124651862d61f28519a5d9dc0ab1a0133fb7 | remotecv/result_store/redis_store.py | remotecv/result_store/redis_store.py | from redis import Redis
from remotecv.result_store import BaseStore
from remotecv.utils import logger
class ResultStore(BaseStore):
WEEK = 604800
redis_instance = None
def __init__(self, config):
super(ResultStore, self).__init__(config)
if not ResultStore.redis_instance:
R... | from redis import Redis
from remotecv.result_store import BaseStore
from remotecv.utils import logger
class ResultStore(BaseStore):
WEEK = 604800
redis_instance = None
def __init__(self, config):
super(ResultStore, self).__init__(config)
if not ResultStore.redis_instance:
R... | Make compatible with py-redis 3.x | Make compatible with py-redis 3.x
Fixes https://github.com/thumbor/remotecv/issues/25
| Python | mit | thumbor/remotecv | from redis import Redis
from remotecv.result_store import BaseStore
from remotecv.utils import logger
class ResultStore(BaseStore):
WEEK = 604800
redis_instance = None
def __init__(self, config):
super(ResultStore, self).__init__(config)
if not ResultStore.redis_instance:
R... | Make compatible with py-redis 3.x
Fixes https://github.com/thumbor/remotecv/issues/25
from redis import Redis
from remotecv.result_store import BaseStore
from remotecv.utils import logger
class ResultStore(BaseStore):
WEEK = 604800
redis_instance = None
def __init__(self, config):
super(Resul... |
0b7e957fea7bbd08c79c2b2b4d9b8edfced38496 | tests/providers.py | tests/providers.py | import unittest
import foauth.providers
class ProviderTests(unittest.TestCase):
def setUp(self):
class Example(foauth.providers.OAuth):
provider_url = 'http://example.com'
api_domain = 'api.example.com'
self.provider = Example
def test_auto_name(self):
self.as... | import unittest
import foauth.providers
import urllib
class ProviderTests(unittest.TestCase):
def setUp(self):
class Example(foauth.providers.OAuth):
provider_url = 'http://example.com'
api_domain = 'api.example.com'
self.provider = Example
def test_auto_name(self):
... | Fix favicon tests to match the new scheme | Fix favicon tests to match the new scheme
| Python | bsd-3-clause | foauth/foauth.org,foauth/foauth.org,foauth/foauth.org | import unittest
import foauth.providers
import urllib
class ProviderTests(unittest.TestCase):
def setUp(self):
class Example(foauth.providers.OAuth):
provider_url = 'http://example.com'
api_domain = 'api.example.com'
self.provider = Example
def test_auto_name(self):
... | Fix favicon tests to match the new scheme
import unittest
import foauth.providers
class ProviderTests(unittest.TestCase):
def setUp(self):
class Example(foauth.providers.OAuth):
provider_url = 'http://example.com'
api_domain = 'api.example.com'
self.provider = Example
... |
8f993412a0110085fee10331daecfb3d36973518 | __init__.py | __init__.py | ###
# Copyright (c) 2012, spline
# All rights reserved.
#
#
###
"""
Add a description of the plugin (to be presented to the user inside the wizard)
here. This should describe *what* the plugin does.
"""
import supybot
import supybot.world as world
# Use this for the version of this plugin. You may wish to put a CV... | ###
# Copyright (c) 2012, spline
# All rights reserved.
#
#
###
"""
Add a description of the plugin (to be presented to the user inside the wizard)
here. This should describe *what* the plugin does.
"""
import supybot
import supybot.world as world
# Use this for the version of this plugin. You may wish to put a CV... | Add reload to init for config | Add reload to init for config
| Python | mit | reticulatingspline/Scores,cottongin/Scores | ###
# Copyright (c) 2012, spline
# All rights reserved.
#
#
###
"""
Add a description of the plugin (to be presented to the user inside the wizard)
here. This should describe *what* the plugin does.
"""
import supybot
import supybot.world as world
# Use this for the version of this plugin. You may wish to put a CV... | Add reload to init for config
###
# Copyright (c) 2012, spline
# All rights reserved.
#
#
###
"""
Add a description of the plugin (to be presented to the user inside the wizard)
here. This should describe *what* the plugin does.
"""
import supybot
import supybot.world as world
# Use this for the version of this pl... |
8e59e994370749db03ffda32bc449049c49a3f22 | python/example_code/sqs/change_visibility.py | python/example_code/sqs/change_visibility.py | # Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file ac... | Add SQS visibility timeout message example | Add SQS visibility timeout message example
| Python | apache-2.0 | awsdocs/aws-doc-sdk-examples,imshashank/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,imshashank/aws-doc-sdk-exam... | # Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file ac... | Add SQS visibility timeout message example
| |
ce7e9b95a9faef242b66e9c551861986f311cdee | guardian/management/commands/clean_orphan_obj_perms.py | guardian/management/commands/clean_orphan_obj_perms.py | from __future__ import unicode_literals
from django.core.management.base import NoArgsCommand
from guardian.utils import clean_orphan_obj_perms
class Command(NoArgsCommand):
"""
clean_orphan_obj_perms command is a tiny wrapper around
:func:`guardian.utils.clean_orphan_obj_perms`.
Usage::
$ ... | from __future__ import unicode_literals
from django.core.management.base import BaseCommand
from guardian.utils import clean_orphan_obj_perms
class Command(BaseCommand):
"""
clean_orphan_obj_perms command is a tiny wrapper around
:func:`guardian.utils.clean_orphan_obj_perms`.
Usage::
$ pyth... | Drop django.core.management.base.NoArgsCommand (django 1.10 compat) | Drop django.core.management.base.NoArgsCommand (django 1.10 compat)
See https://github.com/django/django/blob/stable/1.9.x/django/core/management/base.py#L574-L578
| Python | bsd-2-clause | rmgorman/django-guardian,lukaszb/django-guardian,benkonrath/django-guardian,rmgorman/django-guardian,lukaszb/django-guardian,lukaszb/django-guardian,benkonrath/django-guardian,rmgorman/django-guardian,benkonrath/django-guardian | from __future__ import unicode_literals
from django.core.management.base import BaseCommand
from guardian.utils import clean_orphan_obj_perms
class Command(BaseCommand):
"""
clean_orphan_obj_perms command is a tiny wrapper around
:func:`guardian.utils.clean_orphan_obj_perms`.
Usage::
$ pyth... | Drop django.core.management.base.NoArgsCommand (django 1.10 compat)
See https://github.com/django/django/blob/stable/1.9.x/django/core/management/base.py#L574-L578
from __future__ import unicode_literals
from django.core.management.base import NoArgsCommand
from guardian.utils import clean_orphan_obj_perms
class C... |
6a9fb4f8ad3c8fda2b12688be5058e95d5e995e7 | tests/test_main.py | tests/test_main.py | import os
def test_qt_api():
"""
If QT_API is specified, we check that the correct Qt wrapper was used
"""
from qtpy import QtCore, QtGui, QtWidgets, QtWebEngineWidgets
QT_API = os.environ.get('QT_API', None)
if QT_API == 'pyside':
import PySide
assert QtCore.QEvent is PySid... | import os
from qtpy import QtCore, QtGui, QtWidgets, QtWebEngineWidgets
def assert_pyside():
import PySide
assert QtCore.QEvent is PySide.QtCore.QEvent
assert QtGui.QPainter is PySide.QtGui.QPainter
assert QtWidgets.QWidget is PySide.QtGui.QWidget
assert QtWebEngineWidgets.QWebEnginePage is PySid... | Check that the priority order is respected if QT_API or USE_QT_API are not specified. | Check that the priority order is respected if QT_API or USE_QT_API are not specified. | Python | mit | goanpeca/qtpy,davvid/qtpy,davvid/qtpy,goanpeca/qtpy,spyder-ide/qtpy | import os
from qtpy import QtCore, QtGui, QtWidgets, QtWebEngineWidgets
def assert_pyside():
import PySide
assert QtCore.QEvent is PySide.QtCore.QEvent
assert QtGui.QPainter is PySide.QtGui.QPainter
assert QtWidgets.QWidget is PySide.QtGui.QWidget
assert QtWebEngineWidgets.QWebEnginePage is PySid... | Check that the priority order is respected if QT_API or USE_QT_API are not specified.
import os
def test_qt_api():
"""
If QT_API is specified, we check that the correct Qt wrapper was used
"""
from qtpy import QtCore, QtGui, QtWidgets, QtWebEngineWidgets
QT_API = os.environ.get('QT_API', None)
... |
f0b27af3cc09808146442c94df7c76127776acf8 | gslib/devshell_auth_plugin.py | gslib/devshell_auth_plugin.py | # -*- coding: utf-8 -*-
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | # -*- coding: utf-8 -*-
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | Fix provider check causing Devshell auth failure | Fix provider check causing Devshell auth failure
This commit builds on commit 13c4926, allowing Devshell credentials to
be used only with Google storage.
| Python | apache-2.0 | GoogleCloudPlatform/gsutil,GoogleCloudPlatform/gsutil,fishjord/gsutil,BrandonY/gsutil | # -*- coding: utf-8 -*-
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | Fix provider check causing Devshell auth failure
This commit builds on commit 13c4926, allowing Devshell credentials to
be used only with Google storage.
# -*- coding: utf-8 -*-
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this... |
0519824c537a96474e0501e1ac45f7a626391a31 | tests/test_model_object.py | tests/test_model_object.py | # encoding: utf-8
from marathon.models.base import MarathonObject
import unittest
class MarathonObjectTest(unittest.TestCase):
def test_hashable(self):
"""
Regression test for issue #203
MarathonObject defined __eq__ but not __hash__, meaning that in
in Python2.7 MarathonObjects... | # encoding: utf-8
from marathon.models.base import MarathonObject
from marathon.models.base import MarathonResource
import unittest
class MarathonObjectTest(unittest.TestCase):
def test_hashable(self):
"""
Regression test for issue #203
MarathonObject defined __eq__ but not __hash__, me... | Add regression test for MarathonResource | Add regression test for MarathonResource
| Python | mit | thefactory/marathon-python,thefactory/marathon-python | # encoding: utf-8
from marathon.models.base import MarathonObject
from marathon.models.base import MarathonResource
import unittest
class MarathonObjectTest(unittest.TestCase):
def test_hashable(self):
"""
Regression test for issue #203
MarathonObject defined __eq__ but not __hash__, me... | Add regression test for MarathonResource
# encoding: utf-8
from marathon.models.base import MarathonObject
import unittest
class MarathonObjectTest(unittest.TestCase):
def test_hashable(self):
"""
Regression test for issue #203
MarathonObject defined __eq__ but not __hash__, meaning th... |
b3f5aed7097241adffd54d9b1ff705cd44455165 | examples/python/setup.py | examples/python/setup.py |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'Python Connector for Mongrel2',
'author': 'Zed A. Shaw',
'url': 'http://pypi.python.org/pypi/mongrel2-python',
'download_url': 'http://pypi.python.org/pypi/mongrel2-python',
'a... |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'Python Connector for Mongrel2',
'author': 'Zed A. Shaw',
'url': 'http://pypi.python.org/pypi/mongrel2-python',
'download_url': 'http://pypi.python.org/pypi/mongrel2-python',
'a... | Make m2sh have the same version number as mongrel2. | Make m2sh have the same version number as mongrel2. | Python | bsd-3-clause | ged/mongrel2,ged/mongrel2,ged/mongrel2,ged/mongrel2 |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'Python Connector for Mongrel2',
'author': 'Zed A. Shaw',
'url': 'http://pypi.python.org/pypi/mongrel2-python',
'download_url': 'http://pypi.python.org/pypi/mongrel2-python',
'a... | Make m2sh have the same version number as mongrel2.
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'Python Connector for Mongrel2',
'author': 'Zed A. Shaw',
'url': 'http://pypi.python.org/pypi/mongrel2-python',
'download_url': '... |
299fadcde71558bc1e77ba396cc544619373c2b1 | conditional/blueprints/spring_evals.py | conditional/blueprints/spring_evals.py | from flask import Blueprint
from flask import render_template
from flask import request
spring_evals_bp = Blueprint('spring_evals_bp', __name__)
@spring_evals_bp.route('/spring_evals/')
def display_spring_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
... | from flask import Blueprint
from flask import render_template
from flask import request
spring_evals_bp = Blueprint('spring_evals_bp', __name__)
@spring_evals_bp.route('/spring_evals/')
def display_spring_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
... | Add social events to spring evals 😿 | Add social events to spring evals 😿
| Python | mit | RamZallan/conditional,ComputerScienceHouse/conditional,RamZallan/conditional,ComputerScienceHouse/conditional,RamZallan/conditional,ComputerScienceHouse/conditional | from flask import Blueprint
from flask import render_template
from flask import request
spring_evals_bp = Blueprint('spring_evals_bp', __name__)
@spring_evals_bp.route('/spring_evals/')
def display_spring_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
... | Add social events to spring evals 😿
from flask import Blueprint
from flask import render_template
from flask import request
spring_evals_bp = Blueprint('spring_evals_bp', __name__)
@spring_evals_bp.route('/spring_evals/')
def display_spring_evals():
# get user data
user_name = request.headers.get('x-webaut... |
1dca59c4de479d2a75c34c0d1aae3948d819b84b | imagersite/imager_profile/models.py | imagersite/imager_profile/models.py | """Models."""
from django.db import models
# Create your models here.
class ImagerProfile(models.Model):
"""Imager Profile Model."""
camera_model = models.CharField(max_length=200)
photography_type = models.TextField()
Friends = models.ManyToManyField('self')
Region = models.CharField(max_lengt... | """Models."""
from django.db import models
# Create your models here.
class ImagerProfile(models.Model):
"""Imager Profile Model."""
camera_model = models.CharField(max_length=200)
photography_type = models.TextField()
friends = models.ManyToManyField('self')
region = models.CharField(max_lengt... | Change model fields to lower case letters | Change model fields to lower case letters
| Python | mit | DZwell/django-imager | """Models."""
from django.db import models
# Create your models here.
class ImagerProfile(models.Model):
"""Imager Profile Model."""
camera_model = models.CharField(max_length=200)
photography_type = models.TextField()
friends = models.ManyToManyField('self')
region = models.CharField(max_lengt... | Change model fields to lower case letters
"""Models."""
from django.db import models
# Create your models here.
class ImagerProfile(models.Model):
"""Imager Profile Model."""
camera_model = models.CharField(max_length=200)
photography_type = models.TextField()
Friends = models.ManyToManyField('sel... |
d794fea9cce98c719caef69b1c50f2783da81b1d | pritunl_node/call_buffer.py | pritunl_node/call_buffer.py | from constants import *
import collections
import uuid
class CallBuffer():
def __init__(self):
self.waiters = set()
self.cache = collections.deque(maxlen=CALL_CACHE_MAX)
self.call_waiters = {}
def wait_for_calls(self, callback, cursor=None):
if cursor:
calls = []
... | from constants import *
import collections
import uuid
class CallBuffer():
def __init__(self):
self.waiters = set()
self.cache = collections.deque(maxlen=CALL_CACHE_MAX)
self.call_waiters = {}
def wait_for_calls(self, callback, cursor=None):
if cursor:
calls = []
... | Add optional callbacks for call buffer | Add optional callbacks for call buffer
| Python | agpl-3.0 | pritunl/pritunl-node,pritunl/pritunl-node | from constants import *
import collections
import uuid
class CallBuffer():
def __init__(self):
self.waiters = set()
self.cache = collections.deque(maxlen=CALL_CACHE_MAX)
self.call_waiters = {}
def wait_for_calls(self, callback, cursor=None):
if cursor:
calls = []
... | Add optional callbacks for call buffer
from constants import *
import collections
import uuid
class CallBuffer():
def __init__(self):
self.waiters = set()
self.cache = collections.deque(maxlen=CALL_CACHE_MAX)
self.call_waiters = {}
def wait_for_calls(self, callback, cursor=None):
... |
84b4fc8fdc3808340293c076a1628bf0decd2d2c | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
setup(name="minishift-python",
version="0.1.2",
description="Python interface for the minishift",
author="Nick Johnson",
author_email="nick@arachnidlabs.com",
url="https://github.com/arachnidlabs/minishift-python/",
packages=["... | #!/usr/bin/env python
from distutils.core import setup
setup(name="minishift-python",
version="0.1.3",
description="Python interface for the minishift",
author="Nick Johnson",
author_email="nick@arachnidlabs.com",
url="https://github.com/arachnidlabs/minishift-python/",
packages=["... | Add python-daemon as a dep | Add python-daemon as a dep
| Python | bsd-3-clause | arachnidlabs/minishift-python | #!/usr/bin/env python
from distutils.core import setup
setup(name="minishift-python",
version="0.1.3",
description="Python interface for the minishift",
author="Nick Johnson",
author_email="nick@arachnidlabs.com",
url="https://github.com/arachnidlabs/minishift-python/",
packages=["... | Add python-daemon as a dep
#!/usr/bin/env python
from distutils.core import setup
setup(name="minishift-python",
version="0.1.2",
description="Python interface for the minishift",
author="Nick Johnson",
author_email="nick@arachnidlabs.com",
url="https://github.com/arachnidlabs/minishift... |
37c3e8f804b508247d3899a63c861102d76d1593 | docs/conf.py | docs/conf.py | import os
import pathlib
import sys
import toml
# Allow autodoc to import listparser.
sys.path.append(os.path.abspath("../src"))
# General configuration
# ---------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custo... | import os
import pathlib
import sys
import toml
# Allow autodoc to import listparser.
sys.path.append(os.path.abspath("../src"))
# General configuration
# ---------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custo... | Fix a build error reported by ReadTheDocs | Fix a build error reported by ReadTheDocs
| Python | mit | kurtmckee/listparser | import os
import pathlib
import sys
import toml
# Allow autodoc to import listparser.
sys.path.append(os.path.abspath("../src"))
# General configuration
# ---------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custo... | Fix a build error reported by ReadTheDocs
import os
import pathlib
import sys
import toml
# Allow autodoc to import listparser.
sys.path.append(os.path.abspath("../src"))
# General configuration
# ---------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with ... |
13f271c7d6d259e8a478657fa05822f9584090c4 | tests/keras/utils/generic_utils_test.py | tests/keras/utils/generic_utils_test.py | import pytest
from keras.utils.generic_utils import custom_object_scope
from keras import activations
from keras import regularizers
def test_custom_objects_scope():
def custom_fn():
pass
class CustomClass(object):
pass
with custom_object_scope({'CustomClass': CustomClass,
... | Add unit test for custom objects scope. | Add unit test for custom objects scope. | Python | apache-2.0 | keras-team/keras,keras-team/keras | import pytest
from keras.utils.generic_utils import custom_object_scope
from keras import activations
from keras import regularizers
def test_custom_objects_scope():
def custom_fn():
pass
class CustomClass(object):
pass
with custom_object_scope({'CustomClass': CustomClass,
... | Add unit test for custom objects scope.
| |
e382e25f47533fad12583e5a7e1213381a92751b | CsvToSepaDD.py | CsvToSepaDD.py | #!/usr/bin/env python
import argparse
import pprint
DEFAULT_CONFIG_FILE_NAME = 'CsvToSepaDD.config'
DEFAULT_CURRENCY = 'EUR'
def csvToSepa(args):
'''
[TODO] Converts the SEPA direct debit data from a given CSV file to SEPA XML
'''
pass
def createConfig(args):
'''Interactively creates a con... | Add a first draft for the user interface | Add a first draft for the user interface
| Python | bsd-3-clause | mfiedler/CsvToSepaDD | #!/usr/bin/env python
import argparse
import pprint
DEFAULT_CONFIG_FILE_NAME = 'CsvToSepaDD.config'
DEFAULT_CURRENCY = 'EUR'
def csvToSepa(args):
'''
[TODO] Converts the SEPA direct debit data from a given CSV file to SEPA XML
'''
pass
def createConfig(args):
'''Interactively creates a con... | Add a first draft for the user interface
| |
2697859df141b2dc6c34df5c0ac3ec87741d6b84 | examples/tour_examples/bootstrap_google_tour.py | examples/tour_examples/bootstrap_google_tour.py | from seleniumbase import BaseCase
class MyTourClass(BaseCase):
def test_google_tour(self):
self.open('https://google.com')
self.wait_for_element('input[title="Search"]')
self.create_bootstrap_tour() # OR self.create_tour(theme="bootstrap")
self.add_tour_step(
"Click ... | Add Bootstrap Google Tour example | Add Bootstrap Google Tour example
| Python | mit | mdmintz/SeleniumBase,mdmintz/seleniumspot,mdmintz/SeleniumBase,mdmintz/seleniumspot,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase | from seleniumbase import BaseCase
class MyTourClass(BaseCase):
def test_google_tour(self):
self.open('https://google.com')
self.wait_for_element('input[title="Search"]')
self.create_bootstrap_tour() # OR self.create_tour(theme="bootstrap")
self.add_tour_step(
"Click ... | Add Bootstrap Google Tour example
| |
b6208c1f9b6f0afca1dff40a66d2c915594b1946 | blaze/io/server/tests/start_simple_server.py | blaze/io/server/tests/start_simple_server.py | """
Starts a Blaze server for tests.
$ start_test_server.py /path/to/catalog_config.yaml <portnumber>
"""
import sys, os
import blaze
from blaze.io.server.app import app
blaze.catalog.load_config(sys.argv[1])
app.run(port=int(sys.argv[2]), use_reloader=False)
| """
Starts a Blaze server for tests.
$ start_test_server.py /path/to/catalog_config.yaml <portnumber>
"""
import sys, os
if os.name == 'nt':
old_excepthook = sys.excepthook
# Exclude this from our autogenerated API docs.
undoc = lambda func: func
@undoc
def gui_excepthook(exctype, value, tb):
... | Add exception hook to help diagnose server test errors in python3 gui mode | Add exception hook to help diagnose server test errors in python3 gui mode
| Python | bsd-3-clause | caseyclements/blaze,dwillmer/blaze,jcrist/blaze,mrocklin/blaze,cowlicks/blaze,ContinuumIO/blaze,jcrist/blaze,xlhtc007/blaze,FrancescAlted/blaze,aterrel/blaze,nkhuyu/blaze,AbhiAgarwal/blaze,markflorisson/blaze-core,nkhuyu/blaze,FrancescAlted/blaze,ChinaQuants/blaze,markflorisson/blaze-core,alexmojaki/blaze,alexmojaki/bl... | """
Starts a Blaze server for tests.
$ start_test_server.py /path/to/catalog_config.yaml <portnumber>
"""
import sys, os
if os.name == 'nt':
old_excepthook = sys.excepthook
# Exclude this from our autogenerated API docs.
undoc = lambda func: func
@undoc
def gui_excepthook(exctype, value, tb):
... | Add exception hook to help diagnose server test errors in python3 gui mode
"""
Starts a Blaze server for tests.
$ start_test_server.py /path/to/catalog_config.yaml <portnumber>
"""
import sys, os
import blaze
from blaze.io.server.app import app
blaze.catalog.load_config(sys.argv[1])
app.run(port=int(sys.argv[2]), us... |
c01f4014d3ccda8a168c6298d05e894e381f1ded | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Aparajita Fishman
# Copyright (c) 2015-2016 The SublimeLinter Community
# Copyright (c) 2013-2014 Aparajita Fishman
#
# License: MIT
#
"""This module exports the Pydocstyle plugin linter class."""
from SublimeLinter... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Aparajita Fishman
# Copyright (c) 2015-2016 The SublimeLinter Community
# Copyright (c) 2013-2014 Aparajita Fishman
#
# License: MIT
#
"""This module exports the Pydocstyle plugin linter class."""
from SublimeLinter... | Fix for pydocstyle > 1.1.1 | Fix for pydocstyle > 1.1.1 | Python | mit | SublimeLinter/SublimeLinter-pep257 | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Aparajita Fishman
# Copyright (c) 2015-2016 The SublimeLinter Community
# Copyright (c) 2013-2014 Aparajita Fishman
#
# License: MIT
#
"""This module exports the Pydocstyle plugin linter class."""
from SublimeLinter... | Fix for pydocstyle > 1.1.1
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Aparajita Fishman
# Copyright (c) 2015-2016 The SublimeLinter Community
# Copyright (c) 2013-2014 Aparajita Fishman
#
# License: MIT
#
"""This module exports the Pydocstyle plugin linter cl... |
a3d655bd311161679bafbcad66f678d412e158f0 | colour/examples/volume/examples_rgb.py | colour/examples/volume/examples_rgb.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Showcases RGB colourspace volume computations.
"""
from __future__ import division, unicode_literals
import colour
from colour.utilities.verbose import message_box
message_box('RGB Colourspace Volume Computations')
message_box('Computing "ProPhoto RGB" RGB coloursp... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Showcases RGB colourspace volume computations.
"""
from __future__ import division, unicode_literals
import colour
from colour.utilities.verbose import message_box
message_box('RGB Colourspace Volume Computations')
message_box('Computing "ProPhoto RGB" RGB coloursp... | Add "Pointer's Gamut" coverage computation example. | Add "Pointer's Gamut" coverage computation example.
| Python | bsd-3-clause | colour-science/colour | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Showcases RGB colourspace volume computations.
"""
from __future__ import division, unicode_literals
import colour
from colour.utilities.verbose import message_box
message_box('RGB Colourspace Volume Computations')
message_box('Computing "ProPhoto RGB" RGB coloursp... | Add "Pointer's Gamut" coverage computation example.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Showcases RGB colourspace volume computations.
"""
from __future__ import division, unicode_literals
import colour
from colour.utilities.verbose import message_box
message_box('RGB Colourspace Volume Computations'... |
b8636987742455d440ebe2fcfb77c41be56e8f39 | setup.py | setup.py | #!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='django-bleach',
version="0.1.3",
description='Easily use bleach with Django models and te... | #!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='django-bleach',
version="0.1.3",
description='Easily use bleach with Django models and te... | Add Django as a requirement | Add Django as a requirement
Django>=1.3 is required, although >=1.4.1 is recommended
| Python | bsd-2-clause | python-force/django-bleach | #!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='django-bleach',
version="0.1.3",
description='Easily use bleach with Django models and te... | Add Django as a requirement
Django>=1.3 is required, although >=1.4.1 is recommended
#!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='django-ble... |
859d5ce6553b7651f05f27adec28e8c4330ca9bb | handler/supervisor_to_serf.py | handler/supervisor_to_serf.py | #!/usr/bin/env python
import json
import sys
from utils import serf_event
def write_stdout(s):
sys.stdout.write(s)
sys.stdout.flush()
def write_stderr(s):
sys.stderr.write(s)
sys.stderr.flush()
def main():
while True:
write_stdout('READY\n') # transition from ACKNOWLEDGED to READY
... | #!/usr/bin/env python
import json
import sys
from utils import serf_event
def write_stdout(s):
sys.stdout.write(s)
sys.stdout.flush()
def write_stderr(s):
sys.stderr.write(s)
sys.stderr.flush()
def main():
while True:
write_stdout('READY\n') # transition from ACKNOWLEDGED to READY
... | Add id of node generating the supervisor event | Add id of node generating the supervisor event
| Python | mit | waltermoreira/serfnode,waltermoreira/serfnode,waltermoreira/serfnode | #!/usr/bin/env python
import json
import sys
from utils import serf_event
def write_stdout(s):
sys.stdout.write(s)
sys.stdout.flush()
def write_stderr(s):
sys.stderr.write(s)
sys.stderr.flush()
def main():
while True:
write_stdout('READY\n') # transition from ACKNOWLEDGED to READY
... | Add id of node generating the supervisor event
#!/usr/bin/env python
import json
import sys
from utils import serf_event
def write_stdout(s):
sys.stdout.write(s)
sys.stdout.flush()
def write_stderr(s):
sys.stderr.write(s)
sys.stderr.flush()
def main():
while True:
write_stdout('READY\... |
75ff727cd29ae1b379c551f46217fa75bf0fb2bc | videoeditor.py | videoeditor.py | from moviepy.editor import *
def bake_annotations(video_file, end_point, annotations):
clip = VideoFileClip(video_file)
composite_clips = [clip]
#for annotation in annotations:
# txt_clip = TextClip(annotation["text"], color="white", fontsize=70)
# txt_clip = txt_clip.set_position(("center",... | from moviepy.editor import *
def bake_annotations(video_file, end_point, annotations):
clip = VideoFileClip(video_file)
composite_clips = [clip]
#for annotation in annotations:
# txt_clip = TextClip(annotation["text"], color="white", fontsize=70)
# txt_clip = txt_clip.set_position(("center",... | Make pause dependant on annotation text length | Make pause dependant on annotation text length
| Python | mit | melonmanchan/achso-video-exporter,melonmanchan/achso-video-exporter | from moviepy.editor import *
def bake_annotations(video_file, end_point, annotations):
clip = VideoFileClip(video_file)
composite_clips = [clip]
#for annotation in annotations:
# txt_clip = TextClip(annotation["text"], color="white", fontsize=70)
# txt_clip = txt_clip.set_position(("center",... | Make pause dependant on annotation text length
from moviepy.editor import *
def bake_annotations(video_file, end_point, annotations):
clip = VideoFileClip(video_file)
composite_clips = [clip]
#for annotation in annotations:
# txt_clip = TextClip(annotation["text"], color="white", fontsize=70)
... |
25cee68231c350d124614237402ae4cb5fc7c19d | setup.py | setup.py | import os
from setuptools import setup, find_packages
version = '1.5.0_patch1'
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='django-cas-client',
version=version,
description="Django Cas Client",
long_description=read('README.md'),
class... | import os
from setuptools import setup, find_packages
version = '1.5.0'
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='django-cas-client',
version=version,
description="Django Cas Client",
long_description=read('README.md'),
classifiers=... | Revert version update made for our mirror. | Revert version update made for our mirror.
| Python | mit | kstateome/django-cas | import os
from setuptools import setup, find_packages
version = '1.5.0'
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='django-cas-client',
version=version,
description="Django Cas Client",
long_description=read('README.md'),
classifiers=... | Revert version update made for our mirror.
import os
from setuptools import setup, find_packages
version = '1.5.0_patch1'
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='django-cas-client',
version=version,
description="Django Cas Client",
lon... |
ab63a427361ef72f0e573654cf6100754b268616 | l10n_es_facturae/components/edi_output_l10n_es_facturae.py | l10n_es_facturae/components/edi_output_l10n_es_facturae.py | # Copyright 2020 Creu Blanca
# @author: Enric Tobella
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.addons.component.core import Component
class EdiOutputL10nEsFacturae(Component):
_name = "edi.output.generate.l10n_es_facturae"
_inherit = "edi.component.output.mixin"
_usage = ... | # Copyright 2020 Creu Blanca
# @author: Enric Tobella
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.addons.component.core import Component
class EdiOutputL10nEsFacturae(Component):
_name = "edi.output.generate.l10n_es_facturae"
_inherit = "edi.component.output.mixin"
_usage = ... | Fix components names using the new logic | [FIX] l10n_es_facturae: Fix components names using the new logic
| Python | agpl-3.0 | OCA/l10n-spain,OCA/l10n-spain,OCA/l10n-spain | # Copyright 2020 Creu Blanca
# @author: Enric Tobella
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.addons.component.core import Component
class EdiOutputL10nEsFacturae(Component):
_name = "edi.output.generate.l10n_es_facturae"
_inherit = "edi.component.output.mixin"
_usage = ... | [FIX] l10n_es_facturae: Fix components names using the new logic
# Copyright 2020 Creu Blanca
# @author: Enric Tobella
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.addons.component.core import Component
class EdiOutputL10nEsFacturae(Component):
_name = "edi.output.generate.l10n_es_f... |
9b422f71123246632e0e8c505ea9721955a2eada | setup.py | setup.py | """
Flask-Script
--------------
Flask support for writing external scripts.
Links
`````
* `documentation <http://packages.python.org/Flask-Script>`_
"""
from setuptools import setup
# Hack to prevent stupid TypeError: 'NoneType' object is not callable error on
# exit of python setup.py test # in multiprocessing/u... | """
Flask-Script
--------------
Flask support for writing external scripts.
Links
`````
* `documentation <http://flask-script.readthedocs.org>`_
"""
from setuptools import setup
# Hack to prevent stupid TypeError: 'NoneType' object is not callable error on
# exit of python setup.py test # in multiprocessing/util.... | Update documentation link on PyPI to flask-script.readthedocs.org | Update documentation link on PyPI to flask-script.readthedocs.org
| Python | bsd-3-clause | blakev/flask-script,z4y4ts/flask-script,z4y4ts/flask-script,wjt/flask-script,dext0r/flask-script,xingkaixin/flask-script,denismakogon/flask-script | """
Flask-Script
--------------
Flask support for writing external scripts.
Links
`````
* `documentation <http://flask-script.readthedocs.org>`_
"""
from setuptools import setup
# Hack to prevent stupid TypeError: 'NoneType' object is not callable error on
# exit of python setup.py test # in multiprocessing/util.... | Update documentation link on PyPI to flask-script.readthedocs.org
"""
Flask-Script
--------------
Flask support for writing external scripts.
Links
`````
* `documentation <http://packages.python.org/Flask-Script>`_
"""
from setuptools import setup
# Hack to prevent stupid TypeError: 'NoneType' object is not call... |
a216d01adaae04289443343e790cfa3317863e6e | 1_boilerpipe_lib_scrapping.py | 1_boilerpipe_lib_scrapping.py | # -*- coding: UTF-8 -*-
from boilerpipe.extract import Extractor
from bs4 import BeautifulSoup
from urllib2 import urlopen
URL='http://sportv.globo.com/site/eventos/mundial-de-motovelocidade/noticia/2016/06/em-duelo-eletrizante-rossi-vence-marquez-salom-e-homenageado.html'
soup = BeautifulSoup(urlopen(URL).read(), "... | Add web scrapping example to boilerpipe lib | Add web scrapping example to boilerpipe lib
| Python | apache-2.0 | fabriciojoc/redes-sociais-web,fabriciojoc/redes-sociais-web | # -*- coding: UTF-8 -*-
from boilerpipe.extract import Extractor
from bs4 import BeautifulSoup
from urllib2 import urlopen
URL='http://sportv.globo.com/site/eventos/mundial-de-motovelocidade/noticia/2016/06/em-duelo-eletrizante-rossi-vence-marquez-salom-e-homenageado.html'
soup = BeautifulSoup(urlopen(URL).read(), "... | Add web scrapping example to boilerpipe lib
| |
45a46bec14c2c0a2793083cb391f29a632281f11 | senlin/tests/tempest/api/profiles/test_profile_type.py | senlin/tests/tempest/api/profiles/test_profile_type.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | Add API test for profile type show/list | Add API test for profile type show/list
Change-Id: Ibb260e41f5ddcc9ac1e6603a8e749167927efc54
| Python | apache-2.0 | openstack/senlin,stackforge/senlin,openstack/senlin,openstack/senlin,stackforge/senlin | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | Add API test for profile type show/list
Change-Id: Ibb260e41f5ddcc9ac1e6603a8e749167927efc54
| |
811421407379dedc217795000f6f2cbe54510f96 | kolibri/core/utils/urls.py | kolibri/core/utils/urls.py | from django.urls import reverse
from six.moves.urllib.parse import urljoin
from kolibri.utils.conf import OPTIONS
def reverse_remote(
baseurl, viewname, urlconf=None, args=None, kwargs=None, current_app=None
):
# Get the reversed URL
reversed_url = reverse(
viewname, urlconf=urlconf, args=args, k... | from django.urls import reverse
from six.moves.urllib.parse import urljoin
from kolibri.utils.conf import OPTIONS
def reverse_remote(
baseurl, viewname, urlconf=None, args=None, kwargs=None, current_app=None
):
# Get the reversed URL
reversed_url = reverse(
viewname, urlconf=urlconf, args=args, k... | Truncate rather than replace to prevent erroneous substitutions. | Truncate rather than replace to prevent erroneous substitutions.
| Python | mit | learningequality/kolibri,learningequality/kolibri,learningequality/kolibri,learningequality/kolibri | from django.urls import reverse
from six.moves.urllib.parse import urljoin
from kolibri.utils.conf import OPTIONS
def reverse_remote(
baseurl, viewname, urlconf=None, args=None, kwargs=None, current_app=None
):
# Get the reversed URL
reversed_url = reverse(
viewname, urlconf=urlconf, args=args, k... | Truncate rather than replace to prevent erroneous substitutions.
from django.urls import reverse
from six.moves.urllib.parse import urljoin
from kolibri.utils.conf import OPTIONS
def reverse_remote(
baseurl, viewname, urlconf=None, args=None, kwargs=None, current_app=None
):
# Get the reversed URL
rever... |
6f29293e6f447dfd80d10c173b7c5a6cc13a4243 | main/urls.py | main/urls.py | from django.conf.urls import url
from django.views import generic
from . import views
app_name = 'main'
urlpatterns = [
url(r'^$', views.AboutView.as_view(), name='about'),
url(r'^chas/$', views.AboutChasView.as_view(), name='chas'),
url(r'^evan/$', views.AboutEvanView.as_view(), name='evan'),
]
| from django.urls import include, path
from . import views
app_name = 'main'
urlpatterns = [
path('', views.AboutView.as_view(), name='about'),
path('chas/', views.AboutChasView.as_view(), name='chas'),
path('evan/', views.AboutEvanView.as_view(), name='evan'),
]
| Move some urlpatterns to DJango 2.0 preferred method | Move some urlpatterns to DJango 2.0 preferred method
| Python | mit | evanepio/dotmanca,evanepio/dotmanca,evanepio/dotmanca | from django.urls import include, path
from . import views
app_name = 'main'
urlpatterns = [
path('', views.AboutView.as_view(), name='about'),
path('chas/', views.AboutChasView.as_view(), name='chas'),
path('evan/', views.AboutEvanView.as_view(), name='evan'),
]
| Move some urlpatterns to DJango 2.0 preferred method
from django.conf.urls import url
from django.views import generic
from . import views
app_name = 'main'
urlpatterns = [
url(r'^$', views.AboutView.as_view(), name='about'),
url(r'^chas/$', views.AboutChasView.as_view(), name='chas'),
url(r'^evan/$', vi... |
45a319f4bf4ae310a2299b58cf8a3f907fdb7f3c | receipt_tracker/urls.py | receipt_tracker/urls.py | """receipt_tracker URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/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')
... | """receipt_tracker URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/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')
... | Disable static to get something running | Disable static to get something running | Python | agpl-3.0 | openreceipts/openreceipts-server,openreceipts/openreceipts-server,openreceipts/openreceipts-server | """receipt_tracker URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/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')
... | Disable static to get something running
"""receipt_tracker URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpattern... |
6ec4307173f3eafa87fd063978914bf5816ecb0a | reports/utils.py | reports/utils.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
def default_graph_layout_options():
"""Default layout options for all graphs.
"""
return {
'font': {
'color': 'rgba(0, 0, 0, 1)',
# Bootstrap 4 font family.
'family': '-apple-system, BlinkMacSystemF... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
def default_graph_layout_options():
"""Default layout options for all graphs.
"""
return {
'font': {
'color': 'rgba(0, 0, 0, 1)',
# Bootstrap 4 font family.
'family': '-apple-system, BlinkMacSystemF... | Increase default top margin to account for two line graph titles. | Increase default top margin to account for two line graph titles.
| Python | bsd-2-clause | cdubz/babybuddy,cdubz/babybuddy,cdubz/babybuddy | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
def default_graph_layout_options():
"""Default layout options for all graphs.
"""
return {
'font': {
'color': 'rgba(0, 0, 0, 1)',
# Bootstrap 4 font family.
'family': '-apple-system, BlinkMacSystemF... | Increase default top margin to account for two line graph titles.
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
def default_graph_layout_options():
"""Default layout options for all graphs.
"""
return {
'font': {
'color': 'rgba(0, 0, 0, 1)',
# Bootstrap 4... |
c306f6963e53b971674421eddca7f6b5c913281e | core/data/DataWriter.py | core/data/DataWriter.py | """
DataWriter.py
"""
from DataController import DataController
from DataReader import DataReader
from vtk import vtkMetaImageWriter
from vtk import vtkXMLImageDataWriter
class DataWriter(DataController):
"""
DataWriter writes an image data object to
disk using the provided format.
"""
def __init__(self):
sup... | """
DataWriter.py
"""
from DataController import DataController
from DataReader import DataReader
from vtk import vtkMetaImageWriter
from vtk import vtkXMLImageDataWriter
class DataWriter(DataController):
"""
DataWriter writes an image data object to
disk using the provided format.
"""
def __init__(self):
sup... | Fix for comparing with the wrong data type. | Fix for comparing with the wrong data type.
| Python | mit | berendkleinhaneveld/Registrationshop,berendkleinhaneveld/Registrationshop | """
DataWriter.py
"""
from DataController import DataController
from DataReader import DataReader
from vtk import vtkMetaImageWriter
from vtk import vtkXMLImageDataWriter
class DataWriter(DataController):
"""
DataWriter writes an image data object to
disk using the provided format.
"""
def __init__(self):
sup... | Fix for comparing with the wrong data type.
"""
DataWriter.py
"""
from DataController import DataController
from DataReader import DataReader
from vtk import vtkMetaImageWriter
from vtk import vtkXMLImageDataWriter
class DataWriter(DataController):
"""
DataWriter writes an image data object to
disk using the pro... |
ca791d66b85baae91d6decd5f5a201a2b7512efb | wafer/schedule/migrations/0002_auto_20140909_1403.py | wafer/schedule/migrations/0002_auto_20140909_1403.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('schedule', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='slot',
options={'or... | Update migration to latest schedule work | Update migration to latest schedule work
| Python | isc | CarlFK/wafer,CTPUG/wafer,CarlFK/wafer,CTPUG/wafer,CarlFK/wafer,CTPUG/wafer,CarlFK/wafer,CTPUG/wafer | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('schedule', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='slot',
options={'or... | Update migration to latest schedule work
| |
4b43a2f50740bbeab95f64137eb8993ed8ac4617 | other/password_generator.py | other/password_generator.py | import string
from random import *
letters = string.ascii_letters
digits = string.digits
symbols = string.punctuation
chars = letters + digits + symbols
min_length = 8
max_length = 16
password = ''.join(choice(chars) for x in range(randint(min_length, max_length)))
print('Password: %s' % password)
print('[ If you are... | import string
import random
letters = [letter for letter in string.ascii_letters]
digits = [digit for digit in string.digits]
symbols = [symbol for symbol in string.punctuation]
chars = letters + digits + symbols
random.shuffle(chars)
min_length = 8
max_length = 16
password = ''.join(random.choice(chars) for x in ran... | Add another randomness into the password generator | Add another randomness into the password generator
Uses import random for namespace cleanliness
Uses list instead of string for 'chars' variable in order to shuffle, increases randomness
Instead of string formatting, uses string concatenation because (currently) it is simpler | Python | mit | TheAlgorithms/Python | import string
import random
letters = [letter for letter in string.ascii_letters]
digits = [digit for digit in string.digits]
symbols = [symbol for symbol in string.punctuation]
chars = letters + digits + symbols
random.shuffle(chars)
min_length = 8
max_length = 16
password = ''.join(random.choice(chars) for x in ran... | Add another randomness into the password generator
Uses import random for namespace cleanliness
Uses list instead of string for 'chars' variable in order to shuffle, increases randomness
Instead of string formatting, uses string concatenation because (currently) it is simpler
import string
from random import *
lett... |
48a9701fc57679a3526f55e516710b7b787d479f | setup.py | setup.py | import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='mdot',
version='0.1',
packages=['mdot'],
include_packa... | import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='mdot',
version='0.1',
packages=['mdot'],
include_packa... | Revert "Try less than 2.0." | Revert "Try less than 2.0."
This reverts commit 1bffae34a767e56943bb83027719fbe6dffcdc3b.
| Python | apache-2.0 | uw-it-aca/mdot,uw-it-aca/mdot,charlon/mdot,uw-it-aca/mdot,charlon/mdot,uw-it-aca/mdot,charlon/mdot | import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='mdot',
version='0.1',
packages=['mdot'],
include_packa... | Revert "Try less than 2.0."
This reverts commit 1bffae34a767e56943bb83027719fbe6dffcdc3b.
import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pa... |
942315bb5baa45df4dfde9b04b99685a6be6f574 | diagnose_error.py | diagnose_error.py | from __future__ import with_statement
import os, sys, tempfile, subprocess, re
__all__ = ["has_error", "get_error_line_number", "make_reg_string", "get_coq_output"]
DEFAULT_ERROR_REG_STRING = 'File "[^"]+", line ([0-9]+), characters [0-9-]+:\n([^\n]+)'
DEFAULT_ERROR_REG_STRING_GENERIC = 'File "[^"]+", line ([0-9]+), ... | Add a file to extract error strings | Add a file to extract error strings
| Python | mit | JasonGross/coq-tools,JasonGross/coq-tools | from __future__ import with_statement
import os, sys, tempfile, subprocess, re
__all__ = ["has_error", "get_error_line_number", "make_reg_string", "get_coq_output"]
DEFAULT_ERROR_REG_STRING = 'File "[^"]+", line ([0-9]+), characters [0-9-]+:\n([^\n]+)'
DEFAULT_ERROR_REG_STRING_GENERIC = 'File "[^"]+", line ([0-9]+), ... | Add a file to extract error strings
| |
3e0b91b310afb64589e934a18fd75e767b75e43f | project/settings_prod.py | project/settings_prod.py | from project.settings_common import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
# CACHE
from memcacheify import memcacheify
CACHES = memcacheify()
MIDDLEWARE_CLASSES += (
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
)
STATIC_ROOT = os.path.join(PROJECT_ROO... | from project.settings_common import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
# CACHE
from memcacheify import memcacheify
CACHES = memcacheify()
MIDDLEWARE_CLASSES += (
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
)
STATIC_ROOT = os.path.join(PROJECT_ROO... | Comment out s3 settings. It was breaking admin static file serve | Comment out s3 settings. It was breaking admin static file serve
| Python | mit | AxisPhilly/lobbying.ph-django,AxisPhilly/lobbying.ph-django,AxisPhilly/lobbying.ph-django | from project.settings_common import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
# CACHE
from memcacheify import memcacheify
CACHES = memcacheify()
MIDDLEWARE_CLASSES += (
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
)
STATIC_ROOT = os.path.join(PROJECT_ROO... | Comment out s3 settings. It was breaking admin static file serve
from project.settings_common import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
# CACHE
from memcacheify import memcacheify
CACHES = memcacheify()
MIDDLEWARE_CLASSES += (
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.cache.Fe... |
727939269aef168513ad6d62913e20f0af95b4e6 | dduplicated/hashs.py | dduplicated/hashs.py | import hashlib
import os
def get_hash(path):
return get_md5(path)
def get_md5(path):
hash_md5 = hashlib.md5()
if os.path.isfile(path):
with open(path, "rb") as file:
while True:
buffer = file.read(4096)
if not buffer:
break
hash_md5.update(buffer)
return hash_md5.hexdigest()
| import hashlib
import os
def get_hash(path):
return get_md5(path)
# MD5 methods is based on second answer from: https://exceptionshub.com/get-md5-hash-of-big-files-in-python.html
def get_md5(path):
hash_md5 = hashlib.md5()
if os.path.isfile(path):
with open(path, "rb") as file:
while True:
buffer = file.re... | Add reference to md5 method. | Add reference to md5 method. | Python | mit | messiasthi/dduplicated-cli | import hashlib
import os
def get_hash(path):
return get_md5(path)
# MD5 methods is based on second answer from: https://exceptionshub.com/get-md5-hash-of-big-files-in-python.html
def get_md5(path):
hash_md5 = hashlib.md5()
if os.path.isfile(path):
with open(path, "rb") as file:
while True:
buffer = file.re... | Add reference to md5 method.
import hashlib
import os
def get_hash(path):
return get_md5(path)
def get_md5(path):
hash_md5 = hashlib.md5()
if os.path.isfile(path):
with open(path, "rb") as file:
while True:
buffer = file.read(4096)
if not buffer:
break
hash_md5.update(buffer)
return ... |
e8dae2888576fa2305cddda0e48f332276b176b5 | app/__init__.py | app/__init__.py | #!flask/bin/python
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
from app import views, models
| #!flask/bin/python
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
from app import views, models
| Update to flask_sqlalchemy to use python 3 import | Update to flask_sqlalchemy to use python 3 import | Python | agpl-3.0 | lasa/website,lasa/website,lasa/website | #!flask/bin/python
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
from app import views, models
| Update to flask_sqlalchemy to use python 3 import
#!flask/bin/python
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
from app import views, models
|
4244f9c4d9e64783d391139457d7761dbc19e546 | softwareindex/handlers/coreapi.py | softwareindex/handlers/coreapi.py | # This is a software index handler that gives a score based on the
# number of mentions in open access articles. It uses the CORE
# aggregator (http://core.ac.uk/) to search the full text of indexed
# articles.
#
# Inputs:
# - identifier (String)
#
# Outputs:
# - score (Number)
# - description (String)
import reque... | # This is a software index handler that gives a score based on the
# number of mentions in open access articles. It uses the CORE
# aggregator (http://core.ac.uk/) to search the full text of indexed
# articles.
#
# Inputs:
# - identifier (String)
#
# Outputs:
# - score (Number)
# - description (String)
import reque... | Remove unneeded import of json module. | Remove unneeded import of json module.
| Python | bsd-3-clause | softwaresaved/softwareindex,softwaresaved/softwareindex | # This is a software index handler that gives a score based on the
# number of mentions in open access articles. It uses the CORE
# aggregator (http://core.ac.uk/) to search the full text of indexed
# articles.
#
# Inputs:
# - identifier (String)
#
# Outputs:
# - score (Number)
# - description (String)
import reque... | Remove unneeded import of json module.
# This is a software index handler that gives a score based on the
# number of mentions in open access articles. It uses the CORE
# aggregator (http://core.ac.uk/) to search the full text of indexed
# articles.
#
# Inputs:
# - identifier (String)
#
# Outputs:
# - score (Number... |
52fc9bc79343632a034d2dc51645306f4b58210c | tests/services/conftest.py | tests/services/conftest.py | import pytest
from responses import RequestsMock
from netvisor import Netvisor
@pytest.fixture
def netvisor():
kwargs = dict(
sender='Test client',
partner_id='xxx_yyy',
partner_key='E2CEBB1966C7016730C70CA92CBB93DD',
customer_id='xx_yyyy_zz',
customer_key='7767899D6F5FB33... | import pytest
from responses import RequestsMock
from netvisor import Netvisor
@pytest.fixture
def netvisor():
kwargs = dict(
sender='Test client',
partner_id='xxx_yyy',
partner_key='E2CEBB1966C7016730C70CA92CBB93DD',
customer_id='xx_yyyy_zz',
customer_key='7767899D6F5FB33... | Fix tests to work with responses 0.3.0 | Fix tests to work with responses 0.3.0
| Python | mit | fastmonkeys/netvisor.py | import pytest
from responses import RequestsMock
from netvisor import Netvisor
@pytest.fixture
def netvisor():
kwargs = dict(
sender='Test client',
partner_id='xxx_yyy',
partner_key='E2CEBB1966C7016730C70CA92CBB93DD',
customer_id='xx_yyyy_zz',
customer_key='7767899D6F5FB33... | Fix tests to work with responses 0.3.0
import pytest
from responses import RequestsMock
from netvisor import Netvisor
@pytest.fixture
def netvisor():
kwargs = dict(
sender='Test client',
partner_id='xxx_yyy',
partner_key='E2CEBB1966C7016730C70CA92CBB93DD',
customer_id='xx_yyyy_zz... |
644df0955d1a924b72ffdceaea9d8da14100dae0 | scipy/weave/tests/test_inline_tools.py | scipy/weave/tests/test_inline_tools.py | from numpy import *
from numpy.testing import *
from scipy.weave import inline_tools
class TestInline(TestCase):
""" These are long running tests...
I'd like to benchmark these things somehow.
"""
@dec.slow
def test_exceptions(self):
a = 3
code = """
if (a < 2)... | from numpy import *
from numpy.testing import *
from scipy.weave import inline_tools
class TestInline(TestCase):
""" These are long running tests...
I'd like to benchmark these things somehow.
"""
@dec.slow
def test_exceptions(self):
a = 3
code = """
if (a < 2)... | Disable weave tests that cause compilation failure, since this causes distutils to do a SystemExit, which break the test suite. | Disable weave tests that cause compilation failure, since this causes
distutils to do a SystemExit, which break the test suite.
git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@5402 d6536bca-fef9-0310-8506-e4c0a848fbcf
| Python | bsd-3-clause | scipy/scipy-svn,lesserwhirls/scipy-cwt,scipy/scipy-svn,jasonmccampbell/scipy-refactor,scipy/scipy-svn,lesserwhirls/scipy-cwt,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,scipy/scipy-svn,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor | from numpy import *
from numpy.testing import *
from scipy.weave import inline_tools
class TestInline(TestCase):
""" These are long running tests...
I'd like to benchmark these things somehow.
"""
@dec.slow
def test_exceptions(self):
a = 3
code = """
if (a < 2)... | Disable weave tests that cause compilation failure, since this causes
distutils to do a SystemExit, which break the test suite.
git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@5402 d6536bca-fef9-0310-8506-e4c0a848fbcf
from numpy import *
from numpy.testing import *
from scipy.weave import inline_tools
class Te... |
a576432d045d14308012a4eaa6eaeb12fe004a37 | scarplet.py | scarplet.py | """ Functions for determinig best-fit template parameters by convolution with a
grid """
| """ Functions for determinig best-fit template parameters by convolution with a
grid """
import dem
import WindowedTemplate as wt
import numpy as np
from scipy import signal
def calculate_best_fit_parameters(dem, template_function, **kwargs):
template_args = parse_args(**kwargs)
num_angles = 180/ang_ste... | Add generic grid search function | Add generic grid search function
| Python | mit | rmsare/scarplet,stgl/scarplet | """ Functions for determinig best-fit template parameters by convolution with a
grid """
import dem
import WindowedTemplate as wt
import numpy as np
from scipy import signal
def calculate_best_fit_parameters(dem, template_function, **kwargs):
template_args = parse_args(**kwargs)
num_angles = 180/ang_ste... | Add generic grid search function
""" Functions for determinig best-fit template parameters by convolution with a
grid """
|
f3ec0593bb67db25c4f5af4b3b00d82d5e4e0f04 | csv2ofx/mappings/gls.py | csv2ofx/mappings/gls.py | from operator import itemgetter
mapping = {
'has_header': True,
'currency': 'EUR',
'delimiter': ';',
'bank': 'GLS Bank',
'account': itemgetter('Kontonummer'),
# Chop up the dotted German date format and put it in ridiculous M/D/Y order
'date': lambda r:
r['Buchungstag'][3:5] + '/' ... | from __future__ import absolute_import
from operator import itemgetter
mapping = {
'has_header': True,
'currency': 'EUR',
'delimiter': ';',
'bank': 'GLS Bank',
'account': itemgetter('Kontonummer'),
# Chop up the dotted German date format and put it in ridiculous M/D/Y order
'date': lambda ... | Add import for other python versions | Add import for other python versions | Python | mit | reubano/csv2ofx,reubano/csv2ofx | from __future__ import absolute_import
from operator import itemgetter
mapping = {
'has_header': True,
'currency': 'EUR',
'delimiter': ';',
'bank': 'GLS Bank',
'account': itemgetter('Kontonummer'),
# Chop up the dotted German date format and put it in ridiculous M/D/Y order
'date': lambda ... | Add import for other python versions
from operator import itemgetter
mapping = {
'has_header': True,
'currency': 'EUR',
'delimiter': ';',
'bank': 'GLS Bank',
'account': itemgetter('Kontonummer'),
# Chop up the dotted German date format and put it in ridiculous M/D/Y order
'date': lambda r:... |
3da5a4dd70b50b7988d0023087a9d73274f273ba | tests/test_smartypants.py | tests/test_smartypants.py | # -*- coding: utf-8 -*-
# This file is part of python-markups test suite
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012
from markups.common import educate as ed
import unittest
class SmartyTest(unittest.TestCase):
def test_quotes(self):
self.assertEqual(ed('"Isn\'t this fun?"'), '“Isn’t this fun?”')
self... | Add (currently failing) smartypants test | Add (currently failing) smartypants test
| Python | bsd-3-clause | mitya57/pymarkups,retext-project/pymarkups | # -*- coding: utf-8 -*-
# This file is part of python-markups test suite
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012
from markups.common import educate as ed
import unittest
class SmartyTest(unittest.TestCase):
def test_quotes(self):
self.assertEqual(ed('"Isn\'t this fun?"'), '“Isn’t this fun?”')
self... | Add (currently failing) smartypants test
| |
6a07e4b3b0c67c442f0501f19c0253b4c99637cd | setup.py | setup.py | from setuptools import setup
import transip
setup(
name = transip.__name__,
version = transip.__version__,
author = transip.__author__,
author_email = transip.__email__,
license = transip.__license__,
description = transip.__doc__.splitlines()[0],
long_description = open('README.rst').read... | from setuptools import setup
import transip
setup(
name = transip.__name__,
version = transip.__version__,
author = transip.__author__,
author_email = transip.__email__,
license = transip.__license__,
description = transip.__doc__.splitlines()[0],
long_description = open('README.rst').read... | Add more requirements that are needed for this module | Add more requirements that are needed for this module
| Python | mit | benkonrath/transip-api,benkonrath/transip-api | from setuptools import setup
import transip
setup(
name = transip.__name__,
version = transip.__version__,
author = transip.__author__,
author_email = transip.__email__,
license = transip.__license__,
description = transip.__doc__.splitlines()[0],
long_description = open('README.rst').read... | Add more requirements that are needed for this module
from setuptools import setup
import transip
setup(
name = transip.__name__,
version = transip.__version__,
author = transip.__author__,
author_email = transip.__email__,
license = transip.__license__,
description = transip.__doc__.splitlin... |
10426b049baeceb8dda1390650503e1d75ff8b64 | us_ignite/common/management/commands/common_load_fixtures.py | us_ignite/common/management/commands/common_load_fixtures.py | import urlparse
from django.conf import settings
from django.core.management.base import BaseCommand
from django.contrib.sites.models import Site
from us_ignite.profiles.models import Interest
INTEREST_LIST = (
('SDN', 'sdn'),
('OpenFlow', 'openflow'),
('Ultra fast', 'ultra-fast'),
('Advanced wirele... | import urlparse
from django.conf import settings
from django.core.management.base import BaseCommand
from django.contrib.sites.models import Site
from us_ignite.profiles.models import Category, Interest
INTEREST_LIST = (
('SDN', 'sdn'),
('OpenFlow', 'openflow'),
('Ultra fast', 'ultra-fast'),
('Advan... | Add initial fixtures for the categories. | Add initial fixtures for the categories.
| Python | bsd-3-clause | us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite | import urlparse
from django.conf import settings
from django.core.management.base import BaseCommand
from django.contrib.sites.models import Site
from us_ignite.profiles.models import Category, Interest
INTEREST_LIST = (
('SDN', 'sdn'),
('OpenFlow', 'openflow'),
('Ultra fast', 'ultra-fast'),
('Advan... | Add initial fixtures for the categories.
import urlparse
from django.conf import settings
from django.core.management.base import BaseCommand
from django.contrib.sites.models import Site
from us_ignite.profiles.models import Interest
INTEREST_LIST = (
('SDN', 'sdn'),
('OpenFlow', 'openflow'),
('Ultra f... |
2428dcc620fae28e3f7f5ed268ff4bffb96c4501 | owney/managers.py | owney/managers.py | from django.db.models import Manager
class ShipmentManager(Manager):
"""Returns Shipments that are not delivered"""
def undelivered(self):
return self.get_query_set().exclude(status__exact='delivered')
| from django.db.models import Manager
class ShipmentManager(Manager):
"""Returns Shipments that are not delivered"""
def undelivered(self):
return self.get_query_set().exclude(status='delivered')
| Change filter syntax to be more direct. | Change filter syntax to be more direct.
| Python | mit | JohnSpeno/owney | from django.db.models import Manager
class ShipmentManager(Manager):
"""Returns Shipments that are not delivered"""
def undelivered(self):
return self.get_query_set().exclude(status='delivered')
| Change filter syntax to be more direct.
from django.db.models import Manager
class ShipmentManager(Manager):
"""Returns Shipments that are not delivered"""
def undelivered(self):
return self.get_query_set().exclude(status__exact='delivered')
|
12929fe96de4f7892856b72d86eb82217ad2972e | test/test_serve.py | test/test_serve.py | import unittest
import asyncio
import io
import multiprocessing
import urllib.request
import time
import grole
def simple_server():
app = grole.Grole()
@app.route('/')
def hello(env, req):
return 'Hello, World!'
app.run()
class TestServe(unittest.TestCase):
def test_simple(self):
... | Add test of running the server | Add test of running the server
| Python | mit | witchard/grole | import unittest
import asyncio
import io
import multiprocessing
import urllib.request
import time
import grole
def simple_server():
app = grole.Grole()
@app.route('/')
def hello(env, req):
return 'Hello, World!'
app.run()
class TestServe(unittest.TestCase):
def test_simple(self):
... | Add test of running the server
| |
5063bed38d64843387a681f72734b3cc1e9d6394 | tools/create_images_xml.py | tools/create_images_xml.py | #! /usr/bin/python3
import sys
import argparse
import xml_utils as u
import datetime
import pdb
import os
from argparse import RawTextHelpFormatter
from collections import defaultdict
##------------------------------------------------------------
## can be called with:
## find_bears *.xml dirs
##-----------------... | Create xml of all jpg/png from list of files & directories. | Create xml of all jpg/png from list of files & directories.
| Python | mit | hypraptive/bearid,hypraptive/bearid,hypraptive/bearid | #! /usr/bin/python3
import sys
import argparse
import xml_utils as u
import datetime
import pdb
import os
from argparse import RawTextHelpFormatter
from collections import defaultdict
##------------------------------------------------------------
## can be called with:
## find_bears *.xml dirs
##-----------------... | Create xml of all jpg/png from list of files & directories.
| |
5efc9c9d8bc226759574bf2334fffffab340e4ff | boxsdk/auth/developer_token_auth.py | boxsdk/auth/developer_token_auth.py | # coding: utf-8
from __future__ import unicode_literals, absolute_import
from six.moves import input
from .oauth2 import OAuth2
class DeveloperTokenAuth(OAuth2):
ENTER_TOKEN_PROMPT = 'Enter developer token: '
def __init__(self, get_new_token_callback=None, **kwargs):
self._get_new_token = get_new_... | # coding: utf-8
from __future__ import unicode_literals, absolute_import
from six.moves import input # pylint:disable=redefined-builtin
from .oauth2 import OAuth2
class DeveloperTokenAuth(OAuth2):
ENTER_TOKEN_PROMPT = 'Enter developer token: '
def __init__(self, get_new_token_callback=None, **kwargs):
... | Fix pylint error for redefined builtin input. | Fix pylint error for redefined builtin input.
| Python | apache-2.0 | Frencil/box-python-sdk,box/box-python-sdk,Frencil/box-python-sdk | # coding: utf-8
from __future__ import unicode_literals, absolute_import
from six.moves import input # pylint:disable=redefined-builtin
from .oauth2 import OAuth2
class DeveloperTokenAuth(OAuth2):
ENTER_TOKEN_PROMPT = 'Enter developer token: '
def __init__(self, get_new_token_callback=None, **kwargs):
... | Fix pylint error for redefined builtin input.
# coding: utf-8
from __future__ import unicode_literals, absolute_import
from six.moves import input
from .oauth2 import OAuth2
class DeveloperTokenAuth(OAuth2):
ENTER_TOKEN_PROMPT = 'Enter developer token: '
def __init__(self, get_new_token_callback=None, **... |
d295575284e712a755d3891806a7e40b65377a69 | music_essentials/chord.py | music_essentials/chord.py | class Chord(object):
# TODO: doctring
def __init__(self, root_note):
# TODO: doctring
# TODO: validation
self.notes = [root_note]
def root(self):
# TODO: doctring
# TODO: tests
return self.notes[0]
def add_note(self, new_note):
# TODO: docstr... | class Chord(object):
# TODO: doctring
def __init__(self, root_note):
# TODO: doctring
# TODO: validation
self.notes = [root_note]
def root(self):
# TODO: doctring
# TODO: tests
return self.notes[0]
def add_note(self, new_note):
# TODO: docstr... | Add __str__ method for Chord class. | Add __str__ method for Chord class.
Signed-off-by: Charlotte Pierce <351429ca27f6e4bff2dbb77adb5046c88cd12fae@malformed-bits.com>
| Python | mit | charlottepierce/music_essentials | class Chord(object):
# TODO: doctring
def __init__(self, root_note):
# TODO: doctring
# TODO: validation
self.notes = [root_note]
def root(self):
# TODO: doctring
# TODO: tests
return self.notes[0]
def add_note(self, new_note):
# TODO: docstr... | Add __str__ method for Chord class.
Signed-off-by: Charlotte Pierce <351429ca27f6e4bff2dbb77adb5046c88cd12fae@malformed-bits.com>
class Chord(object):
# TODO: doctring
def __init__(self, root_note):
# TODO: doctring
# TODO: validation
self.notes = [root_note]
def root(self):
... |
78eaa907ea986c12716b27fc6a4533d83242b97a | bci/__init__.py | bci/__init__.py | from fakebci import FakeBCI | import os
import sys
import platform
import shutil
import inspect
#
#def machine():
# """Return type of machine."""
# if os.name == 'nt' and sys.version_info[:2] < (2,7):
# return os.environ.get("PROCESSOR_ARCHITEW6432",
# os.environ.get('PROCESSOR_ARCHITECTURE', ''))
# else:
# re... | Make some changes to the bci package file. | Make some changes to the bci package file.
| Python | bsd-3-clause | NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock | import os
import sys
import platform
import shutil
import inspect
#
#def machine():
# """Return type of machine."""
# if os.name == 'nt' and sys.version_info[:2] < (2,7):
# return os.environ.get("PROCESSOR_ARCHITEW6432",
# os.environ.get('PROCESSOR_ARCHITECTURE', ''))
# else:
# re... | Make some changes to the bci package file.
from fakebci import FakeBCI |
9fba9934c9b47881ee468f295a3710f2c184fab1 | tendrl/node_agent/__init__.py | tendrl/node_agent/__init__.py | try:
from gevent import monkey
except ImportError:
pass
else:
monkey.patch_all()
from tendrl.commons import CommonNS
from tendrl.node_agent.objects.definition import Definition
from tendrl.node_agent.objects.config import Config
from tendrl.node_agent.objects.node_context import NodeContext
from tendrl.no... | try:
from gevent import monkey
except ImportError:
pass
else:
monkey.patch_all()
from tendrl.commons import CommonNS
from tendrl.node_agent.objects.definition import Definition
from tendrl.node_agent.objects.config import Config
from tendrl.node_agent.objects.node_context import NodeContext
from tendrl.no... | Fix greenlet and essential objects startup order | Fix greenlet and essential objects startup order
| Python | lgpl-2.1 | Tendrl/node_agent,Tendrl/node-agent,r0h4n/node-agent,Tendrl/node_agent,Tendrl/node-agent,Tendrl/node-agent,r0h4n/node-agent,r0h4n/node-agent | try:
from gevent import monkey
except ImportError:
pass
else:
monkey.patch_all()
from tendrl.commons import CommonNS
from tendrl.node_agent.objects.definition import Definition
from tendrl.node_agent.objects.config import Config
from tendrl.node_agent.objects.node_context import NodeContext
from tendrl.no... | Fix greenlet and essential objects startup order
try:
from gevent import monkey
except ImportError:
pass
else:
monkey.patch_all()
from tendrl.commons import CommonNS
from tendrl.node_agent.objects.definition import Definition
from tendrl.node_agent.objects.config import Config
from tendrl.node_agent.obje... |
e5b98d072017c8a70cf033cdb34233b2d0a56b2e | pyfirmata/boards.py | pyfirmata/boards.py | BOARDS = {
'arduino': {
'digital': tuple(x for x in range(14)),
'analog': tuple(x for x in range(6)),
'pwm': (3, 5, 6, 9, 10, 11),
'use_ports': True,
'disabled': (0, 1) # Rx, Tx, Crystal
},
'arduino_mega': {
'digital': tuple(x for x in range(54)),
'an... | BOARDS = {
'arduino': {
'digital': tuple(x for x in range(14)),
'analog': tuple(x for x in range(6)),
'pwm': (3, 5, 6, 9, 10, 11),
'use_ports': True,
'disabled': (0, 1) # Rx, Tx, Crystal
},
'arduino_mega': {
'digital': tuple(x for x in range(54)),
'an... | Correct class name of arduino nano | Correct class name of arduino nano
| Python | mit | JoseU/pyFirmata,tino/pyFirmata | BOARDS = {
'arduino': {
'digital': tuple(x for x in range(14)),
'analog': tuple(x for x in range(6)),
'pwm': (3, 5, 6, 9, 10, 11),
'use_ports': True,
'disabled': (0, 1) # Rx, Tx, Crystal
},
'arduino_mega': {
'digital': tuple(x for x in range(54)),
'an... | Correct class name of arduino nano
BOARDS = {
'arduino': {
'digital': tuple(x for x in range(14)),
'analog': tuple(x for x in range(6)),
'pwm': (3, 5, 6, 9, 10, 11),
'use_ports': True,
'disabled': (0, 1) # Rx, Tx, Crystal
},
'arduino_mega': {
'digital': tupl... |
f157ad4c971628c8fb0b1f94f6fd080c75413064 | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name="xoxzo.logwatch",
version="0.4",
packages=find_packages(),
install_requires=[
'Baker==1.3',
'pytz==2016.3',
],
entry_points={
'console_scripts': [
'logwatch = xoxzo.logwatch.main:main',
],
},... | from setuptools import setup, find_packages
setup(
name="xoxzo.logwatch",
version="0.4",
packages=find_packages(),
install_requires=[
'Baker==1.3',
'pytz>=2016.3',
],
entry_points={
'console_scripts': [
'logwatch = xoxzo.logwatch.main:main',
],
},... | Set pytz version minimum 2016.3 | Set pytz version minimum 2016.3
| Python | mit | xoxzo/xoxzo.logwatch | from setuptools import setup, find_packages
setup(
name="xoxzo.logwatch",
version="0.4",
packages=find_packages(),
install_requires=[
'Baker==1.3',
'pytz>=2016.3',
],
entry_points={
'console_scripts': [
'logwatch = xoxzo.logwatch.main:main',
],
},... | Set pytz version minimum 2016.3
from setuptools import setup, find_packages
setup(
name="xoxzo.logwatch",
version="0.4",
packages=find_packages(),
install_requires=[
'Baker==1.3',
'pytz==2016.3',
],
entry_points={
'console_scripts': [
'logwatch = xoxzo.logwa... |
caf2806124df489f28ceadf2db5d4abfdd27aae7 | core/management/commands/send_tweets.py | core/management/commands/send_tweets.py | import twitter
from django.core.management.base import BaseCommand
from django.conf import settings
from core.models import Tweet
class Command(BaseCommand):
help = "Send out tweets."
def handle(self, *args, **options):
for tweet in Tweet.objects.filter(was_sent=False, failed_trails__lte=5):
... | import twitter
from django.core.management.base import BaseCommand
from django.conf import settings
from core.models import Tweet
class Command(BaseCommand):
help = "Send out tweets."
def handle(self, *args, **options):
for tweet in Tweet.objects.filter(was_sent=False, failed_trials__lte=5):
... | Fix typo in field name | Fix typo in field name
| Python | agpl-3.0 | enjaz/enjaz,enjaz/enjaz,osamak/student-portal,osamak/student-portal,osamak/student-portal,enjaz/enjaz,enjaz/enjaz,osamak/student-portal,osamak/student-portal,enjaz/enjaz | import twitter
from django.core.management.base import BaseCommand
from django.conf import settings
from core.models import Tweet
class Command(BaseCommand):
help = "Send out tweets."
def handle(self, *args, **options):
for tweet in Tweet.objects.filter(was_sent=False, failed_trials__lte=5):
... | Fix typo in field name
import twitter
from django.core.management.base import BaseCommand
from django.conf import settings
from core.models import Tweet
class Command(BaseCommand):
help = "Send out tweets."
def handle(self, *args, **options):
for tweet in Tweet.objects.filter(was_sent=False, failed_... |
7536d46435bd4841f538a4d9ca6fc58b3b0113bf | test/569-duplicate-points.py | test/569-duplicate-points.py | import sys
def assert_no_repeated_points(coords):
last_coord = coords[0]
for i in range(1, len(coords)):
coord = coords[i]
if coord == last_coord:
raise Exception("Coordinate %r (at %d) == %r (at %d), but "
"coordinates should not be repeated." %
... | Add test for duplicate / repeated points. | Add test for duplicate / repeated points.
| Python | mit | mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource | import sys
def assert_no_repeated_points(coords):
last_coord = coords[0]
for i in range(1, len(coords)):
coord = coords[i]
if coord == last_coord:
raise Exception("Coordinate %r (at %d) == %r (at %d), but "
"coordinates should not be repeated." %
... | Add test for duplicate / repeated points.
| |
5a971cc7fecf05ce3f38bf1fcd48592ef04554ff | setup.py | setup.py | try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
import numpy as np
setup(name='parcels',
version='0.0.1',
description="""Framework for Lagrangian tracking of virtual
ocean particles in the petascale age.""",
author="Imperial College ... | try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
import numpy as np
setup(name='parcels',
version='0.0.1',
description="""Framework for Lagrangian tracking of virtual
ocean particles in the petascale age.""",
author="Imperial College ... | Automate package discovery to include sub-packages | Setup: Automate package discovery to include sub-packages
| Python | mit | OceanPARCELS/parcels,OceanPARCELS/parcels | try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
import numpy as np
setup(name='parcels',
version='0.0.1',
description="""Framework for Lagrangian tracking of virtual
ocean particles in the petascale age.""",
author="Imperial College ... | Setup: Automate package discovery to include sub-packages
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
import numpy as np
setup(name='parcels',
version='0.0.1',
description="""Framework for Lagrangian tracking of virtual
ocean particle... |
b92fb486107ef6feb4def07f601e7390d80db565 | plugins/androidapp.py | plugins/androidapp.py | """
paragoo plugin for retrieving card on an Android app
"""
import os
import requests
from bs4 import BeautifulSoup
class AppNotFoundException(Exception):
pass
def render(site_path, params):
"""
Look up the Android app details from its Play Store listing
Format of params: <app_key>
app_key look... | """
paragoo plugin for retrieving card on an Android app
"""
import os
import requests
from bs4 import BeautifulSoup
class AppNotFoundException(Exception):
pass
def get_app_details(app_key):
url_full = 'https://play.google.com/store/apps/details?id=' + app_key
url = 'https://play.google.com/store/apps/d... | Split out the app detail lookup into function | Split out the app detail lookup into function
| Python | apache-2.0 | aquatix/paragoo,aquatix/paragoo | """
paragoo plugin for retrieving card on an Android app
"""
import os
import requests
from bs4 import BeautifulSoup
class AppNotFoundException(Exception):
pass
def get_app_details(app_key):
url_full = 'https://play.google.com/store/apps/details?id=' + app_key
url = 'https://play.google.com/store/apps/d... | Split out the app detail lookup into function
"""
paragoo plugin for retrieving card on an Android app
"""
import os
import requests
from bs4 import BeautifulSoup
class AppNotFoundException(Exception):
pass
def render(site_path, params):
"""
Look up the Android app details from its Play Store listing
... |
e6c65ef51fc7a08a50b671e30e5e27a051824927 | cyder/__init__.py | cyder/__init__.py | from base.constants import *
from django.dispatch import receiver
from django.db.models.signals import post_syncdb
from south.signals import post_migrate
# South doesn't automatically load custom SQL like Django does, and regardless,
# the filename isn't what Django would expect.
def _load_custom_sql():
from dj... | from base.constants import *
from django.dispatch import receiver
from django.db.models.signals import post_syncdb
from south.signals import post_migrate
# South doesn't automatically load custom SQL like Django does, and regardless,
# the filename isn't what Django would expect.
def _load_custom_sql():
from dj... | Sort initial_data/ files by filename | Sort initial_data/ files by filename
| Python | bsd-3-clause | zeeman/cyder,OSU-Net/cyder,OSU-Net/cyder,akeym/cyder,akeym/cyder,murrown/cyder,murrown/cyder,zeeman/cyder,drkitty/cyder,drkitty/cyder,murrown/cyder,murrown/cyder,OSU-Net/cyder,OSU-Net/cyder,drkitty/cyder,drkitty/cyder,zeeman/cyder,akeym/cyder,akeym/cyder,zeeman/cyder | from base.constants import *
from django.dispatch import receiver
from django.db.models.signals import post_syncdb
from south.signals import post_migrate
# South doesn't automatically load custom SQL like Django does, and regardless,
# the filename isn't what Django would expect.
def _load_custom_sql():
from dj... | Sort initial_data/ files by filename
from base.constants import *
from django.dispatch import receiver
from django.db.models.signals import post_syncdb
from south.signals import post_migrate
# South doesn't automatically load custom SQL like Django does, and regardless,
# the filename isn't what Django would expec... |
c6108cacc7705c27b8913d82229c331551796830 | openprescribing/frontend/management/commands/migrate_some_dmd_data.py | openprescribing/frontend/management/commands/migrate_some_dmd_data.py | # This is a one-off command to migrate all TariffPrice and NCSOConcession data
# from the dmd app to the frontend app. It can be deleted once the dmd app has
# been removed.
from django.db import transaction
from django.core.management import BaseCommand
from dmd.models import TariffPrice as TariffPriceOld
from dmd.... | Add task to migrate TariffPrice and NCSOConcession data | Add task to migrate TariffPrice and NCSOConcession data
This file can be removed once the migration is done. (Should it be a
data migration?)
| Python | mit | ebmdatalab/openprescribing,annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc | # This is a one-off command to migrate all TariffPrice and NCSOConcession data
# from the dmd app to the frontend app. It can be deleted once the dmd app has
# been removed.
from django.db import transaction
from django.core.management import BaseCommand
from dmd.models import TariffPrice as TariffPriceOld
from dmd.... | Add task to migrate TariffPrice and NCSOConcession data
This file can be removed once the migration is done. (Should it be a
data migration?)
| |
31c0863d088488da5dd85e2cbe3c01c6b01aa4a2 | system_tests/test_default.py | system_tests/test_default.py | # Copyright 2016 Google 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 required by applicable law or agreed to in writing,... | # Copyright 2016 Google 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 required by applicable law or agreed to in writing,... | Fix system tests when running on GCE | Fix system tests when running on GCE
The new project ID logic for Cloud SDK invokes Cloud SDK directly. Cloud SDK helpfully falls back to the GCE project ID if the project ID is unset in the configuration. This breaks one of our previous expectations.
| Python | apache-2.0 | googleapis/google-auth-library-python,googleapis/google-auth-library-python | # Copyright 2016 Google 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 required by applicable law or agreed to in writing,... | Fix system tests when running on GCE
The new project ID logic for Cloud SDK invokes Cloud SDK directly. Cloud SDK helpfully falls back to the GCE project ID if the project ID is unset in the configuration. This breaks one of our previous expectations.
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License... |
3f7091cbf22c483672aa6c07ad640ee2c3d18e5b | lbrynet/daemon/auth/factory.py | lbrynet/daemon/auth/factory.py | import logging
import os
from twisted.web import server, guard, resource
from twisted.cred import portal
from lbrynet import conf
from .auth import PasswordChecker, HttpPasswordRealm
from .util import initialize_api_key_file
log = logging.getLogger(__name__)
class AuthJSONRPCResource(resource.Resource):
def __... | import logging
import os
from twisted.web import server, guard, resource
from twisted.cred import portal
from lbrynet import conf
from .auth import PasswordChecker, HttpPasswordRealm
from .util import initialize_api_key_file
log = logging.getLogger(__name__)
class AuthJSONRPCResource(resource.Resource):
def __... | Make curl work in py3 again | Make curl work in py3 again
| Python | mit | lbryio/lbry,lbryio/lbry,lbryio/lbry | import logging
import os
from twisted.web import server, guard, resource
from twisted.cred import portal
from lbrynet import conf
from .auth import PasswordChecker, HttpPasswordRealm
from .util import initialize_api_key_file
log = logging.getLogger(__name__)
class AuthJSONRPCResource(resource.Resource):
def __... | Make curl work in py3 again
import logging
import os
from twisted.web import server, guard, resource
from twisted.cred import portal
from lbrynet import conf
from .auth import PasswordChecker, HttpPasswordRealm
from .util import initialize_api_key_file
log = logging.getLogger(__name__)
class AuthJSONRPCResource(r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.