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
1e6fcb134f55cb70ddd394a051a86c45aa50c944
cli_helpers/tabular_output/tabulate_adapter.py
cli_helpers/tabular_output/tabulate_adapter.py
from cli_helpers.packages import tabulate from .preprocessors import bytes_to_string, align_decimals tabulate.PRESERVE_WHITESPACE = True supported_markup_formats = ('mediawiki', 'html', 'latex', 'latex_booktabs', 'textile', 'moinmoin', 'jira') supported_table_formats = ('plain', 'simple', ...
from cli_helpers.packages import tabulate from .preprocessors import bytes_to_string, align_decimals supported_markup_formats = ('mediawiki', 'html', 'latex', 'latex_booktabs', 'textile', 'moinmoin', 'jira') supported_table_formats = ('plain', 'simple', 'grid', 'fancy_grid', 'pipe', ...
Make whitespace and numparse configurable.
Make whitespace and numparse configurable.
Python
bsd-3-clause
dbcli/cli_helpers,dbcli/cli_helpers
aa0ebe55ae5804f4f324a83de64e0879228261bd
securedrop/request_that_secures_file_uploads.py
securedrop/request_that_secures_file_uploads.py
from flask import wrappers from tempfile import NamedTemporaryFile from io import BytesIO class RequestThatSecuresFileUploads(wrappers.Request): def _secure_file_stream(self, total_content_length, content_type, filename=None, content_length=None): if total_content_length > 1024 * 5...
from io import BytesIO from flask import wrappers from secure_tempfile import SecureTemporaryFile class RequestThatSecuresFileUploads(wrappers.Request): def _secure_file_stream(self, total_content_length, content_type, filename=None, content_length=None): """Storage class for...
Use SecureTemporaryFile for Source Interface requests
Use SecureTemporaryFile for Source Interface requests
Python
agpl-3.0
jeann2013/securedrop,chadmiller/securedrop,harlo/securedrop,micahflee/securedrop,jrosco/securedrop,GabeIsman/securedrop,chadmiller/securedrop,heartsucker/securedrop,heartsucker/securedrop,chadmiller/securedrop,pwplus/securedrop,micahflee/securedrop,jeann2013/securedrop,jaseg/securedrop,ehartsuyker/securedrop,jrosco/sec...
9ba9e26888578e66469a63e412f46cf151fbcfd7
common/data_refinery_common/test_microarray.py
common/data_refinery_common/test_microarray.py
from unittest.mock import Mock, patch from django.test import TestCase from data_refinery_common import microarray CEL_FILE_HUMAN = "test-files/C30057.CEL" CEL_FILE_RAT = "test-files/SG2_u34a.CEL" CEL_FILE_MOUSE = "test-files/97_(Mouse430_2).CEL" CEL_FILE_ZEBRAFISH = "test-files/CONTROL6.cel" class MicroarrayTestCas...
from unittest.mock import Mock, patch from django.test import TestCase from data_refinery_common import microarray CEL_FILE_HUMAN = "test-files/C30057.CEL.gz" CEL_FILE_RAT = "test-files/SG2_u34a.CEL.gz" CEL_FILE_MOUSE = "test-files/97_(Mouse430_2).CEL.gz" CEL_FILE_ZEBRAFISH = "test-files/CONTROL6.cel.gz" class Micro...
Update test file paths for common to point to compressed versions.
Update test file paths for common to point to compressed versions.
Python
bsd-3-clause
data-refinery/data_refinery,data-refinery/data_refinery,data-refinery/data_refinery
42518bb29357194257b45989f9c64028f27ac804
boundaryservice/urls.py
boundaryservice/urls.py
from django.conf.urls.defaults import patterns, include, url from boundaryservice.views import * urlpatterns = patterns('', url(r'^boundary-set/$', BoundarySetListView.as_view(), name='boundaryservice_set_list'), url(r'^boundary-set/(?P<slug>[\w_-]+)/$', BoundarySetDetailView.as_view(), name='boundaryservice_...
from django.conf.urls.defaults import patterns, include, url from boundaryservice.views import * urlpatterns = patterns('', url(r'^boundary-set/$', BoundarySetListView.as_view(), name='boundaryservice_set_list'), url(r'^boundary-set/(?P<slug>[\w_-]+)/$', BoundarySetDetailView.as_view(), name='boundaryservice_...
Allow shape output on /boundary/ queries
Allow shape output on /boundary/ queries
Python
mit
opencorato/represent-boundaries,opencorato/represent-boundaries,datamade/represent-boundaries,opencorato/represent-boundaries,datamade/represent-boundaries,datamade/represent-boundaries
95cfb8176432fcf289571026ebfb88626ad8b3fb
mopidy_scrobbler/__init__.py
mopidy_scrobbler/__init__.py
import os from mopidy import config, ext __version__ = "1.2.1" class Extension(ext.Extension): dist_name = "Mopidy-Scrobbler" ext_name = "scrobbler" version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), "ext.conf") return config.rea...
import pathlib from mopidy import config, ext __version__ = "1.2.1" class Extension(ext.Extension): dist_name = "Mopidy-Scrobbler" ext_name = "scrobbler" version = __version__ def get_default_config(self): return config.read(pathlib.Path(__file__).parent / "ext.conf") def get_config_s...
Use pathlib to read ext.conf
Use pathlib to read ext.conf
Python
apache-2.0
mopidy/mopidy-scrobbler
4aab1eb2d2d3a0c9b9c4ab6df23b043e6822ff84
examples/delta/delta.py
examples/delta/delta.py
import sys from SALib.analyze import delta from SALib.util import read_param_file import numpy as np sys.path.append('../..') # Read the parameter range file and generate samples # Since this is "given data", the bounds in the parameter file will not be used # but the columns are still expected proble...
import sys from SALib.analyze import delta from SALib.util import read_param_file import numpy as np sys.path.append('../..') # Read the parameter range file and generate samples # Since this is "given data", the bounds in the parameter file will not be used # but the columns are still expected proble...
Fix up example with corrected path
Fix up example with corrected path
Python
mit
jdherman/SALib,SALib/SALib,jdherman/SALib
4e9de4dd4c408a056f72c833d89832a1981a7b0d
features/tags/forms.py
features/tags/forms.py
from django import forms from django.db.models.functions import Lower from . import models class TagGroup(forms.ModelForm): class Meta: model = models.Tagged fields = [] group = forms.ModelChoiceField(label='Gruppe', queryset=None) def __init__(self, **kwargs): tagger = kwargs.p...
from django import forms from django.db.models.functions import Lower from . import models class TagGroup(forms.ModelForm): class Meta: model = models.Tagged fields = [] group = forms.ModelChoiceField(label='Gruppe', queryset=None) def __init__(self, **kwargs): tagger = kwargs.p...
Fix save for empty tags
Fix save for empty tags
Python
agpl-3.0
stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten
8c00c71de736c54c22fedfae86101eb99846ba4f
anyjson.py
anyjson.py
""" Get the best JSON encoder/decoder available on this system. """ __version__ = "0.1" __author__ = "Rune Halvorsen <runefh@gmail.com>" __homepage__ = "http://bitbucket.org/runeh/anyjson/" __docformat__ = "restructuredtext" """ .. function:: serialize(obj) Serialize the object to JSON. .. function:: deseriali...
""" Get the best JSON encoder/decoder available on this system. """ __version__ = "0.1" __author__ = "Rune Halvorsen <runefh@gmail.com>" __homepage__ = "http://bitbucket.org/runeh/anyjson/" __docformat__ = "restructuredtext" """ .. function:: serialize(obj) Serialize the object to JSON. .. function:: deseriali...
Raise our own ImportError if all fails. Looks better than to complain about django when that happens
Raise our own ImportError if all fails. Looks better than to complain about django when that happens
Python
bsd-3-clause
newvem/anyjson,kennethreitz-archive/anyjson
4706d6feaff7057d04def0544e291900a754558e
nbgrader/apps/solutionapp.py
nbgrader/apps/solutionapp.py
from IPython.config.loader import Config from IPython.config.application import catch_config_error from IPython.utils.traitlets import Unicode from nbgrader.apps.customnbconvertapp import CustomNbConvertApp class SolutionApp(CustomNbConvertApp): name = Unicode(u'nbgrader-solution') description = Unicode(u...
from IPython.config.loader import Config from IPython.config.application import catch_config_error from IPython.utils.traitlets import Unicode from nbgrader.apps.customnbconvertapp import CustomNbConvertApp class SolutionApp(CustomNbConvertApp): name = Unicode(u'nbgrader-solution') description = Unicode(u...
Add files writer to solution app
Add files writer to solution app
Python
bsd-3-clause
ellisonbg/nbgrader,jupyter/nbgrader,modulexcite/nbgrader,ellisonbg/nbgrader,modulexcite/nbgrader,jupyter/nbgrader,ellisonbg/nbgrader,dementrock/nbgrader,jdfreder/nbgrader,jupyter/nbgrader,EdwardJKim/nbgrader,jhamrick/nbgrader,MatKallada/nbgrader,dementrock/nbgrader,jhamrick/nbgrader,jupyter/nbgrader,alope107/nbgrader,a...
20733c6b3d3bc249098297a73341f56e781aabbe
plugins/storage/storagetype/test/test_integration.py
plugins/storage/storagetype/test/test_integration.py
#!/usr/bin/env python #-*- coding: utf-8 -*- #This software is distributed under the Creative Commons license (CC0) version 1.0. A copy of this license should have been distributed with this software. #The license can also be read online: <https://creativecommons.org/publicdomain/zero/1.0/>. If this online license dif...
#!/usr/bin/env python #-*- coding: utf-8 -*- #This software is distributed under the Creative Commons license (CC0) version 1.0. A copy of this license should have been distributed with this software. #The license can also be read online: <https://creativecommons.org/publicdomain/zero/1.0/>. If this online license dif...
Add simple test case to test plug-in discovery
Add simple test case to test plug-in discovery This just tests if can_read is callable for now, but at least the plug-in discovery in tests works. It doesn't work beautifully, but we can work from here.
Python
cc0-1.0
Ghostkeeper/Luna
23a9aaae78cc4d9228f8d0705647fbcadcaf7975
markymark/fields.py
markymark/fields.py
from django import forms from django.db import models from .widgets import MarkdownTextarea class MarkdownFormField(forms.fields.CharField): def __init__(self, *args, **kwargs): kwargs['widget'] = MarkdownTextarea super(MarkdownFormField, self).__init__(*args, **kwargs) class MarkdownField(mode...
from django import forms from django.db import models from .widgets import MarkdownTextarea class MarkdownFormField(forms.fields.CharField): def __init__(self, *args, **kwargs): kwargs['widget'] = kwargs.pop('widget', MarkdownTextarea) super(MarkdownFormField, self).__init__(*args, **kwargs) cl...
Allow widget overwriting on form field
Allow widget overwriting on form field
Python
mit
moccu/django-markymark,moccu/django-markymark,moccu/django-markymark
dbe28b1d00a17acdd276263c9042dbd7b5dfc311
src/adhocracy_kit/adhocracy_kit/__init__.py
src/adhocracy_kit/adhocracy_kit/__init__.py
"""Adhocracy extension.""" from pyramid.config import Configurator from adhocracy_core import root_factory def includeme(config): """Setup adhocracy extension. The kit package should be exactly like the spd package but with different root permissions and default translations for the emails. """ ...
"""Adhocracy extension.""" from pyramid.config import Configurator from adhocracy_core import root_factory def includeme(config): """Setup adhocracy extension. The kit package should be exactly like the spd package but with different root permissions and default translations for the emails. """ ...
Fix wrong config includes in kit package
Fix wrong config includes in kit package
Python
agpl-3.0
liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.m...
2e299c5c2a35d3cd42be43c90af41c28e5d27c15
reindexer/reindex_shard_generator/src/test_reindex_shard_config.py
reindexer/reindex_shard_generator/src/test_reindex_shard_config.py
# -*- encoding: utf-8 import pytest from reindex_shard_config import create_reindex_shard @pytest.mark.parametrize( 'source_name, source_id, expected_reindex_shard', [ ('sierra', 'b0000001', 'sierra/2441'), ('miro', 'A0000001', 'miro/128') ]) def test_create_reindex_shard(source_name, source_id, expecte...
# -*- encoding: utf-8 import pytest from reindex_shard_config import create_reindex_shard @pytest.mark.parametrize( 'source_name, source_id, expected_reindex_shard', [ ('sierra', 'b0000001', 'sierra/2441'), ('miro', 'A0000001', 'miro/128') ]) def test_create_reindex_shard(source_name, source_id, expecte...
Fix a Python lint error
Fix a Python lint error
Python
mit
wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api
eff924e07999bd0aaaa36373c658efb1ffefe5c7
magpie/utils/solr.py
magpie/utils/solr.py
from mysolr import Solr from magpie.settings import settings _solr = None def open_solr_connection(core_name): global _solr if not _solr: url = '{}/{}'.format(settings.SOLR_URL, core_name) _solr = Solr(url) return _solr
from mysolr import Solr from magpie.settings import settings _solr = None def open_solr_connection(core_name): global _solr if not _solr: url = '{}/{}'.format(settings.SOLR_URL, core_name) _solr = Solr(url) return _solr def escape_solr_query(query): """ Escape special chars fo...
Add method to escape special chars in Solr queries
Add method to escape special chars in Solr queries
Python
apache-2.0
nimiq/moogle-project
8d831e4834b61c04b3f5f2d8a812095eea8c022f
personDb.py
personDb.py
import pickle class PersonDb(object): def __init__(self, dbName, autoload = True): self.dbName = dbName self.db = None if autoload: self.setup() def setup(self): self.db = PersonDb.load(self.dbName) self.getGroups() def getGroups(self): tmp = s...
import pickle import os class PersonDb(object): def __init__(self, dbName, autoload = True): self.dbName = dbName self.db = None if autoload: self.setup() def setup(self): self.db = PersonDb.load(self.dbName) self.getGroups() def getGroups(self): ...
Add handling of not present file.
Add handling of not present file. Signed-off-by: Matej Dujava <03ce64f61b3ea1fda633fb2a103b989e3272d16b@gmail.com>
Python
mit
matejd11/birthdayNotify
42901554db49cd1204054ea695cea6ee4e368b1e
tests/basics/int-long.py
tests/basics/int-long.py
# This tests long ints for 32-bit machine a = 0x1ffffffff b = 0x100000000 print(a) print(b) print(a + b) print(a - b) print(b - a) # overflows long long implementation #print(a * b) print(a // b) print(a % b) print(a & b) print(a | b) print(a ^ b) print(a << 3) print(a >> 1) a += b print(a) a -= 123456 print(a) a *= ...
# This tests long ints for 32-bit machine a = 0x1ffffffff b = 0x100000000 print(a) print(b) print(a + b) print(a - b) print(b - a) # overflows long long implementation #print(a * b) print(a // b) print(a % b) print(a & b) print(a | b) print(a ^ b) print(a << 3) print(a >> 1) a += b print(a) a -= 123456 print(a) a *= ...
Add regression test for improper inplace op implementation.
objint_longlong: Add regression test for improper inplace op implementation.
Python
mit
jmarcelino/pycom-micropython,cwyark/micropython,puuu/micropython,rubencabrera/micropython,lbattraw/micropython,warner83/micropython,skybird6672/micropython,methoxid/micropystat,blmorris/micropython,alex-march/micropython,rubencabrera/micropython,dxxb/micropython,firstval/micropython,ahotam/micropython,TDAbboud/micropyt...
1771e1d37f48c62dc20c3a83e480b98cb7c4500c
xoinvader/application.py
xoinvader/application.py
import time class Application(object): def __init__(self, startup_args={}): self._state = None self._states = {} self._mspf = None # ms per frame @property def state(self): return self._state @state.setter def state(self, name): if name in self._states: ...
import time class Application(object): def __init__(self, startup_args={}): self._state = None self._states = {} self._mspf = None # ms per frame self._running = False @property def running(self): return self._running @property def state(self): if ...
Make loop stopable, some fixes.
Make loop stopable, some fixes.
Python
mit
pkulev/xoinvader,pankshok/xoinvader
ea46030784640d86a70c382ece7913eeb0996ba9
01_dataprep/trn_to_phn.py
01_dataprep/trn_to_phn.py
#!/usr/bin/env python3 import os import sys def main(trn_file, phn_dir): phone_map = {v[0]: v[1].strip() for v in (l.split(None, 1) for l in open('data/phone_map', encoding='utf-8'))} for line in open(trn_file): parts = line.split() sentence = parts[:-1] sid = parts[-1][1:-1] ...
#!/usr/bin/env python3 import os import sys def main(langdat_dir, trn_file, phn_dir): phone_map = {v[0]: v[1].strip() for v in (l.split(None, 1) for l in open('{}/phones'.format(langdat_dir), encoding='utf-8'))} for line in open(trn_file): parts = line.split() sentence = parts[:-1] si...
Fix trn to phn script
Fix trn to phn script
Python
bsd-3-clause
phsmit/iwclul2016-scripts,phsmit/iwclul2016-scripts,phsmit/iwclul2016-scripts
03ad5a9e31127828ce7f14de61af80af20362624
test/field/test_date.py
test/field/test_date.py
# encoding: utf-8 from __future__ import unicode_literals from common import FieldExam from marrow.mongo.field import Date class TestDateField(FieldExam): __field__ = Date
# encoding: utf-8 from __future__ import unicode_literals from datetime import datetime from bson import ObjectId from common import FieldExam from marrow.mongo.field import Date class TestDateField(FieldExam): __field__ = Date def test_date_like_oid(self, Sample): oid = ObjectId('586846800000000000000000') ...
Add test for extraction of dates from ObjectIds.
Add test for extraction of dates from ObjectIds.
Python
mit
marrow/mongo
326ae45949c2ee4f53e9c377582313155d9d0b70
kk/models/base.py
kk/models/base.py
from django.conf import settings from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ class ModifiableModel(models.Model): created_at = models.DateTimeField(verbose_name=_('Time of creation'), default=timezone.now) created_by = models.ForeignKe...
import base64 import struct from django.conf import settings from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ def generate_id(): t = time.time() * 1000000 b = base64.b32encode(struct.pack(">Q", int(t)).lstrip(b'\x00')).strip(b'=').lower() ...
Set char primary key. Generate ID.
Set char primary key. Generate ID.
Python
mit
vikoivun/kerrokantasi,stephawe/kerrokantasi,City-of-Helsinki/kerrokantasi,vikoivun/kerrokantasi,stephawe/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,vikoivun/kerrokantasi,stephawe/kerrokantasi
b21f540ca7b53aeb569f7034de41da0dc4dd7b03
__init__.py
__init__.py
from vod_metadata.md5_checksum import * from vod_metadata.media_info import * from vod_metadata.parse_config import * from vod_metadata.VodPackage import * (extensions, MediaInfo_path, product, provider_id, prefix, title_category, provider, ecn_2009) = parse_config("./template_values.ini")
import os.path from vod_metadata.md5_checksum import * from vod_metadata.media_info import * from vod_metadata.parse_config import * from vod_metadata.VodPackage import * _script_path = os.path.abspath(__file__) _script_path = os.path.split(_script_path)[0] config_path = os.path.join(_script_path, "template_values.ini...
Read the configuration file upon import
Read the configuration file upon import
Python
mit
bbayles/vod_metadata
1fe88c1a619211a93297e1081133017ff2ef0370
scenario/__main__.py
scenario/__main__.py
import sys from scenario import run_scenario def main(args=None): if args is None: args = sys.argv[1:] assert len(args) == 2, 'Usage: python -m foo <executable> <scenario>' executable_path = args[0] scenario_path = args[1] run_scenario(executable_path, scenario_path) if __name__ =...
import sys from scenario import run_scenario def main(args=None): if args is None: args = sys.argv[1:] assert len(args) == 2, 'Usage: scenario <executable> <scenario>' executable_path = args[0] scenario_path = args[1] run_scenario(executable_path, scenario_path) if __name__ == '__...
Update command line usage with scenario
Update command line usage with scenario
Python
mit
shlomihod/scenario,shlomihod/scenario,shlomihod/scenario
c85631d77cd25de520688666a3d0e72537e482eb
acquisition_record.py
acquisition_record.py
""" AcquisitionRecord: database interface class. These classes provide an interface between the database and the top-level ingest algorithm (AbstractIngester and its subclasses). They also provide the implementation of the database and tile store side of the ingest process. They are expected to be independent of the s...
""" AcquisitionRecord: database interface class. These classes provide an interface between the database and the top-level ingest algorithm (AbstractIngester and its subclasses). They also provide the implementation of the database and tile store side of the ingest process. They are expected to be independent of the s...
Test of github push from Eclipse.
Test of github push from Eclipse.
Python
apache-2.0
ama-jharrison/agdc,GeoscienceAustralia/agdc,jeremyh/agdc,sixy6e/agdc,jeremyh/agdc,smr547/agdc,smr547/agdc,alex-ip/agdc,sixy6e/agdc,GeoscienceAustralia/agdc,alex-ip/agdc,ama-jharrison/agdc
6403229da220fddac236a8e3ccf061446c37e27c
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
Vauxoo/server-tools,Vauxoo/server-tools,Vauxoo/server-tools
33394f4081880c2718f1c017fb90588628c2bfcc
tests/test_extension.py
tests/test_extension.py
import unittest import mock from mopidy_spotify import Extension, backend as backend_lib class ExtensionTest(unittest.TestCase): def test_get_default_config(self): ext = Extension() config = ext.get_default_config() self.assertIn('[spotify]', config) self.assertIn('enabled = t...
import mock from mopidy_spotify import Extension, backend as backend_lib def test_get_default_config(): ext = Extension() config = ext.get_default_config() assert '[spotify]' in config assert 'enabled = true' in config def test_get_config_schema(): ext = Extension() schema = ext.get_conf...
Convert extension tests to pytest syntax
tests: Convert extension tests to pytest syntax
Python
apache-2.0
jodal/mopidy-spotify,kingosticks/mopidy-spotify,mopidy/mopidy-spotify
69d2620ee64d367331edcf0260c73034384aae8e
subprocrunner/retry.py
subprocrunner/retry.py
import time from random import uniform from typing import Callable, Optional class Retry: def __init__(self, total: int = 3, backoff_factor: float = 0.2, jitter: float = 0.2) -> None: self.total = total self.__backoff_factor = backoff_factor self.__jitter = jitter if self.total <=...
import time from random import uniform from typing import Callable, Optional class Retry: def __init__( self, total: int = 3, backoff_factor: float = 0.2, jitter: float = 0.2, quiet: bool = False ) -> None: self.total = total self.__backoff_factor = backoff_factor self.__jitter...
Add quiet mode support for Retry
Add quiet mode support for Retry
Python
mit
thombashi/subprocrunner,thombashi/subprocrunner
d676065cb9f137c5feb18b125d0d30dfae4e0b65
Dice.py
Dice.py
import random class Die(object): def __init__(self, sides = 6): self.sides = sides self.held = False self.die_face = 1 def change_held(self, held): self.held = held def roll_die(self): if (self.held == False): self.die_face = random.randint(1, self.sides) ...
import random class Die(object): def __init__(self, sides = 6): self.sides = sides self.held = False self.die_face = 1 def change_held(self, held): self.held = held def roll_die(self): if (self.held == False): self.die_face = random.randint(1, self.sides) ...
Add get dice roll function
Add get dice roll function
Python
mit
achyutreddy24/DiceGame
8ea896e3290d441e6025822cc4e67b2fd86c3a8c
social_django/compat.py
social_django/compat.py
# coding=utf-8 import six import django from django.db import models try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse if django.VERSION >= (1, 10): from django.utils.deprecation import MiddlewareMixin else: MiddlewareMixin = object def get_rel_mod...
# coding=utf-8 import six import django from django.db import models try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse try: from django.utils.deprecation import MiddlewareMixin except ImportError: MiddlewareMixin = object def get_rel_model(field):...
Remove version check in favor of import error check
Remove version check in favor of import error check
Python
bsd-3-clause
python-social-auth/social-app-django,python-social-auth/social-app-django,python-social-auth/social-app-django
342f2a948ba88d6c67c003457923b135234088a0
JSON.py
JSON.py
import os import json import ast from functions import quit from encryption import encrypt, decrypt global name global key def setOfflineUsername(_name, _key): global name global key name = _name key = _key def getServicesOffline(): dir_path = os.path.expanduser("~/.passman") file_path = os....
import os import json import ast from functions import quit from encryption import encrypt, decrypt global name global key def setOfflineUsername(_name, _key): global name global key name = _name key = _key def getServicesOffline(): global name dir_path = os.path.expanduser("~/.passman") f...
Call global name in getservicesoffline function
Call global name in getservicesoffline function
Python
mit
regexpressyourself/passman
a6ae05c13666b83a1f1a8707fe21972bd1f758d9
walltime.py
walltime.py
#!/usr/bin/env python """ Created on Fri Mar 14 15:25:36 2014 @author: ibackus """ import matplotlib.pyplot as plt import numpy as np import datetime import sys if len(sys.argv) < 2: print 'USAGE: walltime filename' else: fname = sys.argv[-1] log_file = np.genfromtxt(fname, comments='#...
#!/usr/bin/env python """ Created on Fri Mar 14 15:25:36 2014 @author: ibackus """ import time t0 = time.time() import matplotlib.pyplot as plt import numpy as np import datetime import sys t1 = time.time() print 'Importing took {} s'.format(t1-t0) if len(sys.argv) < 2: print 'USAGE: walltime filename...
Print statements added for profiling
Print statements added for profiling
Python
mit
ibackus/custom_python_packages,trquinn/custom_python_packages
692a6d4480e917ff2648bac7ac4975f981e4c571
scripts/util/assignCounty.py
scripts/util/assignCounty.py
from pyIEM import iemdb import re i = iemdb.iemdb() mydb = i["mesosite"] rs = mydb.query("select s.id, c.name from stations s, counties c WHERE \ s.geom && c.the_geom and s.county IS NULL").dictresult() for i in range(len(rs)): id = rs[i]['id'] cnty = re.sub("'", " ", rs[i]['name']) print id, cnty mydb.que...
from pyIEM import iemdb import re i = iemdb.iemdb() mydb = i["mesosite"] rs = mydb.query(""" select s.id, c.name from stations s, counties c, states t WHERE ST_Contains(c.the_geom, s.geom) and s.geom && c.the_geom and s.county IS NULL and s.state = t.state_abbr and t.state_fips = c.state_fips """).dictresul...
Make sure that the county is in the right state even.
Make sure that the county is in the right state even.
Python
mit
akrherz/iem,akrherz/iem,akrherz/iem,akrherz/iem,akrherz/iem
2dbd2d385e821cee9a8bc8414bfba71c8b4dbc06
tests/test_ehrcorral.py
tests/test_ehrcorral.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_ehrcorral ---------------------------------- Tests for `ehrcorral` module. """ import unittest from ehrcorral import ehrcorral class TestEhrcorral(unittest.TestCase): def setUp(self): pass def test_something(self): pass def tear...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_ehrcorral ---------------------------------- Tests for `ehrcorral` module. """ from __future__ import print_function from __future__ import division from __future__ import absolute_import from __future__ import unicode_literals import unittest from ehrcorral i...
Add test case setUp to generate fake patient info
Add test case setUp to generate fake patient info
Python
isc
nsh87/ehrcorral
4783f7047500865da06202a7d6d777801cf49c71
Box.py
Box.py
class Box: def __init__(self, length, width, height): self.length = length self.width = width self.height = height self.plist = list() def main(): N = input() box = list() for i in range(N): x = input() x = x.split('') b = Box(x[0], x[1], x[2]) ...
class Box: def __init__(self, length, width, height): self.length = length self.width = width self.height = height self.plist = list() self.plength = 0 def __lt__(self, other): return (self.length < other.length and self.width < other.width ...
Redefine function __lt__ and define a function to set link with others.
Redefine function __lt__ and define a function to set link with others.
Python
mit
hane1818/Algorithm_HW4_box_problem
ea15b51ad444eeca3fdbc9eeb30fb8434ec3bfbd
pyscores/api_wrapper.py
pyscores/api_wrapper.py
import json import os import requests class APIWrapper(object): def __init__(self, base_url=None, auth_token=None): if base_url: self.base_url = base_url else: self.base_url = "http://api.football-data.org/v1" if auth_token: self.headers = { ...
import os import requests class APIWrapper(object): def __init__(self, base_url=None, auth_token=None): if base_url: self.base_url = base_url else: self.base_url = "http://api.football-data.org/v1" if auth_token: self.headers = { 'X-A...
Remove unused json import in api wrapper
Remove unused json import in api wrapper
Python
mit
conormag94/pyscores
3d48732d577514d888ba5769a27d811d55fd9979
app.py
app.py
from flask import Flask import subprocess from config import repos app = Flask(__name__) @app.route("/", methods=['GET']) def hello(): current_repo = repos.get('key') remote_name = current_repo('remote_name') remote_branch = current_repo('remote_branch') local_dir = current_repo('local_dir') cmd =...
from flask import Flask from flask import request import subprocess from config import repos app = Flask(__name__) @app.route("/", methods=['GET']) def hello(): repo_id = request.args.get('key') current_repo = repos.get(repo_id) remote_name = current_repo.get('remote_name') remote_branch = current_rep...
Send repo id in get param
Send repo id in get param
Python
mit
Heads-and-Hands/pullover
552ea94c9fe2a42a8041d986e929b7defcdc4a4e
bot.py
bot.py
#! /usr/bin/env python from time import gmtime, strftime from foaas import foaas from diaspy_client import Client import re import urllib2 client = Client() notify = client.notifications() for n in notify: if not n.unread: continue idm = re.search('href=\\"/posts/(\d+?)\\"', n._data['note_html']) if hasattr(i...
#! /usr/bin/env python from time import gmtime, strftime from foaas import foaas from diaspy_client import Client import re import urllib2 client = Client() notify = client.notifications() for n in notify: if not n.unread: continue idm = re.search('href=\\"/posts/(\d+?)\\"', n._data['note_html']) if hasattr(i...
Add link to foaas profile
Add link to foaas profile
Python
mit
Zauberstuhl/foaasBot
ea4949dab887a14a0ca8f5ffbcd3c578c61c005e
api/urls.py
api/urls.py
from django.conf.urls import include, url from api import views urlpatterns = [ url(r'^services/$', views.services, name='api-services'), url(r'^collect/$', views.collect_response, name='api-collect'), url(r'^search/text/$', views.text_search, name='api-text-search'), url(r'^license/$', views.licensing...
from django.conf.urls import include, url from api import views urlpatterns = [ url(r'^v1/services/$', views.services, name='api-services'), url(r'^v1/collect/$', views.collect_response, name='api-collect'), url(r'^v1/search/text/$', views.text_search, name='api-text-search'), url(r'^v1/license/$', vie...
Add API versioning at the url
Add API versioning at the url https://github.com/AudioCommons/ac-mediator/issues/13
Python
apache-2.0
AudioCommons/ac-mediator,AudioCommons/ac-mediator,AudioCommons/ac-mediator
21193559b063e85f26971d5ae6181a0bd097cda3
tests/utilities_test.py
tests/utilities_test.py
#pylint: disable=W0104,W0108 import pytest import pyop import numpy as np ####################################################################### # Tests # ####################################################################### def testEnsure2dColumn(cap...
#pylint: disable=W0104,W0108 import pyop import numpy as np ####################################################################### # Tests # ####################################################################### def testEnsure2dColumn(capsys): @py...
Test vector, passes matrix and vector input.
Test vector, passes matrix and vector input.
Python
bsd-3-clause
ryanorendorff/pyop
98a6b04b83843861003862d835b3a2f6f2364506
tests/context_tests.py
tests/context_tests.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from mock import Mock from nose.tools import eq_ from cg.context import Context, ContextFactory class TestContextFactory(object): def test_context_gets_created_correctly(self): handle = 123 bridge = Mock()...
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from mock import Mock from nose.tools import eq_ from cg.context import Context, ContextFactory class TestContextFactory(object): def test_context_gets_created_correctly(self): handle = 123 bridge = Mock()...
Update test to match last changes in the API
Update test to match last changes in the API
Python
mit
jstasiak/python-cg,jstasiak/python-cg
377beee13a8cd0ca23f8f2e37dd2816571721921
tests/sources_tests.py
tests/sources_tests.py
import os import subprocess from nose.tools import istest, assert_equal from whack.sources import PackageSourceFetcher from whack.tempdir import create_temporary_dir from whack.files import read_file, write_file @istest def can_fetch_package_source_from_source_control(): with create_temporary_dir() as package_s...
import os import subprocess from nose.tools import istest, assert_equal from whack.sources import PackageSourceFetcher from whack.tempdir import create_temporary_dir from whack.files import read_file, write_file @istest def can_fetch_package_source_from_source_control(): with create_temporary_dir() as package_s...
Add test for fetching local package sources
Add test for fetching local package sources
Python
bsd-2-clause
mwilliamson/whack
c4db09cd2d4dac37afcf75d5cf4d8c8f881aac2d
tests/test_examples.py
tests/test_examples.py
'''Search all our doc comments for "Example" blocks and try executing them.''' import re import sourcer def run_examples(package): pattern = re.compile(r''' (\s*) # initial indent Example # magic keyword ([^\n]*) # optional description \:\: # magic marker #...
'''Search all our doc comments for "Example" blocks and try executing them.''' import re import sourcer.expressions def run_examples(package): pattern = re.compile(r''' (\s*) # initial indent Example # magic keyword ([^\n]*) # optional description \:\: # magic marke...
Test the doc comments in the expressions module.
Test the doc comments in the expressions module.
Python
mit
jvs/sourcer
aaae301f62b4e0b3cdd5d1756a03b619a8f18222
tests/test_hamilton.py
tests/test_hamilton.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the Hamiltonian method.""" import pytest from numpy.testing import assert_allclose from parameters import KPT, T_VALUES @pytest.mark.parametrize("kpt", KPT) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def te...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the Hamiltonian method.""" import pytest from numpy.testing import assert_allclose from parameters import KPT, T_VALUES @pytest.mark.parametrize("kpt", KPT) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def te...
Add test for invalid 'convention' in hamilton method
Add test for invalid 'convention' in hamilton method
Python
apache-2.0
Z2PackDev/TBmodels,Z2PackDev/TBmodels
08730308134d0a15be996e8e7bb1a19bc1930f12
tests/test_plotting.py
tests/test_plotting.py
from contextlib import contextmanager import os import tempfile import unittest from matplotlib.pyplot import Artist, savefig from shapely.geometry import Polygon, LineString, Point from geopandas import GeoSeries @contextmanager def get_tempfile(): f, path = tempfile.mkstemp() try: yield path f...
import os import unittest from matplotlib.pyplot import Artist, savefig from matplotlib.testing.decorators import image_comparison from shapely.geometry import Polygon, LineString, Point from geopandas import GeoSeries # If set to True, generate images rather than perform tests (all tests will pass!) GENERATE_BASELI...
Use matplotlib image_comparison to actually compare plot output
TST: Use matplotlib image_comparison to actually compare plot output
Python
bsd-3-clause
jorisvandenbossche/geopandas,jorisvandenbossche/geopandas,jdmcbr/geopandas,koldunovn/geopandas,ozak/geopandas,maxalbert/geopandas,IamJeffG/geopandas,ozak/geopandas,geopandas/geopandas,fonnesbeck/geopandas,kwinkunks/geopandas,geopandas/geopandas,geopandas/geopandas,jorisvandenbossche/geopandas,urschrei/geopandas,snario/...
5b8b210a73282f6176883f3fab1dd0b2801b3f34
wsgi/app.py
wsgi/app.py
# flake8: noqa # newrelic import & initialization must come first # https://docs.newrelic.com/docs/agents/python-agent/installation/python-agent-advanced-integration#manual-integration try: import newrelic.agent except ImportError: newrelic = False if newrelic: newrelic_ini = config('NEWRELIC_PYTHON_INI_F...
# flake8: noqa # newrelic import & initialization must come first # https://docs.newrelic.com/docs/agents/python-agent/installation/python-agent-advanced-integration#manual-integration try: import newrelic.agent except ImportError: newrelic = False else: newrelic.agent.initialize() import os from bedrock...
Remove unused ability to use custom newrelic.ini
Remove unused ability to use custom newrelic.ini
Python
mpl-2.0
flodolo/bedrock,craigcook/bedrock,hoosteeno/bedrock,sylvestre/bedrock,craigcook/bedrock,pascalchevrel/bedrock,kyoshino/bedrock,kyoshino/bedrock,sgarrity/bedrock,ericawright/bedrock,ericawright/bedrock,MichaelKohler/bedrock,mozilla/bedrock,alexgibson/bedrock,alexgibson/bedrock,hoosteeno/bedrock,ericawright/bedrock,sgarr...
0e533ad0cc42431a57758b577cf96783ee4b7484
spacy/tests/test_download.py
spacy/tests/test_download.py
# coding: utf-8 from __future__ import unicode_literals from ..download import download, get_compatibility, get_version, check_error_depr import pytest def test_download_fetch_compatibility(): compatibility = get_compatibility() assert type(compatibility) == dict @pytest.mark.slow @pytest.mark.parametrize(...
# coding: utf-8 from __future__ import unicode_literals from ..download import download, get_compatibility, get_version, check_error_depr import pytest @pytest.mark.slow def test_download_fetch_compatibility(): compatibility = get_compatibility() assert type(compatibility) == dict @pytest.mark.slow @pytest...
Mark compatibility table test as slow (temporary)
Mark compatibility table test as slow (temporary) Prevent Travis from running test test until models repo is published
Python
mit
oroszgy/spaCy.hu,oroszgy/spaCy.hu,aikramer2/spaCy,spacy-io/spaCy,raphael0202/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,aikramer2/spaCy,spacy-io/spaCy,explosion/spaCy,oroszgy/spaCy.hu,raphael0202/spaCy,recognai/spaCy,spacy-io/spaCy,spacy-io/spaCy,Gregory-Howard/spaCy,oroszgy/spaCy.hu,oroszgy/spaCy.hu,raphael0202/spaCy,...
a6a4c2920abd099a97839584b96af10dcd25afe2
tests/test_public_api.py
tests/test_public_api.py
# This file is part of python-markups test suite # License: BSD # Copyright: (C) Dmitry Shachnev, 2012-2015 import markups import unittest class APITest(unittest.TestCase): def test_api(self): all_markups = markups.get_all_markups() self.assertIn(markups.MarkdownMarkup, all_markups) self.assertIn(markups.ReStr...
# This file is part of python-markups test suite # License: BSD # Copyright: (C) Dmitry Shachnev, 2012-2015 import markups import unittest class APITest(unittest.TestCase): def test_api(self): all_markups = markups.get_all_markups() self.assertIn(markups.MarkdownMarkup, all_markups) self.assertIn(markups.ReStr...
Add a test for get_available_markups() function
Add a test for get_available_markups() function
Python
bsd-3-clause
mitya57/pymarkups,retext-project/pymarkups
9ce5a020ac6e9bbdf7e2fc0c34c98cdfaf9e0a45
tests/formatters/conftest.py
tests/formatters/conftest.py
import npc import pytest @pytest.fixture(scope="module") def character(): char = npc.character.Character() char.append('description', 'Fee fie foe fum') char.append('type', 'human') return char
import npc import pytest @pytest.fixture(scope="module") def character(): char = npc.character.Character() char.tags('description').append('Fee fie foe fum') char.tags('type').append('human') return char
Set up defaults using tag syntax
Set up defaults using tag syntax
Python
mit
aurule/npc,aurule/npc
69ec55e0a6b4d314eb1381afc09236a5aa01d3d8
util/git-author-comm.py
util/git-author-comm.py
#!/usr/bin/env python # Display authors which appear as contributors in both (two) repositories. import os,sys def usage(): print 'Show authors which appear in two git repositories.' print 'python2 git-author-comm.py [path-to-git-repo] [path-to-git-repo]' def sysout(command): return os.popen(command).read() d...
#!/usr/bin/env python # Display authors which appear as contributors in both (two) repositories. import os,sys def usage(): print 'Show authors which appear in two local git repositories.' print 'python2 git-author-comm.py [path-to-local-git-repo] [path-to-local-git-repo]' def sysout(command): return os.popen(...
Make it more obvious that you need to use a local repository as an argument, not a url
Make it more obvious that you need to use a local repository as an argument, not a url
Python
mit
baykovr/toolbox,baykovr/toolbox,baykovr/toolbox,baykovr/toolbox,baykovr/toolbox
4669a033ee4fbde5e3c2447778657a20a73d5df8
thefuck/shells/powershell.py
thefuck/shells/powershell.py
from .generic import Generic class Powershell(Generic): def app_alias(self, fuck): return 'function ' + fuck + ' { \n' \ ' $fuck = $(thefuck (Get-History -Count 1).CommandLine);\n' \ ' if (-not [string]::IsNullOrWhiteSpace($fuck)) {\n' \ ' if ($fuc...
from .generic import Generic class Powershell(Generic): def app_alias(self, fuck): return 'function ' + fuck + ' {\n' \ ' $history = (Get-History -Count 1).CommandLine;\n' \ ' if (-not [string]::IsNullOrWhiteSpace($history)) {\n' \ ' $fuck = $(thef...
Update PowerShell alias to handle no history
Update PowerShell alias to handle no history If history is cleared (or the shell is new and there is no history), invoking thefuck results in an error because the alias attempts to execute the usage string. The fix is to check if Get-History returns anything before invoking thefuck.
Python
mit
Clpsplug/thefuck,scorphus/thefuck,nvbn/thefuck,nvbn/thefuck,scorphus/thefuck,mlk/thefuck,Clpsplug/thefuck,mlk/thefuck,SimenB/thefuck,SimenB/thefuck
7654d9dcebb0ad1e862e376b5b694234173289ed
twitter_helper/util.py
twitter_helper/util.py
import random def random_line(afile, max_chars = 123, min_chars = 5): line = next(afile) for num, aline in enumerate(afile): aline = aline.strip() if (len(aline) < min_chars or aline[0].islower() or len(aline) > max_chars) or random.randrange(num + 2): continue line = aline ...
import random def random_line(afile, max_chars = 123, min_chars = 5): line = next(afile) for num, aline in enumerate(afile): aline = aline.strip() if (len(aline) < min_chars or aline[0].islower() or len(aline) > max_chars) or random.randrange(num + 2): continue line = aline ...
Reset pointer to the beginning of file once read it
Reset pointer to the beginning of file once read it Be polite, put things back in the place you found them
Python
mit
kuzeko/Twitter-Importer,kuzeko/Twitter-Importer
8307188a5cbaf0dab824b58a6436affdea1b039b
mesonwrap/inventory.py
mesonwrap/inventory.py
_ORGANIZATION = 'mesonbuild' _RESTRICTED_PROJECTS = [ 'meson', 'meson-ci', 'mesonwrap', 'wrapweb', ] _RESTRICTED_ORG_PROJECTS = [ _ORGANIZATION + '/' + proj for proj in _RESTRICTED_PROJECTS ] def is_wrap_project_name(project: str) -> bool: return project not in _RESTRICTED_PROJECTS def is_wr...
_ORGANIZATION = 'mesonbuild' _RESTRICTED_PROJECTS = [ 'meson', 'meson-ci', 'mesonwrap', 'wrapdevtools', 'wrapweb', ] _RESTRICTED_ORG_PROJECTS = [ _ORGANIZATION + '/' + proj for proj in _RESTRICTED_PROJECTS ] def is_wrap_project_name(project: str) -> bool: return project not in _RESTRICTED_...
Add wrapdevtools to restricted projects
Add wrapdevtools to restricted projects
Python
apache-2.0
mesonbuild/wrapweb,mesonbuild/wrapweb,mesonbuild/wrapweb
82f2fb3c3956e4ad4c65b03b3918ea409593d4ef
gcloud/__init__.py
gcloud/__init__.py
"""GCloud API access in idiomatic Python.""" __version__ = '0.02.2'
"""GCloud API access in idiomatic Python.""" from pkg_resources import get_distribution __version__ = get_distribution('gcloud').version
Read module version from setup.py
Read module version from setup.py
Python
apache-2.0
googleapis/google-cloud-python,blowmage/gcloud-python,thesandlord/gcloud-python,calpeyser/google-cloud-python,CyrusBiotechnology/gcloud-python,waprin/gcloud-python,VitalLabs/gcloud-python,waprin/google-cloud-python,jonparrott/google-cloud-python,Fkawala/gcloud-python,tswast/google-cloud-python,waprin/gcloud-python,dher...
2e88154eb9ea86bcf686e3cf4c92d5b696ec6efc
neo4j/__init__.py
neo4j/__init__.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) 2002-2016 "Neo Technology," # Network Engine for Objects in Lund AB [http://neotechnology.com] # # This file is part of Neo4j. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Li...
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) 2002-2016 "Neo Technology," # Network Engine for Objects in Lund AB [http://neotechnology.com] # # This file is part of Neo4j. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Li...
Add option to import neo4j for latest version
Add option to import neo4j for latest version
Python
apache-2.0
neo4j/neo4j-python-driver,neo4j/neo4j-python-driver
df3ab8bcae326ceb157106d076eaa90f13717107
astroquery/astrometry_net/tests/setup_package.py
astroquery/astrometry_net/tests/setup_package.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst import os # setup paths to the test data # can specify a single file or a list of files def get_package_data(): paths = [os.path.join('data', '*.fit')] # finally construct and return a dict for the sub module return {'astroquery.astrometry_ne...
# Licensed under a 3-clause BSD style license - see LICENSE.rst import os # setup paths to the test data # can specify a single file or a list of files def get_package_data(): paths = [os.path.join('data', '*.fit')] + [os.path.join('data', '*.fit.gz')] # finally construct and return a dict for the sub module ...
Include gzipped fits files in test data
Include gzipped fits files in test data
Python
bsd-3-clause
imbasimba/astroquery,ceb8/astroquery,ceb8/astroquery,imbasimba/astroquery
cee291799e9aa19e23593b3618a45f7cee16d0ed
modules/cah/CAHGame.py
modules/cah/CAHGame.py
#Cards Against Humanity game engine class CAHGame: def __init__(self): self.status = "Loaded CAHGame." #flag to keep track of whether or not game is running self.running = False #list of active pl...
#Cards Against Humanity game engine from cards import Deck, NoMoreCards class CAHGame: def __init__(self): self.status = "Loaded CAHGame." #flag to keep track of whether or not game is running self.running = False ...
Use the new Deck class
Use the new Deck class
Python
mit
tcoppi/scrappy,tcoppi/scrappy,johnmiked15/scrappy,johnmiked15/scrappy
a2f4b30cab3dafe119e42181772f4d77b575ec0e
05/test_find_password.py
05/test_find_password.py
import unittest from find_password import find_password class TestFindPassword(unittest.TestCase): def test_find_password(self): assert find_password('abc', length=8) == '18f47a30'
import unittest from find_password import find_password class TestFindPassword(unittest.TestCase): def test_find_password(self): assert find_password('abc', length=8) == '18f47a30' assert find_password('abc', length=8, complex=True) == '05ace8e3'
Add test for part 2 of day 5.
Add test for part 2 of day 5.
Python
mit
machinelearningdeveloper/aoc_2016
e64101e31fadaf54f8c1d7a6acb9b302060efefc
script/lib/config.py
script/lib/config.py
#!/usr/bin/env python import platform import sys BASE_URL = 'http://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = 'c01b10faf0d478e48f537210ec263fabd551578d' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }...
#!/usr/bin/env python import platform import sys BASE_URL = 'http://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = 'e0213676879061470efe50720368bce9b99aaa12' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }...
Upgrade libchromiumcontent to use the static_library build
Upgrade libchromiumcontent to use the static_library build
Python
mit
wan-qy/electron,deed02392/electron,John-Lin/electron,aliib/electron,nicobot/electron,Andrey-Pavlov/electron,leethomas/electron,Jonekee/electron,simongregory/electron,leolujuyi/electron,michaelchiche/electron,greyhwndz/electron,sircharleswatson/electron,jacksondc/electron,jsutcodes/electron,bpasero/electron,tylergibson/...
d5a578e6b72fae3c92827895055ed32baf8aa806
coney/response_codes.py
coney/response_codes.py
class ResponseCodes(object): SUCCESS = 0 USER_CODE_START = 1 USER_CODE_END = 0x7fffffff RESERVED_CODE_START = 0x80000000 MALFORMED_RESPONSE = RESERVED_CODE_START REQUEST_ENCODING_FAILURE = RESERVED_CODE_START + 1 REMOTE_UNHANDLED_EXCEPTION = RESERVED_CODE_START + 2 CALL_REPLY_TIMEOUT...
class ResponseCodes(object): SUCCESS = 0 USER_CODE_START = 1 USER_CODE_END = 0x7fffffff RESERVED_CODE_START = 0x80000000 MALFORMED_RESPONSE = RESERVED_CODE_START MALFORMED_REQUEST = RESERVED_CODE_START + 1 REQUEST_ENCODING_FAILURE = RESERVED_CODE_START + 2 REMOTE_UNHANDLED_EXCEPTION ...
Add additional codes used by server implementation
Add additional codes used by server implementation
Python
mit
cbigler/jackrabbit
adc3fa70c32bce764a6b6a7efd7a39c349d3a685
quick_sort.py
quick_sort.py
"""Doc string to end all doc strings""" def quick_srt(un_list): _helper(un_list, 0, len(un_list)-1) def _helper(un_list, first, last): if first < last: split = _split(un_list, first, last) _helper(un_list, first, split-1) _helper(un_list, split+1, last) def _split(un_list, first, l...
"""Doc string to end all doc strings""" def quick_srt(un_list): _helper(un_list, 0, len(un_list)-1) def _helper(un_list, first, last): if first < last: split = _split(un_list, first, last) _helper(un_list, first, split-1) _helper(un_list, split+1, last) def _split(un_list, first, l...
Update index error in _sort method
Update index error in _sort method
Python
mit
jonathanstallings/data-structures
fc7aac4f68c4b694162ed146b8b5ab2b4401895c
test/features/test_create_pages.py
test/features/test_create_pages.py
import time import unittest from hamcrest import * from splinter import Browser from support.stub_server import HttpStub class test_create_pages(unittest.TestCase): def setUp(self): HttpStub.start() time.sleep(2) def tearDown(self): HttpStub.stop() def test_about_page(self): ...
import time import unittest from hamcrest import * from splinter import Browser from support.stub_server import HttpStub class test_create_pages(unittest.TestCase): def setUp(self): HttpStub.start() time.sleep(2) def tearDown(self): HttpStub.stop() def test_about_page(self): ...
Test for page existing on master branch
Test for page existing on master branch
Python
mit
alphagov/transactions-explorer,gds-attic/transactions-explorer,gds-attic/transactions-explorer,gds-attic/transactions-explorer,gds-attic/transactions-explorer,alphagov/transactions-explorer,alphagov/transactions-explorer,gds-attic/transactions-explorer,alphagov/transactions-explorer,alphagov/transactions-explorer
209fef39f72a625e154f4455eaa6754d6a85e98b
zeus/utils/revisions.py
zeus/utils/revisions.py
from dataclasses import dataclass from typing import List, Tuple from zeus.exceptions import UnknownRevision from zeus.models import Repository, Revision from zeus.vcs import vcs_client @dataclass class RevisionResult: sha: str message: str author: str author_date: str committer: str committe...
from dataclasses import dataclass from typing import List, Tuple from zeus.exceptions import UnknownRevision from zeus.models import Repository, Revision from zeus.vcs import vcs_client @dataclass class RevisionResult: sha: str message: str author: str author_date: str committer: str committe...
Fix invalid next() call on api result
Fix invalid next() call on api result
Python
apache-2.0
getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus
4ab14b3de299b58aee94511910d199cd1d1737a5
zou/app/utils/emails.py
zou/app/utils/emails.py
from flask_mail import Message from zou.app import mail def send_email(subject, body, recipient_email, html=None): """ Send an email with given subject and body to given recipient. """ if html is None: html = body message = Message( body=body, html=html, subject=su...
from flask_mail import Message from zou.app import mail, app def send_email(subject, body, recipient_email, html=None): """ Send an email with given subject and body to given recipient. """ if html is None: html = body with app.app_context(): message = Message( body=bo...
Fix email sending in production environment
Fix email sending in production environment
Python
agpl-3.0
cgwire/zou
8639f91fba318c4b8c64f7c25885f8fe95e0ebe4
robot/game.py
robot/game.py
import logging import time from enum import Enum from threading import Thread from typing import NewType import _thread from robot.board import Board Zone = NewType('Zone', int) LOGGER = logging.getLogger(__name__) def kill_after_delay(timeout_seconds): """ Interrupts main process after the given delay. ...
import logging import signal from enum import Enum from typing import NewType from robot.board import Board Zone = NewType('Zone', int) LOGGER = logging.getLogger(__name__) def timeout_handler(signum, stack): """ Handle the `SIGALRM` to kill the current process. """ raise SystemExit("Timeout expire...
Replace thread killing with SIGALRM
Replace thread killing with SIGALRM
Python
mit
sourcebots/robot-api,sourcebots/robot-api
5c88f210644cbe59cf3b3a71345a3fc64dfc542a
spiff/api/plugins.py
spiff/api/plugins.py
from django.conf import settings import importlib import inspect def find_api_classes(module, superclass, test=lambda x: True): for app in map(lambda x:'%s.%s'%(x, module), settings.INSTALLED_APPS): try: appAPI = importlib.import_module(app) except ImportError, e: continue for name, cls in in...
from django.conf import settings import importlib import inspect def find_api_classes(*args, **kwargs): for app, cls in find_api_implementations(*args, **kwargs): yield cls def find_api_implementations(module, superclass, test=lambda x: True): for app in map(lambda x:'%s.%s'%(x, module), settings.INSTALLED_AP...
Add a method to also easily find what app an api object was found in
Add a method to also easily find what app an api object was found in
Python
agpl-3.0
SYNHAK/spiff,SYNHAK/spiff,SYNHAK/spiff
d36ac9a113608aadbda79c724f6aa6f6da5ec0bd
cellcounter/mixins.py
cellcounter/mixins.py
import simplejson as json from django.http import HttpResponse class JSONResponseMixin(object): """ A Mixin that renders context as a JSON response """ def render_to_response(self, context): """ Returns a JSON response containing 'context' as payload """ return self.get...
import json from django.http import HttpResponse class JSONResponseMixin(object): """ A Mixin that renders context as a JSON response """ def render_to_response(self, context): """ Returns a JSON response containing 'context' as payload """ return self.get_json_response...
Use json rather than simplejson
Use json rather than simplejson
Python
mit
haematologic/cellcounter,cellcounter/cellcounter,cellcounter/cellcounter,cellcounter/cellcounter,cellcounter/cellcounter,haematologic/cellcounter,haematologic/cellcounter
85e10e4c4eaf46ed89bc4b148b9c483df79cf410
test/test_fields.py
test/test_fields.py
import numpy as np import pyfds as fds def test_dimension(): dim = fds.Dimension(3, 0.1) assert np.allclose(dim.vector, np.asarray([0, 0.1, 0.2])) assert dim.get_index(0.1) == 1
import numpy as np import pyfds as fds def test_dimension(): dim = fds.Dimension(3, 0.1) assert np.allclose(dim.vector, np.asarray([0, 0.1, 0.2])) assert dim.get_index(0.1) == 1 def test_field_component_boundary_1(): fc = fds.FieldComponent(100) fc.values = np.random.rand(100) fc.boundaries ...
Add test cases for FieldComponent class.
Add test cases for FieldComponent class.
Python
bsd-3-clause
emtpb/pyfds
845192bb91a2421c54a9bbb924e1e09e700aee66
Lib/dialogKit/__init__.py
Lib/dialogKit/__init__.py
""" dialogKit: easy bake dialogs """ # determine the environment try: import FL haveFL = True except ImportError: haveFL = False try: import vanilla haveVanilla = True except ImportError: haveVanilla = False # perform the environment specific import if haveFL: from _dkFL import * if haveVan...
""" dialogKit: easy bake dialogs """ # determine the environment haveFL = False haveVanilla = False try: import FL haveFL = True except ImportError: pass if not haveFL: try: import vanilla haveVanilla = True except ImportError: pass # perform the environment specific import ...
Stop trying imports after something has been successfully loaded.
Stop trying imports after something has been successfully loaded.
Python
mit
anthrotype/dialogKit,daltonmaag/dialogKit,typesupply/dialogKit
992e0e2f50418bd87052741f7f1937f8efd052c0
tests/mpath_test.py
tests/mpath_test.py
import unittest import os from utils import create_sparse_tempfile from gi.repository import BlockDev if not BlockDev.is_initialized(): BlockDev.init(None, None) class MpathTestCase(unittest.TestCase): def setUp(self): self.dev_file = create_sparse_tempfile("mpath_test", 1024**3) succ, loop = ...
import unittest import os from utils import create_sparse_tempfile from gi.repository import BlockDev if not BlockDev.is_initialized(): BlockDev.init(None, None) class MpathTestCase(unittest.TestCase): def setUp(self): self.dev_file = create_sparse_tempfile("mpath_test", 1024**3) succ, loop = ...
Make the tearDown method of the mpath test case better visible
Make the tearDown method of the mpath test case better visible By moving it to the beginning of the file.
Python
lgpl-2.1
vpodzime/libblockdev,atodorov/libblockdev,vpodzime/libblockdev,vpodzime/libblockdev,snbueno/libblockdev,dashea/libblockdev,atodorov/libblockdev,snbueno/libblockdev,rhinstaller/libblockdev,atodorov/libblockdev,rhinstaller/libblockdev,dashea/libblockdev,rhinstaller/libblockdev
290f0beb0103ee8f8d3d59bf2fabc227ed743d30
lib/smisk/mvc/model.py
lib/smisk/mvc/model.py
# encoding: utf-8 '''Model in MVC :requires: `elixir <http://elixir.ematia.de/>`__ ''' # Ignore the SA string type depr warning from sqlalchemy.exceptions import SADeprecationWarning from warnings import filterwarnings filterwarnings('ignore', 'Using String type with no length for CREATE TABLE', SADepr...
# encoding: utf-8 '''Model in MVC :requires: `elixir <http://elixir.ematia.de/>`__ ''' # Ignore the SA string type depr warning from sqlalchemy.exceptions import SADeprecationWarning from warnings import filterwarnings filterwarnings('ignore', 'Using String type with no length for CREATE TABLE', SADepr...
Set sqlalchemy option shortnames to True by default.
Set sqlalchemy option shortnames to True by default.
Python
mit
rsms/smisk,rsms/smisk,rsms/smisk
80b8ef8b227baa1f4af842716ebfb83dcabf9703
tests/scoring_engine/web/views/test_auth.py
tests/scoring_engine/web/views/test_auth.py
from tests.scoring_engine.web.web_test import WebTest class TestAuth(WebTest): def test_login_page_auth_required(self): resp = self.client.get('/login') assert resp.status_code == 200 def test_unauthorized(self): resp = self.client.get('/unauthorized') assert resp.status_code...
from tests.scoring_engine.web.web_test import WebTest class TestAuth(WebTest): def test_login_page_auth_required(self): resp = self.client.get('/login') assert resp.status_code == 200 def test_unauthorized(self): resp = self.client.get('/unauthorized') assert resp.status_code...
Add test for incorrect password auth view
Add test for incorrect password auth view
Python
mit
pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine
349bb1ce2c15239ae3f9c066ed774b20369b9c0d
src/ggrc/settings/app_engine.py
src/ggrc/settings/app_engine.py
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: dan@reciprocitylabs.com # Maintained By: dan@reciprocitylabs.com APP_ENGINE = True ENABLE_JASMINE = False LOGIN_MANAGER = 'ggrc.login.appengine' FU...
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: dan@reciprocitylabs.com # Maintained By: dan@reciprocitylabs.com APP_ENGINE = True ENABLE_JASMINE = False LOGIN_MANAGER = 'ggrc.login.appengine' FU...
Enable Calendar integration on App Engine deployments
Enable Calendar integration on App Engine deployments
Python
apache-2.0
NejcZupec/ggrc-core,uskudnik/ggrc-core,j0gurt/ggrc-core,j0gurt/ggrc-core,edofic/ggrc-core,kr41/ggrc-core,hasanalom/ggrc-core,andrei-karalionak/ggrc-core,hyperNURb/ggrc-core,edofic/ggrc-core,selahssea/ggrc-core,vladan-m/ggrc-core,jmakov/ggrc-core,prasannav7/ggrc-core,vladan-m/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/...
5a84249b7e96d9d2f82ee1b27a33b7978d63b16e
src/urls.py
src/urls.py
# -*- coding: utf-8 -*- # urls.py used as base for developing wirecloud. try: from django.conf.urls import patterns, include, url except ImportError: # pragma: no cover # for Django version less than 1.4 from django.conf.urls.defaults import patterns, include, url from django.contrib import admin from dja...
# -*- coding: utf-8 -*- # urls.py used as base for developing wirecloud. from django.conf.urls import patterns, include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns import wirecloud.platform.urls admin.autodiscover() urlpatterns = patterns('', # Show...
Remove django < 1.4 code
Remove django < 1.4 code
Python
agpl-3.0
rockneurotiko/wirecloud,jpajuelo/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud,rockneurotiko/wirecloud,jpajuelo/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud
b704a92c919d7fa950a65ee0c569864c4549331f
glue/core/tests/util.py
glue/core/tests/util.py
from __future__ import absolute_import, division, print_function import tempfile from contextlib import contextmanager import os import zlib from mock import MagicMock from ... import core from ...core.application_base import Application @contextmanager def make_file(contents, suffix, decompress=False): """Con...
from __future__ import absolute_import, division, print_function import tempfile from contextlib import contextmanager import os import zlib from mock import MagicMock from ... import core from ...core.application_base import Application @contextmanager def make_file(contents, suffix, decompress=False): """Con...
Add workaround for failing unlink on Windows
Add workaround for failing unlink on Windows
Python
bsd-3-clause
saimn/glue,stscieisenhamer/glue,JudoWill/glue,saimn/glue,JudoWill/glue,stscieisenhamer/glue
17fe6d36a34218e74b53e9617212f0e67b05297d
pysteps/io/__init__.py
pysteps/io/__init__.py
from .interface import get_method from .archive import * from .importers import * from .readers import *
from .interface import get_method from .archive import * from .exporters import * from .importers import * from .readers import *
Add missing import of the exporters module
Add missing import of the exporters module
Python
bsd-3-clause
pySTEPS/pysteps
29b7a69a39ac66ebd8f61c6c9c65e7e60b40b4a0
numpy/_array_api/_types.py
numpy/_array_api/_types.py
""" This file defines the types for type annotations. These names aren't part of the module namespace, but they are used in the annotations in the function signatures. The functions in the module are only valid for inputs that match the given type annotations. """ __all__ = ['Array', 'Device', 'Dtype', 'SupportsDLPac...
""" This file defines the types for type annotations. These names aren't part of the module namespace, but they are used in the annotations in the function signatures. The functions in the module are only valid for inputs that match the given type annotations. """ __all__ = ['Array', 'Device', 'Dtype', 'SupportsDLPac...
Use better type definitions for the array API custom types
Use better type definitions for the array API custom types
Python
bsd-3-clause
anntzer/numpy,simongibbons/numpy,jakirkham/numpy,rgommers/numpy,pdebuyl/numpy,endolith/numpy,simongibbons/numpy,mhvk/numpy,pdebuyl/numpy,charris/numpy,rgommers/numpy,jakirkham/numpy,mattip/numpy,mhvk/numpy,mattip/numpy,rgommers/numpy,charris/numpy,numpy/numpy,simongibbons/numpy,endolith/numpy,anntzer/numpy,anntzer/nump...
74a2e0825f3029b6d3a3164221d11fbdf551b8d1
demo/demo/widgets/live.py
demo/demo/widgets/live.py
from moksha.api.widgets.live import LiveWidget class HelloWorldWidget(LiveWidget): topic = "helloworld" template = """ <b>Hello World Widget</b> <ul id="data"/> """ onmessage = """ $('<li/>').text(json.msg).prependTo('#data'); """
from moksha.api.widgets.live import LiveWidget class HelloWorldWidget(LiveWidget): topic = "helloworld" template = """ <b>Hello World Widget</b> <form onsubmit="return send_msg()"> <input name="text" id="text"/> </form> <ul id="data"/> <script> ...
Allow people to send messages in our basic HelloWorldWidget demo
Allow people to send messages in our basic HelloWorldWidget demo
Python
apache-2.0
ralphbean/moksha,ralphbean/moksha,lmacken/moksha,mokshaproject/moksha,mokshaproject/moksha,lmacken/moksha,ralphbean/moksha,pombredanne/moksha,mokshaproject/moksha,mokshaproject/moksha,pombredanne/moksha,pombredanne/moksha,pombredanne/moksha,lmacken/moksha
26581b24dd00c3b0a0928fe0b24ae129c701fb58
jarbas/frontend/tests/test_bundle_dependecies.py
jarbas/frontend/tests/test_bundle_dependecies.py
from django.test import TestCase from webassets.bundle import get_all_bundle_files from jarbas.frontend.assets import elm class TestDependencies(TestCase): def test_dependencies(self): files = set(get_all_bundle_files(elm)) self.assertEqual(9, len(files), files)
from glob import glob from django.test import TestCase from webassets.bundle import get_all_bundle_files from jarbas.frontend.assets import elm class TestDependencies(TestCase): def test_dependencies(self): expected = len(glob('jarbas/frontend/elm/**/*.elm', recursive=True)) files = set(get_all_...
Fix test for Elm files lookup
Fix test for Elm files lookup
Python
mit
datasciencebr/jarbas,rogeriochaves/jarbas,Guilhermeslucas/jarbas,marcusrehm/serenata-de-amor,marcusrehm/serenata-de-amor,datasciencebr/jarbas,marcusrehm/serenata-de-amor,Guilhermeslucas/jarbas,datasciencebr/jarbas,Guilhermeslucas/jarbas,rogeriochaves/jarbas,rogeriochaves/jarbas,Guilhermeslucas/jarbas,datasciencebr/jarb...
cd199c379145c6dcabd66f1771397c82e445c932
test_installation.py
test_installation.py
#!/usr/bin/env python from sys import exit try: import sympy except ImportError: print("SymPy must be installed for the tutorial") if sympy.__version__ != '1.1': print("SymPy 1.1 is required for the tutorial. Note SymPy 1.1 will be released before July 10.") try: import numpy except ImportError: ...
#!/usr/bin/env python from sys import exit try: import sympy except ImportError: print("SymPy must be installed for the tutorial") if sympy.__version__ != '1.1': print("SymPy 1.1 is required for the tutorial. Note SymPy 1.1 will be released before July 10.") try: import numpy except ImportError: ...
Make test script more extensive (conda, notebook, matplotlib)
Make test script more extensive (conda, notebook, matplotlib)
Python
bsd-3-clause
sympy/scipy-2017-codegen-tutorial,sympy/scipy-2017-codegen-tutorial,sympy/scipy-2017-codegen-tutorial,sympy/scipy-2017-codegen-tutorial,sympy/scipy-2017-codegen-tutorial
4a8170079e2b715d40e94f5d407d110a635f8a5d
InvenTree/common/apps.py
InvenTree/common/apps.py
from django.apps import AppConfig from django.db.utils import OperationalError, ProgrammingError, IntegrityError class CommonConfig(AppConfig): name = 'common' def ready(self): """ Will be called when the Common app is first loaded """ self.add_instance_name() self.add_default_settin...
from django.apps import AppConfig from django.db.utils import OperationalError, ProgrammingError, IntegrityError class CommonConfig(AppConfig): name = 'common' def ready(self): pass
Remove code which automatically created settings objects on server launch
Remove code which automatically created settings objects on server launch
Python
mit
inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree
ec42a3cfcb491b265c87160ed9dae0005552acb4
tests/test_result.py
tests/test_result.py
from django.core import management import pytest from model_mommy import mommy import time from example.app.models import SimpleObject @pytest.mark.django_db def test_get(es_client): management.call_command("sync_es") test_object = mommy.make(SimpleObject) time.sleep(1) # Let the index refresh fr...
from django.core import management import pytest from model_mommy import mommy import time from example.app.models import SimpleObject, RelatableObject @pytest.mark.django_db def test_simple_get(es_client): management.call_command("sync_es") test_object = mommy.make(SimpleObject) time.sleep(1) # Let t...
Work on testing, bulk indexing, etc
Work on testing, bulk indexing, etc
Python
mit
theonion/djes
517bb590edb65baedc603d8ea64a5b6f5988f076
polyaxon/polyaxon/config_settings/scheduler/__init__.py
polyaxon/polyaxon/config_settings/scheduler/__init__.py
from polyaxon.config_settings.cors import * from polyaxon.config_settings.dirs import * from polyaxon.config_settings.k8s import * from polyaxon.config_settings.spawner import * from polyaxon.config_settings.registry import * from .apps import *
from polyaxon.config_settings.cors import * from polyaxon.config_settings.dirs import * from polyaxon.config_settings.k8s import * from polyaxon.config_settings.spawner import * from polyaxon.config_settings.registry import * from polyaxon.config_settings.volume_claims import * from .apps import *
Add volume claims to scheduler
Add volume claims to scheduler
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
39077720e2fcc340b0cc26a4720aa8d895c53263
src/txamqp/queue.py
src/txamqp/queue.py
# coding: utf-8 from twisted.internet.defer import DeferredQueue class Empty(Exception): pass class Closed(Exception): pass class TimeoutDeferredQueue(DeferredQueue): END = object() def _timeout(self, deferred): if not deferred.called: if deferred in self.waiting: ...
# coding: utf-8 from twisted.internet.defer import DeferredQueue class Empty(Exception): pass class Closed(Exception): pass class TimeoutDeferredQueue(DeferredQueue): END = object() def _timeout(self, deferred): if not deferred.called: if deferred in self.waiting: ...
Remove call to setTimeout and use callLater instead.
Remove call to setTimeout and use callLater instead.
Python
apache-2.0
williamsjj/txamqp,dotsent/txamqp,txamqp/txamqp
ed46ee16ed1b8efcee3697d3da909f72b0755a13
webcomix/tests/test_docker.py
webcomix/tests/test_docker.py
import docker from webcomix.docker import DockerManager def test_no_javascript_spawns_no_container(): manager = DockerManager(False) manager.__enter__() manager.client = docker.from_env() assert manager._get_container() is None def test_javascript_spawns_container(): manager = DockerManager(True)...
import docker import pytest from webcomix.docker import DockerManager, CONTAINER_NAME @pytest.fixture def cleanup_container(test): yield None client = docker.from_env() for container in client.containers().list(): if container.attrs["Config"]["Image"] == CONTAINER_NAME: container.kill(...
Add test fixture for docker tests
Add test fixture for docker tests
Python
mit
J-CPelletier/webcomix,J-CPelletier/webcomix
16b07dd961cbe55ee452ed6057048ec452ffbd72
custom/icds/management/commands/copy_icds_app.py
custom/icds/management/commands/copy_icds_app.py
from __future__ import absolute_import, print_function, unicode_literals from django.core.management import BaseCommand from corehq.apps.app_manager.dbaccessors import get_build_doc_by_version, wrap_app from corehq.apps.app_manager.models import import_app class Command(BaseCommand): help = "Make a copy of a sp...
from __future__ import absolute_import, print_function, unicode_literals from django.core.management import BaseCommand from corehq.apps.app_manager.dbaccessors import get_build_doc_by_version, wrap_app from corehq.apps.app_manager.models import import_app class Command(BaseCommand): help = "Make a copy of a sp...
Replace old config IDs with the new ones
Replace old config IDs with the new ones
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
6f356a94c56053b47fb38670a93e04f46740f21e
tartpy/eventloop.py
tartpy/eventloop.py
""" Very basic implementation of an event loop ========================================== The eventloop is a singleton to schedule and run events. Exports ------- - ``EventLoop``: the basic eventloop """ import asyncio import queue import sched import threading import time from .singleton import Singleton clas...
""" Very basic implementation of an event loop ========================================== The eventloop is a singleton to schedule and run events. Exports ------- - ``EventLoop``: the basic eventloop """ import asyncio import queue import sched import threading import time from .singleton import Singleton clas...
Make sure that 'stop' works from everywhere
Make sure that 'stop' works from everywhere
Python
mit
waltermoreira/tartpy
39b5f794503149351d03879083d336dfe5f2351b
openprescribing/frontend/tests/test_api_utils.py
openprescribing/frontend/tests/test_api_utils.py
from django.test import TestCase from django.db import OperationalError class ApiTestUtils(TestCase): def test_db_timeout(self): from api.view_utils import db_timeout @db_timeout(1) def do_long_running_query(): from django.db import connection cursor = conn...
from django.test import TestCase from django.db import OperationalError class ApiTestUtils(TestCase): def test_db_timeout(self): from api.view_utils import db_timeout @db_timeout(1) def do_long_running_query(): from django.db import connection cursor = conn...
Add a missing test for param-parsing
Add a missing test for param-parsing
Python
mit
ebmdatalab/openprescribing,ebmdatalab/openprescribing,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc
d108f090f198cba47083225c0de46e77b22ab5cc
serfclient/__init__.py
serfclient/__init__.py
from pkg_resources import get_distribution __version__ = get_distribution('serfclient').version from serfclient.client import SerfClient
from pkg_resources import get_distribution from serfclient.client import SerfClient __version__ = get_distribution('serfclient').version
Move module level import to top of file (PEP8)
Move module level import to top of file (PEP8) Error: E402 module level import not at top of file
Python
mit
charleswhchan/serfclient-py,KushalP/serfclient-py
01a8fcb70ea75d854aaf16547b837d861750c160
tilequeue/queue/file.py
tilequeue/queue/file.py
from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage import threading class OutputFileQueue(object): def __init__(self, fp): self.fp = fp self.lock = threading.RLock() def enqueue(self, coord): with self.lock: payload = serialize_coord(coord) ...
from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage import threading class OutputFileQueue(object): def __init__(self, fp): self.fp = fp self.lock = threading.RLock() def enqueue(self, coord): with self.lock: payload = serialize_coord(coord) ...
Use readline() instead of next() to detect changes.
Use readline() instead of next() to detect changes. tilequeue/queue/file.py -`readline()` will pick up new lines appended to the file, whereas `next()` will not since the iterator will just hit `StopIteration` and stop generating new lines. Use `readline()` instead, then, since it might be desirable to append some...
Python
mit
tilezen/tilequeue,mapzen/tilequeue
5456ae0af9ad83b8e0339c671ce8954bb48d62cf
database.py
database.py
from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base import config as cfg class DB(object): engine = None db_session = None Base = declarative_base() def __init__(self, dbstring): self.engine = crea...
from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker, class_mapper from sqlalchemy.ext.declarative import declarative_base import config as cfg class DB(object): engine = None db_session = None Base = declarative_base() def __init__(self, dbstring): self...
Add ImposterBase mixin class so we can add methods and properties to the sqlalchemy based models
Add ImposterBase mixin class so we can add methods and properties to the sqlalchemy based models
Python
bsd-2-clause
jkossen/imposter,jkossen/imposter
be1e31c78f17961851d41dea11cd912d237cf5fb
lib/rapidsms/message.py
lib/rapidsms/message.py
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import copy class Message(object): def __init__(self, backend, caller=None, text=None): self._backend = backend self.caller = caller self.text = text # initialize some empty attributes self.received = None ...
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import copy class Message(object): def __init__(self, backend, caller=None, text=None): self._backend = backend self.caller = caller self.text = text self.responses = [] def __unicode__(self): return self.text ...
Remove unused attributes; also, empty responses after it's flushed.
Remove unused attributes; also, empty responses after it's flushed.
Python
bsd-3-clause
unicefuganda/edtrac,caktus/rapidsms,eHealthAfrica/rapidsms,dimagi/rapidsms,catalpainternational/rapidsms,peterayeni/rapidsms,peterayeni/rapidsms,ken-muturi/rapidsms,ehealthafrica-ci/rapidsms,rapidsms/rapidsms-core-dev,eHealthAfrica/rapidsms,lsgunth/rapidsms,dimagi/rapidsms-core-dev,ehealthafrica-ci/rapidsms,catalpainte...
536575db87968014f75d2ad68456c3684d6c92de
auditlog/__manifest__.py
auditlog/__manifest__.py
# -*- coding: utf-8 -*- # © 2015 ABF OSIELL <http://osiell.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': "Audit Log", 'version': "9.0.1.0.0", 'author': "ABF OSIELL,Odoo Community Association (OCA)", 'license': "AGPL-3", 'website': "http://www.osiell.com", 'categ...
# -*- coding: utf-8 -*- # © 2015 ABF OSIELL <http://osiell.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': "Audit Log", 'version': "9.0.1.0.0", 'author': "ABF OSIELL,Odoo Community Association (OCA)", 'license': "AGPL-3", 'website': "http://www.osiell.com", 'categ...
Remove pre_init_hook reference from openerp, no pre_init hook exists any more
auditlog: Remove pre_init_hook reference from openerp, no pre_init hook exists any more
Python
agpl-3.0
brain-tec/server-tools,brain-tec/server-tools,bmya/server-tools,brain-tec/server-tools,bmya/server-tools,bmya/server-tools
7f2e91064eabc020cbe660639713278fc187a034
tests/test_result.py
tests/test_result.py
import pytest from serfclient import result class TestSerfResult(object): def test_initialises_to_none(self): r = result.SerfResult() assert r.head is None assert r.body is None def test_provides_a_pretty_printed_form_for_repl_use(self): r = result.SerfResult(head={"a": 1}, b...
from serfclient import result class TestSerfResult(object): def test_initialises_to_none(self): r = result.SerfResult() assert r.head is None assert r.body is None def test_provides_a_pretty_printed_form_for_repl_use(self): r = result.SerfResult(head={"a": 1}, body=('foo', 'ba...
Remove unused import of pytest
Remove unused import of pytest
Python
mit
charleswhchan/serfclient-py,KushalP/serfclient-py
a9cd0a385253cef42d03d6a45e81ef4dd582e9de
base/settings/testing.py
base/settings/testing.py
# -*- coding: utf-8 -*- from .base import Base as Settings class Testing(Settings): # Database Configuration. # -------------------------------------------------------------------------- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': ...
# -*- coding: utf-8 -*- from .base import Base as Settings class Testing(Settings): # Database Configuration. # -------------------------------------------------------------------------- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', ...
Use SQLite in an attempt to speed up the tests.
Use SQLite in an attempt to speed up the tests.
Python
apache-2.0
hello-base/web,hello-base/web,hello-base/web,hello-base/web
211ee03b811cb196dd9f36026fcfc6e75dda2ec6
byceps/config_defaults.py
byceps/config_defaults.py
""" byceps.config_defaults ~~~~~~~~~~~~~~~~~~~~~~ Default configuration values :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from datetime import timedelta from pathlib import Path # database connection SQLALCHEMY_ECHO = False # Avoid connection errors after...
""" byceps.config_defaults ~~~~~~~~~~~~~~~~~~~~~~ Default configuration values :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from datetime import timedelta from pathlib import Path # database connection SQLALCHEMY_ECHO = False # Avoid connection errors after...
Set session cookie flag `SameSite` to `Lax` (instead of `None`)
Set session cookie flag `SameSite` to `Lax` (instead of `None`)
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps
5f9a3c62c4117e0e674d33e675c3a54d800dacb6
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 from comics.core.models import Comic @receiver(models.signals.post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.cr...
import uuid from django.contrib.auth.models import User from django.db import models from django.dispatch import receiver from comics.core.models import Comic @receiver(models.signals.post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.cr...
Add a M2M table for the subscription relation between users and comics
Add a M2M table for the subscription relation between users and comics
Python
agpl-3.0
jodal/comics,datagutten/comics,datagutten/comics,jodal/comics,datagutten/comics,datagutten/comics,jodal/comics,jodal/comics
ccdefc6584f64a832614be172ec384022805fa20
hitchstory/arguments.py
hitchstory/arguments.py
from hitchstory import utils, exceptions from ruamel.yaml.comments import CommentedMap, CommentedSeq class Arguments(object): """A null-argument, single argument or group of arguments of a hitchstory step.""" def __init__(self, yaml_args): """Create arguments from dict (from yaml).""" if yaml...
from hitchstory import utils, exceptions from ruamel.yaml.comments import CommentedMap, CommentedSeq class Arguments(object): """A null-argument, single argument or group of arguments of a hitchstory step.""" def __init__(self, yaml_args): """Create arguments from dict (from yaml).""" if yaml...
REFACTOR : Removed unnecessary code.
REFACTOR : Removed unnecessary code.
Python
agpl-3.0
hitchtest/hitchstory
0e5b0ccb7eb79fe68b8e40ad46d8e2e0efa01ba7
test_queue.py
test_queue.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """A series of pytest tests to test the quality of our Queue class and its methods """ from __future__ import unicode_literals import pytest import queue @pytest.fixture(scope="function") def create_queue(request): """Create a queue with numbers 1 - 5""" new_queu...
#!/usr/bin/env python # -*- coding: utf-8 -*- """A series of pytest tests to test the quality of our Queue class and its methods """ from __future__ import unicode_literals import pytest import queue @pytest.fixture(scope="function") def create_queue(request): """Create a queue with numbers 1 - 5 """ new...
Fix errors in test file
Fix errors in test file Fix errors and typos in 'test_queue.py'
Python
mit
jesseklein406/data-structures
26de6c5decac3345dee470a0968926a65d3497b9
test_stack.py
test_stack.py
import pytest from stack import Element from stack import Stack def test_element_init(): n = Element() assert n.val is None assert n.next is None n = Element(3) assert n.val == 3 assert n.next is None def test_stack_init(): l = Stack() assert l.top is None def test_stack_push(): ...
import pytest from stack import Element from stack import Stack def test_element_init(): n = Element() assert n.val is None assert n.previous is None m = Element(3) assert m.val == 3 assert m.previous is None def test_stack_init(): l = Stack() assert l.top is None def test_stack_pu...
Add test for pop and adjust element init test
Add test for pop and adjust element init test
Python
mit
constanthatz/data-structures
151c97a3a5cd0f9103c891ee9c60f3fe52fc3d12
test_suite.py
test_suite.py
import os os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' from django.core import management management.call_command('test', 'resources', 'forms', 'tokens')
import os import sys os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' from django.core import management apps = sys.argv[1:] if not apps: apps = [ 'resources', 'forms', 'tokens', ] management.call_command('test', *apps)
Allow apps to be specified from the command line
Allow apps to be specified from the command line
Python
bsd-2-clause
chop-dbhi/serrano,chop-dbhi/serrano,rv816/serrano_night,rv816/serrano_night
1243d484009e621338a5fcd609d62bedd9796f05
tests/base.py
tests/base.py
import unittest from app import create_app, db class Base(unittest.TestCase): def setUp(self): self.app = create_app("testing") self.client = self.app.test_client() self.user = { "username": "brian", "password": "password" } with self.app.app_contex...
import unittest import json from app import create_app, db from app.models import User class Base(unittest.TestCase): def setUp(self): self.app = create_app("testing") self.client = self.app.test_client() self.user = json.dumps({ "username": "brian", "password": "pa...
Add authorization and content-type headers to request for tests
[CHORE] Add authorization and content-type headers to request for tests
Python
mit
brayoh/bucket-list-api