commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
e395d32770c2a4f7a2e4cab98d0a459e690ffeba
zeus/api/schemas/job.py
zeus/api/schemas/job.py
from marshmallow import Schema, fields from .failurereason import FailureReasonSchema from .fields import ResultField, StatusField from .stats import StatsSchema class JobSchema(Schema): id = fields.UUID(dump_only=True) number = fields.Integer(dump_only=True) created_at = fields.DateTime(attribute="date_...
from marshmallow import Schema, fields from .failurereason import FailureReasonSchema from .fields import ResultField, StatusField from .stats import StatsSchema class JobSchema(Schema): id = fields.UUID(dump_only=True) number = fields.Integer(dump_only=True) created_at = fields.DateTime(attribute='date_...
Add updated_at to Job schema
feat: Add updated_at to Job schema
Python
apache-2.0
getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus
ec9e401cd083c095c916055d04fc049a6dbc8ab1
ui/tcmui/core/management/commands/create_company.py
ui/tcmui/core/management/commands/create_company.py
from django.core.management.base import BaseCommand, CommandError from ...api import admin from ...models import Company, CompanyList from ....users.models import Role, RoleList, PermissionList DEFAULT_NEW_USER_ROLE_PERMISSIONS = set([ "PERMISSION_COMPANY_INFO_VIEW", "PERMISSION_PRODUCT_VIEW", ...
from django.core.management.base import BaseCommand, CommandError from ...api import admin from ...models import Company, CompanyList from ....users.models import Role, RoleList, PermissionList DEFAULT_NEW_USER_ROLE_PERMISSIONS = set([ "PERMISSION_COMPANY_INFO_VIEW", "PERMISSION_PRODUCT_VIEW", ...
Remove unneeded TEST_RUN_EDIT permission from default new user role.
Remove unneeded TEST_RUN_EDIT permission from default new user role.
Python
bsd-2-clause
mozilla/moztrap,mozilla/moztrap,mozilla/moztrap,shinglyu/moztrap,mozilla/moztrap,bobsilverberg/moztrap,mccarrmb/moztrap,bobsilverberg/moztrap,shinglyu/moztrap,shinglyu/moztrap,bobsilverberg/moztrap,shinglyu/moztrap,shinglyu/moztrap,bobsilverberg/moztrap,mccarrmb/moztrap,mozilla/moztrap,mccarrmb/moztrap,mccarrmb/moztrap...
ad0e14561a4fe0cfa659bd99678b0d82de892dc5
helpers/text.py
helpers/text.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import unicodedata from html.parser import HTMLParser class HTMLStripper(HTMLParser): def __init__(self): super(HTMLStripper, self).__init__() self.reset() self.fed = [] def handle_starttag(self, tag, attrs): pass def handle_endtag(self, tag): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import unicodedata from html.parser import HTMLParser class HTMLStripper(HTMLParser): def __init__(self): super(HTMLStripper, self).__init__() self.reset() self.fed = [] def handle_starttag(self, tag, attrs): pass def handle_endtag(self, tag): ...
Add symbols to the list of symbols to replace in the slugify function
Add symbols to the list of symbols to replace in the slugify function
Python
mit
finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is
243cf3c18228b0c50b6b48a69c420922576ed723
grano/logic/plugins.py
grano/logic/plugins.py
import logging from grano.model import Entity, Relation, Project, Schema from grano.logic.entities import _entity_changed from grano.logic.relations import _relation_changed from grano.logic.projects import _project_changed from grano.logic.schemata import _schema_changed log = logging.getLogger(__name__) def rebu...
import logging from grano.model import Entity, Relation, Project from grano.logic.entities import _entity_changed from grano.logic.relations import _relation_changed from grano.logic.projects import _project_changed from grano.logic.schemata import _schema_changed log = logging.getLogger(__name__) def rebuild(): ...
Rebuild by project, not by type.
Rebuild by project, not by type.
Python
mit
4bic-attic/grano,granoproject/grano,CodeForAfrica/grano,4bic/grano
27423205b06b031572b675ee29a487f4b900fe56
cura_app.py
cura_app.py
#!/usr/bin/env python3 # Copyright (c) 2015 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. import sys def exceptHook(type, value, traceback): import cura.CrashHandler cura.CrashHandler.show(type, value, traceback) sys.excepthook = exceptHook # Workaround for a race condition on ...
#!/usr/bin/env python3 # Copyright (c) 2015 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. import sys def exceptHook(hook_type, value, traceback): import cura.CrashHandler cura.CrashHandler.show(hook_type, value, traceback) sys.excepthook = exceptHook # Workaround for a race con...
Rename type into hook_type "type" itself if a built-in function. Using this name could be unsave.
Rename type into hook_type "type" itself if a built-in function. Using this name could be unsave.
Python
agpl-3.0
hmflash/Cura,Curahelper/Cura,ynotstartups/Wanhao,senttech/Cura,totalretribution/Cura,fieldOfView/Cura,hmflash/Cura,Curahelper/Cura,ynotstartups/Wanhao,totalretribution/Cura,senttech/Cura,fieldOfView/Cura
4d1d2e12d8882084ce8deb80c3b3e162cc71b20b
osmaxx-py/osmaxx/excerptexport/forms/new_excerpt_form.py
osmaxx-py/osmaxx/excerptexport/forms/new_excerpt_form.py
from django import forms from django.utils.translation import gettext_lazy class NewExcerptForm(forms.Form): new_excerpt_name = forms.CharField(label=gettext_lazy('Excerpt name')) new_excerpt_bounding_box_north = forms.CharField(label=gettext_lazy('North')) new_excerpt_bounding_box_west = forms.CharField(...
from django import forms from django.utils.translation import gettext_lazy class NewExcerptForm(forms.Form): new_excerpt_name = forms.CharField(label=gettext_lazy('Excerpt name')) new_excerpt_bounding_box_north = forms.CharField(label=gettext_lazy('North')) new_excerpt_bounding_box_west = forms.CharField(...
Allow private excerpts (form validation)
Bugfix: Allow private excerpts (form validation)
Python
mit
geometalab/osmaxx,geometalab/drf-utm-zone-info,geometalab/osmaxx-frontend,geometalab/osmaxx,geometalab/osmaxx,geometalab/osmaxx,geometalab/osmaxx-frontend,geometalab/drf-utm-zone-info,geometalab/osmaxx-frontend,geometalab/osmaxx-frontend
b4ef31e6fa195480f8de1e516606aa32fecfdd15
future/builtins/backports/newround.py
future/builtins/backports/newround.py
""" ``python-future``: pure Python implementation of Python 3 round(). """ def newround(number, ndigits=None): """ See Python 3 documentation: uses Banker's Rounding. Delegates to the __round__ method if for some reason this exists. If not, rounds a number to a given precision in decimal digits (d...
""" ``python-future``: pure Python implementation of Python 3 round(). """ from future.utils import PYPY def newround(number, ndigits=None): """ See Python 3 documentation: uses Banker's Rounding. Delegates to the __round__ method if for some reason this exists. If not, rounds a number to a give...
Add workaround for PyPy round() bug with NumPy data types
Add workaround for PyPy round() bug with NumPy data types
Python
mit
krischer/python-future,QuLogic/python-future,PythonCharmers/python-future,michaelpacer/python-future,QuLogic/python-future,krischer/python-future,michaelpacer/python-future,PythonCharmers/python-future
82e0987375ff99e0d94068c1ec6078d3920249f2
nc/data/__init__.py
nc/data/__init__.py
DEFAULT_URL = "https://s3-us-west-2.amazonaws.com/openpolicingdata/TS_2016_04_13T13.38.34.887.zip" # noqa
DEFAULT_URL = "https://s3-us-west-2.amazonaws.com/openpolicingdata/TS_2016_06_22T09.52.20.780.zip" # noqa
Add this fix from the master branch
Add this fix from the master branch (It was in the import_nc management command file, but newer code places it here.)
Python
mit
OpenDataPolicingNC/Traffic-Stops,OpenDataPolicingNC/Traffic-Stops,OpenDataPolicingNC/Traffic-Stops,OpenDataPolicingNC/Traffic-Stops
7b90d75f260e76baf8b57840d96bb36b62e2c56c
__init__.py
__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division, unicode_literals import bikeshed import os import subprocess def main(): scriptPath = os.path.dirname(os.path.realpath(__file__)) dataPath = os.path.join(scriptPath, "data") bikeshed.config.quiet = False #bikeshed.update.update(path=d...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division, unicode_literals import bikeshed import os import subprocess def main(): scriptPath = os.path.dirname(os.path.realpath(__file__)) dataPath = os.path.join(scriptPath, "data") bikeshed.config.quiet = False bikeshed.update.update(path=da...
Update script with proper git-ing.
Update script with proper git-ing.
Python
mit
tabatkins/bikeshed-data
6d2f6df3543bc287e59151e823b7a62c245c27b0
.gitlab/linters/check-cpp.py
.gitlab/linters/check-cpp.py
#!/usr/bin/env python3 # A linter to warn for ASSERT macros which are separated from their argument # list by a space, which Clang's CPP barfs on from linter import run_linters, RegexpLinter linters = [ RegexpLinter(r'ASSERT\s+\(', message='CPP macros should not have a space between the macro na...
#!/usr/bin/env python3 # A linter to warn for ASSERT macros which are separated from their argument # list by a space, which Clang's CPP barfs on from linter import run_linters, RegexpLinter linters = [ RegexpLinter(r'WARN\s+\(', message='CPP macros should not have a space between the macro name...
Check for WARN macro with space separating it from its paren
linters: Check for WARN macro with space separating it from its paren
Python
bsd-3-clause
sdiehl/ghc,sdiehl/ghc,sdiehl/ghc,sdiehl/ghc,sdiehl/ghc,sdiehl/ghc,sdiehl/ghc
ed09a3ded286cc4d5623c17e65b2d40ef55ccee7
valohai_yaml/parsing.py
valohai_yaml/parsing.py
from typing import IO, Union from valohai_yaml.objs import Config from .utils import read_yaml def parse(yaml: Union[dict, list, bytes, str, IO], validate: bool = True) -> Config: """ Parse the given YAML data into a `Config` object, optionally validating it first. :param yaml: YAML data (either a stri...
from typing import IO, Union from valohai_yaml.objs import Config from .utils import read_yaml def parse(yaml: Union[dict, list, bytes, str, IO], validate: bool = True) -> Config: """ Parse the given YAML data into a `Config` object, optionally validating it first. :param yaml: YAML data (either a stri...
Handle empty YAML files in parse()
Handle empty YAML files in parse() Refs valohai/valohai-cli#170
Python
mit
valohai/valohai-yaml
dc6f82bce52419c7c2153a33be15f3d811161d1d
flask_app.py
flask_app.py
from flask import Flask, abort, jsonify from flask_caching import Cache from flask_cors import CORS import main app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': 'simple'}) cors = CORS(app, resources={r"/*": {"origins": "*"}}) @app.route('/api/') @cache.cached(timeout=3600) def nbis_list_entities(): ...
from flask import Flask, abort, jsonify from flask_caching import Cache from flask_cors import CORS import main app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': 'simple'}) cors = CORS(app, resources={r"/*": {"origins": "*"}}) @app.route('/api/') @cache.cached(timeout=3600) def list_entities(): ret...
Return a list of identifiers instead of almost all info
Return a list of identifiers instead of almost all info
Python
bsd-3-clause
talavis/kimenu
fef17579a8a084987ea5e413ad512662ab24aa56
ntm/similarities.py
ntm/similarities.py
import theano import theano.tensor as T import numpy as np def cosine_similarity(x, y, eps=1e-9): y = y.dimshuffle(1, 0) z = T.dot(x, y) z /= x.norm(2) * y.norm(2, axis=0).dimshuffle('x', 0) + eps return z
import theano import theano.tensor as T import numpy as np def cosine_similarity(x, y, eps=1e-9): y = y.dimshuffle(1, 0) z = T.dot(x, y) z /= T.sqrt(T.sum(x * x) * T.sum(y * y, axis=0).dimshuffle('x', 0) + 1e-6) return z
Replace T.norm in the cosine similarity
Replace T.norm in the cosine similarity
Python
mit
snipsco/ntm-lasagne
980f9abc5b95c9f9ed089b13e9538173bcac0952
app/user_administration/urls.py
app/user_administration/urls.py
from django.conf.urls import url from .views import HomePage urlpatterns = [ url(r'^', HomePage.as_view(), name='HomePage'), ]
from django.conf.urls import url from .views import HomePage, LoginPage from django.contrib.auth.views import logout_then_login urlpatterns = [ url(r'^$', HomePage.as_view(), name='HomePage'), url(r'^login/', LoginPage.as_view(), name='LoginPage'), url(r'^logout/', logout_then_login, name='LoginPage'), ]
Add Login & Logout Routing
Add Login & Logout Routing
Python
mit
rexhepberlajolli/RHChallenge,rexhepberlajolli/RHChallenge
54655ff23297b302f12eff9900f8d1c5ce986ab2
moksha/tests/test_hub.py
moksha/tests/test_hub.py
"""Test Moksha's Hub """ from nose.tools import eq_, assert_true from moksha.hub import MokshaHub class TestHub: def setUp(self): self.hub = MokshaHub() def tearDown(self): self.hub.close() def test_creating_queue(self): self.hub.create_queue('test') eq_(len(self.hub.que...
"""Test Moksha's Hub """ #from nose.tools import eq_, assert_true #from moksha.hub import MokshaHub # #class TestHub: # # def setUp(self): # self.hub = MokshaHub() # # def tearDown(self): # self.hub.close() # # def test_creating_queue(self): # self.hub.create_queue('test') # eq_(le...
Comment out some hub tests, as they do not currently work
Comment out some hub tests, as they do not currently work
Python
apache-2.0
lmacken/moksha,mokshaproject/moksha,pombredanne/moksha,ralphbean/moksha,mokshaproject/moksha,pombredanne/moksha,pombredanne/moksha,ralphbean/moksha,lmacken/moksha,mokshaproject/moksha,pombredanne/moksha,lmacken/moksha,ralphbean/moksha,mokshaproject/moksha
9d7cec35a1771f45d0083a80e2f1823182d8d0b8
MarkovChainBibleBot/get_bible.py
MarkovChainBibleBot/get_bible.py
import requests from os import path project_gutenberg_bible_url = 'http://www.gutenberg.org/cache/epub/10/pg10.txt' bible_filename = 'bible.txt' bible_path = path.join('..', 'data', bible_filename) def bible_text(url=project_gutenberg_bible_url): """Get the bible text""" return requests.get(url).text def ...
import requests from os import path, linesep project_gutenberg_bible_url = 'http://www.gutenberg.org/cache/epub/10/pg10.txt' bible_filename = 'bible.txt' bible_path = path.join('..', 'data', bible_filename) def bible_text(url=project_gutenberg_bible_url): """Get the bible text""" return requests.get(url).te...
Use os independent line seperator
Use os independent line seperator
Python
mit
salvor7/MarkovChainBibleBot
c3d22dd13bf56e65452e2e7d634c527d66e2a3b4
pyptools/objects.py
pyptools/objects.py
class Parser(object): """Base class for all parsers to inheret with common interface""" def iterparse(self, iterator, **kwargs): """ Parses a iterator/generator. Must be implemented by each parser. :param value: Iterable containing data :return: yeilds parsed data...
class Parser(object): """Base class for all parsers to inheret with common interface""" def iterparse(self, iterator, **kwargs): """ Parses a iterator/generator. Must be implemented by each parser. :param value: Iterable containing data :return: yeilds parsed data...
Fix a bug where splitlines was called twice for parse_file
Fix a bug where splitlines was called twice for parse_file
Python
mit
tandreas/pyptools
4987b2e5a2d5ee208a274702f6b88a9021149c86
tests/blueprints/user_message/test_address_formatting.py
tests/blueprints/user_message/test_address_formatting.py
""" :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from unittest.mock import patch import pytest from byceps.services.user_message import service as user_message_service from tests.conftest import database_recreated from tests.helpers import app_context, create_brand...
""" :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from unittest.mock import patch import pytest from byceps.services.user_message import service as user_message_service from tests.conftest import database_recreated from tests.helpers import app_context, create_brand...
Speed up user message address formatting test
Speed up user message address formatting test The common set-up is moved to the fixture, then the fixture's scope is widened so that it is used for all test cases in the module, avoiding duplicate work.
Python
bsd-3-clause
m-ober/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps
d3fd59325f592bd3409d8466ba288e0c377c7440
mklocale/cmd.py
mklocale/cmd.py
import argparse import logging import yaml from mklocale import transifex from mklocale.cats import merge_by_language, write_catalog from mklocale.utils import listify log = logging.getLogger("mklocale") def cmdline(argv): logging.basicConfig(level=logging.INFO) ap = argparse.ArgumentParser() ap.add_ar...
import argparse import hashlib import logging import os import yaml from mklocale import transifex from mklocale.cats import merge_by_language, write_catalog from mklocale.utils import listify log = logging.getLogger("mklocale") def cmdline(argv): logging.basicConfig(level=logging.INFO) ap = argparse.Argum...
Add optional use of requests_cache
Add optional use of requests_cache
Python
mit
akx/mklocale
803e128b8e151c061f75051b5a4386d4c624ba56
core/settings-wni-Windows_NT.py
core/settings-wni-Windows_NT.py
#!/usr/bin/python2 from __future__ import absolute_import from qubes.storage.wni import QubesWniVmStorage def apply(system_path, vm_files, defaults): system_path['qubes_base_dir'] = 'c:\\qubes' system_path['config_template_pv'] = 'c:/program files/Invisible Things Lab/Qubes/vm-template.xml' system_path['...
#!/usr/bin/python2 from __future__ import absolute_import from qubes.storage.wni import QubesWniVmStorage def apply(system_path, vm_files, defaults): system_path['qubes_base_dir'] = 'c:\\qubes' system_path['config_template_pv'] = 'c:/program files/Invisible Things Lab/Qubes/vm-template.xml' system_path['...
Add qrexec-client path to WNI settings
wni: Add qrexec-client path to WNI settings
Python
lgpl-2.1
marmarek/qubes-core-admin,QubesOS/qubes-core-admin,QubesOS/qubes-core-admin,woju/qubes-core-admin,marmarek/qubes-core-admin,QubesOS/qubes-core-admin,woju/qubes-core-admin,woju/qubes-core-admin,woju/qubes-core-admin,marmarek/qubes-core-admin
8598cd0dd4938a2c5d46c350445e5c36c7792a30
leapp/utils/workarounds/mp.py
leapp/utils/workarounds/mp.py
import os import multiprocessing.util def apply_workaround(): # Implements: # https://github.com/python/cpython/commit/e8a57b98ec8f2b161d4ad68ecc1433c9e3caad57 # # Detection of fix: os imported to compare pids, before the fix os has not # been imported if getattr(multiprocessing.util, 'os', No...
import os import multiprocessing.util def apply_workaround(): # Implements: # https://github.com/python/cpython/commit/e8a57b98ec8f2b161d4ad68ecc1433c9e3caad57 # # Detection of fix: os imported to compare pids, before the fix os has not # been imported if getattr(multiprocessing.util, 'os', No...
Disable pylint signature-differs in md.py
Disable pylint signature-differs in md.py
Python
lgpl-2.1
leapp-to/prototype,leapp-to/prototype,leapp-to/prototype,leapp-to/prototype
d373404a496713596bed91f62082c5a01b1891fb
ydf/cli.py
ydf/cli.py
""" ydf/cli ~~~~~~~ Defines the command-line interface. """ import click import sys from ydf import templating, yaml_ext @click.command('ydf') @click.argument('yaml', type=click.File('r')) @click.option('-v', '--variables', type=click.Path(dir_okay=False), he...
""" ydf/cli ~~~~~~~ Defines the command-line interface. """ import click import sys from ydf import templating, yaml_ext @click.command('ydf') @click.argument('yaml', type=click.Path(dir_okay=False)) @click.option('-v', '--variables', type=click.Path(dir_okay=False), ...
Switch yaml CLI argument from file to file path.
Switch yaml CLI argument from file to file path.
Python
apache-2.0
ahawker/ydf
913d7f39bdbce53e64ea306b7bd2d95ffa0e0adb
lambdawebhook/hook.py
lambdawebhook/hook.py
#!/usr/bin/env python import os import sys import hashlib # Add the lib directory to the path for Lambda to load our libs sys.path.append(os.path.join(os.path.dirname(__file__), 'lib')) import requests # NOQA import hmac # NOQA def verify_signature(secret, signature, payload): computed_hash = hmac.new(str(secr...
#!/usr/bin/env python import os import sys import hashlib import hmac # Add the lib directory to the path for Lambda to load our libs sys.path.append(os.path.join(os.path.dirname(__file__), 'lib')) import requests # NOQA def verify_signature(secret, signature, payload): computed_hash = hmac.new(str(secret), pay...
Clean up order of imports
Clean up order of imports
Python
bsd-3-clause
pristineio/lambda-webhook
76da7e8bcee5cb91723ebe47006b1e3c20e7cc60
services/httplib.py
services/httplib.py
from __future__ import absolute_import from . import HttpService from . import Response from httplib import HTTPConnection from httplib import HTTPException from httplib import HTTPSConnection from socket import timeout, error import time class HttpLibHttpService(HttpService): """ HttpService using python bat...
from __future__ import absolute_import from . import HttpService from . import Response from httplib import HTTPConnection from httplib import HTTPException from httplib import HTTPSConnection from socket import timeout, error import time class HttpLibHttpService(HttpService): """ HttpService using python bat...
Make HttpLibHttpService compatible with Exception (no kwarg).
Make HttpLibHttpService compatible with Exception (no kwarg).
Python
bsd-2-clause
storecast/holon
fdd87814f68810a390c50f7bf2a08359430722fa
conda_build/main_index.py
conda_build/main_index.py
from __future__ import absolute_import, division, print_function import argparse import os from locale import getpreferredencoding from os.path import abspath from conda.compat import PY3 from conda_build.index import update_index def main(): p = argparse.ArgumentParser( description="Update package ind...
from __future__ import absolute_import, division, print_function import os from locale import getpreferredencoding from os.path import abspath from conda.compat import PY3 from conda.cli.conda_argparse import ArgumentParser from conda_build.index import update_index def main(): p = ArgumentParser( desc...
Update command docs for conda index
Update command docs for conda index
Python
bsd-3-clause
frol/conda-build,rmcgibbo/conda-build,shastings517/conda-build,mwcraig/conda-build,mwcraig/conda-build,dan-blanchard/conda-build,mwcraig/conda-build,dan-blanchard/conda-build,sandhujasmine/conda-build,frol/conda-build,rmcgibbo/conda-build,ilastik/conda-build,dan-blanchard/conda-build,shastings517/conda-build,frol/conda...
6f557ed73372aa5823393a53b079bf4cec7511b8
docker/ssladapter/ssladapter.py
docker/ssladapter/ssladapter.py
""" Resolves OpenSSL issues in some servers: https://lukasa.co.uk/2013/01/Choosing_SSL_Version_In_Requests/ https://github.com/kennethreitz/requests/pull/799 """ from distutils.version import StrictVersion from requests.adapters import HTTPAdapter try: from requests.packages.urllib3.poolmanager import P...
""" Resolves OpenSSL issues in some servers: https://lukasa.co.uk/2013/01/Choosing_SSL_Version_In_Requests/ https://github.com/kennethreitz/requests/pull/799 """ from distutils.version import StrictVersion from requests.adapters import HTTPAdapter try: import requests.packages.urllib3 as urllib3 except ...
Fix some urllib3 import issues
Fix some urllib3 import issues
Python
apache-2.0
runcom/docker-py,kaiyou/docker-py,TomasTomecek/docker-py,vpetersson/docker-py,dimaspivak/docker-py,paulbellamy/docker-py,ClusterHQ/docker-py,terminalmage/docker-py,ticosax/docker-py,kaiyou/docker-py,dimaspivak/docker-py,auready/docker-py,dnephin/docker-py,docker/docker-py,docker/docker-py,mrfuxi/docker-py,bboreham/dock...
d58a85b922d2159b16bc16be46b5c09175567ece
dockci/migrations/0002.py
dockci/migrations/0002.py
""" Migrate config to docker hosts list """ import os import yaml filename = os.path.join('data', 'configs.yaml') with open(filename) as handle: data = yaml.load(handle) host = data.pop('docker_host') data['docker_hosts'] = [host] with open(filename, 'w') as handle: yaml.dump(data, handle, default_flow_styl...
""" Migrate config to docker hosts list """ import os import sys import yaml filename = os.path.join('data', 'configs.yaml') try: with open(filename) as handle: data = yaml.load(handle) except FileNotFoundError: # This is fine; will fail for new installs sys.exit(0) host = data.pop('docker_host')...
Handle no config.yaml in migrations
Handle no config.yaml in migrations
Python
isc
RickyCook/DockCI,RickyCook/DockCI,RickyCook/DockCI,sprucedev/DockCI,sprucedev/DockCI,sprucedev/DockCI,sprucedev/DockCI-Agent,sprucedev/DockCI,RickyCook/DockCI,sprucedev/DockCI-Agent
b56320247044e1a3187d59b003e1fd5c9e4d49cd
cq/utils.py
cq/utils.py
import time from contextlib import contextmanager import six import inspect import importlib import logging from redis.exceptions import RedisError from django_redis import get_redis_connection logger = logging.getLogger('cq') def to_import_string(func): if inspect.isfunction(func) or inspect.isbuiltin(func): ...
import time from contextlib import contextmanager import six import inspect import importlib import logging from redis.exceptions import RedisError from django_redis import get_redis_connection logger = logging.getLogger('cq') def to_import_string(func): if inspect.isfunction(func) or inspect.isbuiltin(func): ...
Remove a logging call, not needed anymore.
Remove a logging call, not needed anymore.
Python
bsd-3-clause
furious-luke/django-cq
3e4360e831d98dadca3f9346f324f3d17769257f
alg_selection_sort.py
alg_selection_sort.py
from __future__ import absolute_import from __future__ import print_function from __future__ import division def selection_sort(a_list): """Selection Sort algortihm. Time complexity: O(n^2). """ for max_slot in reversed(range(len(a_list))): select_slot = 0 for slot in range(1, max_slo...
from __future__ import absolute_import from __future__ import print_function from __future__ import division def selection_sort(ls): """Selection Sort algortihm. Time complexity: O(n^2). Space complexity: O(1). """ # Start from the last elemenet reversely: len(ls) - 1, ..., 0. for i_max in re...
Refactor selection sort w/ adding comments
Refactor selection sort w/ adding comments
Python
bsd-2-clause
bowen0701/algorithms_data_structures
2555988a8eaf8e5620a8bf964092f23d1e309e91
examples/traffic_light.py
examples/traffic_light.py
import statemachine as fsm class TrafficLight(fsm.Machine): initial_state = 'red' count = 0 @fsm.after_transition('red', 'green') def chime(self): print 'GO GO GO' self.count += 1 @fsm.after_transition('*', 'red') def apply_brakes(self): self.stopped = True @fsm....
from __future__ import print_function import statemachine as fsm class TrafficLight(fsm.Machine): initial_state = 'red' count = 0 @fsm.after_transition('red', 'green') def chime(self): print('GO GO GO') self.count += 1 @fsm.after_transition('*', 'red') def apply_brakes(self): ...
Use the print function for python 3 support
Use the print function for python 3 support
Python
mit
kyleconroy/statemachine
8ada9ee4b394119a73de8d85a9db2be9df547aae
lib/pegasus/python/Pegasus/cli/startup-validation.py
lib/pegasus/python/Pegasus/cli/startup-validation.py
#!/usr/bin/python3 import sys if not sys.version_info >= (3, 5): sys.stderr.write('Pegasus requires Python 3.5 or above\n') sys.exit(1) try: import yaml except: sys.stderr.write('Pegasus requires the Python3 YAML module to be installed\n') sys.exit(1) try: import OpenSSL except: sys.stde...
#!/usr/bin/python3 import sys if not sys.version_info >= (3, 5): sys.stderr.write("Pegasus requires Python 3.5 or above\n") sys.exit(1) try: import yaml except: sys.stderr.write("Pegasus requires the Python3 YAML module to be installed\n") sys.exit(1)
Remove check for pyOpenSSL as it is only needed in pegasus-service to use ssl certs.
Remove check for pyOpenSSL as it is only needed in pegasus-service to use ssl certs.
Python
apache-2.0
pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus
c00f0f2c0f89b1596c73cb671ef7127ecf56150f
features/steps/sensors.py
features/steps/sensors.py
from behave import given, when, then from mock import patch, call from tinkerforge.ip_connection import IPConnection from pytoon.models import Electricity, db from pytoon.connection import BrickConnection @given('we connect to the master brick') @patch('pytoon.connection.IPConnection') def step_impl(context, mock_cla...
from behave import given, when, then from mock import patch, call from tinkerforge.ip_connection import IPConnection from pytoon.models import Electricity, db from pytoon.connection import BrickConnection @given('we connect to the master brick') @patch('pytoon.connection.IPConnection') def step_impl(context, mock_cla...
Create database if it doesn't exist
Create database if it doesn't exist
Python
bsd-3-clause
marcoplaisier/pytoon,marcofinalist/pytoon,marcoplaisier/pytoon,marcofinalist/pytoon
ef8a6616876ee044d07cf8f30b51af0cbb2bc7e4
geozones/factories.py
geozones/factories.py
# coding: utf-8 import factory import random from .models import Location, Region class RegionFactory(factory.Factory): FACTORY_FOR = Region name = factory.Sequence(lambda n: "Region_%s" % n) cityId = factory.SubFactory(CityFactory) slug = factory.LazyAttribute(lambda a: a.name.lower()) zoomLvl...
# coding: utf-8 import factory import random from .models import Location, Region class RegionFactory(factory.Factory): FACTORY_FOR = Region name = factory.Sequence(lambda n: "Region_%s" % n) slug = factory.LazyAttribute(lambda a: a.name.lower()) latitude = random.uniform(-90.0, 90.0) longtitud...
Fix region factory to reflect region model
Fix region factory to reflect region model
Python
mit
sarutobi/Rynda,sarutobi/Rynda,sarutobi/ritmserdtsa,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/flowofkindness,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/ritmserdtsa
03a95c87dde1a5b20658b3b61b4c4abc070e3bf3
flowtype/commands/base.py
flowtype/commands/base.py
import abc import sublime import sublime_plugin from ..helpers import is_js_source class BaseCommand(sublime_plugin.TextCommand, metaclass=abc.ABCMeta): """Common properties and methods for children commands.""" def get_content(self): """Return file content.""" return self.view.substr(subli...
import sublime import sublime_plugin from ..helpers import is_js_source class BaseCommand(sublime_plugin.TextCommand): """Common properties and methods for children commands.""" def get_content(self): """Return file content.""" return self.view.substr(sublime.Region(0, self.view.size())) ...
Fix travis by removing abc metaclass.
Fix travis by removing abc metaclass.
Python
mit
Pegase745/sublime-flowtype
93c978ba422b26971180a4277a0b69e82848ee78
src/yunohost/data_migrations/0009_migrate_to_apps_json.py
src/yunohost/data_migrations/0009_migrate_to_apps_json.py
from moulinette.utils.log import getActionLogger from yunohost.app import app_fetchlist, app_removelist, _read_appslist_list from yunohost.tools import Migration logger = getActionLogger('yunohost.migration') class MyMigration(Migration): "Migrate from official.json to apps.json" def migrate(self): ...
import os from moulinette.utils.log import getActionLogger from yunohost.app import app_fetchlist, app_removelist, _read_appslist_list, APPSLISTS_JSON from yunohost.tools import Migration logger = getActionLogger('yunohost.migration') BASE_CONF_PATH = '/home/yunohost.conf' BACKUP_CONF_DIR = os.path.join(BASE_CONF_PA...
Backup / restore original appslist to handle backward case properly
Backup / restore original appslist to handle backward case properly
Python
agpl-3.0
YunoHost/moulinette-yunohost,YunoHost/yunohost,YunoHost/yunohost,YunoHost/moulinette-yunohost,YunoHost/moulinette-yunohost,YunoHost/moulinette-yunohost,YunoHost/moulinette-yunohost,YunoHost/yunohost,YunoHost/yunohost
92ecaea827da56a15297ffc240312b1767ebb845
ibmcnx/doc/DataSources.py
ibmcnx/doc/DataSources.py
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Appli...
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Appli...
Create documentation of DataSource Settings
8: Create documentation of DataSource Settings Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8
Python
apache-2.0
stoeps13/ibmcnx2,stoeps13/ibmcnx2
b2e1fd5727eed1818d0ddc3c29a1cf9f7e38d024
wger/exercises/management/commands/submitted-exercises.py
wger/exercises/management/commands/submitted-exercises.py
# -*- coding: utf-8 *-* # This file is part of wger Workout Manager. # # wger Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any ...
# -*- coding: utf-8 *-* # This file is part of wger Workout Manager. # # wger Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any ...
Fix management command for submitted exercises
Fix management command for submitted exercises
Python
agpl-3.0
DeveloperMal/wger,kjagoo/wger_stark,rolandgeider/wger,rolandgeider/wger,DeveloperMal/wger,petervanderdoes/wger,kjagoo/wger_stark,wger-project/wger,wger-project/wger,petervanderdoes/wger,wger-project/wger,kjagoo/wger_stark,rolandgeider/wger,rolandgeider/wger,petervanderdoes/wger,DeveloperMal/wger,DeveloperMal/wger,wger-...
1004cc88032e816116bd46f2eb66e4b89f3f766f
tests/test_web_caller.py
tests/test_web_caller.py
from unittest import TestCase from mock import NonCallableMock, patch from modules.web_caller import get_google, GOOGLE_URL class TestWebCaller(TestCase): """ Tests for the `web_caller` module. """ @patch('modules.web_caller.requests.get') def test_get_google(self, get): """ Call...
from unittest import TestCase from requests.exceptions import ConnectionError from mock import NonCallableMock, patch from modules.web_caller import get_google, GOOGLE_URL MOCK_GOOGLE_URL = 'http://not-going-to-work!!!' class TestWebCaller(TestCase): """ Tests for the `web_caller` module. """ @patc...
Add test examples to assert against exceptions
Add test examples to assert against exceptions
Python
mit
tkh/test-examples,tkh/test-examples
e82045217fa262fbfe30563fef9945a67024d27f
project/creditor/management/commands/addrecurring.py
project/creditor/management/commands/addrecurring.py
# -*- coding: utf-8 -*- from creditor.models import RecurringTransaction from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): help = 'Gets all RecurringTransactions and runs conditional_add_transaction()' def handle(self, *args, **options): for t in RecurringT...
# -*- coding: utf-8 -*- import datetime import itertools import dateutil.parser from creditor.models import RecurringTransaction from django.core.management.base import BaseCommand, CommandError from django.utils import timezone from asylum.utils import datetime_proxy, months class Command(BaseCommand): help = ...
Add "since" parameter to this command
Add "since" parameter to this command Fixes #25
Python
mit
HelsinkiHacklab/asylum,hacklab-fi/asylum,rambo/asylum,rambo/asylum,HelsinkiHacklab/asylum,jautero/asylum,hacklab-fi/asylum,HelsinkiHacklab/asylum,rambo/asylum,HelsinkiHacklab/asylum,jautero/asylum,jautero/asylum,jautero/asylum,hacklab-fi/asylum,hacklab-fi/asylum,rambo/asylum
8f7640fd5a145dba724974ca5a46f73b9c991c45
cloud_notes/templatetags/markdown_filters.py
cloud_notes/templatetags/markdown_filters.py
from django import template import markdown as md import bleach register = template.Library() def markdown(value): """convert to markdown""" return md.markdown(bleach.clean(value)) register.filter('markdown', markdown)
from django import template import markdown as md import bleach import copy register = template.Library() def markdown(value): """convert to markdown""" allowed_tags = bleach.ALLOWED_TAGS + ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'] return bleach.clean(md.markdown(value), tags = allowed_tags) register...
Fix blockquote missing from markdown filter
Fix blockquote missing from markdown filter
Python
apache-2.0
kiwiheretic/logos-v2,kiwiheretic/logos-v2,kiwiheretic/logos-v2,kiwiheretic/logos-v2
ec1f7db3f1bd637807b4b9d69a0b702af36fbef1
morenines/ignores.py
morenines/ignores.py
import os from fnmatch import fnmatchcase import click class Ignores(object): @classmethod def read(cls, path): ignores = cls() if path: with click.open_file(path, 'r') as stream: ignores.patterns = [line.strip() for line in stream] return ignores ...
import os from fnmatch import fnmatchcase import click from morenines.util import find_file class Ignores(object): @classmethod def read(cls, path): if not path: path = find_file('.mnignore') ignores = cls() if path: with click.open_file(path, 'r') as stream:...
Make Ignores try to find '.mnignore'
Make Ignores try to find '.mnignore' If it doesn't find it, that's okay, and no action is required.
Python
mit
mcgid/morenines,mcgid/morenines
9a81879bd4eb01be5ed74acfdaf22acb635a9817
pikalang/__init__.py
pikalang/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """pikalang module. A brainfuck derivative based off the vocabulary of Pikachu from Pokemon. Copyright (c) 2019 Blake Grotewold """ import sys import os from pikalang.interpreter import PikalangProgram def load_source(file): if os.path.isfile(file): if os.p...
#!/usr/bin/env python # -*- coding: utf-8 -*- """pikalang module. A brainfuck derivative based off the vocabulary of Pikachu from Pokemon. Copyright (c) 2019 Blake Grotewold """ from __future__ import print_function import sys import os from pikalang.interpreter import PikalangProgram def load_source(file): i...
Add proper printing for py2
Add proper printing for py2
Python
mit
groteworld/pikalang,grotewold/pikalang
07ae9397835bc064d0119d2f35b2c1255597ea63
dipy/io/tests/test_utils.py
dipy/io/tests/test_utils.py
from dipy.io.utils import decfa from nibabel import Nifti1Image import numpy as np def test_decfa(): data_orig = np.zeros((4, 4, 4, 3)) data_orig[0, 0, 0] = np.array([1, 0, 0]) img_orig = Nifti1Image(data_orig, np.eye(4)) img_new = decfa(img_orig) data_new = img_new.get_data() assert data_new[...
from dipy.io.utils import decfa from nibabel import Nifti1Image import numpy as np def test_decfa(): data_orig = np.zeros((4, 4, 4, 3)) data_orig[0, 0, 0] = np.array([1, 0, 0]) img_orig = Nifti1Image(data_orig, np.eye(4)) img_new = decfa(img_orig) data_new = img_new.get_data() assert data_new[0...
Test properly, including the dtype.
TST: Test properly, including the dtype.
Python
bsd-3-clause
FrancoisRheaultUS/dipy,FrancoisRheaultUS/dipy
093127f85f6d8f3f0ef669abfc0ba7cc9778fbe5
chef/data_bag.py
chef/data_bag.py
import abc import collections from chef.base import ChefObject, ChefQuery, ChefObjectMeta class DataBagMeta(ChefObjectMeta, abc.ABCMeta): """A metaclass to allow DataBag to use multiple inheritance.""" class DataBag(ChefObject, ChefQuery): __metaclass__ = DataBagMeta url = '/data' def _popu...
import abc import collections from chef.base import ChefObject, ChefQuery, ChefObjectMeta class DataBagMeta(ChefObjectMeta, abc.ABCMeta): """A metaclass to allow DataBag to use multiple inheritance.""" class DataBag(ChefObject, ChefQuery): __metaclass__ = DataBagMeta url = '/data' def _populate(se...
Handle both possible JSON formats for data bag items.
Handle both possible JSON formats for data bag items. This won't work if there is an actual data bag item key called 'json_class', but that would be silly.
Python
apache-2.0
dipakvwarade/pychef,coderanger/pychef,Scalr/pychef,coderanger/pychef,jarosser06/pychef,dipakvwarade/pychef,cread/pychef,Scalr/pychef,jarosser06/pychef,cread/pychef
a273342b6e89709fc838dfd6abcee0a525272cea
management/admin.py
management/admin.py
from django.contrib import admin from django.contrib.contenttypes.admin import GenericTabularInline from .models import (Location, Permanence, Equipment, Lending, Position, MembershipType, Membership, PublicFile, PublicImage, ProtectedFile, ProtectedImage, AdminFile, AdminImage) ...
from django.contrib import admin from django.contrib.contenttypes.admin import GenericTabularInline from .models import (Location, Permanence, Equipment, Lending, Position, MembershipType, Membership, PublicFile, PublicImage, ProtectedFile, ProtectedImage, AdminFile, AdminImage) ...
Add ProtectedFile, ProtectedImage, AdminFile and AdminImage.
Add ProtectedFile, ProtectedImage, AdminFile and AdminImage.
Python
mit
QSchulz/sportassociation,QSchulz/sportassociation,QSchulz/sportassociation
e118ee78b534a83b33f91b27cfc1f75d64e8e924
test_utils/testmaker/base_serializer.py
test_utils/testmaker/base_serializer.py
import cPickle as pickle import logging import time ser = logging.getLogger('testserializer') class Serializer(object): """A pluggable Serializer class""" name = "default" def __init__(self, name='default'): """Constructor""" self.data = {} self.name = name def save_request(...
import cPickle as pickle import logging import time class Serializer(object): """A pluggable Serializer class""" name = "default" def __init__(self, name='default'): """Constructor""" self.ser = logging.getLogger('testserializer') self.data = {} self.name = name def ...
Move serializer into the class so it can be subclassed.
Move serializer into the class so it can be subclassed.
Python
mit
frac/django-test-utils,acdha/django-test-utils,ericholscher/django-test-utils,frac/django-test-utils,ericholscher/django-test-utils,acdha/django-test-utils
b3935065232a97b7eb65c38e5c7bc60570467c71
news/urls.py
news/urls.py
from django.conf.urls import url from . import views app_name = 'news' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$', views.ArticleView.as_view(), name='article'), ]
from django.urls import include, path from . import views app_name = 'news' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:year>/<int:month>/<int:day>/<slug:slug>/', views.ArticleView.as_view(), name='article'), ]
Move news urlpatterns to Django 2.0 preferred method
Move news urlpatterns to Django 2.0 preferred method
Python
mit
evanepio/dotmanca,evanepio/dotmanca,evanepio/dotmanca
910d9e724e1e80d967853b21f553d753c70fefc0
noah/noah.py
noah/noah.py
import json import random class Noah(object): def __init__(self, dictionary_file): self.dictionary = json.load(dictionary_file) def list(self): return '\n'.join([entry['word'] for entry in self.dictionary]) def define(self, word): entry = next((x for x in self.dictionary if x['wor...
import json import random import pprint class Noah(object): def __init__(self, dictionary_file): self.dictionary = json.load(dictionary_file) def list(self): return '\n'.join([entry['word'] for entry in self.dictionary]) def define(self, word): return self.output(filter(lambda x: ...
Define returns all entries for given query.
Define returns all entries for given query.
Python
mit
maxdeviant/noah
c246f0e9add0a5b6d7fce9b9e2107671440b5f90
mica/starcheck/tests/make_database.py
mica/starcheck/tests/make_database.py
import os import tempfile from Chandra.Time import DateTime from Ska.Shell import bash import mica.common # Override MICA_ARCHIVE with a temporary directory TESTDIR = tempfile.mkdtemp() mica.common.MICA_ARCHIVE = TESTDIR # import mica.starcheck.starcheck after setting MICA_ARCHIVE import mica.starcheck.process # Just...
import os import tempfile from Chandra.Time import DateTime from Ska.Shell import bash import mica.common # Override MICA_ARCHIVE with a temporary directory TESTDIR = tempfile.mkdtemp() mica.common.MICA_ARCHIVE = TESTDIR # import mica.starcheck.starcheck after setting MICA_ARCHIVE import mica.starcheck.process # Just...
Update test script to use a provided start time
Update test script to use a provided start time
Python
bsd-3-clause
sot/mica,sot/mica
2fd5f0656434340763cc51c47238d4a40e61789b
modernrpc/__init__.py
modernrpc/__init__.py
# coding: utf-8 from packaging.version import Version import django # Set default_app_config only with Django up to 3.1. This prevents a Warning on newer releases # See https://docs.djangoproject.com/fr/3.2/releases/3.2/#automatic-appconfig-discovery if Version(django.get_version()) < Version("3.2"): default_app_c...
# coding: utf-8 from distutils.version import StrictVersion import django # distutils.version, overridden by setuptools._distutils.version in recent python releases, is deprecated # and will be removed in Python 3.12. We will probably drop Django < 3.2 until then, so this should be fine if StrictVersion(django.get_ve...
Remove unwanted dependency to 'packaging'
Remove unwanted dependency to 'packaging'
Python
mit
alorence/django-modern-rpc,alorence/django-modern-rpc
1f76df1fe6b77850f8741b2f52b2509ce204f93f
stats-to-datadog.py
stats-to-datadog.py
import urllib2 import json import sys from statsd import statsd statsd.connect('localhost', 8125) topology = sys.argv[1] state = urllib2.urlopen( "http://localhost:9000/api/status?toporoot={}&topic={}".format( sys.argv[2], sys.argv[3] ) ).read() data = json.loads(state) amount = 0 for looplord in d...
import urllib2 import json import sys from statsd import statsd statsd.connect('localhost', 8125) topology = sys.argv[1] toporoot = sys.argv[2] topic = sys.argv[3] state = urllib2.urlopen( "http://localhost:9000/api/status?toporoot={}&topic={}".format( toporoot, topic ) ).read() data = json.loads(st...
Add stats for each partition.
Add stats for each partition.
Python
mit
evertrue/capillary,evertrue/capillary,evertrue/capillary,keenlabs/capillary,evertrue/capillary,keenlabs/capillary,keenlabs/capillary
6a8f39104a1a7722ee0a0a2437256dd3c123ab18
src/newt/db/tests/base.py
src/newt/db/tests/base.py
import gc import sys PYPY = hasattr(sys, 'pypy_version_info') from .. import pg_connection class DBSetup(object): maxDiff = None @property def dsn(self): return 'postgresql://localhost/' + self.dbname def setUp(self, call_super=True): self.dbname = self.__class__.__name__.lower() + ...
import gc import sys import unittest PYPY = hasattr(sys, 'pypy_version_info') from .. import pg_connection from .._util import closing class DBSetup(object): maxDiff = None @property def dsn(self): return 'postgresql://localhost/' + self.dbname def setUp(self, call_super=True): sel...
Make it easier to clean up tests by closing db sessions
Make it easier to clean up tests by closing db sessions Also added a convenience test base class
Python
mit
newtdb/db
0128ca2edb48cb58c8a68b4b6e9a8eaeba53518c
python/play/dwalk.py
python/play/dwalk.py
#! /usr/bin/env python """dwalk: walk a directory tree, printing entries hierarchically + top | > file | > file | + dir | | > file | | > file | | + dir | | | > file | | + dir | | | > file | | | > file | + dir | | + dir | | | > file""" import os import sys def dwalk(path, hea...
#! /usr/bin/env python # vim: set sw=4 ai et sm: """dwalk: walk a directory tree, printing entries hierarchically + top | > file | > file | + dir | | > file | | > file | | + dir | | | > file | | + dir | | | > file | | | > file | + dir | | + dir | | | > file""" import os impo...
Convert tabs to spaces, and set up vim modeline to expand tabs going forward.
Convert tabs to spaces, and set up vim modeline to expand tabs going forward.
Python
bsd-2-clause
tedzo/python_play
f1be3f0920bbd270a5906364e77182b67ae4c354
rejected/__init__.py
rejected/__init__.py
""" Rejected is a Python RabbitMQ Consumer Framework and Controller Daemon """ __author__ = 'Gavin M. Roy <gavinmroy@gmail.com>' __since__ = "2009-09-10" __version__ = "3.7.0" from consumer import Consumer from consumer import PublishingConsumer from consumer import SmartConsumer from consumer import SmartPublishingC...
""" Rejected is a Python RabbitMQ Consumer Framework and Controller Daemon """ __author__ = 'Gavin M. Roy <gavinmroy@gmail.com>' __since__ = "2009-09-10" __version__ = "3.7.0" import logging try: # not available in python 2.6 from logging import NullHandler except ImportError: class NullHandler(logging.H...
Include a NullHandler to avoid logging warnings
Include a NullHandler to avoid logging warnings
Python
bsd-3-clause
gmr/rejected,gmr/rejected
85de2a0bb8727583fef61fdadcca6bb3e649a454
apps/addons/api/views.py
apps/addons/api/views.py
from rest_framework import generics, serializers from rest_framework.response import Response from waffle.decorators import waffle_switch import amo from addons.models import Addon class AddonSerializer(serializers.ModelSerializer): addon_type = serializers.SerializerMethodField('get_addon_type') descriptio...
from rest_framework import generics, serializers from rest_framework.response import Response from waffle.decorators import waffle_switch import amo from addons.models import Addon class AddonSerializer(serializers.ModelSerializer): addon_type = serializers.SerializerMethodField('get_addon_type') descriptio...
Set CORS header for add-on search API
Set CORS header for add-on search API
Python
bsd-3-clause
eviljeff/olympia,harry-7/addons-server,mozilla/olympia,Prashant-Surya/addons-server,mozilla/addons-server,atiqueahmedziad/addons-server,mozilla/olympia,harikishen/addons-server,mozilla/addons-server,bqbn/addons-server,mstriemer/olympia,jpetto/olympia,Prashant-Surya/addons-server,psiinon/addons-server,mozilla/addons-ser...
6ba1d1805a65ff7e07b795ed7b54fc3375a1e3e4
main_AWS.py
main_AWS.py
def process_single_user(username, password): try: lingo = duolingo.Duolingo(username, password) except ValueError: raise Exception("Username Invalid") print("Trying to Buy Streak Freeze for " + username) if(lingo.buy_streak_freeze()): print("Bought streak freeze for " + username...
def process_single_user(username, password): import duolingo try: lingo = duolingo.Duolingo(username, password) except ValueError: raise Exception("Username Invalid") stuff_to_purchase = ['streak_freeze', 'rupee_wager'] for item in stuff_to_purchase: try: print(...
UPdate to duolingo for the API
UPdate to duolingo for the API
Python
mit
alexsanjoseph/duolingo-save-streak,alexsanjoseph/duolingo-save-streak
fa36fc3301e7db47d72d0cd7c47bddf30cd7719d
06_test/unit_test_func.py
06_test/unit_test_func.py
#/usr/bin/env python import unittest from my_calc import my_add class test_func(unittest.TestCase): def test_my_add(self): res = my_add(1, 2) self.assertEqual(res, 3) if __name__ == "__main__": unittest.main()
#/usr/bin/env python import unittest from my_calc import my_add class test_func(unittest.TestCase): def test_my_add(self): print("Test begin") res = my_add(1, 2) self.assertEqual(res, 3) def setUp(self): print("Setup") def tearDown(self): print("Tear down") if __na...
Test unit test constructor and destructor
Test unit test constructor and destructor
Python
bsd-2-clause
zzz0072/Python_Exercises,zzz0072/Python_Exercises
219eddef46d17486324240856005dc2be40083a4
newparp/tasks/__init__.py
newparp/tasks/__init__.py
import os import raven from celery import Celery, Task from classtools import reify from redis import StrictRedis from raven.contrib.celery import register_signal, register_logger_signal from newparp.model import sm from newparp.model.connections import redis_pool celery = Celery("newparp", include=[ "newparp.ta...
import os import raven from celery import Celery, Task from classtools import reify from redis import StrictRedis from raven.contrib.celery import register_signal, register_logger_signal from newparp.model import sm from newparp.model.connections import redis_pool celery = Celery("newparp", include=[ "newparp.ta...
Add test tasks to the celery includes.
Add test tasks to the celery includes.
Python
agpl-3.0
MSPARP/newparp,MSPARP/newparp,MSPARP/newparp
455783a2ef4c47a5bc9933d48e7d44dcf3c41dc0
tests/integration/grains/test_core.py
tests/integration/grains/test_core.py
# -*- coding: utf-8 -*- ''' Test the core grains ''' # Import python libs from __future__ import absolute_import # Import Salt Testing libs import tests.integration as integration from tests.support.unit import skipIf # Import salt libs import salt.utils if salt.utils.is_windows(): try: import salt.modul...
# -*- coding: utf-8 -*- ''' Test the core grains ''' # Import python libs from __future__ import absolute_import # Import Salt Testing libs import tests.integration as integration from tests.support.unit import skipIf # Import salt libs import salt.utils if salt.utils.is_windows(): try: import salt.modul...
Add ImportError to exception instead of bare "except"
Add ImportError to exception instead of bare "except" Fixes lint error on develop.
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
a07c3db369fec32507a7f51b96927bfe383597bc
tests/PexpectTestCase.py
tests/PexpectTestCase.py
''' PEXPECT LICENSE This license is approved by the OSI and FSF as GPL-compatible. http://opensource.org/licenses/isc-license.txt Copyright (c) 2012, Noah Spurrier <noah@noah.org> PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY PURPOSE WITH OR WITHOUT FEE IS HEREBY GR...
''' PEXPECT LICENSE This license is approved by the OSI and FSF as GPL-compatible. http://opensource.org/licenses/isc-license.txt Copyright (c) 2012, Noah Spurrier <noah@noah.org> PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY PURPOSE WITH OR WITHOUT FEE IS HEREBY GR...
Make test case base compatible with Python 3
Make test case base compatible with Python 3
Python
isc
Wakeupbuddy/pexpect,dongguangming/pexpect,nodish/pexpect,Depado/pexpect,bangi123/pexpect,bangi123/pexpect,Depado/pexpect,quatanium/pexpect,dongguangming/pexpect,bangi123/pexpect,nodish/pexpect,blink1073/pexpect,Depado/pexpect,Wakeupbuddy/pexpect,dongguangming/pexpect,Wakeupbuddy/pexpect,crdoconnor/pexpect,blink1073/pex...
cd59731f1b62265b699f82359a2e3c146feb7845
oslo_cache/_i18n.py
oslo_cache/_i18n.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
Update the documentation link for doc migration
Update the documentation link for doc migration This patch is proposed according to the Direction 10 of doc migration(https://etherpad.openstack.org/p/doc-migration-tracking). Change-Id: I62ae28d10f70d63ba693ac0ab6581faf85f1bf6e
Python
apache-2.0
openstack/oslo.cache,openstack/oslo.cache
7ff0e821b2d5e04f5d4edd198ae913a2e8e1da6e
micronota/db/test/test_tigrfam.py
micronota/db/test/test_tigrfam.py
#!/usr/bin/env python # ---------------------------------------------------------------------------- # Copyright (c) 2015--, micronota development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. # ----------------------...
#!/usr/bin/env python # ---------------------------------------------------------------------------- # Copyright (c) 2015--, micronota development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. # ----------------------...
Update the equality test for database files
Update the equality test for database files
Python
bsd-3-clause
RNAer/micronota,tkosciol/micronota,mortonjt/micronota,mortonjt/micronota,RNAer/micronota,biocore/micronota,biocore/micronota,tkosciol/micronota
c74b3a4d80b8d7002b6836a421cf2b3032377545
filterable.py
filterable.py
class Filterable: no_delays_filter = lambda filterable: filterable.condition.record_id == str(6) query_delay_filter = lambda filterable: filterable.condition.record_id == str(7) document_delay_filter = lambda filterable: filterable.condition.record_id == str(8) combined_delay_filter = lambda filterable: filtera...
class Filterable: no_delays_filter = lambda filterable: filterable.condition.record_id == str(6) query_delay_filter = lambda filterable: filterable.condition.record_id == str(7) document_delay_filter = lambda filterable: filterable.condition.record_id == str(8) combined_delay_filter = lambda filterable: filtera...
Add filter for rejecting practice topic
Add filter for rejecting practice topic
Python
mit
fire-uta/iiix-data-parser
5f62db4246e67cec6ac39f27960d6f17e9f163c5
test/functional/rpc_deprecated.py
test/functional/rpc_deprecated.py
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test deprecation of RPC calls.""" from test_framework.test_framework import BitcoinTestFramework from test_f...
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test deprecation of RPC calls.""" from test_framework.test_framework import BitcoinTestFramework class Depr...
Remove test for deprecated createmultsig option
[tests] Remove test for deprecated createmultsig option
Python
mit
chaincoin/chaincoin,chaincoin/chaincoin,chaincoin/chaincoin,chaincoin/chaincoin,chaincoin/chaincoin,chaincoin/chaincoin
fd2c03b2e6f48dac071b813b20cc2f70a2658f24
tests/test_path_paths.py
tests/test_path_paths.py
import nose from nose.tools import raises import dpath.path import dpath.exceptions import dpath.options @raises(dpath.exceptions.InvalidKeyName) def test_path_paths_invalid_keyname(): tdict = { "I/contain/the/separator": 0 } for x in dpath.path.paths(tdict): pass @raises(dpath.excepti...
import nose from nose.tools import raises import dpath.path import dpath.exceptions import dpath.options @raises(dpath.exceptions.InvalidKeyName) def test_path_paths_invalid_keyname(): tdict = { "I/contain/the/separator": 0 } for x in dpath.path.paths(tdict): pass @raises(dpath.excepti...
Print statement was breaking python 3 builds
Print statement was breaking python 3 builds
Python
mit
akesterson/dpath-python,calebcase/dpath-python,benthomasson/dpath-python,lexhung/dpath-python,pombredanne/dpath-python
0da5820816187dd6b6d6ebbd554fc9646853e0fc
tests/git_code_debt/logic_test.py
tests/git_code_debt/logic_test.py
import testify as T from git_code_debt.create_tables import get_metric_ids from git_code_debt.discovery import get_metric_parsers from git_code_debt.logic import get_metric_mapping from testing.base_classes.sandbox_test_case import SandboxTestCase class TestLogic(SandboxTestCase): def test_get_metric_mapping(s...
import testify as T from git_code_debt.create_tables import get_metric_ids from git_code_debt.discovery import get_metric_parsers from git_code_debt.logic import get_metric_mapping from git_code_debt.logic import get_metric_values from git_code_debt.logic import get_previous_sha from git_code_debt.logic import insert...
Add more tests to logic test
Add more tests to logic test
Python
mit
ucarion/git-code-debt,ucarion/git-code-debt,Yelp/git-code-debt,Yelp/git-code-debt,Yelp/git-code-debt,ucarion/git-code-debt,Yelp/git-code-debt
ce3fa12a6fc497264529d5f44e3f4a20b5317fcd
gapipy/resources/booking/customer.py
gapipy/resources/booking/customer.py
from __future__ import unicode_literals from ..base import Resource class Customer(Resource): _resource_name = 'customers' _is_listable = False _is_parent_resource = True _as_is_fields = [ 'id', 'href', 'place_of_birth', 'meal_preference', 'meal_notes', 'emergency_contacts', 'medical...
from __future__ import unicode_literals from ..base import Resource class Customer(Resource): _resource_name = 'customers' _is_listable = False _is_parent_resource = True _as_is_fields = [ 'id', 'href', 'place_of_birth', 'meal_preference', 'meal_notes', 'emergency_contacts', 'medical...
Add gender to Customer model.
Add gender to Customer model.
Python
mit
gadventures/gapipy
aed959a0593558b6063e70c3b594feb6caa4bdda
tests/runner/compose/init_test.py
tests/runner/compose/init_test.py
import os import tempfile import shutil from unittest import TestCase import yaml from dusty import constants from dusty.runner.compose import _write_composefile class TestComposeRunner(TestCase): def setUp(self): self.temp_compose_dir = tempfile.mkdtemp() self.temp_compose_path = os.path.join(se...
import os import tempfile import shutil from unittest import TestCase from mock import patch import yaml from dusty import constants from dusty.runner.compose import _write_composefile, _get_docker_env class TestComposeRunner(TestCase): def setUp(self): self.temp_compose_dir = tempfile.mkdtemp() ...
Add a test for _get_docker_env
Add a test for _get_docker_env
Python
mit
gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty
4c74a02b669efd7ec66dbc217d8e55f149cd94d1
tests/test_parse.py
tests/test_parse.py
from hypothesis_auto import auto_pytest_magic from isort import parse auto_pytest_magic(parse.import_comment)
from hypothesis_auto import auto_pytest_magic from isort import parse from isort.finders import FindersManager from isort.settings import DEFAULT_SECTIONS, default TEST_CONTENTS = """ import xyz import abc def function(): pass """ auto_pytest_magic(parse.import_comment) auto_pytest_magic(parse.import_type) auto...
Add test cases for parse modue
Add test cases for parse modue
Python
mit
PyCQA/isort,PyCQA/isort
78585c783013c6f06f7e20eee6a654759b70e99c
tests/test_ttfmt.py
tests/test_ttfmt.py
import unittest class TestTtFmt(unittest.TestCase): def testName(self): pass if __name__ == "__main__": unittest.main()
import unittest import tt.fmttools.ttfmt as ttfmt class TestTtFmt(unittest.TestCase): def test_get_vars(self): data_provider = { # Simple test cases "F = A and B" : ["F", "A", "B"], "F = A and B or C" : ["F", "A", "B", "...
Add basic tests for ttfmt get_vars method
Add basic tests for ttfmt get_vars method
Python
mit
welchbj/tt,welchbj/tt,welchbj/tt
c2eeb0a7d8d3a2692537f2004052b9fad9b1527a
tests/test_utils.py
tests/test_utils.py
import os from unittest import TestCase import requests from furikura import utils def test_request(): requests.get('https://example.com') class TestUtils(TestCase): def test_get_file(self): self.assertEqual(utils.get_file("testfile"), "/usr/share/testfile") def test_check_connection(self): ...
import os from unittest import TestCase import requests from furikura import utils def test_request(): requests.get('https://example.com') class TestUtils(TestCase): def test_get_file(self): self.assertEqual(utils.get_file("testfile"), "/usr/share/testfile") def test_check_connection(self): ...
Create autostart folder for tests
Create autostart folder for tests
Python
mit
benjamindean/furi-kura,benjamindean/furi-kura
fc8c949c58caaa012f166f1d0266e896f4ab0e3f
getTwitter.py
getTwitter.py
print 'This script will be used to get the page and information from tiwtter'
import urllib2 print 'Welcome to the Get Twitter tool. This tool will allow you to download a page from Twitter to be used to extract the data' userResponse = raw_input("Please enter the full URL from the Tweet page") response = urllib2.urlopen(userResponse) html = response.read()
Allow user to input url
Allow user to input url Allows the user to input a URL which will then be retrieved
Python
artistic-2.0
christaylortf/FinalYearProject
dd68fbb86100d0d3da08172505e7c564cc5bd3e7
monitor-notifier-slack.py
monitor-notifier-slack.py
#!/usr/bin/env python import pika import json import requests SLACK_WEBHOOK_URL = os.environ["SLACK_WEBHOOK_URL"] RABBIT_MQ_SERVER = os.environ["RABBIT_MQ_SERVER"] connection = pika.BlockingConnection(pika.ConnectionParameters( RABBIT_MQ_SERVER)) channel = connection.channel() channel.queue_declare(que...
#!/usr/bin/env python import pika import json import requests import os RABBIT_MQ_SERVER = os.environ["RABBIT_MQ_SERVER"] RABBIT_MQ_USER = os.environ["RABBIT_MQ_USER"] RABBIT_MQ_PWD = os.environ["RABBIT_MQ_PWD"] credentials = pika.PlainCredentials(RABBIT_MQ_USER, RABBIT_MQ_PWD) connection = pika.BlockingConnection(p...
Add credentials + read webhook_url from notifier arguments
Add credentials + read webhook_url from notifier arguments
Python
mit
observer-hackaton/monitor-notifier-slack
275cec3a846093769eaddda87b753a7e5c224f59
odbc2csv.py
odbc2csv.py
import pypyodbc import csv conn = pypyodbc.connect("DSN=HOSS_DB") cur = conn.cursor() tables = [] cur.execute("select * from sys.tables") for row in cur.fetchall(): tables.append(row[0]) for table in tables: print(table) cur.execute("select * from {}".format(table)) column_names = [] for d i...
import pypyodbc import csv conn = pypyodbc.connect("DSN=HOSS_DB") cur = conn.cursor() tables = [] cur.execute("select * from sys.tables") for row in cur.fetchall(): tables.append(row[0]) for table in tables: print(table) cur.execute("select * from {}".format(table)) column_names = [] for d i...
Use just newline for file terminator.
Use just newline for file terminator.
Python
isc
wablair/misc_scripts,wablair/misc_scripts,wablair/misc_scripts,wablair/misc_scripts
c345e73ac22be8dde7e0230121e0e02b581d1209
uncertainty/lib/nlp/summarizer.py
uncertainty/lib/nlp/summarizer.py
from . import chunktagger, lemmatizer, postagger, stemmer, tokenizer class Summarizer(object): def __init__(self, text): self.text = text def execute(self): tokens = tokenizer.NLTKTokenizer(self.text).execute() stems = stemmer.Stemmer(tokens).execute() pos = postagger.PosTagge...
from . import chunktagger, lemmatizer, postagger, stemmer, tokenizer class Summarizer(object): def __init__(self, text): self.text = text def execute(self): tokens = tokenizer.NLTKTokenizer(self.text).execute() stems = stemmer.Stemmer(tokens).execute() pos = postagger.PosTagge...
Fix bug that returned a zip object instead of list
Fix bug that returned a zip object instead of list
Python
mit
meyersbs/uncertainty
e22886416b04d3900bed76c699bbfcdb20534ea2
semillas_backend/users/serializers.py
semillas_backend/users/serializers.py
#from phonenumber_field.serializerfields import PhoneNumberField from rest_framework import serializers from drf_extra_fields.geo_fields import PointField from .models import User class UserSerializer(serializers.ModelSerializer): """ Usage: from rest_framework.renderers import JSONRenderer from ...
#from phonenumber_field.serializerfields import PhoneNumberField from rest_framework import serializers from drf_extra_fields.geo_fields import PointField from .models import User class UserSerializer(serializers.ModelSerializer): """ Usage: from rest_framework.renderers import JSONRenderer from ...
Add is_staff to user serializer
Add is_staff to user serializer
Python
mit
Semillas/semillas_platform,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_backend,Semillas/semillas_backend
dd50adfa567f7be04b3c000508f3f649147be387
scripts/update_vv.py
scripts/update_vv.py
#!/usr/bin/env python import mica.vv mica.vv.update()
#!/usr/bin/env python import matplotlib matplotlib.use('Agg') import mica.vv mica.vv.update()
Set vv cron script to use Agg backend
Set vv cron script to use Agg backend
Python
bsd-3-clause
sot/mica,sot/mica
51854e2f437c3abc2a89d4e31e10aa6b36eef2e1
pylons/__init__.py
pylons/__init__.py
"""Base objects to be exported for use in Controllers""" from paste.registry import StackedObjectProxy from pylons.configuration import config __all__ = ['app_globals', 'cache', 'config', 'request', 'response', 'session', 'tmpl_context', 'url'] def __figure_version(): try: from pkg_resources i...
"""Base objects to be exported for use in Controllers""" # Import pkg_resources first so namespace handling is properly done so the # paste imports work import pkg_resources from paste.registry import StackedObjectProxy from pylons.configuration import config __all__ = ['app_globals', 'cache', 'config', 'request', '...
Handle namespacing properly so pylons imports without errors.
Handle namespacing properly so pylons imports without errors. --HG-- branch : trunk
Python
bsd-3-clause
Pylons/pylons,Pylons/pylons,moreati/pylons,Pylons/pylons,moreati/pylons,moreati/pylons
bc4486063325fc18bee00ba3ee8ba4e5e2323bee
doc/tools/make_cookbook.py
doc/tools/make_cookbook.py
""" Generate the rst files for the cookbook from the recipes. """ import sys import os body = r""" .. raw:: html [<a href="{code}">source code</a>] .. literalinclude:: {code} :language: python :linenos: """ def recipe_to_rst(recipe): """ Convert a .py recipe to a .rst entry for sphinx """ ...
""" Generate the rst files for the cookbook from the recipes. """ import sys import os body = r""" **Download** source code: :download:`{recipe}<{code}>` .. literalinclude:: {code} :language: python """ def recipe_to_rst(recipe): """ Convert a .py recipe to a .rst entry for sphinx """ sys.stderr...
Remove line numbers from recipe code
Remove line numbers from recipe code The larger font made the numbers not match the code. Added better link text to download the recipe.
Python
bsd-3-clause
santis19/fatiando,rafaelmds/fatiando,drandykass/fatiando,eusoubrasileiro/fatiando,eusoubrasileiro/fatiando,eusoubrasileiro/fatiando_seismic,fatiando/fatiando,eusoubrasileiro/fatiando_seismic,victortxa/fatiando,fatiando/fatiando,rafaelmds/fatiando,victortxa/fatiando,cmeessen/fatiando,santis19/fatiando,mtb-za/fatiando,eu...
bfbdf34e2efd1d22ee6f15f4655334764106725c
locksmith/lightauth/common.py
locksmith/lightauth/common.py
from locksmith.common import apicall try: from django.conf import settings SIGNING_KEY = settings.LOCKSMITH_SIGNING_KEY, API_NAME = settings.LOCKSMITH_API_NAME ENDPOINT = settings.LOCKSMITH_HUB_URL.replace('analytics', 'accounts') + 'checkkey/' except: SIGNING_KEY = "" API_NAME = "" ENDPOIN...
from locksmith.common import apicall import urllib2 try: from django.conf import settings SIGNING_KEY = settings.LOCKSMITH_SIGNING_KEY API_NAME = settings.LOCKSMITH_API_NAME ENDPOINT = settings.LOCKSMITH_HUB_URL.replace('analytics', 'accounts') + 'checkkey/' except: SIGNING_KEY = "" API_NAME = ...
Make client key checking actually work.
Make client key checking actually work.
Python
bsd-3-clause
sunlightlabs/django-locksmith,sunlightlabs/django-locksmith,sunlightlabs/django-locksmith
eecb3468b581b4854f2162c2b62ac06ea744045e
malcolm/core/attributemeta.py
malcolm/core/attributemeta.py
from collections import OrderedDict from malcolm.core.serializable import Serializable class AttributeMeta(Serializable): """Abstract base class for Meta objects""" # Type constants SCALAR = "scalar" TABLE = "table" SCALARARRAY = "scalar_array" def __init__(self, name, description, *args): ...
from collections import OrderedDict from malcolm.core.serializable import Serializable class AttributeMeta(Serializable): """Abstract base class for Meta objects""" def __init__(self, name, description, *args): super(AttributeMeta, self).__init__(name, *args) self.description = description ...
Remove unused AttributeMeta type constants
Remove unused AttributeMeta type constants
Python
apache-2.0
dls-controls/pymalcolm,dls-controls/pymalcolm,dls-controls/pymalcolm
a49a3c133478c01774adfe8853b608e110a5a2e6
examples/test_double_click.py
examples/test_double_click.py
from seleniumbase import BaseCase class MyTestClass(BaseCase): def test_double_click(self): self.open("https://www.w3schools.com/jsref" "/tryit.asp?filename=tryjsref_ondblclick") self.switch_to_frame("iframeResult") self.double_click('[ondblclick="myFunction()"]') ...
from seleniumbase import BaseCase class MyTestClass(BaseCase): def test_double_click_and_switch_to_frame(self): self.open("https://www.w3schools.com/jsref" "/tryit.asp?filename=tryjsref_ondblclick") self.ad_block() self.switch_to_frame("#iframeResult") self.doubl...
Update a test for entering iframes and double-clicking
Update a test for entering iframes and double-clicking
Python
mit
seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase
6d43df828cb34c8949c8f87c256bde2e6ccb7d3c
atamatracker/moviefile.py
atamatracker/moviefile.py
"""Movie module for atamaTracker """ import cv2 class Movie(object): """Movie file object. """ def __init__(self, file_path): self.__capture = cv2.VideoCapture(file_path) def __del__(self): self.__capture.release() def load_image(self, time_sec): """Load image at the de...
"""Movie module for atamaTracker """ import cv2 class Movie(object): """Movie file object. Public properties: fps (read-only) -- [float] frames per second width (read-only) -- [int] frame dimension height (read-only) -- [int] frame dimension """ def __init__(self, file_path): ca...
Add some useful read-only properties to Movie class
Add some useful read-only properties to Movie class
Python
mit
ptsg/AtamaTracker
0a7dfca0e4783abc24a6ec9d0bd9b84219593a1f
common/djangoapps/util/json_request.py
common/djangoapps/util/json_request.py
from functools import wraps import copy import json def expect_json(view_function): @wraps(view_function) def expect_json_with_cloned_request(request, *args, **kwargs): if request.META['CONTENT_TYPE'] == "application/json": cloned_request = copy.copy(request) cloned_request.POS...
from functools import wraps import copy import json def expect_json(view_function): @wraps(view_function) def expect_json_with_cloned_request(request, *args, **kwargs): # cdodge: fix postback errors in CMS. The POST 'content-type' header can include additional information # e.g. 'charset', so ...
Fix JSON postback error where the content-type header line can contain more info than just the application/json descriptor. Now we just to a compare on the start of the header value.
Fix JSON postback error where the content-type header line can contain more info than just the application/json descriptor. Now we just to a compare on the start of the header value.
Python
agpl-3.0
deepsrijit1105/edx-platform,waheedahmed/edx-platform,jamesblunt/edx-platform,pku9104038/edx-platform,prarthitm/edxplatform,rismalrv/edx-platform,kamalx/edx-platform,LICEF/edx-platform,miptliot/edx-platform,abdoosh00/edraak,RPI-OPENEDX/edx-platform,shubhdev/edxOnBaadal,mtlchun/edx,Ayub-Khan/edx-platform,rationalAgent/ed...
7af8ee5ca8a036ae2339187b689507989d43aaa6
elmo/moon_tracker/utils.py
elmo/moon_tracker/utils.py
def user_can_view_scans(user, moon): return ( user_can_delete_scans(user, moon) or user.has_perm('eve_sde.can_view_scans', moon.planet.system) or user.has_perm('eve_sde.can_view_scans', moon.planet.system.constellation) or user.has_perm('eve_sde.can_view_scans', moon.planet.system.co...
def user_can_view_scans(user, moon): return ( user_can_delete_scans(user, moon) or user.has_perm('eve_sde.sys_can_view_scans', moon.planet.system) or user.has_perm('eve_sde.con_can_view_scans', moon.planet.system.constellation) or user.has_perm('eve_sde.reg_can_view_scans', moon.plan...
Update the permission helper functions.
Update the permission helper functions.
Python
mit
StephenSwat/eve_lunar_mining_organiser,StephenSwat/eve_lunar_mining_organiser
184cc6448a7bed4c945b0c5cb1e3739c3fb9c7f8
examples/list_vmss_pips.py
examples/list_vmss_pips.py
import azurerm import json import sys # check for single command argument if len(sys.argv) == 3: rg = sys.argv[1] vmss = sys.argv[2] else: sys.exit('Expecting resource group name and vmss name as arguments.') # Load Azure app defaults try: with open('azurermconfig.json') as configFile: c...
import argparse import azurerm import json import re import sys # validate command line arguments argParser = argparse.ArgumentParser() argParser.add_argument('--vmssname', '-n', required=True, action='store', help='VMSS Name') argParser.add_argument('--rgname', '-g', required=True, ...
Improve list VMSS public IP example
Improve list VMSS public IP example
Python
mit
gbowerman/azurerm
cc7b8f5dc95d09af619e588aea8042376be6edfc
secondhand/urls.py
secondhand/urls.py
from django.conf.urls import patterns, include, url from tastypie.api import Api from tracker.api import UserResource, TaskResource, WorkSessionResource, \ ApiTokenResource from tracker.views import SignupView # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscov...
from django.conf.urls import patterns, include, url from tastypie.api import Api from tracker.api import TaskResource, WorkSessionResource, \ ApiTokenResource, ProjectResource from tracker.views import SignupView # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodis...
Remove UserResource from the API and add ProjectResource.
Remove UserResource from the API and add ProjectResource.
Python
mit
GeneralMaximus/secondhand
f840af6621fd63dd9021fcb68a32ba14c925fcf7
wellknown/models.py
wellknown/models.py
from django.db import models from django.db.models.signals import post_save import mimetypes import wellknown # # create default host-meta handler # from wellknown.resources import HostMeta wellknown.register('host-meta', handler=HostMeta(), content_type='application/xrd+xml') # # resource model # class Resource(mo...
from django.db import models from django.db.models.signals import post_save import mimetypes import wellknown # # create default host-meta handler # from wellknown.resources import HostMeta try: wellknown.register('host-meta', handler=HostMeta(), content_type='application/xrd+xml') except ...
Check for an existing handler before registering default host-meta handler.
Check for an existing handler before registering default host-meta handler.
Python
bsd-3-clause
jcarbaugh/django-wellknown
06ead54d0d4b93038df32cbbe622ea5f5fc8288a
boardinghouse/__init__.py
boardinghouse/__init__.py
""" """ __version__ = '0.1' __release__ = '0.1a3' def inject_app_defaults(): """ Automatically inject the default settings for this app. If settings has already been configured, then we need to add our defaults to that (if not overridden), and in all cases we also want to inject our settings i...
""" """ __version__ = '0.2' __release__ = '0.2a1' def inject_app_defaults(): """ Automatically inject the default settings for this app. If settings has already been configured, then we need to add our defaults to that (if not overridden), and in all cases we also want to inject our settings into ...
Bump version number (so readthedocs picks it up).
Bump version number (so readthedocs picks it up).
Python
bsd-3-clause
luzfcb/django-boardinghouse,luzfcb/django-boardinghouse,luzfcb/django-boardinghouse
693b904a9053fbddc6c93cfab1d6448c4b644d1c
scripts/travis_build_dependent_projects.py
scripts/travis_build_dependent_projects.py
# -*- coding: utf-8 -*- import os from click import echo from travispy import travispy from travispy import TravisPy def main(): restarted = [] building = [] for domain in [travispy.PUBLIC, travispy.PRIVATE]: echo("Enumerate repos on {!r}".format(domain)) conn = TravisPy.github_auth(o...
# -*- coding: utf-8 -*- import os from click import echo from travispy import travispy from travispy import TravisPy def main(): restarted = [] building = [] for domain in [travispy.PUBLIC, travispy.PRIVATE]: echo("Enumerate repos on {!r}".format(domain)) conn = TravisPy.github_auth(o...
Fix Travis dependant build trigger
Fix Travis dependant build trigger
Python
mit
dgnorth/drift,dgnorth/drift,dgnorth/drift
aed4ddb9cd50baf318822830ba49d5b994e4e518
youmap/views.py
youmap/views.py
from django.views.generic import TemplateView from chickpea.models import Map class Home(TemplateView): template_name = "youmap/home.html" list_template_name = "chickpea/map_list.html" def get_context_data(self, **kwargs): maps = Map.objects.all()[:100] return { "maps": maps ...
from django.views.generic import TemplateView from chickpea.models import Map class Home(TemplateView): template_name = "youmap/home.html" list_template_name = "chickpea/map_list.html" def get_context_data(self, **kwargs): maps = Map.objects.order_by('-modified_at')[:100] return { ...
Order map by modified_at desc in list
Order map by modified_at desc in list
Python
agpl-3.0
diraol/umap
42339932811493bdd398fda4f7a2322a94bdc2e9
saleor/shipping/migrations/0018_default_zones_countries.py
saleor/shipping/migrations/0018_default_zones_countries.py
# Generated by Django 3.0.6 on 2020-06-05 14:35 from django.db import migrations from ..utils import get_countries_without_shipping_zone def assign_countries_in_default_shipping_zone(apps, schema_editor): ShippingZone = apps.get_model("shipping", "ShippingZone") qs = ShippingZone.objects.filter(default=True...
# Generated by Django 3.0.6 on 2020-06-05 14:35 from django.db import migrations from django_countries import countries def get_countries_without_shipping_zone(ShippingZone): """Return countries that are not assigned to any shipping zone.""" covered_countries = set() for zone in ShippingZone.objects.all(...
Move utility function to migration
Move utility function to migration
Python
bsd-3-clause
mociepka/saleor,mociepka/saleor,mociepka/saleor
208c17449b42dc7d87ac24a04675612e17a31984
sierra_adapter/s3_demultiplexer/src/s3_demultiplexer.py
sierra_adapter/s3_demultiplexer/src/s3_demultiplexer.py
# -*- encoding: utf-8 -*- import json import os import boto3 from wellcome_aws_utils import s3_utils, sns_utils def main(event, _): print(f'event = {event!r}') topic_arn = os.environ["TOPIC_ARN"] s3_events = s3_utils.parse_s3_record(event=event) assert len(s3_events) == 1 s3_event = s3_events...
# -*- encoding: utf-8 -*- """ We have a sierra_reader that reads records from Sierra, and uploads them to files in S3. Each file in S3 contains multiple records. Our downstream applications want to process records one at a time, so this demultiplexer receives the event stream of PUTs from S3, and splits each file int...
Add a comment explaining the purpose of the demultiplexer
Add a comment explaining the purpose of the demultiplexer
Python
mit
wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api
8f93bad77371fbc0d7dc75548472c7715eb8a2ee
climlab/tests/test_rcm.py
climlab/tests/test_rcm.py
from __future__ import division import numpy as np import climlab import pytest @pytest.fixture() def rcm(): # initial state (temperatures) state = climlab.column_state(num_lev=num_lev, num_lat=1, water_depth=5.) ## Create individual physical process models: # fixed relative humidity h2o = climlab...
from __future__ import division import numpy as np import climlab import pytest @pytest.fixture() def rcm(): # initial state (temperatures) state = climlab.column_state(num_lev=num_lev, num_lat=1, water_depth=5.) ## Create individual physical process models: # fixed relative humidity h2o = climlab...
Mark rcm test as fast so it executes during build and test
Mark rcm test as fast so it executes during build and test
Python
mit
cjcardinale/climlab,cjcardinale/climlab,brian-rose/climlab,cjcardinale/climlab,brian-rose/climlab
2fff4600d701d6f5ac9675d96916ca74cf3cfdbd
riker/worker/apps.py
riker/worker/apps.py
from __future__ import unicode_literals from django.apps import AppConfig from worker.utils import LircListener class WorkerConfig(AppConfig): name = 'worker' def ready(self): lirc_name = getattr(settings, 'RIKER_LIRC_LISTENER_NAME', 'riker') LircListener(lirc_name=lirc_name).start()
from __future__ import unicode_literals from django.apps import AppConfig from worker.utils import LircListener class WorkerConfig(AppConfig): name = 'worker'
Remove prematurely inserted 'ready' method
Remove prematurely inserted 'ready' method
Python
mit
haikuginger/riker
93149023bb28319d05213a122c7f4e59a8589e38
pirx/base.py
pirx/base.py
import collections class Settings(object): def __init__(self): self._settings = collections.OrderedDict() def __setattr__(self, name, value): if name.startswith('_'): super(Settings, self).__setattr__(name, value) else: self._settings[name] = value def __s...
import collections import datetime class Settings(object): docstring = 'Settings built with Pirx on %(datetime)s' def __init__(self): self._settings = collections.OrderedDict() docstring = self.docstring % { 'datetime': datetime.datetime.now() } self._set_raw_v...
Insert customizable docstring at the beginning of settings file
Insert customizable docstring at the beginning of settings file
Python
mit
piotrekw/pirx
749219a1282a347133ba73127ed7cc8d8009897d
anchore_engine/clients/syft_wrapper.py
anchore_engine/clients/syft_wrapper.py
import json import os import shlex from anchore_engine.utils import run_check def run_syft(image): proc_env = os.environ.copy() syft_env = { "SYFT_CHECK_FOR_APP_UPDATE": "0", "SYFT_LOG_STRUCTURED": "1", } proc_env.update(syft_env) cmd = "syft -vv -o json oci-dir:{image}".format...
import json import os import shlex from anchore_engine.utils import run_check def run_syft(image): proc_env = os.environ.copy() syft_env = { "SYFT_CHECK_FOR_APP_UPDATE": "0", "SYFT_LOG_STRUCTURED": "1", } proc_env.update(syft_env) cmd = "syft -vv -o json oci-dir:{image}".format...
Make the syft invocation only log the full output at spew level instead of debug.
Make the syft invocation only log the full output at spew level instead of debug. The syft json output for very large images can be 100s of MB and cause the analyzer to be unusable due to the logging itself. This changes that call to only dump output at "spew" level logging. Signed-off-by: Zach Hill <9de8c4480303b533...
Python
apache-2.0
anchore/anchore-engine,anchore/anchore-engine,anchore/anchore-engine
a800bacf217ef903fd266e1fbf8103365ab64c94
source/segue/frontend/exporter.py
source/segue/frontend/exporter.py
# :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. from PySide import QtGui from .selector import SelectorWidget from .options import OptionsWidget class ExporterWidget(QtGui.QWidget): '''Manage exporting.''' def __init__(self, host, parent=None): ...
# :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. from PySide import QtGui from .selector import SelectorWidget from .options import OptionsWidget class ExporterWidget(QtGui.QWidget): '''Manage exporting.''' def __init__(self, host, parent=None): ...
Add basic validation of ui state.
Add basic validation of ui state.
Python
apache-2.0
4degrees/segue
73e5fe29074f52e0b769fd2a6c40669040bef330
app/notify_client/invite_api_client.py
app/notify_client/invite_api_client.py
from notifications_python_client.base import BaseAPIClient from app.notify_client.models import User class InviteApiClient(BaseAPIClient): def __init__(self, base_url=None, client_id=None, secret=None): super(self.__class__, self).__init__(base_url=base_url or 'base_url', ...
from notifications_python_client.base import BaseAPIClient from app.notify_client.models import User class InviteApiClient(BaseAPIClient): def __init__(self, base_url=None, client_id=None, secret=None): super(self.__class__, self).__init__(base_url=base_url or 'base_url', ...
Change cancel_invited_user client to not return anything.
Change cancel_invited_user client to not return anything.
Python
mit
alphagov/notifications-admin,gov-cjwaszczuk/notifications-admin,alphagov/notifications-admin,gov-cjwaszczuk/notifications-admin,gov-cjwaszczuk/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,gov-cjwaszczuk/notifications-admin
6fc304f21d762d692188057fcded195fa6c5675a
test/test_amqp_message.py
test/test_amqp_message.py
import unittest from amqp import Message from mock import patch from sir.amqp.message import (InvalidMessageContentException, Message as PMessage, MESSAGE_TYPES) class AmqpMessageTest(unittest.TestCase): @staticmethod def _parsed_message(body="artis...
import unittest from amqp import Message from mock import patch from sir.amqp.message import (InvalidMessageContentException, Message as PMessage, MESSAGE_TYPES) class AmqpMessageTest(unittest.TestCase): @staticmethod def _parsed_message(body="artis...
Remove a reference to search.update
Remove a reference to search.update
Python
mit
jeffweeksio/sir