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
acbace21652d45a5fb17bbb487692ab6057313df
api/parsers/datanasa.py
api/parsers/datanasa.py
import json from flaskext.mongoalchemy import MongoAlchemy import requests from api import app from api import db ENDPOINT = 'http://data.nasa.gov/api/' class Dataset(db.Document): """ Represents a dataset, we could split this out to hold all the actual data, slug, url, title, etc """ remote_id ...
import json from flaskext.mongoalchemy import BaseQuery import requests from api import app from api import db ENDPOINT = 'http://data.nasa.gov/api/' class DatasetQuery(BaseQuery): def get_by_remote_id(self, pk): return self.filter(self.type.remote_id==pk) class Dataset(db.Document): """ Represen...
Define a query on Dataset to retrive them by remote id
Define a query on Dataset to retrive them by remote id
Python
mit
oxford-space-apps/open-data-api
044f1169b518628c8409a38845ffa5c18b7cb748
packs/clicrud/actions/config_command.py
packs/clicrud/actions/config_command.py
# encoding: utf-8 from st2actions.runners.pythonrunner import Action from clicrud.device.generic import generic import sys class ConfigCommand(Action): def run(self, host, command, save): self.method = self.config['method'] self.username = self.config['username'] self.password = self.conf...
# encoding: utf-8 from st2actions.runners.pythonrunner import Action from clicrud.device.generic import generic import sys class ConfigCommand(Action): def run(self, host, command, save): self.method = self.config['method'] self.username = self.config['username'] self.password = self.conf...
Use finally so connection is also closed on exception.
Use finally so connection is also closed on exception.
Python
apache-2.0
StackStorm/st2contrib,StackStorm/st2contrib,StackStorm/st2contrib
43291c827d2d7b0a350971b2efa26ca9e1c1e593
src/sentry/api/endpoints/system_health.py
src/sentry/api/endpoints/system_health.py
from __future__ import absolute_import import itertools from rest_framework.response import Response from sentry import status_checks from sentry.api.base import Endpoint from sentry.api.permissions import SuperuserPermission class SystemHealthEndpoint(Endpoint): permission_classes = (SuperuserPermission,) ...
from __future__ import absolute_import import itertools from hashlib import md5 from rest_framework.response import Response from sentry import status_checks from sentry.api.base import Endpoint from sentry.api.permissions import SuperuserPermission class SystemHealthEndpoint(Endpoint): permission_classes = (S...
Add `id` to `SystemHealthEndpoint` response.
Add `id` to `SystemHealthEndpoint` response.
Python
bsd-3-clause
gencer/sentry,zenefits/sentry,looker/sentry,alexm92/sentry,JackDanger/sentry,zenefits/sentry,alexm92/sentry,ifduyue/sentry,ifduyue/sentry,beeftornado/sentry,fotinakis/sentry,jean/sentry,JamesMura/sentry,BuildingLink/sentry,mvaled/sentry,BuildingLink/sentry,mvaled/sentry,mvaled/sentry,mvaled/sentry,JamesMura/sentry,beef...
f617c1ce192739594c161f717d5d04cc17ede22e
distarray/local/tests/paralleltest_io.py
distarray/local/tests/paralleltest_io.py
import tempfile import h5py from numpy.testing import assert_allclose from os import path from distarray.local import LocalArray, save, load, save_hdf5 from distarray.testing import comm_null_passes, MpiTestCase class TestFlatFileIO(MpiTestCase): @comm_null_passes def test_flat_file_read_write(self): ...
import tempfile from numpy.testing import assert_allclose from os import path from distarray.local import LocalArray, save, load, save_hdf5 from distarray.testing import comm_null_passes, MpiTestCase class TestFlatFileIO(MpiTestCase): @comm_null_passes def test_flat_file_read_write(self): larr0 = Loc...
Move h5py import into HDF test.
Move h5py import into HDF test.
Python
bsd-3-clause
RaoUmer/distarray,enthought/distarray,RaoUmer/distarray,enthought/distarray
80d0ba5716d4b6cdef1c5d64a670abfa59f81557
bin/verify_cached_graphs.py
bin/verify_cached_graphs.py
#!/usr/bin/env python import sys from pprint import pprint as pp from cc.payment import flow def verify(): for ignore_balances in (True, False): cached = flow.get_cached_graph(ignore_balances) if not cached: continue graph = flow.build_graph(ignore_balances) diff = com...
#!/usr/bin/env python import sys from pprint import pprint as pp from cc.payment import flow def verify(): for ignore_balances in (True, False): graph = flow.build_graph(ignore_balances) cached = flow.get_cached_graph(ignore_balances) if not cached: flow.set_cached_graph(graph...
Load cached graph in verify cached graphs tool if not already present.
Load cached graph in verify cached graphs tool if not already present.
Python
agpl-3.0
rfugger/villagescc,rfugger/villagescc,rfugger/villagescc,rfugger/villagescc
610eeb064ba95e79617650d939ae5e9110b6ab89
restlib2/structures.py
restlib2/structures.py
import re class AttrDict(object): "A case-insensitive attribute accessible dict-like object" def __init__(self, name, *args, **kwargs): for key, value in dict(*args, **kwargs).iteritems(): if not isinstance(key, basestring) or not key: raise TypeError('attribute names must ...
import re class AttrDict(object): "A case-insensitive attribute accessible dict-like object" def __init__(self, name, *args, **kwargs): self.name = name for key, value in dict(*args, **kwargs).iteritems(): if not isinstance(key, basestring) or not key: raise TypeEr...
Add missing assignment of name in constructor
Add missing assignment of name in constructor
Python
bsd-2-clause
bruth/restlib2
373d5d55279695ead6b83fb99824a3249416697f
auditlog/__openerp__.py
auditlog/__openerp__.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 ABF OSIELL (<http://osiell.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU ...
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 ABF OSIELL (<http://osiell.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU ...
Add OCA as author of OCA addons
Add OCA as author of OCA addons In order to get visibility on https://www.odoo.com/apps the OCA board has decided to add the OCA as author of all the addons maintained as part of the association.
Python
agpl-3.0
YannickB/server-tools,YannickB/server-tools,OCA/server-tools,YannickB/server-tools,OCA/server-tools,OCA/server-tools
3535ea637112ef21fefd8df811721d271c109581
salt/runners/manage.py
salt/runners/manage.py
''' General management functions for salt, tools like seeing what hosts are up and what hosts are down ''' # Import salt modules import salt.client import salt.cli.key def down(): ''' Print a list of all the down or unresponsive salt minions ''' client = salt.client.LocalClient(__opts__['config']) ...
''' General management functions for salt, tools like seeing what hosts are up and what hosts are down ''' # Import salt modules import salt.client import salt.cli.key def down(): ''' Print a list of all the down or unresponsive salt minions ''' client = salt.client.LocalClient(__opts__['config']) ...
Add an "up" to list all "up" minions
Add an "up" to list all "up" minions
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
c34960e07ccce749a7fb5e53ff7593b87fe453d7
sazabi/plugins/joke.py
sazabi/plugins/joke.py
import requests from random import choice from sazabi.types import SazabiBotPlugin class Joke(SazabiBotPlugin): async def parse(self, client, message, *args, **kwargs): if message.content == "~joke": response = requests.get('https://www.reddit.com/r/oneliners/new.json').json() if ...
import requests from random import choice from sazabi.types import SazabiBotPlugin class Joke(SazabiBotPlugin): async def parse(self, client, message, *args, **kwargs): if message.content == "~joke": response = requests.get( 'https://www.reddit.com/r/oneliners/new.json', ...
Add user agent to reddit request
Add user agent to reddit request
Python
mit
frankzhao/sazabi,frankzhao/sazabi
dd1e6cdf2f6f040f532863549df606083f3f4bf2
utils/gyb_syntax_support/protocolsMap.py
utils/gyb_syntax_support/protocolsMap.py
SYNTAX_BUILDABLE_EXPRESSIBLE_AS_CONFORMANCES = { 'ExpressibleAsConditionElement': [ 'ExpressibleAsConditionElementList' ], 'ExpressibleAsDeclBuildable': [ 'ExpressibleAsCodeBlockItem', 'ExpressibleAsMemberDeclListItem', 'ExpressibleAsSyntaxBuildable' ], 'ExpressibleAs...
SYNTAX_BUILDABLE_EXPRESSIBLE_BY_CONFORMANCES = { 'ExpressibleByConditionElement': [ 'ExpressibleByConditionElementList' ], 'ExpressibleByDeclBuildable': [ 'ExpressibleByCodeBlockItem', 'ExpressibleByMemberDeclListItem', 'ExpressibleBySyntaxBuildable' ], 'ExpressibleBy...
Replace ExpressibleAs protocols by ExpressibleBy protocols
[SwiftSyntax] Replace ExpressibleAs protocols by ExpressibleBy protocols The protocols in the standard library are called `ExpressibleBy*` and SwiftSyntax should follow the same naming convention.
Python
apache-2.0
JGiola/swift,apple/swift,gregomni/swift,atrick/swift,roambotics/swift,benlangmuir/swift,atrick/swift,roambotics/swift,ahoppen/swift,glessard/swift,apple/swift,ahoppen/swift,gregomni/swift,gregomni/swift,glessard/swift,atrick/swift,benlangmuir/swift,apple/swift,roambotics/swift,glessard/swift,benlangmuir/swift,gregomni/...
3642fefbb1d4b5f2aeead54135ac37f0a5b635cd
tests/general.py
tests/general.py
import unittest from app import create_app, configure_settings, db class AppTestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.app_ctx = self.app.app_context() self.app_ctx.push() db.create_all() configure_settings(self.app) def tearDo...
import unittest from app import create_app, db class AppTestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.app_ctx = self.app.app_context() self.app_ctx.push() db.create_all() # Temporary. Will be removed once default settings has been set...
Add placeholder settings to unit tests
Add placeholder settings to unit tests
Python
mit
Encrylize/flask-blogger,Encrylize/flask-blogger,Encrylize/flask-blogger
4377cb01932fb6cb9d324f98c55b4467e803add5
tests/test_go.py
tests/test_go.py
# -*- coding: utf-8 -*- import mock import completor from completor.compat import to_unicode from completers.go import Go # noqa def test_format_cmd(vim_mod): vim_mod.funcs['line2byte'] = mock.Mock(return_value=20) vim_mod.funcs['completor#utils#tempname'] = mock.Mock( return_value=b'/tmp/vJBio2A/2....
# -*- coding: utf-8 -*- import mock import completor from completor.compat import to_unicode from completers.go import Go # noqa def test_format_cmd(vim_mod): vim_mod.funcs['line2byte'] = mock.Mock(return_value=20) vim_mod.funcs['completor#utils#tempname'] = mock.Mock( return_value=b'/tmp/vJBio2A/2....
Fix test for go completor.
Fix test for go completor.
Python
mit
maralla/completor.vim,maralla/completor.vim
bd170dc4ce58c78213ea5dc7c9d779ad914762bb
social_core/tests/backends/test_udata.py
social_core/tests/backends/test_udata.py
import json from six.moves.urllib_parse import urlencode from .oauth import OAuth2Test class DatagouvfrOAuth2Test(OAuth2Test): backend_path = 'social_core.backends.udata.DatagouvfrOAuth2' user_data_url = 'https://www.data.gouv.fr/api/1/me/' expected_username = 'foobar' access_token_body = json.dumps...
import json from six.moves.urllib_parse import urlencode from .oauth import OAuth2Test class DatagouvfrOAuth2Test(OAuth2Test): backend_path = 'social_core.backends.udata.DatagouvfrOAuth2' user_data_url = 'https://www.data.gouv.fr/api/1/me/' expected_username = 'foobar' access_token_body = json.dumps...
Fix tests for udata/datagouvfr backend
Fix tests for udata/datagouvfr backend
Python
bsd-3-clause
python-social-auth/social-core,python-social-auth/social-core
83020d996733b5376cfa5814ca81c8f823029346
tests/run/pyclass_annotations_pep526.py
tests/run/pyclass_annotations_pep526.py
# cython: language_level=3 # mode: run # tag: pure3.7, pep526, pep484 from __future__ import annotations try: from typing import ClassVar except ImportError: # Py<=3.5 ClassVar = {int: int} class PyAnnotatedClass: """ >>> PyAnnotatedClass.__annotations__["CLASS_VAR"] 'ClassVar[int]' >>> PyA...
# cython: language_level=3 # mode: run # tag: pure3.7, pep526, pep484 from __future__ import annotations import sys try: from typing import ClassVar except ImportError: # Py<=3.5 ClassVar = {int: int} class PyAnnotatedClass: """ >>> PyAnnotatedClass.__annotations__["CLASS_VAR"] 'ClassVar[int]'...
Repair a Python compatibility test in Py3.10.
Repair a Python compatibility test in Py3.10.
Python
apache-2.0
scoder/cython,scoder/cython,scoder/cython,da-woods/cython,cython/cython,cython/cython,da-woods/cython,cython/cython,da-woods/cython,da-woods/cython,scoder/cython,cython/cython
1517bb31a8ec0d5df96e2693977081b3d1a64f69
tests/integration/minion/test_timeout.py
tests/integration/minion/test_timeout.py
# -*- coding: utf-8 -*- ''' Tests for various minion timeouts ''' # Import Python libs from __future__ import absolute_import import os import sys import salt.utils # Import Salt Testing libs from tests.support.case import ShellCase class MinionTimeoutTestCase(ShellCase): ''' Test minion timing functions ...
# -*- coding: utf-8 -*- ''' Tests for various minion timeouts ''' # Import Python libs from __future__ import absolute_import import os import sys import salt.utils.platform # Import Salt Testing libs from tests.support.case import ShellCase class MinionTimeoutTestCase(ShellCase): ''' Test minion timing fu...
Update old utils paths to use new paths
Update old utils paths to use new paths
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
4ffd42f132769b23ee93c8a5c3416877c772d47e
doc_builder/backends/pdf.py
doc_builder/backends/pdf.py
import re import os from django.conf import settings from doc_builder.base import BaseBuilder from projects.utils import run latex_re = re.compile('the LaTeX files are in (.*)\.') pdf_re = re.compile('Output written on (.*?)') class Builder(BaseBuilder): def build(self, project): self._cd_makefile(proj...
import re import os from django.conf import settings from doc_builder.base import BaseBuilder from projects.utils import run latex_re = re.compile('the LaTeX files are in (.*)\.') pdf_re = re.compile('Output written on (.*?)') class Builder(BaseBuilder): def build(self, project): self._cd_makefile(proj...
Move instead of symlink because we blow that dir away.
Move instead of symlink because we blow that dir away.
Python
mit
wanghaven/readthedocs.org,LukasBoersma/readthedocs.org,clarkperkins/readthedocs.org,CedarLogic/readthedocs.org,nyergler/pythonslides,d0ugal/readthedocs.org,sunnyzwh/readthedocs.org,soulshake/readthedocs.org,mhils/readthedocs.org,johncosta/private-readthedocs.org,nikolas/readthedocs.org,ojii/readthedocs.org,KamranMackey...
9937823496db32a4d3eac3eee0fa4d310ea07e11
dvhb_hybrid/files/models.py
dvhb_hybrid/files/models.py
import uuid from django.conf import settings from django.contrib.postgres.fields import JSONField from django.db import models from django.utils.translation import ugettext_lazy as _ from ..models import UpdatedMixin from .storages import image_storage class Image(UpdatedMixin, models.Model): author = models.Fo...
import uuid from django.conf import settings from django.contrib.postgres.fields import JSONField from django.contrib.postgres.indexes import GinIndex from django.db import models from django.utils.translation import ugettext_lazy as _ from ..models import UpdatedMixin from .storages import image_storage class Imag...
Add index for image metainformation
Add index for image metainformation
Python
mit
dvhbru/dvhb-hybrid
2d9e7843106b2fce247dda8f14bc192c3d98e91f
tests/test_simpleflow.py
tests/test_simpleflow.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from simpleflow import simpleflow def test_basic(): assert 0, 'write me!'
#!/usr/bin/env python # -*- coding: utf-8 -*- def test_basic(): import simpleflow assert True
Add basic test that only import simpleflow
Add basic test that only import simpleflow
Python
mit
botify-labs/simpleflow,botify-labs/simpleflow
6093d2954861f2783da3e5b8473cb13b0469685b
elasticquery/filterquery.py
elasticquery/filterquery.py
# ElasticQuery # File: elasticquery/filterquery.py # Desc: The base query class & metaclass import json from .util import make_dsl_object, unroll_definitions, unroll_struct class MetaFilterQuery(type): def __init__(cls, name, bases, d): super(MetaFilterQuery, cls).__init__(name, bases, d) unroll...
# ElasticQuery # File: elasticquery/filterquery.py # Desc: The base query class & metaclass import json from .util import make_dsl_object, unroll_definitions, unroll_struct class MetaFilterQuery(type): def __init__(cls, name, bases, d): super(MetaFilterQuery, cls).__init__(name, bases, d) unroll...
Support nosetests, handle magic names (and_, or_, etc)
Support nosetests, handle magic names (and_, or_, etc)
Python
mit
Fizzadar/ElasticQuery,Fizzadar/ElasticQuery
51f0cd392cab5737cb444b9eef8700fcd4713ea0
tests/recipes_test.py
tests/recipes_test.py
#!/usr/bin/env python # Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Runs simulation tests and lint on the recipes.""" import os import subprocess ROOT_DIR = os.path.dirname(os.path.dirname(os.p...
#!/usr/bin/env python # Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Runs simulation tests and lint on the recipes.""" import os import subprocess ROOT_DIR = os.path.dirname(os.path.dirname(os.p...
Remove deprecated (ignored) --use-bootstrap flag
[recipes] Remove deprecated (ignored) --use-bootstrap flag This has been ignored for a long time, and I'd like to get rid of it. R=jchinlee@chromium.org, ef4933a197ef7b4b3f55f1bec4942aead3637a2a@chromium.org Change-Id: I240d59cc10a2882041ac2c8abfeb1894237516a6 Reviewed-on: https://chromium-review.googlesource.com/c/...
Python
bsd-3-clause
CoherentLabs/depot_tools,CoherentLabs/depot_tools
df68b821807d25d204f43d7b1805da6c25f42b43
src/lib/pagination.py
src/lib/pagination.py
from collections import OrderedDict from django.utils.translation import ugettext_lazy as _ from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response class LegacyPaginator(PageNumberPagination): """ A legacy paginator that mocks the one from Eve Python """ ...
from collections import OrderedDict from django.utils.translation import ugettext_lazy as _ from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response class LegacyPaginator(PageNumberPagination): """ A legacy paginator that mocks the one from Eve Python """ ...
Set a maximum to the number of elements that may be requested
Set a maximum to the number of elements that may be requested
Python
agpl-3.0
lafranceinsoumise/api-django,lafranceinsoumise/api-django,lafranceinsoumise/api-django,lafranceinsoumise/api-django
f659e612f87ccb2a9d466ae62ed8f2b2700497ab
cms/tests/test_externals.py
cms/tests/test_externals.py
from django.test import TestCase from ..externals import External try: from contextlib import GeneratorContextManager except ImportError: from contextlib import _GeneratorContextManager as GeneratorContextManager from types import FunctionType class TestExternals(TestCase): def test_load(self): ...
from django.test import TestCase from django.utils import six from ..externals import External from types import FunctionType import unittest class TestExternals(TestCase): def test_load(self): external = External('foo') with self.assertRaises(ImportError): external._load('') ...
Disable an externals tests on Py3.
Disable an externals tests on Py3.
Python
bsd-3-clause
dan-gamble/cms,jamesfoley/cms,danielsamuels/cms,lewiscollard/cms,dan-gamble/cms,lewiscollard/cms,dan-gamble/cms,lewiscollard/cms,jamesfoley/cms,jamesfoley/cms,danielsamuels/cms,danielsamuels/cms,jamesfoley/cms
658f0f6825b4f4a226349fcee63a0c5fbbd5ba9e
webapp/cached.py
webapp/cached.py
from datetime import datetime, timedelta import os class cached(object): def __init__(self, *args, **kwargs): self.cached_function_responses = {} self.default_max_age = kwargs.get("default_cache_max_age", timedelta(seconds=int(os.environ['CACHE_AGE']))) def __call__(self, func): def i...
from datetime import datetime, timedelta import os class cached(object): def __init__(self, *args, **kwargs): self.cached_function_responses = {} self.default_max_age = kwargs.get("default_cache_max_age", timedelta(seconds=int(os.environ['CACHE_AGE']))) def __call__(self, func): def i...
Use ternary operator for arg selection.
Use ternary operator for arg selection.
Python
mit
cheddartv/stockstream.live,cheddartv/stockstream.live
45fb01574d410c2a764e5b40a5e93a44fa8f6584
flask_admin/contrib/geoa/form.py
flask_admin/contrib/geoa/form.py
from flask.ext.admin.model.form import converts from flask.ext.admin.contrib.sqla.form import AdminModelConverter as SQLAAdminConverter from .fields import GeoJSONField class AdminModelConverter(SQLAAdminConverter): @converts('Geometry') def convert_geom(self, column, field_args, **extra): field_args[...
from flask.ext.admin.model.form import converts from flask.ext.admin.contrib.sqla.form import AdminModelConverter as SQLAAdminConverter from .fields import GeoJSONField class AdminModelConverter(SQLAAdminConverter): @converts('Geography', 'Geometry') def convert_geom(self, column, field_args, **extra): ...
Add Geography Type to GeoAlchemy Backend
Add Geography Type to GeoAlchemy Backend The current GeoAlchemy backend only works with geometry columns, and ignores geography columns (which are also supported by geoalchemy). This 1-word fix adds support for geography columns.
Python
bsd-3-clause
litnimax/flask-admin,petrus-jvrensburg/flask-admin,closeio/flask-admin,torotil/flask-admin,jmagnusson/flask-admin,marrybird/flask-admin,dxmo/flask-admin,ondoheer/flask-admin,plaes/flask-admin,LennartP/flask-admin,jamesbeebop/flask-admin,NickWoodhams/flask-admin,closeio/flask-admin,CoolCloud/flask-admin,radioprotector/f...
577ec0c981651cb039f768b9eb92ef91f8511017
flocker/control/_clusterstate.py
flocker/control/_clusterstate.py
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Combine and retrieve current cluster state. """ from twisted.application.service import Service from ._model import Deployment, Node class ClusterStateService(Service): """ Store known current cluster state, and combine partial updates with ...
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Combine and retrieve current cluster state. """ from twisted.application.service import Service from ._model import Deployment, Node class ClusterStateService(Service): """ Store known current cluster state, and combine partial updates with ...
Address review comment: Document return type.
Address review comment: Document return type.
Python
apache-2.0
agonzalezro/flocker,Azulinho/flocker,LaynePeng/flocker,runcom/flocker,achanda/flocker,jml/flocker,1d4Nf6/flocker,mbrukman/flocker,jml/flocker,adamtheturtle/flocker,lukemarsden/flocker,moypray/flocker,achanda/flocker,w4ngyi/flocker,LaynePeng/flocker,mbrukman/flocker,w4ngyi/flocker,1d4Nf6/flocker,achanda/flocker,Azulinho...
02f5db5fdb46684b60a9b5e9125da228a927c2c3
mrbelvedereci/build/cumulusci/config.py
mrbelvedereci/build/cumulusci/config.py
from cumulusci.core.config import YamlGlobalConfig from cumulusci.core.config import YamlProjectConfig class MrbelvedereProjectConfig(YamlProjectConfig): def __init__(self, global_config_obj, build_flow): super(MrbelvedereProjectConfig, self).__init__(global_config_obj) self.build_flow = build_flow...
from cumulusci.core.config import YamlGlobalConfig from cumulusci.core.config import YamlProjectConfig class MrbelvedereProjectConfig(YamlProjectConfig): def __init__(self, global_config_obj, build_flow): self.build_flow = build_flow super(MrbelvedereProjectConfig, self).__init__(global_config_obj)...
Set self.build_flow before calling the super __init__ method
Set self.build_flow before calling the super __init__ method
Python
bsd-3-clause
SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci
c8d7224f62d7a8da08514c37acfa83e2754252c6
functionaltests/api/base.py
functionaltests/api/base.py
# -*- coding: utf-8 -*- # # Copyright 2013 - Noorul Islam K M # # 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 applic...
# -*- coding: utf-8 -*- # # Copyright 2013 - Noorul Islam K M # # 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 applic...
Fix Tempest tests failing on gate-solum-devstack-dsvm
Fix Tempest tests failing on gate-solum-devstack-dsvm Due to a new commit on tempest, all our devstack tests were failing. This was due to an inheritance we have to RestClient from tempest. The signature of the constructor has changed. This patch changes the signature of our inherited classes to match the change from...
Python
apache-2.0
ed-/solum,julienvey/solum,devdattakulkarni/test-solum,openstack/solum,stackforge/solum,gilbertpilz/solum,gilbertpilz/solum,ed-/solum,devdattakulkarni/test-solum,gilbertpilz/solum,openstack/solum,stackforge/solum,ed-/solum,julienvey/solum,ed-/solum,gilbertpilz/solum
998586b575149ae549b755067c831f8b066c1845
digi/migrations/0002_theme_page_add_body_and_blog_category.py
digi/migrations/0002_theme_page_add_body_and_blog_category.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.9 on 2016-08-04 11:22 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import wagtail.wagtailcore.blocks import wagtail.wagtailcore.fields class Migration(migrations.Migration): dependencies = [ ...
# -*- coding: utf-8 -*- # Generated by Django 1.9.9 on 2016-08-04 11:22 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import wagtail.wagtailcore.blocks import wagtail.wagtailcore.fields class Migration(migrations.Migration): dependencies = [ ...
Use exact version instead of latest in the migration dependencies
Use exact version instead of latest in the migration dependencies Changed to use the latest migration of wagtail-blog v1.6.9. Refs https://github.com/thelabnyc/wagtail_blog/blob/5147d8129127102009c9bd63b1886e7665f6ccfb/blog/migrations/0005_auto_20151019_1121.py
Python
mit
City-of-Helsinki/digihel,City-of-Helsinki/digihel,City-of-Helsinki/digihel,City-of-Helsinki/digihel
3ced8676d474df3149bf78519e918cfa3b6b0ec3
src/dal_gm2m/fields.py
src/dal_gm2m/fields.py
"""GM2MField support for autocomplete fields.""" class GM2MFieldMixin(object): """GM2MField ror FutureModelForm.""" def value_from_object(self, instance, name): """Return the list of objects in the GM2MField relation.""" return None if not instance.pk else [ x for x in getattr(ins...
"""GM2MField support for autocomplete fields.""" class GM2MFieldMixin(object): """GM2MField ror FutureModelForm.""" def value_from_object(self, instance, name): """Return the list of objects in the GM2MField relation.""" return None if not instance.pk else [ getattr(x, 'gm2m_tgt',...
Support new versions with django-gm2m
Support new versions with django-gm2m
Python
mit
yourlabs/django-autocomplete-light,yourlabs/django-autocomplete-light,yourlabs/django-autocomplete-light,yourlabs/django-autocomplete-light
eb175a077affcdaa1e1cea6da557dd163890d958
djlime/forms/utils.py
djlime/forms/utils.py
# -*- coding: utf-8 -*- """ djlime.forms.utils ~~~~~~~~~~~~~~~~~~ Utilities for forms. :copyright: (c) 2012 by Andrey Voronov. :license: BSD, see LICENSE for more details. """ from django.utils import simplejson def form_errors_to_json(form): return simplejson.dumps({'success': False, ...
# -*- coding: utf-8 -*- """ djlime.forms.utils ~~~~~~~~~~~~~~~~~~ Utilities for forms. :copyright: (c) 2012 by Andrey Voronov. :license: BSD, see LICENSE for more details. """ from django.utils import simplejson def _errors_to_dict(form): return dict([(k, v[0]) for k, v in form.errors.items(...
Improve form_errors_to_json to handle multiple forms
Improve form_errors_to_json to handle multiple forms
Python
bsd-3-clause
freshlimestudio/djlime
cfd6c7c2d7af47329deac3e7ff618b66a078263c
ines/middlewares/logs.py
ines/middlewares/logs.py
# -*- coding: utf-8 -*- import sys from traceback import format_exception from pyramid.decorator import reify from pyramid.httpexceptions import HTTPInternalServerError from pyramid.interfaces import IRequestFactory from ines.middlewares import Middleware from ines.utils import format_error_to_json class LoggingMi...
# -*- coding: utf-8 -*- import sys from traceback import format_exception from pyramid.decorator import reify from pyramid.httpexceptions import HTTPInternalServerError from pyramid.interfaces import IRequestFactory from ines.convert import force_string from ines.middlewares import Middleware from ines.utils import ...
Set log with small message
Set log with small message
Python
mit
hugobranquinho/ines
47d9217b6ee9837987d25d77cc6e3c750766ed90
tests/test_formats.py
tests/test_formats.py
from contextlib import contextmanager from tempfile import TemporaryDirectory from django.core.management import call_command from django.test import TestCase from django_archive import archivers class FormatsTestCase(TestCase): """ Test that the archive command works with all available formats """ ...
from contextlib import contextmanager from tempfile import TemporaryDirectory from django.core.management import call_command from django.test import TestCase from django_archive import archivers class FormatsTestCase(TestCase): """ Test that the archive command works with all available formats """ ...
Fix bug in temporary directory generation.
Fix bug in temporary directory generation.
Python
mit
nathan-osman/django-archive,nathan-osman/django-archive
4ec8a5b5880f7e5300d71c34f5b293ea5993f5b2
tests/test_storage.py
tests/test_storage.py
import os import json import pytest def test_add_single(identity_fixures, identity_store): for d in identity_fixures: identity = identity_store.add_identity(d) for key, val in d.items(): assert getattr(identity, key) == val def test_add_multiple(identity_fixures, identity_store): ...
import os import json import pytest def test_add_single(identity_fixures, identity_store): for d in identity_fixures: identity = identity_store.add_identity(d) for key, val in d.items(): assert getattr(identity, key) == val def test_add_multiple(identity_fixures, identity_store): ...
Convert dict view to list for Py3
Convert dict view to list for Py3
Python
mit
nocarryr/AWS-Identity-Manager
0fbffce39b7e0209d04e26bd43009c2e6e5e0c46
testsuite/settings.py
testsuite/settings.py
from pathlib import Path from hoover.site.settings.common import * INSTALLED_APPS = INSTALLED_APPS + [ 'hoover.contrib.twofactor', 'django_otp', 'django_otp.plugins.otp_totp', ] MIDDLEWARE = MIDDLEWARE + [ 'django_otp.middleware.OTPMiddleware', 'hoover.contrib.twofactor.middleware.AutoLogout', ...
from pathlib import Path from hoover.site.settings.common import * INSTALLED_APPS = INSTALLED_APPS + [ 'hoover.contrib.twofactor', 'django_otp', 'django_otp.plugins.otp_totp', ] MIDDLEWARE = MIDDLEWARE + [ 'django_otp.middleware.OTPMiddleware', 'hoover.contrib.twofactor.middleware.AutoLogout', ...
Remove some indirection, set db password
Remove some indirection, set db password
Python
mit
hoover/search,hoover/search,hoover/search
ce05a68965a252a1756d6eac64bf319ef17ed158
packages/python/plotly/plotly/io/_utils.py
packages/python/plotly/plotly/io/_utils.py
from __future__ import absolute_import import plotly import plotly.graph_objs as go def validate_coerce_fig_to_dict(fig, validate, clone=True): from plotly.basedatatypes import BaseFigure if isinstance(fig, BaseFigure): fig_dict = fig.to_dict(clone=clone) elif isinstance(fig, dict): if v...
from __future__ import absolute_import import plotly import plotly.graph_objs as go def validate_coerce_fig_to_dict(fig, validate, clone=True): from plotly.basedatatypes import BaseFigure if isinstance(fig, BaseFigure): fig_dict = fig.to_dict(clone=clone) elif isinstance(fig, dict): if v...
Handle Dash objects in to_json
Handle Dash objects in to_json
Python
mit
plotly/plotly.py,plotly/plotly.py,plotly/plotly.py
510ea7c6971ede66206cfb5d24b16a38f18ffee1
mzalendo/odekro/management/commands/add_mps.py
mzalendo/odekro/management/commands/add_mps.py
from django.core.management.base import BaseCommand, CommandError from odekro import data class Command(BaseCommand): """Read in an info page file and either create or update existing info""" help = 'Add MPs data' args = '<file>' def handle(self, *args, **options): # file = open(args[]) ...
from django.core.management.base import BaseCommand, CommandError from odekro import data class Command(BaseCommand): """Read in mps data and either create or update existing info""" help = 'Add MPs data' args = '<file>' def handle(self, *args, **options): # file = open(args[]) if l...
Update a docstring to match the upstream odekro branch
Update a docstring to match the upstream odekro branch
Python
agpl-3.0
mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola,mysociety/pombola,geoffkilpin/pombola,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola,geoffkilpin/pombola
a376d66b4d58e22f35ad4f43e8b6f2ad775d68a8
vaux/api/downloads.py
vaux/api/downloads.py
from flask.ext import restful from . import database from flask import abort, send_file from werkzeug import secure_filename import os class DownloadInstance(restful.Resource): def get(self, id): document = database.get_document(id) if document is None: abort(404) return send_f...
from flask.ext import restful from . import database from flask import abort, send_file import mimetypes class DownloadInstance(restful.Resource): def get(self, id): document = database.get_document(id) if document is None: abort(404) mt = mimetypes.guess_type(document['path'])...
Make sure we give people a download with the actual name of the file
Make sure we give people a download with the actual name of the file
Python
mit
VauxIo/core
deac9119d4d03434a2d610920a431127927ac56a
netdisco/discoverables/belkin_wemo.py
netdisco/discoverables/belkin_wemo.py
""" Discovers Belkin Wemo devices. """ from . import SSDPDiscoverable class Discoverable(SSDPDiscoverable): """ Adds support for discovering Belkin WeMo platform devices. """ def info_from_entry(self, entry): """ Returns most important info from a uPnP entry. """ device = entry.description.f...
""" Discovers Belkin Wemo devices. """ from . import SSDPDiscoverable class Discoverable(SSDPDiscoverable): """ Adds support for discovering Belkin WeMo platform devices. """ def info_from_entry(self, entry): """ Returns most important info from a uPnP entry. """ device = entry.description.f...
Update discovery method for Wemo devices
Update discovery method for Wemo devices
Python
mit
sfam/netdisco,toddeye/netdisco,rohitranjan1991/netdisco,tomduijf/netdisco,brburns/netdisco,balloob/netdisco
e2c4529fc35c07721f1ed70ae2bf88538a67677b
slave/skia_slave_scripts/compare_gms.py
slave/skia_slave_scripts/compare_gms.py
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Compare the generated GM images to the baselines """ # System-level imports import os import sys from build_step import Build...
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Compare the generated GM images to the baselines """ # System-level imports import os import sys from build_step import Build...
Remove Ubuntu12 32 from may_fail_with_warning
Remove Ubuntu12 32 from may_fail_with_warning It's empty now. TODO: Remove the functionality once we're sure we don't need it. R=robertphillips@google.com Review URL: https://codereview.chromium.org/23545022 git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@11055 2bbb7eff-a529-9590-31e7-b0007b416f81
Python
bsd-3-clause
Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Ti...
53764e4ce0f82dc0706a9fd64877ccda5e97c32f
compd-score-match.py
compd-score-match.py
#!/usr/bin/env python import os import sys import yaml import score def usage(): print "Usage: score-match.py MATCH_NUMBER" print " Scores the match file at matches/MATCH_NUMBER.yaml" print " Outputs scoring format suitable for piping at compd" if len(sys.argv) is not 2: usage() exit(1) matc...
#!/usr/bin/env python import os import sys import yaml import score MATCH_ID = 'match-{0}' def usage(): print "Usage: score-match.py MATCH_NUMBER" print " Scores the match file at matches/MATCH_NUMBER.yaml" print " Outputs scoring format suitable for piping at compd" if len(sys.argv) is not 2: u...
Update match-id to equal that used in compd.
Update match-id to equal that used in compd.
Python
mit
samphippen/scoring_2013,samphippen/scoring_2013
e97a1ed2015db2eb2d5fe6abe15af6d9020c16d9
mbuild/tests/test_box.py
mbuild/tests/test_box.py
import pytest import numpy as np import mbuild as mb from mbuild.tests.base_test import BaseTest class TestBox(BaseTest): def test_init_lengths(self): box = mb.Box(lengths=np.ones(3)) assert np.array_equal(box.lengths, np.ones(3)) assert np.array_equal(box.mins, np.zeros(3)) asser...
import pytest import numpy as np import mbuild as mb from mbuild.tests.base_test import BaseTest class TestBox(BaseTest): def test_init_lengths(self): box = mb.Box(lengths=np.ones(3)) assert np.array_equal(box.lengths, np.ones(3)) assert np.array_equal(box.mins, np.zeros(3)) asser...
Remove box tests for non-existant functionality
Remove box tests for non-existant functionality
Python
mit
ctk3b/mbuild,iModels/mbuild,iModels/mbuild,ctk3b/mbuild,tcmoore3/mbuild,tcmoore3/mbuild,summeraz/mbuild,summeraz/mbuild
c63a4b469fae66668214da3b963c03cead99d16d
real_estate_agency/real_estate_agency/views.py
real_estate_agency/real_estate_agency/views.py
from django.shortcuts import render, render_to_response from django.template import RequestContext from new_buildings.models import Builder, ResidentalComplex, NewApartment from new_buildings.forms import SearchForm from feedback.models import Feedback def corporation_benefit_plan(request): return render(request...
from django.shortcuts import render, render_to_response from django.template import RequestContext from new_buildings.models import Builder, ResidentalComplex, NewApartment from new_buildings.forms import SearchForm from feedback.models import Feedback def corporation_benefit_plan(request): return render(request...
Add pupular RC objects to index view.
Add pupular RC objects to index view. Earlier they was at context processor.
Python
mit
Dybov/real_estate_agency,Dybov/real_estate_agency,Dybov/real_estate_agency
84341e0d5f0f1b902c2a334f40cddb29e10a1f16
mozillians/users/cron.py
mozillians/users/cron.py
from django.conf import settings import cronjobs from celery.task.sets import TaskSet from elasticutils.contrib.django import get_es from mozillians.users.tasks import index_objects from mozillians.users.models import UserProfile, UserProfileMappingType @cronjobs.register def index_all_profiles(): # Get an es ...
from django.conf import settings import cronjobs from celery.task.sets import TaskSet from celeryutils import chunked from elasticutils.contrib.django import get_es from mozillians.users.tasks import index_objects from mozillians.users.models import UserProfile, UserProfileMappingType @cronjobs.register def index_...
Index profiles in chunks and not altogether.
Index profiles in chunks and not altogether.
Python
bsd-3-clause
johngian/mozillians,akatsoulas/mozillians,akarki15/mozillians,johngian/mozillians,hoosteeno/mozillians,mozilla/mozillians,chirilo/mozillians,hoosteeno/mozillians,safwanrahman/mozillians,fxa90id/mozillians,fxa90id/mozillians,fxa90id/mozillians,fxa90id/mozillians,johngian/mozillians,akatsoulas/mozillians,anistark/mozilli...
657f72c2aae5bd83efff3520fa642d66ad172822
tests/test_commands.py
tests/test_commands.py
import django from django.core.management import call_command from django.test import TestCase from bananas.management.commands import show_urls class CommandTests(TestCase): def test_show_urls(self): urls = show_urls.collect_urls() if django.VERSION < (1, 9): n_urls = 23 + 8 ...
import django from django.core.management import call_command from django.test import TestCase from bananas.management.commands import show_urls class CommandTests(TestCase): def test_show_urls(self): urls = show_urls.collect_urls() admin_api_url_count = 0 if django.VERSION >= (1, 10): ...
Fix test_show_urls without admin api urls
Fix test_show_urls without admin api urls
Python
mit
5monkeys/django-bananas,5monkeys/django-bananas,5monkeys/django-bananas
9b18e4833a3550d424aa18fddbf5373d142ce3f1
dddp/apps.py
dddp/apps.py
"""Django DDP app config.""" from __future__ import print_function from django.apps import AppConfig from django.conf import settings, ImproperlyConfigured from django.db import DatabaseError from django.db.models import signals from dddp import autodiscover from dddp.models import Connection class DjangoDDPConfig...
"""Django DDP app config.""" from __future__ import print_function from django.apps import AppConfig from django.conf import settings, ImproperlyConfigured from dddp import autodiscover class DjangoDDPConfig(AppConfig): """Django app config for django-ddp.""" api = None name = 'dddp' verbose_name...
Remove unused imports from AppConfig module.
Remove unused imports from AppConfig module.
Python
mit
commoncode/django-ddp,commoncode/django-ddp,commoncode/django-ddp,django-ddp/django-ddp,commoncode/django-ddp,django-ddp/django-ddp,django-ddp/django-ddp,django-ddp/django-ddp
ac5a339f73cb80b54b0298a02bce41c27c25b9ae
authentication/forms.py
authentication/forms.py
from django import forms as newform from django.forms import ModelForm from people.models import Beneficiary, Donor from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ # from django.core.urlresolvers import reverse # from crispy_forms.helper import FormHelper # from cris...
from django import forms as newform class LoginForm(newform.Form): username = newform.CharField() password = newform.CharField(widget=newform.PasswordInput)
Remove unused and commented parts
Remove unused and commented parts
Python
bsd-3-clause
agiliq/fundraiser,agiliq/fundraiser,febinstephen/django-fundrasiser-app,agiliq/fundraiser,febinstephen/django-fundrasiser-app,febinstephen/django-fundrasiser-app
25273e699b2b901eec53656dbcdc437e4a4cdc11
backend/breach/tests.py
backend/breach/tests.py
from django.test import TestCase from breach.models import SampleSet, Victim, Target, Round from breach.analyzer import decide_next_world_state class AnalyzerTestCase(TestCase): def setUp(self): target = Target.objects.create( endpoint='http://di.uoa.gr/', prefix='test', ...
from django.test import TestCase from breach.models import SampleSet, Victim, Target, Round from breach.analyzer import decide_next_world_state class RuptureTestCase(TestCase): def setUp(self): target = Target.objects.create( endpoint='http://di.uoa.gr/', prefix='test', ...
Create base test case class for rupture
Create base test case class for rupture
Python
mit
dimkarakostas/rupture,esarafianou/rupture,dimriou/rupture,dimkarakostas/rupture,esarafianou/rupture,esarafianou/rupture,dionyziz/rupture,dimkarakostas/rupture,dionyziz/rupture,dimriou/rupture,dionyziz/rupture,dimriou/rupture,esarafianou/rupture,dimkarakostas/rupture,dionyziz/rupture,dimriou/rupture,dimriou/rupture,dion...
a28a29af31b1ea604ed97544b2d84a39c9ba3e7b
automation/src/rabird/automation/selenium/webelement.py
automation/src/rabird/automation/selenium/webelement.py
#--IMPORT_ALL_FROM_FUTURE--# ''' @date 2014-11-16 @author Hong-she Liang <starofrainnight@gmail.com> ''' # Import the global selenium unit, not our selenium . global_selenium = __import__('selenium') import types import time def set_attribute(self, name, value): value = value.replace(r"'", r"\'") ...
#--IMPORT_ALL_FROM_FUTURE--# ''' @date 2014-11-16 @author Hong-she Liang <starofrainnight@gmail.com> ''' # Import the global selenium unit, not our selenium . global_selenium = __import__('selenium') import types import time def set_attribute(self, name, value): value = value.replace(r"'", r"\'") ...
Use javascript to force focus on an element, because the action chains seems take no effect!
Use javascript to force focus on an element, because the action chains seems take no effect!
Python
apache-2.0
starofrainnight/rabird.core,starofrainnight/rabird.auto
730b5acb9c715a0b7e2f70d4ee3d26cd2a8a03ca
wordcloud/views.py
wordcloud/views.py
import json import os from django.conf import settings from django.http import HttpResponse from django.views.decorators.cache import cache_page from .wordcloud import popular_words @cache_page(60*60*4) def wordcloud(request, max_entries=30): """ Return tag cloud JSON results""" cache_path = settings.WORDCL...
import json import os from django.conf import settings from django.http import HttpResponse from django.views.decorators.cache import cache_page from .wordcloud import popular_words @cache_page(60*60*4) def wordcloud(request, max_entries=30): """ Return tag cloud JSON results""" cache_path = settings.WORDCL...
Fix a deprecation warning; content_type replaces mimetype
Fix a deprecation warning; content_type replaces mimetype
Python
agpl-3.0
geoffkilpin/pombola,mysociety/pombola,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola,geoffkilpin/pombola,mysociety/pombola,mysociety/pombola,geoffkilpin/pombola,mysociety/pombola,mysociety/pombola,geoffkilpin/pombola
7e6af723e15a785b403010de4b44b49fce924e91
social_auth/backends/pipeline/misc.py
social_auth/backends/pipeline/misc.py
from social_auth.backends import PIPELINE from social_auth.utils import setting PIPELINE_ENTRY = 'social_auth.backends.pipeline.misc.save_status_to_session' def save_status_to_session(request, auth, *args, **kwargs): """Saves current social-auth status to session.""" next_entry = setting('SOCIAL_AUTH_PIPELI...
from social_auth.backends import PIPELINE from social_auth.utils import setting PIPELINE_ENTRY = 'social_auth.backends.pipeline.misc.save_status_to_session' def tuple_index(t, e): for (i, te) in enumerate(t): if te == e: return i return None def save_status_to_session(request, auth, *arg...
Add own tuple_index function to stay compatible with python 2.5
Add own tuple_index function to stay compatible with python 2.5
Python
bsd-3-clause
WW-Digital/django-social-auth,duoduo369/django-social-auth,limdauto/django-social-auth,vuchau/django-social-auth,gustavoam/django-social-auth,1st/django-social-auth,vxvinh1511/django-social-auth,VishvajitP/django-social-auth,MjAbuz/django-social-auth,sk7/django-social-auth,getsentry/django-social-auth,omab/django-socia...
1f83364822a1c80dc26f58d3908006a7f643e7c9
json_protocol.py
json_protocol.py
# -*- coding: iso-8859-1 -*- from twisted.protocols.basic import Int32StringReceiver import json import apps class JSONProtocol(Int32StringReceiver): app = apps.LoginApp def connectionMade(self): self.app = self.__class__.app(self) def connectionLost(self, reason): self.app.disconnect(r...
# -*- coding: iso-8859-1 -*- from twisted.protocols.basic import Int32StringReceiver import json import apps class JSONProtocol(Int32StringReceiver): app = apps.LoginApp def connectionMade(self): self.app = self.__class__.app(self) def connectionLost(self, reason): self.app.disconnect(r...
Change parse errors to standard format.
Change parse errors to standard format.
Python
bsd-3-clause
siggame/server
877f7fe856c640ee7cafa41226622d18eee39257
update-database/update-latest-from-so.py
update-database/update-latest-from-so.py
import pymongo import stackexchange import time so = stackexchange.Site(stackexchange.StackOverflow, "WNe2LOp*hdsbD5U7kp0bhg((") so.be_inclusive() connection = pymongo.Connection() db = connection.stack_doc posts = db.posts up_to_date = False while not up_to_date: last_in_database = posts.find_one(sort=[("last...
import pymongo import stackexchange import time so = stackexchange.Site(stackexchange.StackOverflow) so.be_inclusive() connection = pymongo.Connection() db = connection.stack_doc posts = db.posts up_to_date = False while not up_to_date: last_in_database = posts.find_one(sort=[("last_activity", pymongo.DESCENDI...
Remove API key (it's for the wrong API version)
Remove API key (it's for the wrong API version)
Python
bsd-3-clause
alnorth/stackdoc,alnorth/stackdoc,alnorth/stackdoc
346d6e38e84a5addc5173a331dbc0cc6fa39e754
corehq/apps/domain/management/commands/fill_last_modified_date.py
corehq/apps/domain/management/commands/fill_last_modified_date.py
from django.core.management.base import BaseCommand from corehq.apps.domain.models import Domain from dimagi.utils.couch.database import iter_docs class Command(BaseCommand): def _get_domains_without_last_modified_date(self): docs = iter_docs(Domain.get_db(), [ domain['id'] for d...
from django.core.management.base import BaseCommand from corehq.apps.domain.models import Domain from dimagi.utils.couch.database import iter_docs class Command(BaseCommand): def _get_domains_without_last_modified_date(self): docs = iter_docs(Domain.get_db(), [ domain['id'] for d...
Include domains which have last_modified equal to None
Include domains which have last_modified equal to None
Python
bsd-3-clause
qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq
0293170e0e8d309e4b2c37e3a07f64d4447b244f
pylearn2/costs/tests/test_lp_norm_cost.py
pylearn2/costs/tests/test_lp_norm_cost.py
""" Test LpNorm cost """ import numpy import theano from theano import tensor as T from nose.tools import raises def test_shared_variables(): ''' LpNorm should handle shared variables. ''' assert False def test_symbolic_expressions_of_shared_variables(): ''' LpNorm should handle symbolic exp...
""" Test LpNorm cost """ import os from nose.tools import raises from pylearn2.models.mlp import Linear from pylearn2.models.mlp import Softmax from pylearn2.models.mlp import MLP from pylearn2.costs.cost import LpNorm from pylearn2.datasets.cifar10 import CIFAR10 from pylearn2.training_algorithms.sgd import SGD from p...
Add more code to LpNorm unit tests
Add more code to LpNorm unit tests
Python
bsd-3-clause
caidongyun/pylearn2,mclaughlin6464/pylearn2,kose-y/pylearn2,chrish42/pylearn,sandeepkbhat/pylearn2,junbochen/pylearn2,fishcorn/pylearn2,w1kke/pylearn2,Refefer/pylearn2,hyqneuron/pylearn2-maxsom,chrish42/pylearn,daemonmaker/pylearn2,fulmicoton/pylearn2,hyqneuron/pylearn2-maxsom,fyffyt/pylearn2,TNick/pylearn2,hantek/pyle...
4cc45954ba71af6b81c930a99f05e8a6cf8b48f6
update-database/stackdoc/questionimport.py
update-database/stackdoc/questionimport.py
def import_question(posts, namespaces, id, title, body, tags, last_activity_date, last_updated_date, score, answer_count, has_accepted_answer): namespaces_for_post = {} for name, n in namespaces.items(): namespace_tags = n.get_tags() if not(namespace_tags) or any(map(lambda x: x in tags, namesp...
def import_question(posts, namespaces, id, title, body, tags, last_activity_date, last_updated_date, score, answer_count, has_accepted_answer): namespaces_for_post = {} for name, n in namespaces.items(): namespace_tags = n.get_tags() if not(namespace_tags) or any(map(lambda x: x in tags, namesp...
Rewrite inserting function. It can be a lot simpler now we know we're always dealing with up-to-date data.
Rewrite inserting function. It can be a lot simpler now we know we're always dealing with up-to-date data.
Python
bsd-3-clause
alnorth/stackdoc,alnorth/stackdoc,alnorth/stackdoc
a13e13d0fef4a342c5a419365b9ac7053eddafb3
loader/helpers/lib/forgeFixes.py
loader/helpers/lib/forgeFixes.py
import os import fileinput def modify(path, build): config = os.path.join(path, 'config/forge.cfg') replacements = { 'removeErroringEntities=false': 'removeErroringEntities=true', 'removeErroringTileEntities=false': 'removeErroringTileEntities=true' } if not os.path.isfile(config): ...
import os import fileinput import requests import zipfile import distutils.dir_util import tempfile patchfiles = 'gdn/static/cache/forgepatch01' def patchForge(path): if not os.path.exists(patchfiles): print 'Downloading forgepatch' r = requests.get('http://s3.amazonaws.com/SpaceZips/forgepatch.z...
Add forge libraries to patch helper
Add forge libraries to patch helper
Python
mpl-2.0
MCProHosting/SpaceGDN,XereoNet/SpaceGDN,MCProHosting/SpaceGDN,XereoNet/SpaceGDN,MCProHosting/SpaceGDN,XereoNet/SpaceGDN
90bc53c743095fd3a6a848aa2447b6ae6ab1a98f
tg/release.py
tg/release.py
"""TurboGears project related information""" version = "2.0a1" description = "Next generation TurboGears built on Pylons" long_description=""" TurboGears brings together a variety of best of breed python tools to create an easy to install, easy to use web megaframework. It provides and integrated and well tested set...
"""TurboGears project related information""" version = "2.0a1" description = "Next generation TurboGears built on Pylons" long_description=""" TurboGears brings together a variety of best of breed python tools to create an easy to install, easy to use web megaframework. It provides and integrated and well tested set o...
Convert description in setup.py to rest format for better display in Cheeseshop
Convert description in setup.py to rest format for better display in Cheeseshop --HG-- extra : convert_revision : svn%3A77541ad4-5f01-0410-9ede-a1b63cd9a898/trunk%403340
Python
mit
lucius-feng/tg2,lucius-feng/tg2
a8a7f6ecbe1abd4fcb6dad8e6c635c3ef38ab40f
scoring_engine/engine/execute_command.py
scoring_engine/engine/execute_command.py
from scoring_engine.celery_app import celery_app from celery.exceptions import SoftTimeLimitExceeded import subprocess from scoring_engine.logger import logger @celery_app.task(name='execute_command', soft_time_limit=30) def execute_command(job): output = "" # Disable duplicate celery log messages if log...
from scoring_engine.celery_app import celery_app from celery.exceptions import SoftTimeLimitExceeded import subprocess from scoring_engine.logger import logger @celery_app.task(name='execute_command', acks_late=True, reject_on_worker_lost=True, soft_time_limit=30) def execute_command(job): output = "" # Disa...
Modify worker to requeue jobs if worker is killed
Modify worker to requeue jobs if worker is killed
Python
mit
pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine
1af3111e4f2422c1d6484c237700013386d4638d
minutes/forms.py
minutes/forms.py
from django.forms import ModelForm, Textarea, ChoiceField from django.urls import reverse_lazy from .models import Meeting, Folder MD_INPUT = { 'class': 'markdown-input', 'data-endpoint': reverse_lazy('utilities:preview_safe') } def sorted_folders(): return sorted([(x.pk, str(x)) for x in Folder.objects...
from django.forms import ModelForm, Textarea, ChoiceField from django.utils.functional import lazy from .models import Meeting, Folder MD_INPUT = { 'class': 'markdown-input' } def sorted_folders(): return sorted([(x.pk, str(x)) for x in Folder.objects.all()], key=lambda x: x[1]) class MeetingForm(ModelFor...
Revert "Allow admin preview in minutes as well"
Revert "Allow admin preview in minutes as well" This reverts commit f4806655
Python
isc
ashbc/tgrsite,ashbc/tgrsite,ashbc/tgrsite
dd9030413af99e05fe935a2dafb9a6012b09b248
modules/karma.py
modules/karma.py
import discord from modules.botModule import BotModule class Karma(BotModule): name = 'karma' description = 'Monitors messages for reactions and adds karma accordingly.' help_text = 'This module has no callable functions' trigger_string = '!reddit' module_db = 'karma.json' ...
import discord from modules.botModule import BotModule class Karma(BotModule): name = 'karma' description = 'Monitors messages for reactions and adds karma accordingly.' help_text = 'This module has no callable functions' trigger_string = '!reddit' module_db = 'karma.json' ...
Fix where db name should be used in db operations (name conflict!)
Fix where db name should be used in db operations (name conflict!)
Python
mit
suclearnub/scubot
20e293b49438a2428eee21bdc07799328a69ec48
dadd/worker/handlers.py
dadd/worker/handlers.py
import json import socket import requests from flask import request, jsonify from dadd.worker import app from dadd.worker.proc import ChildProcess @app.route('/run/', methods=['POST']) def run_process(): proc = ChildProcess(request.json) proc.run() return jsonify(proc.info()) @app.route('/register/',...
import os import json import socket import requests from flask import request, jsonify, Response, abort from dadd.worker import app from dadd.worker.proc import ChildProcess @app.route('/run/', methods=['POST']) def run_process(): proc = ChildProcess(request.json) proc.run() return jsonify(proc.info())...
Allow setting the HOSTNAME reported to the master via an env var; Stub and endpoint for tailing the log of a process assuming you know the path.
Allow setting the HOSTNAME reported to the master via an env var; Stub and endpoint for tailing the log of a process assuming you know the path. I'd like to get this log processing a bit more automatic but I need to spend more time in Dadd's API.
Python
bsd-3-clause
ionrock/dadd,ionrock/dadd,ionrock/dadd,ionrock/dadd
c74c38bb615d048eb26634c048a833ddc2da7d62
jcppy/__init__.py
jcppy/__init__.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) 2017 Stanislav Ivochkin <isn@extrn.org> # License: MIT (see LICENSE for details) from jcppy._version import __version__, __revision__ from jcppy.header import header from jcppy.source import source
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) 2017 Stanislav Ivochkin <isn@extrn.org> # License: MIT (see LICENSE for details) try: from jcppy._version import __version__, __revision__ except ImportError: __version__ = 'latest' __revision__ = 'latest' __hash__ = 'unknown' from jcppy.he...
Work around missing jcppy._version for local development
Work around missing jcppy._version for local development
Python
mit
isn-/jcppy,isn-/jcppy
f54db5d4e132fe1c227fe5bf1f7079772433429d
yunity/models/utils.py
yunity/models/utils.py
from django.db.models import Model, CharField, Field class MaxLengthCharField(CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 255 super().__init__(*args, **kwargs) class BaseModel(Model): class Meta: abstract = True def _get_explicit_field_names(self): ...
from django.db.models import Model, CharField, Field class MaxLengthCharField(CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 255 super().__init__(*args, **kwargs) class BaseModel(Model): class Meta: abstract = True def _get_explicit_field_names(self): ...
Add columns and values to repr
Add columns and values to repr
Python
agpl-3.0
yunity/yunity-core,yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend
b2bc77023ed3e19f6f7483645e2a11952c061de0
tests/registryd/test_registry_startup.py
tests/registryd/test_registry_startup.py
PROPERTIES_IFACE = 'org.freedesktop.DBus.Properties' ACCESSIBLE_IFACE = 'org.a11y.atspi.Accessible' def test_accessible_iface_properties(registry, session_manager): val = registry.Get(ACCESSIBLE_IFACE, 'Name', dbus_interface=PROPERTIES_IFACE) assert str(val) == 'main'
PROPERTIES_IFACE = 'org.freedesktop.DBus.Properties' ACCESSIBLE_IFACE = 'org.a11y.atspi.Accessible' def get_property(proxy, iface_name, prop_name): return proxy.Get(iface_name, prop_name, dbus_interface=PROPERTIES_IFACE) def test_accessible_iface_properties(registry, session_manager): values = [ ('Nam...
Test the Description property of the registry's root
Test the Description property of the registry's root
Python
lgpl-2.1
GNOME/at-spi2-core,GNOME/at-spi2-core,GNOME/at-spi2-core
9231612c0631c784dc7188822b47a4bde38db488
uni_form/templatetags/uni_form_field.py
uni_form/templatetags/uni_form_field.py
from django import template register = template.Library() class_converter = { "textinput":"textinput textInput", "fileinput":"fileinput fileUpload", "passwordinput":"passwordinput textInput" } @register.filter def is_checkbox(field): return field.field.widget.__class__.__name__.lower() == "checkboxin...
from django import template register = template.Library() class_converter = { "textinput":"textinput textInput", "fileinput":"fileinput fileUpload", "passwordinput":"textinput textInput", >>>>>>> f85af74... Convert css class of PasswordInput widget:uni_form/templatetags/uni_form_field.py } @register.filt...
Convert css class of PasswordInput widget
Convert css class of PasswordInput widget
Python
mit
maraujop/django-crispy-forms,jtyoung/django-crispy-forms,ngenovictor/django-crispy-forms,saydulk/django-crispy-forms,carltongibson/django-crispy-forms,treyhunner/django-crispy-forms,dessibelle/django-crispy-forms,Stranger6667/django-crispy-forms,iris-edu-int/django-crispy-forms,spectras/django-crispy-forms,HungryCloud/...
efb1057b122664ee8e1ab0a06259988aa9f50092
experiments/management/commands/update_experiment_reports.py
experiments/management/commands/update_experiment_reports.py
import logging l=logging.getLogger(__name__) from django.conf import settings from django.core.management.base import BaseCommand, CommandError from experiments.reports import (EngagementReportGenerator, ConversionReportGenerator) class Command(BaseCommand): help = ('update_exper...
import logging l=logging.getLogger(__name__) from django.conf import settings from django.core.management.base import BaseCommand, CommandError from experiments.reports import (EngagementReportGenerator, ConversionReportGenerator) class Command(BaseCommand): help = ('update_exper...
Fix typos in exception messages and use less specific exception in management commands.
Fix typos in exception messages and use less specific exception in management commands.
Python
bsd-3-clause
e-loue/django-lean,MontmereLimited/django-lean,MontmereLimited/django-lean,uhuramedia/django-lean,MontmereLimited/django-lean,uhuramedia/django-lean,e-loue/django-lean,uhuramedia/django-lean
a1e6da688cc41f0dc4a22e546d076358bd626990
billjobs/tests/tests_export_account_email.py
billjobs/tests/tests_export_account_email.py
from django.test import TestCase from django.contrib.admin.sites import AdminSite from billjobs.admin import UserAdmin class EmailExportTestCase(TestCase): """ Tests for email account export """ def test_method_is_avaible(self): """ Test admin can select the action in dropdown list """ self.as...
from django.test import TestCase from django.contrib.admin.sites import AdminSite from billjobs.admin import UserAdmin class EmailExportTestCase(TestCase): """ Tests for email account export """ def test_method_is_avaible(self): """ Test admin can select the action in dropdown list """ self.as...
Test modelAdmin actions is present
Test modelAdmin actions is present
Python
mit
ioO/billjobs
055fa862e09c1a7c215e26034ad9da5998d90d0f
wafer/sponsors/templatetags/sponsors.py
wafer/sponsors/templatetags/sponsors.py
from django import template from wafer.sponsors.models import Sponsor, SponsorshipPackage register = template.Library() @register.inclusion_tag('wafer.sponsors/sponsors_block.html') def sponsors(): return { 'sponsors': Sponsor.objects.all().order_by('packages'), 'packages': SponsorshipPackage.ob...
from django import template from wafer.sponsors.models import Sponsor, SponsorshipPackage register = template.Library() @register.inclusion_tag('wafer.sponsors/sponsors_block.html') def sponsors(): return { 'sponsors': Sponsor.objects.all().order_by('packages'), 'packages': SponsorshipPackage.ob...
Add template tag to look up sponsor images
Add template tag to look up sponsor images
Python
isc
CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer
a703c68738385319b714b94ada39f847568b9d36
django_evolution/utils.py
django_evolution/utils.py
from django_evolution.db import evolver def write_sql(sql): "Output a list of SQL statements, unrolling parameters as required" for statement in sql: if isinstance(statement, tuple): print unicode(statement[0] % tuple(evolver.quote_sql_param(s) for s in statement[1])) else: ...
from django_evolution.db import evolver def write_sql(sql): "Output a list of SQL statements, unrolling parameters as required" for statement in sql: if isinstance(statement, tuple): print unicode(statement[0] % tuple(evolver.quote_sql_param(s) for s in statement[1])) else: ...
Revert a debugging change that slipped in.
Revert a debugging change that slipped in.
Python
bsd-3-clause
beanbaginc/django-evolution
384e2fd9ae794e182dfdf4072d2689cff5f5d91d
log4django/routers.py
log4django/routers.py
from .settings import CONNECTION_NAME class Log4DjangoRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label == 'log4django': return CONNECTION_NAME return None def db_for_write(self, model, **hints): if model._meta.app_label == 'log4django': ...
from .settings import CONNECTION_NAME class Log4DjangoRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label == 'log4django': return CONNECTION_NAME return None def db_for_write(self, model, **hints): if model._meta.app_label == 'log4django': ...
Fix syncdb in database router
Fix syncdb in database router
Python
bsd-3-clause
CodeScaleInc/log4django,CodeScaleInc/log4django,CodeScaleInc/log4django
df01d83a35c59ee2295b358d8eceeb842adb568d
listings/admin.py
listings/admin.py
from django.contrib import admin from .models import Region, City, GatheringCenter, Resource admin.site.register(Region) admin.site.register(City) class PublishMixin(object): actions = ('publish', 'unpublish') def publish(self, request, queryset): queryset.update(published=True) def unpublish(...
from django.contrib import admin from .models import Region, City, GatheringCenter, Resource admin.site.register(Region) admin.site.register(City) class PublishMixin(object): actions = ('publish', 'unpublish') def publish(self, request, queryset): queryset.update(published=True) def unpublish(...
Order by create, don't filter
Order by create, don't filter
Python
apache-2.0
pony-revolution/helpothers,pony-revolution/helpothers,pony-revolution/helpothers
19ce87dd98c65338a35a4f81c3210745d330fc4c
data/tests/test_data.py
data/tests/test_data.py
from __future__ import absolute_import, division, print_function import os, sys, tempfile sys.path.append("data/") import data try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen def test_check_hashes(): with tempfile.NamedTemporaryFile() as temp: temp.write(b'...
from __future__ import absolute_import, division, print_function import os, sys, tempfile from data import data try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen def test_check_hashes(): with tempfile.NamedTemporaryFile() as temp: temp.write(b'Some data') ...
Fix build exitting from make coverage
Fix build exitting from make coverage
Python
bsd-3-clause
berkeley-stat159/project-delta
d13896e05922d6d57e552719963e6918cef981d0
democracylab/logging.py
democracylab/logging.py
import copy import logging import traceback def dump(obj): for attr in dir(obj): print("obj.%s = %r" % (attr, getattr(obj, attr))) def dump_request_summary(request): user = request.user.username if request.user.is_authenticated() else '' url = request.path method = request.method body = ...
import copy import logging import traceback def dump(obj): for attr in dir(obj): print("obj.%s = %r" % (attr, getattr(obj, attr))) def dump_request_summary(request): user = request.user.username if request.user.is_authenticated() else '' url = request.path method = request.method body = ...
Fix django logger issue when error has no attached request object
Fix django logger issue when error has no attached request object
Python
mit
DemocracyLab/CivicTechExchange,DemocracyLab/CivicTechExchange,DemocracyLab/CivicTechExchange,DemocracyLab/CivicTechExchange
cdef62151437e9bf1187b955ad212d9d32e007e3
django_olcc/olcc/api.py
django_olcc/olcc/api.py
from tastypie.resources import ModelResource from olcc.models import Product, ProductPrice, Store class ProductResource(ModelResource): class Meta: queryset = Product.objects.all() resource_name = 'product' class ProductPriceResource(ModelResource): class Meta: queryset = ProductPrice....
from tastypie import fields from tastypie.resources import ModelResource, ALL from olcc.models import Product, ProductPrice, Store class ProductResource(ModelResource): class Meta: queryset = Product.objects.all() resource_name = 'product' allowed_methods = ['get'] filtering = { ...
Tweak the tastypie resource configuration.
Tweak the tastypie resource configuration.
Python
mit
twaddington/django-olcc,twaddington/django-olcc,twaddington/django-olcc
c3a6554ce24781a3eaa9229f9609a09e4e018069
lcd_restful/__main__.py
lcd_restful/__main__.py
#!/usr/bin/env python import sys from getopt import getopt, GetoptError from .api import Server from .fake import FakeLcdApi USAGE = """\ Usage %s [-h|--help] \t-h or --help\tThis help message """ def get_args(args): try: opts, args = getopt(args[1:], 'hf', ['help', 'fake']) except GetoptError as e...
#!/usr/bin/env python import sys from getopt import getopt, GetoptError from .api import Server from .lcd import Lcd USAGE = """\ Usage %s [-h|--help] [-f|--fake] \t-h or --help\tThis help message \t-f or --fake\tIf on RPi, use FakeHw """ def get_args(args): arg0 = args[0] try: opts, args = getopt(...
Update main Lcd import and init, and fix help msg
Update main Lcd import and init, and fix help msg
Python
mit
rfarley3/lcd-restful,rfarley3/lcd-restful
172175811e6532d23586e54c5b48032e52745f35
fjord/api_auth/migrations/0001_initial.py
fjord/api_auth/migrations/0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Token', fields=[ ('token', models.CharField(hel...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Token', fields=[ ('token', models.CharField(hel...
Update help_text in api_auth initial migration
Update help_text in api_auth initial migration I'm updating the help_text in the original migration rather than creating a new migration that doesn't affect the db, but does do a bunch of SQL stuff in the migration.
Python
bsd-3-clause
hoosteeno/fjord,staranjeet/fjord,rlr/fjord,mozilla/fjord,lgp171188/fjord,rlr/fjord,rlr/fjord,Ritsyy/fjord,mozilla/fjord,Ritsyy/fjord,staranjeet/fjord,staranjeet/fjord,staranjeet/fjord,lgp171188/fjord,lgp171188/fjord,mozilla/fjord,hoosteeno/fjord,hoosteeno/fjord,Ritsyy/fjord,lgp171188/fjord,mozilla/fjord,rlr/fjord,hoost...
596a29505351ec0e497cbe114a6e4d57d7cbada6
backoff/__init__.py
backoff/__init__.py
# coding:utf-8 """ Function decoration for backoff and retry This module provides function decorators which can be used to wrap a function such that it will be retried until some condition is met. It is meant to be of use when accessing unreliable resources with the potential for intermittent failures i.e. network res...
# coding:utf-8 """ Function decoration for backoff and retry This module provides function decorators which can be used to wrap a function such that it will be retried until some condition is met. It is meant to be of use when accessing unreliable resources with the potential for intermittent failures i.e. network res...
Use importlib.metadata to set __version__
Use importlib.metadata to set __version__ This way we don't have to remember to update the version in two places every release. The version will only need to be set in pyproject.toml
Python
mit
litl/backoff
2c8dafec701d80ddd9a3d1855a14a8eef0c44790
tests/modules/contrib/test_network_traffic.py
tests/modules/contrib/test_network_traffic.py
import pytest pytest.importorskip("psutil") pytest.importorskip("netifaces") def test_load_module(): __import__("modules.contrib.network_traffic")
import pytest from unittest import TestCase, mock import core.config import core.widget import modules.contrib.network_traffic from types import SimpleNamespace pytest.importorskip("psutil") pytest.importorskip("netifaces") def io_counters_mock(recv, sent): return { 'lo': SimpleNamespace( by...
Add Network Traffic module tests
Add Network Traffic module tests
Python
mit
tobi-wan-kenobi/bumblebee-status,tobi-wan-kenobi/bumblebee-status
7c494c9216247d4480f2b293947b75947b1fcb01
readme_renderer/__main__.py
readme_renderer/__main__.py
from __future__ import absolute_import, print_function from readme_renderer.rst import render import sys if len(sys.argv) == 2: with open(sys.argv[1]) as fp: out = render(fp.read(), stream=sys.stderr) if out is not None: print(out) else: sys.exit(1) else: print(...
from __future__ import absolute_import, print_function import argparse from readme_renderer.rst import render import sys if __name__ == '__main__': parser = argparse.ArgumentParser( description="Renders a .rst README to HTML", ) parser.add_argument('input', help="Input README file") parser.add...
Use `if __name__` and argparse
Use `if __name__` and argparse
Python
apache-2.0
pypa/readme_renderer,pypa/readme
4a8292f2c01323743cc41cbff4c9dfe0e4203f25
comics/accounts/models.py
comics/accounts/models.py
import uuid from django.contrib.auth.models import User from django.db import models from django.dispatch import receiver @receiver(models.signals.post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): UserProfile.objects.get_or_create(user=instance) class UserProfile(models.Mode...
import uuid from django.contrib.auth.models import User from django.db import models from django.dispatch import receiver @receiver(models.signals.post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) class UserProfile...
Remove conditional sql-select on new user creation
Remove conditional sql-select on new user creation Only create a user profile if a new user is actually created.
Python
agpl-3.0
datagutten/comics,datagutten/comics,jodal/comics,jodal/comics,datagutten/comics,datagutten/comics,jodal/comics,jodal/comics
7443217044931466618e4ed8065b03dd7c08b05d
integration-test/990-add-art-galleries.py
integration-test/990-add-art-galleries.py
# http://www.openstreetmap.org/node/2026996113 assert_has_feature( 16, 10485, 25328, 'pois', { 'id': 2026996113, 'kind': 'gallery', 'min_zoom': 17 }) # http://www.openstreetmap.org/way/31510288 assert_has_feature( 15, 16371, 10895, 'pois', { 'id': 31510288, 'kind': 'gallery' })
# http://www.openstreetmap.org/node/2026996113 assert_has_feature( 16, 10485, 25328, 'pois', { 'id': 2026996113, 'kind': 'gallery', 'min_zoom': 17 }) # https://www.openstreetmap.org/way/83488820 assert_has_feature( 15, 16370, 10894, 'pois', { 'id': 83488820, 'kind': 'gallery' })
Update tests to deal with changeset 41943013, in which the Royal Academy of Arts was changed to a museum.
Update tests to deal with changeset 41943013, in which the Royal Academy of Arts was changed to a museum.
Python
mit
mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource
46f2b508eb5f4350a06bdf832c7481ad8d8aab33
node/multi_var.py
node/multi_var.py
from nodes import Node class MultiVar(Node): char = "'" args = 0 results = None contents = -1 def __init__(self, node_1: Node.NodeSingle, node_2: Node.NodeSingle): self.node_1 = node_1 self.node_2 = node_2 self.args = max([node_1.args, node_2.args]) def pr...
from nodes import Node class MultiVar(Node): char = "'" args = 0 results = None contents = -1 def __init__(self, node_1: Node.NodeSingle, node_2: Node.NodeSingle): self.node_1 = node_1 self.node_2 = node_2 def prepare(self, stack): self.node_1.prepare(stac...
Fix multivar for nodes with variable length stacks
Fix multivar for nodes with variable length stacks
Python
mit
muddyfish/PYKE,muddyfish/PYKE
b5bf3a92309dac40deefbaea555e4d96aa6bca62
jesusmtnez/python/kata/tests/test_game.py
jesusmtnez/python/kata/tests/test_game.py
import unittest from game import Game class BowlingGameTest(unittest.TestCase): def setUp(self): self.g = Game() def tearDown(self): self.g = None def test_gutter_game(self): for i in range(20): self.g.roll(0); self.assertEqual(0, self.g.score()) def tes...
import unittest from game import Game class BowlingGameTest(unittest.TestCase): def setUp(self): self.g = Game() def tearDown(self): self.g = None def _roll_many(self, n, pins): "Roll 'n' times a roll of 'pins' pins" for i in range(n): self.g.roll(pins) d...
Refactor for code to roll many times
[Python] Refactor for code to roll many times
Python
mit
JesusMtnez/devexperto-challenge,JesusMtnez/devexperto-challenge
17bfdbfdf56e01a1bda24dab4b2ac35f871cb4c1
bmibuilder/build.py
bmibuilder/build.py
#! /usr/bin/env python from .writers.c import CWriter def main(): import argparse parser = argparse.ArgumentParser() parser.add_argument('file', type=argparse.FileType('r'), help='YAML file') parser.add_argument('--language', choices=('c', ), default='c', help='BMI language') ...
#! /usr/bin/env python import os from distutils.dir_util import mkpath from jinja2 import Environment, FileSystemLoader import yaml from .writers.c import CWriter YAML_TEMPLATE = """ name: <str> language: c grids: - id: <int> type: <str> rank: <int> time: units: <str> start: <float> end...
Use new jinja templating system.
Use new jinja templating system.
Python
mit
bmi-forum/bmi-builder,bmi-forum/bmi-builder,bmi-forum/bmi-builder
d2643bb7c4eba543da0067eb4bf82539d222845c
Lesson01_Variables/MilestonesSOLUTION.py
Lesson01_Variables/MilestonesSOLUTION.py
birth_year = raw_input("What is the birth year for the milestones?") # raw_input always gives strings, so convert to int birth_year = int(birth_year) # Calculate milestone years driving_year = birth_year + 16 drinking_year = birth_year + 21 president_year = birth_year + 35 print "You are able to drive in " + driving_...
birth_year = raw_input("What is the birth year for the milestones?") # raw_input always gives strings, so convert to int birth_year = int(birth_year) # Calculate milestone years driving_year = birth_year + 16 drinking_year = birth_year + 21 president_year = birth_year + 35 print "You are able to drive in " + str(driv...
Convert int to string for printing
Convert int to string for printing
Python
mit
WomensCodingCircle/CodingCirclePython
5c000543ce943619ea89b2443395a2ee10c49ee0
solutions/beecrowd/1010/1010.py
solutions/beecrowd/1010/1010.py
import sys s = 0.0 for line in sys.stdin: a, b, c = line.split() a, b, c = int(a), int(b), float(c) s += c * b print(f'VALOR A PAGAR: R$ {s:.2f}')
import sys s = 0.0 for line in sys.stdin: _, b, c = line.split() b, c = int(b), float(c) s += c * b print(f'VALOR A PAGAR: R$ {s:.2f}')
Refactor python version of Simple Calculate
Refactor python version of Simple Calculate
Python
mit
deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playgr...
fc5614c040cccff6411c87ad6cc191f7ec0b6971
SoftLayer/CLI/account/bandwidth_pools.py
SoftLayer/CLI/account/bandwidth_pools.py
"""Displays information about the accounts bandwidth pools""" # :license: MIT, see LICENSE for more details. import click from SoftLayer.CLI import environment from SoftLayer.CLI import formatting from SoftLayer.managers.account import AccountManager as AccountManager from SoftLayer import utils @click.command() @en...
"""Displays information about the accounts bandwidth pools""" # :license: MIT, see LICENSE for more details. import click from SoftLayer.CLI import environment from SoftLayer.CLI import formatting from SoftLayer.managers.account import AccountManager as AccountManager from SoftLayer import utils @click.command() @en...
Add id in the result in the command bandwidth-pools
Add id in the result in the command bandwidth-pools
Python
mit
softlayer/softlayer-python,allmightyspiff/softlayer-python
3f27e1997c94bcdac23e5cb478e7d2b9c6dc1f37
astropy/io/misc/asdf/__init__.py
astropy/io/misc/asdf/__init__.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- """ The **asdf** subpackage contains code that is used to serialize astropy types so that they can be represented and stored using the Advanced Scientific Data Format (ASDF). This subpackage defines classes, referred to as **tags**,...
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- """ The **asdf** subpackage contains code that is used to serialize astropy types so that they can be represented and stored using the Advanced Scientific Data Format (ASDF). This subpackage defines classes, referred to as **tags**,...
Put try/except around ASDF import in init file
Put try/except around ASDF import in init file
Python
bsd-3-clause
astropy/astropy,lpsinger/astropy,mhvk/astropy,MSeifert04/astropy,stargaser/astropy,saimn/astropy,stargaser/astropy,larrybradley/astropy,pllim/astropy,aleksandr-bakanov/astropy,dhomeier/astropy,astropy/astropy,stargaser/astropy,pllim/astropy,aleksandr-bakanov/astropy,astropy/astropy,saimn/astropy,larrybradley/astropy,dh...
ed1172cc12654cdf0d221281cd56c51992b4c4af
knotdirectory/knotdirectory/knots/forms.py
knotdirectory/knotdirectory/knots/forms.py
from django import forms from django.forms.models import inlineformset_factory from .models import Knot, Link class KnotForm(forms.ModelForm): class Meta: model = Knot fields = ['name', 'photo', 'other_names', 'creator_name', 'notes', 'tags'] class InlineLinkForm(forms.ModelForm): class Met...
from django import forms from django.forms.models import inlineformset_factory from django.utils import six from .models import Knot, Link def edit_string_for_tags(tags): """ Convert list of Tags into comma-separated list. We can't use the one built into django-taggit, because select2 freaks out abo...
Set up form to use special widget for tags
Set up form to use special widget for tags
Python
mit
althalus/knotcrafters,althalus/knotcrafters,althalus/knotcrafters
d19fd61e746ab4afcb534df6be933716e154b715
memopol/search/templatetags/search_tags.py
memopol/search/templatetags/search_tags.py
from django.core.urlresolvers import reverse from django.template.defaultfilters import urlencode from django import template from dynamiq.utils import get_advanced_search_formset_class from ..forms import MEPSearchForm, MEPSearchAdvancedFormset register = template.Library() @register.simple_tag def simple_search_...
from django.core.urlresolvers import reverse from django.template.defaultfilters import urlencode from django import template from dynamiq.utils import get_advanced_search_formset_class from ..forms import MEPSearchForm, MEPSearchAdvancedFormset register = template.Library() @register.simple_tag def simple_search_...
Make possible to define a sort in simple_search_shortcut tt
[enh] Make possible to define a sort in simple_search_shortcut tt
Python
agpl-3.0
yohanboniface/memopol-core,yohanboniface/memopol-core,yohanboniface/memopol-core
7c3c9e2ab7be0d91b4edc3d15d50cc1245941e47
logicaldelete/models.py
logicaldelete/models.py
from django.db import models try: from django.utils import timezone except ImportError: from datetime import datetime as timezonefrom logicaldelete import managers class Model(models.Model): """ This base model provides date fields and functionality to enable logical delete functionality in deriv...
from django.db import models from logicaldelete import managers try: from django.utils import timezone except ImportError: from datetime import datetime as timezone class Model(models.Model): """ This base model provides date fields and functionality to enable logical delete functionality in der...
Fix issue with manager (error w cut and paste)
Fix issue with manager (error w cut and paste)
Python
bsd-3-clause
angvp/django-logical-delete,angvp/django-logical-delete
30a982448b4f0baa2abe02ea0d9ef0d4d21c8414
Main.py
Main.py
from App import App #try: app = App() app.run() #except: # print('')
from App import App try: app = App() app.run() except KeyboardInterrupt: print('')
Add try except for keyboard interrupts
Add try except for keyboard interrupts
Python
mit
Rookfighter/TextAdventure
9f44c09dcb3ce3bd0bec591597e892d4037936f9
main.py
main.py
import os import json import sys from pprint import pprint def loadJSON(fInput): with open(fInput) as f: return json.load(f) return None if __name__ == '__main__': filePath = 'data/example.json' data = loadJSON(filePath) # check if the data is loaded correctly if data is None: ...
import os import json import sys from pprint import pprint def loadJSON(fInput): with open(fInput) as f: return json.load(f) return None if __name__ == '__main__': filePath = 'data/example.json' data = loadJSON(filePath) # check if the data is loaded correctly if data is None: ...
Add functions to generate python numpy datastructure and write it into generated python file.
Add functions to generate python numpy datastructure and write it into generated python file.
Python
apache-2.0
kilikkuo/kernel-mapper,PyOCL/kernel-mapper
3f178359b8649b6b92900ae790e894971405b720
main.py
main.py
from src import create from src import count from src import thefile from src import execute def main(x, y, file): #Create it seats = create.new_2d(x, y) #Count it counted_start = count.count_array(x, y, seats) print(counted_start) #Get the commands commands = thefile.get_cmmds(file) ...
from src import create from src import count from src import thefile from src import execute def main(x, y, file): #Create it seats = create.new_2d(x, y) #Count it counted_start = count.count_array(x, y, seats) print(counted_start) #Get the commands commands = thefile.get_cmmds(file) ...
CLEAN TEMPLATE Clean up the project template further still
CLEAN TEMPLATE Clean up the project template further still
Python
bsd-2-clause
kevindiltinero/seass3
c83dcddd7451d53214cf02f9ad72e280970a2dc8
hydromet/catchments.py
hydromet/catchments.py
import os import numpy as np from catchment_cutter import get_grid_cells def create_grids(catchments, in_directory, out_directory, grid_file): """ Create grid files for the supplied catchments. :param catchments: List of catchment IDs. :type catchments: Array(string) :param in_dir...
import os import numpy as np from catchment_tools import get_grid_cells def create_grids(catchments, in_directory, out_directory, grid_file): """ Create grid files for the supplied catchments. :param catchments: List of catchment IDs. :type catchments: Array(string) :param in_dire...
Use updated catchment tools import
Use updated catchment tools import
Python
bsd-3-clause
amacd31/hydromet-toolkit,amacd31/hydromet-toolkit
a7386ca8a26a7a1cb14c6a802d284c2b87114f3d
condor-copasi-daemon/condor-copasi-daemon.py
condor-copasi-daemon/condor-copasi-daemon.py
#!/usr/bin/env python #Script adapted from example by Sander Marechal, released into public domain #Taken from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/ import sys, time from daemon import Daemon from web_frontend import settings class MyDaemon(Daemon): def run(self): w...
#!/usr/bin/env python #Script adapted from example by Sander Marechal, released into public domain #Taken from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/ import sys, time from daemon import Daemon from web_frontend import settings class MyDaemon(Daemon): def run(self): w...
Remove print statements from daemon
Remove print statements from daemon
Python
artistic-2.0
Nucleoos/condor-copasi,copasi/condor-copasi,copasi/condor-copasi,Nucleoos/condor-copasi
c073bc3290bbe33ede95a23354062b48b68ca23f
kbcstorage/__init__.py
kbcstorage/__init__.py
from pkg_resources import get_distribution, DistributionNotFound try: __version__ = get_distribution('kbcstorage').version except DistributionNotFound: # package is not installed pass
from pkg_resources import get_distribution, DistributionNotFound try: release = get_distribution('kbcstorage').version __version__ = '.'.join(release.split('.')[:2]) except DistributionNotFound: # package is not installed pass
Make package version string major.minor only
Make package version string major.minor only
Python
mit
Ogaday/sapi-python-client,Ogaday/sapi-python-client
eb2f720d53ea4ff3450e78a30e1cdb53cd3357bb
tests/render/texture/runtest.py
tests/render/texture/runtest.py
#!/usr/bin/env python3 # # Copyright 2011-2015 Jeff Bush # # 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 l...
#!/usr/bin/env python3 # # Copyright 2011-2015 Jeff Bush # # 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 l...
Fix failing test caused by new toolchain
Fix failing test caused by new toolchain The challenge with floating point values in tests is that the value can change slightly based on the order of operations, which can legally be affected by optimizations. The results aren't visible (often just 1 ULP), but the tests validate exact bit patterns. This test would b...
Python
apache-2.0
jbush001/NyuziProcessor,jbush001/NyuziProcessor,jbush001/NyuziProcessor,jbush001/NyuziProcessor,jbush001/NyuziProcessor,jbush001/NyuziProcessor
a04f3d167011e6d0e50d6a088f5877769fbedaa2
testfixtures/shop_order.py
testfixtures/shop_order.py
""" testfixtures.shop_order ~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from byceps.services.shop.order.models.order import Order from byceps.services.shop.order.models.orderer import Orderer from byceps.services.shop.order import service fro...
""" testfixtures.shop_order ~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from byceps.services.shop.order.models.order import Order from byceps.services.shop.order.models.orderer import Orderer from byceps.services.shop.order.transfer.models im...
Remove unused test fixture `create_order_item`
Remove unused test fixture `create_order_item`
Python
bsd-3-clause
homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps
0cad0060afcc5936541b3739ff03c06b8a773ec8
tests/templatetags/test_tags.py
tests/templatetags/test_tags.py
from django import template from lazy_tags.decorators import lazy_tag register = template.Library() @register.simple_tag def test(): return '<p>hello world</p>' @register.simple_tag @lazy_tag def test_decorator(): return 'Success!' @register.simple_tag @lazy_tag def test_simple_dec_args(arg, kwarg=None...
from django import template from django.utils.safestring import mark_safe from lazy_tags.decorators import lazy_tag register = template.Library() @register.simple_tag def test(): return mark_safe('<p>hello world</p>') @register.simple_tag @lazy_tag def test_decorator(): return 'Success!' @register.simp...
Fix test on Django 1.9
Fix test on Django 1.9
Python
mit
grantmcconnaughey/django-lazy-tags,grantmcconnaughey/django-lazy-tags