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
78e6aa845fac79d8b0d015840897db1fef5f06d0
polygon2geojson.py
polygon2geojson.py
import argparse import os import fiona from shapely.geometry import Polygon, mapping def remove_file(file_name): try: os.remove(file_name) except OSError: pass def read_polygon(polygon_filename): with open(polygon_filename) as f: return f.readlines() def clean_poylgon(polygon_d...
import argparse import os import fiona from shapely.geometry import Polygon, mapping def remove_file(file_name): try: os.remove(file_name) except OSError: pass def read_polygon(polygon_filename): with open(polygon_filename) as f: return f.readlines() def clean_poylgon(polygon_d...
Use output name from input name
Use output name from input name
Python
unlicense
ustroetz/polygon2osm
2b7da7ba1ae2eac069762c221c279aa9f204775d
praw/exceptions.py
praw/exceptions.py
"""PRAW exception classes. Includes two main exceptions: :class:`.APIException` for when something goes wrong on the server side, and :class:`.ClientException` when something goes wrong on the client side. Both of these classes extend :class:`.PRAWException`. """ class PRAWException(Exception): """The base PRAW...
"""PRAW exception classes. Includes two main exceptions: :class:`.APIException` for when something goes wrong on the server side, and :class:`.ClientException` when something goes wrong on the client side. Both of these classes extend :class:`.PRAWException`. """ class PRAWException(Exception): """The base PRAW...
Fix a few Sphinx typos
Fix a few Sphinx typos * `.. note:` -> `.. note::` to prevent the `note` from being interpreted as a comment, which wouldn't show up when the docs are rendered. * Double backticks for the code bits. * Correct typo ("atribute" -> "attribute"). * Sphinx doesn't like characters immediately after the backticks, so add ...
Python
bsd-2-clause
gschizas/praw,praw-dev/praw,13steinj/praw,leviroth/praw,gschizas/praw,praw-dev/praw,13steinj/praw,leviroth/praw
ca1b92118d0c432484b3ac7f59924a1a65a59e17
irco/utils.py
irco/utils.py
import os import glob from irco import parser, tabular def get_file_list(sources): for source in sources: if os.path.isdir(source): for path in glob.glob(os.path.join(source, '*.txt')): yield path elif os.path.isfile(source): yield source def get_dataset(...
import os from irco import parser, tabular def get_file_list(sources): for source in sources: if os.path.isdir(source): for path in sorted(os.listdir(source)): _, ext = os.path.splitext(path) if ext not in ('.txt', '.csv', '.tsv'): continue ...
Support recursive import of CSV and TSV files as well as TXT ones.
Support recursive import of CSV and TSV files as well as TXT ones.
Python
mit
GaretJax/irco,GaretJax/irco,GaretJax/irco,GaretJax/irco
bc6392560ea87c74d6c6a94812b6caba7d6c2954
django_elect/settings.py
django_elect/settings.py
from django.conf import settings """ A string that corresponds to the path to the model that should be used for the Election.allowed_voters and Vote.account foreign keys. This is mainly for sites that extend the User model via inheritance, as detailed at http://scottbarnham.com/blog/2008/08/21/extending-the-django-us...
from django.conf import settings """ A string that corresponds to the path to the model that should be used for the Election.allowed_voters and Vote.account foreign keys. This is mainly for sites that extend the User model via inheritance, as detailed at http://scottbarnham.com/blog/2008/08/21/extending-the-django-us...
Change DJANGO_ELECT_USER_MODEL to default to AUTH_USER_MODEL
Change DJANGO_ELECT_USER_MODEL to default to AUTH_USER_MODEL
Python
bsd-3-clause
MasonM/django-elect,MasonM/django-elect,MasonM/django-elect
dcaf7b95264c0d8678bc36e47a14fa6f15175e40
pylearn2/tests/test_dbm_metrics.py
pylearn2/tests/test_dbm_metrics.py
""" Test dbm_metrics script """ from pylearn2.scripts.dbm import dbm_metrics from pylearn2.datasets.mnist import MNIST def test_ais(): """ Test ais computation """ w_list = [None] b_list = [] # Add parameters import trainset = MNIST(which_set='train') testset = MNIST(which_set='test')...
""" Test dbm_metrics script """ from pylearn2.scripts.dbm import dbm_metrics from pylearn2.datasets.mnist import MNIST def test_ais(): """ Test ais computation by comparing the output of estimate_likelihood to Russ's code's output for the same parameters. """ w_list = [None] b_list = [] # ...
Add more info to test_ais docstring
Add more info to test_ais docstring
Python
bsd-3-clause
woozzu/pylearn2,JesseLivezey/plankton,fulmicoton/pylearn2,caidongyun/pylearn2,sandeepkbhat/pylearn2,cosmoharrigan/pylearn2,mkraemer67/pylearn2,ddboline/pylearn2,kastnerkyle/pylearn2,pkainz/pylearn2,lisa-lab/pylearn2,hantek/pylearn2,bartvm/pylearn2,mclaughlin6464/pylearn2,aalmah/pylearn2,fishcorn/pylearn2,fyffyt/pylearn...
3225c14ed1c3d09a68d6cde8af6d83d54a6f5f76
simple_history/__init__.py
simple_history/__init__.py
from __future__ import unicode_literals __version__ = '1.5.1' def register( model, app=None, manager_name='history', records_class=None, **records_config): """ Create historical model for `model` and attach history manager to `model`. Keyword arguments: app -- App to install historic...
from __future__ import unicode_literals __version__ = '1.5.1' def register( model, app=None, manager_name='history', records_class=None, **records_config): """ Create historical model for `model` and attach history manager to `model`. Keyword arguments: app -- App to install historic...
Change style of setting records_class default
Change style of setting records_class default
Python
bsd-3-clause
emergence/django-simple-history,luzfcb/django-simple-history,treyhunner/django-simple-history,pombredanne/django-simple-history,pombredanne/django-simple-history,treyhunner/django-simple-history,emergence/django-simple-history,luzfcb/django-simple-history
e7bbfb94aed0109ccf1609333b8990f21e5f561c
pyhpeimc/__init__.py
pyhpeimc/__init__.py
#!/usr/bin/python3 '''Copyright 2015 Hewlett Packard Enterprise Development LP 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 applica...
#!/usr/bin/env python # -*- coding: <encoding-name> -*- ''' Copyright 2015 Hewlett Packard Enterprise Development LP 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/...
Fix in groups.py for get_custom_views function.
Fix in groups.py for get_custom_views function.
Python
apache-2.0
HPNetworking/HP-Intelligent-Management-Center,netmanchris/PYHPEIMC,HPENetworking/PYHPEIMC
783f59a41cde3c887968920251aa34b6a59c941b
source/cytoplasm/errors.py
source/cytoplasm/errors.py
class ControllerError(StandardError): pass class InterpreterError(StandardError): pass
class CytoplasmError(Exception): pass class ControllerError(CytoplasmError): pass class InterpreterError(CytoplasmError): pass
Use Exception instead of StandardError
Use Exception instead of StandardError Python 3 doesn't have StandardError...
Python
mit
startling/cytoplasm
f1af343bf48843c8298ef6f07227402be1f4e511
angr/engines/soot/values/thisref.py
angr/engines/soot/values/thisref.py
from .base import SimSootValue from .local import SimSootValue_Local class SimSootValue_ThisRef(SimSootValue): __slots__ = [ 'id', 'type', 'heap_alloc_id' ] def __init__(self, heap_alloc_id, type_): self.id = self._create_unique_id(heap_alloc_id, type_) self.heap_alloc_id = heap_alloc_id ...
from .base import SimSootValue from .local import SimSootValue_Local class SimSootValue_ThisRef(SimSootValue): __slots__ = [ 'id', 'type', 'heap_alloc_id' ] def __init__(self, heap_alloc_id, type_): self.id = self._create_unique_id(heap_alloc_id, type_) self.heap_alloc_id = heap_alloc_id ...
Fix naming of 'this' reference
Fix naming of 'this' reference
Python
bsd-2-clause
schieb/angr,schieb/angr,angr/angr,angr/angr,iamahuman/angr,iamahuman/angr,schieb/angr,angr/angr,iamahuman/angr
0c753e644068439376493e4b23a1060d742770ae
tests/__main__.py
tests/__main__.py
import unittest if __name__ == '__main__': all_tests = unittest.TestLoader().discover('./', pattern='*_tests.py') unittest.TextTestRunner().run(all_tests)
import sys import unittest if __name__ == '__main__': all_tests = unittest.TestLoader().discover('./', pattern='*_tests.py') ret = unittest.TextTestRunner().run(all_tests).wasSuccessful() sys.exit(ret)
Fix an issue when unit tests always return 0 status.
Fix an issue when unit tests always return 0 status.
Python
mit
sergeymironov0001/twitch-chat-bot
966c22d4bae270a14176ae1c7b9887eb55743612
tests/conftest.py
tests/conftest.py
import datetime import odin.datetimeutil ARE_YOU_EXPERIENCED = datetime.date(1967, 5, 12) MWT = odin.datetimeutil.FixedTimezone(-6, 'Mountain War Time') BOOM = datetime.datetime(1945, 7, 16, 5, 29, 45, 0, MWT)
import os import sys import datetime import odin.datetimeutil HERE = os.path.abspath(os.path.dirname(__file__)) SRC = os.path.normpath(os.path.join(HERE, "..", "src")) sys.path.insert(0, SRC) ARE_YOU_EXPERIENCED = datetime.date(1967, 5, 12) MWT = odin.datetimeutil.FixedTimezone(-6, "Mountain War Time") BOOM = datetim...
Update tests to find source path
Update tests to find source path
Python
bsd-3-clause
python-odin/odin
37e569bed66e18e0ae80222f2988277023e19916
tests/test_cli.py
tests/test_cli.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import mock import pytest import pypi_cli as pypi @pytest.mark.usefixtures('mock_api') class TestStat: def test_missing_package_arg(self, runner): result = runner.invoke(pypi.cli, ['stat']) assert result.exit_code > 0 def test_w...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import mock import pytest import pypi_cli as pypi @pytest.mark.usefixtures('mock_api') class TestStat: def test_missing_package_arg(self, runner): result = runner.invoke(pypi.cli, ['stat']) assert result.exit_code > 0 def test_w...
Add test for inputting package URL
Add test for inputting package URL
Python
mit
pombredanne/pypi-cli,sloria/pypi-cli,mindw/pypi-cli
6c211bce96eaca17de770b82aab8dac07ff0c2fd
src/dictsdiff/cli.py
src/dictsdiff/cli.py
""" Compare multiple similar dictionary data in JSON/YAML/Pickle files. """ from __future__ import print_function import sys def dictsdiff_cli(files): import pandas from .loader import diff_files, diff_ndjson if files: dd = diff_files(files) else: dd = diff_ndjson(sys.stdin) wi...
""" Compare multiple similar dictionary data in JSON/YAML/Pickle files. """ from __future__ import print_function import sys try: from shutil import get_terminal_size except ImportError: def get_terminal_size(): from subprocess import check_output out = check_output(['stty', 'size'], universa...
Set display.width based on terminal size
Set display.width based on terminal size
Python
bsd-2-clause
tkf/dictsdiff
10bbc402a46e2832f8e62359fd2d86b7ebf7fd84
cloudbot/symfony.py
cloudbot/symfony.py
from util import hook from elasticutils import S @hook.command @hook.command('sf') def symfony(inp): search = S().indexes('doc-index').doctypes('doc-section-type') # cant fit more than 3 links into 1 irs message results = search.query(tags__match=inp, title__match=inp, content__match=inp, should=True)[:3]...
from util import hook import elasticutils from elasticutils import S @hook.command @hook.command('sf') def symfony(inp): if not elasticutils.get_es().indices.exists('doc-index'): return "Index currently unavailable. Try again in a bit." search = S().indexes('doc-index').doctypes('doc-section-type') ...
Check if the index is available before calling the query.
Check if the index is available before calling the query.
Python
mit
mitom/symfony-doc-bot,mitom/symfony-doc-bot
f48554bcc5ac1161314592cb43ba65701d387289
tests/test_check_endpoint.py
tests/test_check_endpoint.py
import pytest def test_get_connection(): assert False def test_verify_hostname_with_valid_hostname(): assert False def test_verify_hostname_with_valid_altname(): assert False def test_verify_hostname_with_invalid_hostname(): assert False def test_expiring_certificate_with_good_cert(): assert Fa...
import pytest # We're going to fake a connection for purposes of testing. # So far all we use is getpeercert method, so that's all we need to fake class fake_connection(object): def __init__(self): pass def getpeercert(self): cert_details = {'notAfter': 'Dec 31 00:00:00 2015 GMT', ...
Add fake connection class, PEP8 changes
Add fake connection class, PEP8 changes Also had a bad assert in there
Python
mit
twirrim/checkendpoint
d7025f92a240284d130ce455b6975ede42d0228e
chalice/cli/filewatch/eventbased.py
chalice/cli/filewatch/eventbased.py
import threading # noqa from typing import Callable, Optional # noqa import watchdog.observers from watchdog.events import FileSystemEventHandler from watchdog.events import FileSystemEvent # noqa from chalice.cli.filewatch import FileWatcher, WorkerProcess class WatchdogWorkerProcess(WorkerProcess): """Work...
import threading # noqa from typing import Callable, Optional # noqa import watchdog.observers # pylint: disable=import-error from watchdog import events # pylint: disable=import-error from chalice.cli.filewatch import FileWatcher, WorkerProcess class WatchdogWorkerProcess(WorkerProcess): """Worker that run...
Make prcheck pass without needing cond deps
Make prcheck pass without needing cond deps
Python
apache-2.0
awslabs/chalice
08bb24ad80db72457c87533288b97942cc178dd6
src/kanboard/urls.py
src/kanboard/urls.py
import os from django.conf.urls.defaults import patterns, url import kanboard urlpatterns = patterns('kanboard.views', url(r'^board/(?P<board_slug>[\w-]+)/$', 'board'), url(r'^board/(?P<board_slug>[\w-]+)/update/$', 'update'), ) # Serve static content static_root = os.path.join(os.path.dirname(kanboard.__file__...
from django.conf.urls.defaults import patterns, url urlpatterns = patterns('kanboard.views', url(r'^board/(?P<board_slug>[\w-]+)/$', 'board'), url(r'^board/(?P<board_slug>[\w-]+)/update/$', 'update'), )
Remove static file serving (using django-staticfiles instead is recommended)
Remove static file serving (using django-staticfiles instead is recommended)
Python
bsd-3-clause
zellyn/django-kanboard,zellyn/django-kanboard
d63d6070576bf22d60bf9684e417163201814353
webapp/worker.py
webapp/worker.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Run a worker for the job queue.""" import os import sys from redis import StrictRedis from rq import Connection, Queue, Worker from bootstrap.util import app_context if __name__ == '__main__': config_name = os.environ.get('ENVIRONMENT') if config_name is No...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Run a worker for the job queue.""" import sys from redis import StrictRedis from rq import Connection, Queue, Worker from bootstrap.util import app_context, get_config_name_from_env if __name__ == '__main__': try: config_name = get_config_name_from_env(...
Use bootstrap utility to retrieve the configuration name from the environment.
Use bootstrap utility to retrieve the configuration name from the environment.
Python
bsd-3-clause
m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps
dec2222cde98b395aac303af4e005937f4085b89
src/ggrc_workflows/migrations/versions/20140804203436_32221e9f330c_remove_prohibitive_foreign_key_.py
src/ggrc_workflows/migrations/versions/20140804203436_32221e9f330c_remove_prohibitive_foreign_key_.py
"""Remove prohibitive foreign key constraints Revision ID: 32221e9f330c Revises: 235b7b9989be Create Date: 2014-08-04 20:34:36.697866 """ # revision identifiers, used by Alembic. revision = '32221e9f330c' down_revision = '235b7b9989be' from alembic import op import sqlalchemy as sa def upgrade(): op.drop_con...
"""Remove prohibitive foreign key constraints Revision ID: 32221e9f330c Revises: 235b7b9989be Create Date: 2014-08-04 20:34:36.697866 """ # revision identifiers, used by Alembic. revision = '32221e9f330c' down_revision = '235b7b9989be' from alembic import op import sqlalchemy as sa def upgrade(): op.drop_con...
Remove uniqueness constraints on Workflow and TaskGroup
Remove uniqueness constraints on Workflow and TaskGroup * Titles need not be unique anymore
Python
apache-2.0
vladan-m/ggrc-core,hyperNURb/ggrc-core,NejcZupec/ggrc-core,prasannav7/ggrc-core,plamut/ggrc-core,AleksNeStu/ggrc-core,hyperNURb/ggrc-core,vladan-m/ggrc-core,plamut/ggrc-core,hasanalom/ggrc-core,prasannav7/ggrc-core,jmakov/ggrc-core,VinnieJohns/ggrc-core,vladan-m/ggrc-core,prasannav7/ggrc-core,plamut/ggrc-core,NejcZupec...
a462cca21e8c6456927727cead09f006e63fed16
src/ggrc/models/section.py
src/ggrc/models/section.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: # Maintained By: from ggrc import db from .associationproxy import association_proxy from .mixins import BusinessObject, Hierarchical class Secti...
# 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: # Maintained By: from ggrc import db from .associationproxy import association_proxy from .mixins import BusinessObject, Hierarchical class Secti...
Add eager-loaded links for Section
Add eager-loaded links for Section
Python
apache-2.0
hamyuan/ggrc-self-test,j0gurt/ggrc-core,vladan-m/ggrc-core,ankit-collective/ggrc-core,selahssea/ggrc-core,VinnieJohns/ggrc-core,vladan-m/ggrc-core,hyperNURb/ggrc-core,andrei-karalionak/ggrc-core,AleksNeStu/ggrc-core,hyperNURb/ggrc-core,2947721120/sagacious-capsicum,plamut/ggrc-core,kr41/ggrc-core,vladan-m/ggrc-core,edo...
8f1d28a5e7f698bf177412eef92529eb5b360301
keeper/logutils.py
keeper/logutils.py
"""Logging helpers and utilities.""" import uuid from functools import wraps from timeit import default_timer as timer from typing import Any, Callable, TypeVar import structlog from flask import make_response, request __all__ = ["log_route"] F = TypeVar("F", bound=Callable[..., Any]) def log_route() -> Callable[...
"""Logging helpers and utilities.""" import uuid from functools import wraps from timeit import default_timer as timer from typing import Any, Callable, TypeVar import structlog from flask import make_response, request __all__ = ["log_route"] F = TypeVar("F", bound=Callable[..., Any]) def log_route() -> Callable[...
Include an event with the response log message
Include an event with the response log message This is now required by structlog
Python
mit
lsst-sqre/ltd-keeper,lsst-sqre/ltd-keeper
1a46149806a66d7f493cf104913ebebde7e6ba5d
chatterbot/adapters/io/tts.py
chatterbot/adapters/io/tts.py
from chatterbot.adapters.io import IOAdapter from chatterbot.utils.read_input import input_function import os import platform import subprocess class MacOSXTTS(IOAdapter): def process_input(self): """ Read the user's input from the terminal. """ user_input = input_function() ...
from chatterbot.adapters.io import IOAdapter from chatterbot.utils.read_input import input_function import os import platform import subprocess class MacOSXTTS(IOAdapter): def process_input(self): """ Read the user's input from the terminal. """ user_input = input_function() ...
Make sure only Mac computers use the MacOSXTTS io adapter
Make sure only Mac computers use the MacOSXTTS io adapter
Python
bsd-3-clause
Gustavo6046/ChatterBot,maclogan/VirtualPenPal,Reinaesaya/OUIRL-ChatBot,vkosuri/ChatterBot,gunthercox/ChatterBot,davizucon/ChatterBot,Reinaesaya/OUIRL-ChatBot,DarkmatterVale/ChatterBot
11d3075ba9d1881526ce90d01ae3b3d5728740fa
setup.py
setup.py
#!/usr/bin/env python3 from distutils.core import setup setup( name='dg', version='HEAD', description='A programming language for the CPython VM', author='pyos', author_email='pyos100500@gmail.com', url='https://github.com/pyos/dg.git', packages=['dg'], package_dir={'dg': '.'}, pack...
#!/usr/bin/env python3 from distutils.core import setup setup( name='dg', version='HEAD', description='A programming language for the CPython VM', author='pyos', author_email='pyos100500@gmail.com', url='https://github.com/pyos/dg.git', packages=['dg'], package_dir={'dg': '.'}, pack...
Install stuff from /addon, too.
Install stuff from /addon, too.
Python
mit
pyos/dg
0df7044bf2c697fe87ea82e4e82ae8895c7fa4a6
wsme/restjson.py
wsme/restjson.py
import base64 from wsme.rest import RestProtocol from wsme.controller import register_protocol import wsme.types try: import simplejson as json except ImportError: import json def prepare_encode(value, datatype): if datatype in wsme.types.pod_types: return value if wsme.types.isstructured(da...
import base64 import datetime from simplegeneric import generic from wsme.rest import RestProtocol from wsme.controller import register_protocol import wsme.types try: import simplejson as json except ImportError: import json @generic def tojson(datatype, value): if wsme.types.isstructured(datatype): ...
Use generic to prepare the json output so that non-structured custom types can be added
Use generic to prepare the json output so that non-structured custom types can be added
Python
mit
stackforge/wsme
6e6a5cfb39ae3f6ee9d0cfb30a6a33be06839bfa
setup.py
setup.py
#!/usr/bin/env python from distutils.core import setup, Extension setup( name='mapcode', ext_modules=[Extension('mapcode', sources=['mapcodemodule.c', 'mapcodelib/mapcoder.c'], include_dirs=['mapcodelib'] )], version='0.3',...
#!/usr/bin/env python from distutils.core import setup, Extension setup( name='mapcode', ext_modules=[Extension('mapcode', sources=['mapcodemodule.c', 'mapcodelib/mapcoder.c'], include_dirs=['mapcodelib'] )], # version numb...
Update module version and tag as v0.4
Update module version and tag as v0.4
Python
apache-2.0
mapcode-foundation/mapcode-python,mapcode-foundation/mapcode-python
101e4832b8fa9fa9da0b447c4c52fb3bd0e3c6a9
ratechecker/migrations/0002_remove_fee_loader.py
ratechecker/migrations/0002_remove_fee_loader.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.22 on 2019-10-31 16:33 from __future__ import unicode_literals from django.db import migrations, OperationalError, ProgrammingError def fix_fee_product_index(apps, schema_editor): try: schema_editor.execute( 'DROP INDEX idx_16977_product_id;' ...
# -*- coding: utf-8 -*- # Generated by Django 1.11.22 on 2019-10-31 16:33 from __future__ import unicode_literals from django.db import migrations, OperationalError, ProgrammingError def fix_fee_product_index(apps, schema_editor): try: schema_editor.execute( 'ALTER TABLE IF EXISTS cfpb.rateche...
Remove DROP INDEX from fix_fee_product_index
Remove DROP INDEX from fix_fee_product_index
Python
cc0-1.0
cfpb/owning-a-home-api
8daf5c8402a981942165d62ccb6057a26ad73012
cms/tests/fixture_loading.py
cms/tests/fixture_loading.py
# -*- coding: utf-8 -*- import tempfile import codecs try: from cStringIO import StringIO except: from io import StringIO from django.core.management import call_command from cms.test_utils.fixtures.navextenders import NavextendersFixture from cms.test_utils.testcases import SettingsOverrideTestCase from cms...
# -*- coding: utf-8 -*- import tempfile import codecs try: from cStringIO import StringIO except: from io import StringIO from django.core.management import call_command from cms.test_utils.fixtures.navextenders import NavextendersFixture from cms.test_utils.testcases import SettingsOverrideTestCase from cms...
Change test_fixture_load to check for rescanned placeholders
Change test_fixture_load to check for rescanned placeholders
Python
bsd-3-clause
stefanw/django-cms,bittner/django-cms,robmagee/django-cms,jsma/django-cms,jeffreylu9/django-cms,AlexProfi/django-cms,Jaccorot/django-cms,yakky/django-cms,memnonila/django-cms,intgr/django-cms,andyzsf/django-cms,intip/django-cms,leture/django-cms,jrief/django-cms,SachaMPS/django-cms,SofiaReis/django-cms,Livefyre/django-...
d8e3612d0defdd55253275e676ef57c22a25c3f7
wishlist/admin.py
wishlist/admin.py
## Django Admin from django.contrib import admin from wishlist.models import Item #admin.site.register( Category ) #admin.site.register( Item ) class ItemAdmin( admin.ModelAdmin ) : list_display = ( "id", "name", "category", "sort_order", "price" ) list_filter = ( "is_active", "category" ) search_fields = ( 'name...
## Django Admin from django.contrib import admin from wishlist.models import * admin.site.register( Category ) class ItemAdmin( admin.ModelAdmin ) : list_display = ( "id", "name", "category", "sort_order", "price" ) list_filter = ( "is_active", "category" ) search_fields = ( 'name', ) list_per_page = 30 admin.si...
Update Django Admin interface to allow editing of Categories
Update Django Admin interface to allow editing of Categories
Python
mit
cgarvey/django-mywishlist,cgarvey/django-mywishlist
d1826b00f4b4944161c66e737978bdc87bb57b52
polyaxon/libs/decorators.py
polyaxon/libs/decorators.py
class IgnoreRawDecorator(object): """The `IgnoreRawDecorator` is a decorator to ignore raw/fixture data during signals handling. usage example: @receiver(post_save, sender=settings.AUTH_USER_MODEL) @ignore_raw def my_signal_handler(sender, instance=None, created=False, **kwargs): ...
from django.conf import settings class IgnoreRawDecorator(object): """The `IgnoreRawDecorator` is a decorator to ignore raw/fixture data during signals handling. usage example: @receiver(post_save, sender=settings.AUTH_USER_MODEL) @ignore_raw def my_signal_handler(sender, instance=Non...
Add decorator for runner signals
Add decorator for runner signals
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
d19a6ea9da1f6fe3313a36d44d6e6b4e9749acaa
test/test_regression_17.py
test/test_regression_17.py
import pytest import python_jsonschema_objects as pjo @pytest.fixture def test_class(): schema = { 'title': 'Example', 'properties': { "claimed_by": { "id": "claimed", "type": ["string", "integer", "null"], "description": "Robots Only. ...
import pytest import python_jsonschema_objects as pjo @pytest.fixture def test_class(): schema = { 'title': 'Example', 'properties': { "claimed_by": { "id": "claimed", "type": ["string", "integer", "null"], "description": "Robots Only. ...
Fix an actual schema validation error in one of the tests
Fix an actual schema validation error in one of the tests
Python
mit
cwacek/python-jsonschema-objects
31b69d9810fb694be005e21d9c1fc80574460d97
promgen/tests/test_rules.py
promgen/tests/test_rules.py
from unittest import mock from django.test import TestCase from promgen import models, prometheus _RULES = ''' # Service: Service 1 # Service URL: /service/1/ ALERT RuleName IF up==0 FOR 1s LABELS {severity="severe"} ANNOTATIONS {service="http://example.com/service/1/", summary="Test case"} '''.lstrip() ...
from unittest import mock from django.test import TestCase from promgen import models, prometheus _RULES = ''' # Service: Service 1 # Service URL: /service/1/ ALERT RuleName IF up==0 FOR 1s LABELS {severity="severe"} ANNOTATIONS {service="http://example.com/service/1/", summary="Test case"} '''.lstrip() ...
Add test for copying rules with their labels and annotations
Add test for copying rules with their labels and annotations
Python
mit
kfdm/promgen,kfdm/promgen,kfdm/promgen,kfdm/promgen
c34f630bf1d4a6c77ec68f69428df930b0ade146
pymc/examples/glm_robust.py
pymc/examples/glm_robust.py
import numpy as np try: import statsmodels.api as sm except ImportError: sys.exit(0) from pymc import * # Generate data size = 50 true_intercept = 1 true_slope = 2 x = np.linspace(0, 1, size) y = true_intercept + x*true_slope + np.random.normal(scale=.5, size=size) # Add outliers x = np.append(x, [.1, .15,...
import numpy as np import sys try: import statsmodels.api as sm except ImportError: print "Example requires statsmodels" sys.exit(0) from pymc import * # Generate data size = 50 true_intercept = 1 true_slope = 2 x = np.linspace(0, 1, size) y = true_intercept + x*true_slope + np.random.normal(scale=.5, s...
Add missing import and explanation of failure
Add missing import and explanation of failure
Python
apache-2.0
superbobry/pymc3,LoLab-VU/pymc,superbobry/pymc3,Anjum48/pymc3,hothHowler/pymc3,jameshensman/pymc3,wanderer2/pymc3,hothHowler/pymc3,MCGallaspy/pymc3,kmather73/pymc3,dhiapet/PyMC3,JesseLivezey/pymc3,kmather73/pymc3,tyarkoni/pymc3,clk8908/pymc3,jameshensman/pymc3,evidation-health/pymc3,MichielCottaar/pymc3,arunlodhi/pymc3...
d46c0a045b8cab7cb51e9fe2aefb4286da8266d6
.ycm_extra_conf.py
.ycm_extra_conf.py
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2014 Adrian Perez <aperez@igalia.com> # # Distributed under terms of the MIT license. from subprocess import check_output from shlex import split as sh_split def FlagsForFile(path, **kwarg): flags = sh_split(check_output(["make", "pri...
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2014 Adrian Perez <aperez@igalia.com> # # Distributed under terms of the MIT license. from subprocess import check_output from shlex import split as sh_split def FlagsForFile(path, **kwarg): flags = sh_split(check_output(["make", "pri...
Remove -DDWT_USE_HEADER_BAR from YCM configuration
Remove -DDWT_USE_HEADER_BAR from YCM configuration The option does not exist anymore, so there is no reason to keep it around.
Python
mit
aperezdc/dwt,aperezdc/dwt
3b1cab31872ba7ed335d1ea254c3c1a477020966
extract_contamination.py
extract_contamination.py
import sys import os header = ['Mouse_single', 'Mouse_multiple', 'Human', 'Other', 'Unmapped'] print '\t'.join(header) for fi in sys.argv[1:]: sample = os.path.basename(fi).split('.')[0] with open(fi) as screen_results: results = {} for line in screen_results: fields = line.strip()....
import sys import os header = ['Sample', 'Mouse_single', 'Mouse_multiple', 'Human', 'Other', 'Unmapped'] print '\t'.join(header) for fi in sys.argv[1:]: sample = os.path.basename(fi).split('.')[0] if sample[-7:] == '_screen': sample = sample[:-7] with open(fi) as screen_results: results = {...
Fix problem with finding sample name from fastqc_screen output
Fix problem with finding sample name from fastqc_screen output
Python
apache-2.0
pombo-lab/gamtools,pombo-lab/gamtools
ed9601b2899aef7fcadfe7306dc1320ce72f232c
raven/transport/requests.py
raven/transport/requests.py
""" raven.transport.requests ~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import from raven.transport.http import HTTPTransport try: import requests has_requests = True exc...
""" raven.transport.requests ~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import from raven.conf import defaults from raven.transport.http import HTTPTransport try: import requ...
Add support for the verify_ssl, ca_certs and timeout parameters for the request transport.
Add support for the verify_ssl, ca_certs and timeout parameters for the request transport.
Python
bsd-3-clause
dbravender/raven-python,johansteffner/raven-python,ronaldevers/raven-python,lepture/raven-python,dbravender/raven-python,jbarbuto/raven-python,johansteffner/raven-python,nikolas/raven-python,jbarbuto/raven-python,recht/raven-python,lepture/raven-python,akheron/raven-python,jmp0xf/raven-python,arthurlogilab/raven-python...
02ef868100ab190b5fa3bff5bad4891f21101ee2
getkey/__init__.py
getkey/__init__.py
from __future__ import absolute_import from .platforms import platform __platform = platform() getkey = __platform.getkey keys = __platform.keys key = keys # alias bang = __platform.bang # __all__ = [getkey, key, bang, platform] __version__ = '0.6'
from __future__ import absolute_import, print_function import sys from .platforms import platform, PlatformError try: __platform = platform() except PlatformError as err: print('Error initializing standard platform: {}'.format(err.args[0]), file=sys.stderr) else: getkey = __platform.getkey ke...
Handle test environment with no real stdin
Handle test environment with no real stdin
Python
mit
kcsaff/getkey
044e9a29e594db1b081175d20d9525151c870e41
torchtext/data/pipeline.py
torchtext/data/pipeline.py
class Pipeline(object): """Defines a pipeline for transforming sequence data.""" def __init__(self, convert_token=None): if convert_token is not None: self.convert_token = convert_token else: self.convert_token = lambda x: x self.pipes = [self] def __call__(...
class Pipeline(object): """Defines a pipeline for transforming sequence data.""" def __init__(self, convert_token=None): if convert_token is not None: self.convert_token = convert_token else: self.convert_token = lambda x: x self.pipes = [self] def __call__(...
Return self in Pipeline add_after and add_before
Return self in Pipeline add_after and add_before
Python
bsd-3-clause
pytorch/text,pytorch/text,pytorch/text,pytorch/text
c54a1286200ce62ef5eddef436428c2244e94798
totemlogs/elasticsearch.py
totemlogs/elasticsearch.py
from __future__ import absolute_import from future.builtins import ( # noqa bytes, dict, int, list, object, range, str, ascii, chr, hex, input, next, oct, open, pow, round, super, filter, map, zip) from functools import wraps import logging from elasticsearch import Elasticsearch from conf.appconfig im...
from __future__ import absolute_import from future.builtins import ( # noqa bytes, dict, int, list, object, range, str, ascii, chr, hex, input, next, oct, open, pow, round, super, filter, map, zip) from functools import wraps import logging from elasticsearch import Elasticsearch from conf.appconfig im...
Use POST instead of GET Request for ES Search API (Issue with query string size)
Use POST instead of GET Request for ES Search API (Issue with query string size)
Python
mit
totem/totem-logs,totem/totem-logs,totem/totem-logs,totem/totem-logs
35a15e06feca24872acb42c5395b58b2a1bed60e
byceps/services/snippet/transfer/models.py
byceps/services/snippet/transfer/models.py
""" byceps.services.snippet.transfer.models ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from __future__ import annotations from dataclasses import dataclass from enum import Enum from typing import NewType from uuid import UUI...
""" byceps.services.snippet.transfer.models ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from __future__ import annotations from dataclasses import dataclass from enum import Enum from typing import NewType from uuid import UUI...
Remove unused class method `Scope.for_global`
Remove unused class method `Scope.for_global`
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps
a3eef3be93e4328194997ea48c509105110145b8
utils/management/commands/get_settings_values.py
utils/management/commands/get_settings_values.py
# Amara, universalsubtitles.org # # Copyright (C) 2012 Participatory Culture Foundation # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your ...
# Amara, universalsubtitles.org # # Copyright (C) 2012 Participatory Culture Foundation # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your ...
Allow for getting a settings value from a single server in the enviroment
Allow for getting a settings value from a single server in the enviroment
Python
agpl-3.0
pculture/unisubs,wevoice/wesub,ofer43211/unisubs,wevoice/wesub,eloquence/unisubs,eloquence/unisubs,norayr/unisubs,norayr/unisubs,pculture/unisubs,wevoice/wesub,pculture/unisubs,eloquence/unisubs,ReachingOut/unisubs,ujdhesa/unisubs,ReachingOut/unisubs,ofer43211/unisubs,norayr/unisubs,eloquence/unisubs,ujdhesa/unisubs,pc...
90bfdbe432763565d7e8ccc8b04e9d3440164557
draftjs_exporter/constants.py
draftjs_exporter/constants.py
from __future__ import absolute_import, unicode_literals # http://stackoverflow.com/a/22723724/1798491 class Enum(object): def __init__(self, *elements): self.elements = tuple(elements) def __getattr__(self, name): if name not in self.elements: raise AttributeError("'Enum' has no ...
from __future__ import absolute_import, unicode_literals # http://stackoverflow.com/a/22723724/1798491 class Enum(object): def __init__(self, *elements): self.elements = tuple(elements) def __getattr__(self, name): if name not in self.elements: raise AttributeError("'Enum' has no ...
Remove unused pullquote block type
Remove unused pullquote block type
Python
mit
springload/draftjs_exporter,springload/draftjs_exporter,springload/draftjs_exporter
45510b1adc401244297fb281b8f6ecd22f7c4b0e
InvenTree/part/serializers.py
InvenTree/part/serializers.py
from rest_framework import serializers from .models import Part class PartSerializer(serializers.ModelSerializer): """ Serializer for complete detail information of a part. Used when displaying all details of a single component. """ class Meta: model = Part fields = [ 'ur...
from rest_framework import serializers from .models import Part class PartSerializer(serializers.ModelSerializer): """ Serializer for complete detail information of a part. Used when displaying all details of a single component. """ def _category_name(self, part): if part.category: ...
Add category info to part serializer
Add category info to part serializer
Python
mit
inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree
d99bdbd710c6b3bf0e1eeed5d2cf8f26790040ef
alembic/versions/38f01b0893b8_add_call_in_campaign_id_to_.py
alembic/versions/38f01b0893b8_add_call_in_campaign_id_to_.py
"""Add call_in_campaign_id to TwilioPhoneNumber Revision ID: 38f01b0893b8 Revises: 3c34cfd19bf8 Create Date: 2016-10-21 18:59:13.190060 """ # revision identifiers, used by Alembic. revision = '38f01b0893b8' down_revision = '3c34cfd19bf8' branch_labels = None depends_on = None from alembic import op import sqlalchem...
"""Add call_in_campaign_id to TwilioPhoneNumber Revision ID: 38f01b0893b8 Revises: 3c34cfd19bf8 Create Date: 2016-10-21 18:59:13.190060 """ # revision identifiers, used by Alembic. revision = '38f01b0893b8' down_revision = '3c34cfd19bf8' branch_labels = None depends_on = None from alembic import op import sqlalchem...
Initialize call_in_campaign_id column after adding
Initialize call_in_campaign_id column after adding
Python
agpl-3.0
OpenSourceActivismTech/call-power,spacedogXYZ/call-power,spacedogXYZ/call-power,18mr/call-congress,spacedogXYZ/call-power,OpenSourceActivismTech/call-power,spacedogXYZ/call-power,OpenSourceActivismTech/call-power,18mr/call-congress,18mr/call-congress,18mr/call-congress,OpenSourceActivismTech/call-power
4ed8f05fa43f29a1881a23ae99fdc3ad8cd661b0
grammpy/StringGrammar.py
grammpy/StringGrammar.py
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """ from .RawGrammar import RawGrammar as Grammar class StringGrammar(Grammar): @staticmethod def __to_string_arr(t): if isinstance(t, str): return [t] retu...
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """ from .RawGrammar import RawGrammar as Grammar class StringGrammar(Grammar): @staticmethod def __to_string_arr(t): if isinstance(t, str): return [t] retu...
Correct return of Terminal instance when parameter is string
Correct return of Terminal instance when parameter is string
Python
mit
PatrikValkovic/grammpy
fdd69cb0b7b11fce9cfc70d85e51a29aaabc0ee0
wagtailmenus/management/commands/autopopulate_main_menus.py
wagtailmenus/management/commands/autopopulate_main_menus.py
# -*- coding: utf-8 -*- import logging from django.core.management.base import BaseCommand from wagtail.wagtailcore.models import Site from wagtailmenus import app_settings logger = logging.getLogger(__name__) class Command(BaseCommand): help = ( "Create a 'main menu' for any 'Site' that doesn't alread...
# -*- coding: utf-8 -*- import logging from django.core.management.base import BaseCommand from wagtail.wagtailcore.models import Site from wagtailmenus import app_settings logger = logging.getLogger(__name__) class Command(BaseCommand): help = ( "Create a 'main menu' for any 'Site' that doesn't alread...
Use the root_page.depth to determine filter value to identify section root pages
Use the root_page.depth to determine filter value to identify section root pages
Python
mit
rkhleics/wagtailmenus,ababic/wagtailmenus,rkhleics/wagtailmenus,ababic/wagtailmenus,rkhleics/wagtailmenus,ababic/wagtailmenus
eadf9bf6ce1bf09c6551f4a54a0a32d6fb872ab3
gaphor/ui/tests/test_recentfiles.py
gaphor/ui/tests/test_recentfiles.py
import pytest from gi.repository import GLib from gaphor.services.eventmanager import EventManager from gaphor.ui.event import FileLoaded from gaphor.ui.recentfiles import RecentFiles class RecentManagerStub: def __init__(self): self.items = [] def add_full(self, uri, meta): self.items.appen...
import pathlib import pytest from gi.repository import GLib from gaphor.services.eventmanager import EventManager from gaphor.ui.event import FileLoaded from gaphor.ui.recentfiles import RecentFiles class RecentManagerStub: def __init__(self): self.items = [] def add_full(self, uri, meta): ...
Fix tests in Windows: decoded_filename contains backslashes
Fix tests in Windows: decoded_filename contains backslashes Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me>
Python
lgpl-2.1
amolenaar/gaphor,amolenaar/gaphor
41ec266722eefb01b7e884696c7825bd5273e4ca
tests/test_diff.py
tests/test_diff.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from livemark.diff import _is_same_node, _next_noempty from wdom.tests.util import TestCase from wdom.parser import parse_html class TestSameNode(TestCase): def test_same_node(self): node1_src = '<h1>A</h1>' node1 = parse_html(node1_src) nod...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from livemark.diff import _is_same_node, _next_noempty from wdom.tests.util import TestCase from wdom.parser import parse_html class TestSameNode(TestCase): def setUp(self): self.src1 = '<h1>text1</h1>' self.src2 = '<h1>text2</h1>' self.src3...
Add test for same node check
Add test for same node check
Python
mit
miyakogi/livemark
88d6728a157a260ed0b8ffc947c710d22a948efb
stock_transfer_restrict_lot/models/stock_move.py
stock_transfer_restrict_lot/models/stock_move.py
from openerp import models, fields, api, _ from openerp.exceptions import UserError class StockPackOperation(models.Model): _inherit = 'stock.pack.operation' code = fields.Selection( related='picking_id.picking_type_id.code', string='Operation Type', readonly=True) @api.one ...
from openerp import models, fields, api, _ from openerp.exceptions import UserError class StockPackOperation(models.Model): _inherit = 'stock.pack.operation' code = fields.Selection( related='picking_id.picking_type_id.code', string='Operation Type', readonly=True) @api.one ...
FIX stock transfer restrict lot when lost is reserved
FIX stock transfer restrict lot when lost is reserved
Python
agpl-3.0
ingadhoc/stock
5ff983c1a464fc559cb13addb5316f99379472bf
tests/test_trip.py
tests/test_trip.py
#!/usr/bin/env python import unittest from parsemypsa.storage import objects class TripTestCase(unittest.TestCase): def setUp(self): self.trip1 = objects.Trip.create(id=1, 1462731168, 200, 1000, 1, 0, 0) def test_mileage_calculation(self): self.trip1.calculate_mileage() self.assertE...
#!/usr/bin/env python import unittest from playhouse.test_utils import test_database from peewee import * from parsemypsa.storage import objects # Data for testing test_db = SqliteDatabase(':memory:') model_list = [objects.Alert, objects.VehiculeInformation, objects.Trip] class TripTestCase(unittest.TestCase): ...
Fix unittests broken after ORM adoption
Fix unittests broken after ORM adoption
Python
mit
klenje/parsemypsa
436195aad8c3e7a069066e9e1d4db6dfa9ac34db
devilry/addons/student/devilry_plugin.py
devilry/addons/student/devilry_plugin.py
from django.utils.translation import ugettext as _ from django.utils.safestring import mark_safe from django.core.urlresolvers import reverse from devilry.addons.dashboard.dashboardplugin_registry import registry, \ DashboardItem import dashboardviews def simpleview(request, *args): return mark_safe(u"""S...
from django.utils.translation import ugettext as _ from django.utils.safestring import mark_safe from django.core.urlresolvers import reverse from devilry.addons.dashboard.dashboardplugin_registry import registry, \ DashboardItem import dashboardviews registry.register_important(DashboardItem( title ...
Set title to 'Assignment' in student dashboard
Set title to 'Assignment' in student dashboard
Python
bsd-3-clause
devilry/devilry-django,devilry/devilry-django,devilry/devilry-django,vegarang/devilry-django,vegarang/devilry-django,devilry/devilry-django
2f37ae17eae3701eb205f5f524de3254f6d965e8
tools/skp/page_sets/skia_worldjournal_nexus10.py
tools/skp/page_sets/skia_worldjournal_nexus10.py
# Copyright 2014 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. # pylint: disable=W0401,W0614 from telemetry.page import page as page_module from telemetry.page import page_set as page_set_module class SkiaBuildbotDesk...
# Copyright 2014 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. # pylint: disable=W0401,W0614 from telemetry.page import page as page_module from telemetry.page import page_set as page_set_module class SkiaBuildbotDesk...
Remove action_runner steps for worldjournal pageset to prevent crashes
Remove action_runner steps for worldjournal pageset to prevent crashes BUG=skia:3196 NOTRY=true Review URL: https://codereview.chromium.org/795173002
Python
bsd-3-clause
OneRom/external_skia,VRToxin-AOSP/android_external_skia,Infinitive-OS/platform_external_skia,Hikari-no-Tenshi/android_external_skia,google/skia,PAC-ROM/android_external_skia,timduru/platform-external-skia,AOSP-YU/platform_external_skia,pcwalton/skia,vanish87/skia,Infinitive-OS/platform_external_skia,TeamExodus/external...
a1c87c491bf936d441ef7fd79b531384fa174138
simpleubjson/version.py
simpleubjson/version.py
# -*- coding: utf-8 -*- # # Copyright (C) 2013 Alexander Shorin # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. # __version_info__ = (0, 6, 0, 'dev', 0) __version__ = '{version}{tag}{build}'.format( version='.'.jo...
# -*- coding: utf-8 -*- # # Copyright (C) 2013 Alexander Shorin # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. # __version_info__ = (0, 6, 0, 'dev', 0) __version__ = '%(version)s%(tag)s%(build)s' % { 'version': '...
Fix compatibility with Python 2.5
Fix compatibility with Python 2.5
Python
bsd-2-clause
kxepal/simpleubjson,brainwater/simpleubjson,samipshah/simpleubjson,498888197/simpleubjson
30f259dbd1c5c9963a5a75855188e4f668626fb7
test/test_Spectrum.py
test/test_Spectrum.py
#!/usr/bin/env python from __future__ import division, print_function import pytest import sys # Add Spectrum location to path sys.path.append('../') import Spectrum # Test using hypothesis def test_spectrum_assigns_data(): x = [1,2,3,4,5,6] y = [1,1,0.9,0.95,1,1] z = 2200*x spec = Spectrum.Spectru...
#!/usr/bin/env python from __future__ import division, print_function import pytest import sys # Add Spectrum location to path sys.path.append('../') import Spectrum # Test using hypothesis from hypothesis import given import hypothesis.strategies as st @given(st.lists(st.integers()), st.lists(st.floats()), st.list...
Add hypothesis test to test assignment
Add hypothesis test to test assignment
Python
mit
jason-neal/spectrum_overload,jason-neal/spectrum_overload,jason-neal/spectrum_overload
0fd464dcd405faa356c18d69a0b7419c5cff0f21
pmxbot/__init__.py
pmxbot/__init__.py
# -*- coding: utf-8 -*- # vim:ts=4:sw=4:noexpandtab import importlib from .dictlib import ConfigDict config = ConfigDict( bot_nickname = 'pmxbot', database = 'sqlite:pmxbot.sqlite', server_host = 'irc.freenode.net', server_port = 6667, use_ssl = False, password = None, silent_bot = False, log_channels = [], ...
# -*- coding: utf-8 -*- # vim:ts=4:sw=4:noexpandtab import importlib from .dictlib import ConfigDict config = ConfigDict( bot_nickname = 'pmxbot', database = 'sqlite:pmxbot.sqlite', server_host = 'localhost', server_port = 6667, use_ssl = False, password = None, silent_bot = False, log_channels = [], other_...
Use IRC server on localhost by default
Use IRC server on localhost by default
Python
bsd-3-clause
jamwt/diesel-pmxbot,jamwt/diesel-pmxbot
547e002534d3a9757c84bad7e125b9186dd78078
tests/test_common.py
tests/test_common.py
import os, os.path import ConfigParser package = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) import slack class TestSlack(object): def setup(self): self.set_up_config() self.set_up_slack() def set_up_config(self): search_paths = [os.path.expanduser('~/.slack'), '/e...
import os, os.path import ConfigParser package = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) import slack class TestSlack(object): def setup(self): self.set_up_config() self.set_up_slack() def set_up_config(self): search_paths = [os.path.expanduser('~/.slack'), '/e...
Add new channel name for test.
Add new channel name for test.
Python
mit
nabetama/slacky
8d32970073c699e06663cae12861b58e7c365f2c
tests/test_rtnorm.py
tests/test_rtnorm.py
# This should plot a histogram looking like a gaussian # ... It does. ## CONFIGURATION (play with different values) samples = int(1e6) minimum = 1. maximum = 17. center = 7. stddev = 5. ## VARIABLES FROM RANDOM TRUNCATED NORMAL DISTRIBUTION from lib.rtnorm import rtnorm variables = rtnorm(minimum, maximum, mu=c...
import unittest import matplotlib.pyplot as plot import numpy as np import sys sys.path.append('.') # T_T from lib.rtnorm import rtnorm class RunTest(unittest.TestCase): longMessage = True def test_histogram(self): """ This should plot a histogram looking like a gaussian ... It d...
Fix the random truncated distribution tests
Fix the random truncated distribution tests
Python
mit
irap-omp/deconv3d,irap-omp/deconv3d
754707379a12058b4c66802c3f0545c0e634103d
bumblebee_status/modules/contrib/taskwarrior.py
bumblebee_status/modules/contrib/taskwarrior.py
"""Displays the number of pending tasks in TaskWarrior. Requires the following library: * taskw Parameters: * taskwarrior.taskrc : path to the taskrc file (defaults to ~/.taskrc) contributed by `chdorb <https://github.com/chdorb>`_ - many thanks! """ from taskw import TaskWarrior import core.module import...
"""Displays the number of pending tasks in TaskWarrior. Requires the following library: * taskw Parameters: * taskwarrior.taskrc : path to the taskrc file (defaults to ~/.taskrc) contributed by `chdorb <https://github.com/chdorb>`_ - many thanks! """ from taskw import TaskWarrior import core.module import...
Add active-task display and scrolling
Add active-task display and scrolling This adds an option allowing you to specify "taskwarrior.show_active=true" in your bar configuration and will display the current, active task id and description on the status bar, but will show the number of pending tasks if one isn't active. This also adds the scrolling decorat...
Python
mit
tobi-wan-kenobi/bumblebee-status,tobi-wan-kenobi/bumblebee-status
3421db3528a655768141b3615d04d84cf7100bb0
ckanext/requestdata/plugin.py
ckanext/requestdata/plugin.py
import ckan.plugins as plugins import ckan.plugins.toolkit as toolkit from ckanext.requestdata.model import setup as model_setup class RequestdataPlugin(plugins.SingletonPlugin): plugins.implements(plugins.IConfigurer) plugins.implements(plugins.IRoutes, inherit=True) plugins.implements(plugins.IConfigur...
import ckan.plugins as plugins import ckan.plugins.toolkit as toolkit from ckanext.requestdata.model import setup as model_setup from ckanext.requestdata.logic import actions from ckanext.requestdata.logic import auth class RequestdataPlugin(plugins.SingletonPlugin): plugins.implements(plugins.IConfigurer) p...
Define actions and auth functions
Define actions and auth functions
Python
agpl-3.0
ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata
89a232538c2ce7bc3ed406e6b9587cebbff2849e
amplpy/amplpython/__init__.py
amplpy/amplpython/__init__.py
# -*- coding: utf-8 -*- from __future__ import absolute_import import os import platform if platform.system() == 'Windows': lib32 = os.path.join(os.path.dirname(__file__), 'lib32') lib64 = os.path.join(os.path.dirname(__file__), 'lib64') os.environ['PATH'] += os.pathsep + lib32 os.environ['PATH'] += o...
# -*- coding: utf-8 -*- from __future__ import absolute_import import os import ctypes import platform if platform.system() == 'Windows': lib32 = os.path.join(os.path.dirname(__file__), 'lib32') lib64 = os.path.join(os.path.dirname(__file__), 'lib64') from glob import glob from ctypes import sizeof ...
Add workaround for conda python
Add workaround for conda python Python versions that come with conda for Windows do not load .dlls in the same way as standard python versions.
Python
bsd-3-clause
ampl/amplpy,ampl/amplpy,ampl/amplpy
7adcf50f27e805931e7bb4c39fa07fa346710acf
anserv/modules/mixpanel/generic_event_handlers.py
anserv/modules/mixpanel/generic_event_handlers.py
from modules.mixpanel.mixpanel import track_event_mixpanel from modules.decorators import view, query, event_handler import re SINGLE_PAGES_TO_TRACK = ['/', '/dashboard', '/create_account'] REGEX_PAGES_TO_TRACK = ['/course', '/about'] @event_handler() def single_page_track_event(fs, db, response): for resp in resp...
from modules.mixpanel.mixpanel import track_event_mixpanel from modules.decorators import view, query, event_handler import re SINGLE_PAGES_TO_TRACK = ['/', '/dashboard', '/create_account'] COURSE_PAGES_TO_TRACK = ['/courses', '/about'] @event_handler() def single_page_track_event(fs, db, response): for resp in re...
Fix up mixpanel course tracking
Fix up mixpanel course tracking
Python
agpl-3.0
edx/edxanalytics,edx/edxanalytics,edx/insights,edx/edxanalytics,edx/edxanalytics,edx/insights
aeef2c319ea5c7d59a0bdf69a5fbe5dc8a1ab1bc
wagtailnews/feeds.py
wagtailnews/feeds.py
from django.contrib.syndication.views import Feed from django.utils import timezone class LatestEnteriesFeed(Feed): description = "Latest news" def items(self): now = timezone.now() NewsItem = self.news_index.get_newsitem_model() newsitem_list = NewsItem.objects.live().order_by('-date...
from django.contrib.syndication.views import Feed from django.utils import timezone class LatestEnteriesFeed(Feed): def items(self): now = timezone.now() NewsItem = self.news_index.get_newsitem_model() newsitem_list = NewsItem.objects.live().order_by('-date').filter( newsindex...
Add some extra item methods / parameters to LatestEntriesFeed
Add some extra item methods / parameters to LatestEntriesFeed
Python
bsd-2-clause
takeflight/wagtailnews,takeflight/wagtailnews,takeflight/wagtailnews,takeflight/wagtailnews
c8bf23253aaacb880f438b7093c85c76767734e7
duedil/resources/pro/company/accounts/__init__.py
duedil/resources/pro/company/accounts/__init__.py
'Accounts' from __future__ import unicode_literals from .... import ProResource, RelatedResourceMixin import six import sys class Account(RelatedResourceMixin, ProResource): 'Abstraction of Accounts resource in duedil v3 pro api' attribute_names = [ 'uri', 'date', 'type' ] acc...
'Accounts' from __future__ import unicode_literals from .... import ProResource, RelatedResourceMixin import six import sys class Account(RelatedResourceMixin, ProResource): 'Abstraction of Accounts resource in duedil v3 pro api' attribute_names = [ 'uri', 'date', 'type' ] acc...
Use dict comprehension instead of dict([...])
Use dict comprehension instead of dict([...])
Python
apache-2.0
founders4schools/duedilv3
b0085ad5268da92181b043c56b64d690e5eb8679
access/admin.py
access/admin.py
from django.contrib.auth.admin import UserAdmin from .forms import UserCreationForm, UserChangeForm class UserAdmin(UserAdmin): form = UserChangeForm add_form = UserCreationForm fieldsets = ( (None, {'fields': ('email', 'password',)}), ('Permissions', {'fields': ('is_active', 'is_staff',...
from django.contrib.auth.admin import UserAdmin from django.utils.translation import ugettext_lazy as _ from .forms import UserCreationForm, UserChangeForm class UserAdmin(UserAdmin): form = UserChangeForm add_form = UserCreationForm fieldsets = ( (None, {'fields': ('email', 'password', 'two_fa_...
Add 2FA field, use localized labels in UserAdmin
Add 2FA field, use localized labels in UserAdmin
Python
agpl-3.0
node13h/droll,node13h/droll
5c2ca9afac5fe29a86de8ff6774c62b7d3d33561
tests/base.py
tests/base.py
from dh_syncserver import config from dh_syncserver import models from dh_syncserver import database from twisted.trial import unittest from twisted.enterprise import adbapi from twisted.internet.defer import inlineCallbacks, returnValue from twistar.registry import Registry class TestBase(unittest.TestCase): @i...
import logging from dh_syncserver import config from dh_syncserver import models from dh_syncserver import database from twisted.trial import unittest from twisted.enterprise import adbapi from twisted.internet.defer import inlineCallbacks, returnValue from twistar.registry import Registry class TestBase(unittest.T...
Write log file from unit tests
Write log file from unit tests
Python
agpl-3.0
sergey-dryabzhinsky/denyhosts_sync,sergey-dryabzhinsky/denyhosts_sync,janpascal/denyhosts_sync,sergey-dryabzhinsky/denyhosts_sync,janpascal/denyhosts_sync,janpascal/denyhosts_sync
c7863c1efa1a030b04e4efcb97948925c84b7508
acute/referrals.py
acute/referrals.py
""" Referral routes for OPAL acute """ from referral import ReferralRoute from acute import models class ClerkingRoute(ReferralRoute): name = 'Acute Take' description = 'Add a patient to the Acute Take list' target_teams = ['take'] success_link = '/#/list/take' verb = 'Book in' progr...
""" Referral routes for OPAL acute """ from referral import ReferralRoute from acute import models class ClerkingRoute(ReferralRoute): name = 'Acute Take' description = 'Add a patient to the Acute Take list' page_title = 'Acute Admissions' target_teams = ['take'] success_link = '/#/lis...
Rename referral portal -> Acute admissions
Rename referral portal -> Acute admissions
Python
agpl-3.0
openhealthcare/acute,openhealthcare/acute,openhealthcare/acute
b37655199a42622dec88ba11f845cc78d2ed0e8c
mama_cas/services/__init__.py
mama_cas/services/__init__.py
from django.utils.module_loading import import_string def _get_backends(): backends = [] for backend_path in ['mama_cas.services.backends.SettingsBackend']: backend = import_string(backend_path)() backends.append(backend) return backends def _is_allowed(attr, *args): for backend in _...
from django.utils.module_loading import import_string def _get_backends(): backends = [] for backend_path in ['mama_cas.services.backends.SettingsBackend']: backend = import_string(backend_path)() backends.append(backend) return backends def _is_allowed(attr, *args): for backend in _...
Join callback lists returned from backends
Join callback lists returned from backends
Python
bsd-3-clause
jbittel/django-mama-cas,orbitvu/django-mama-cas,jbittel/django-mama-cas,orbitvu/django-mama-cas
5253f7fbcea33e28af6348c3cc0f65334cad5623
setuptools/launch.py
setuptools/launch.py
""" Launch the Python script on the command line after setuptools is bootstrapped via import. """ # Note that setuptools gets imported implicitly by the # invocation of this script using python -m setuptools.launch import tokenize import sys def run(): """ Run the script in sys.argv[1] as if it had been invoked ...
""" Launch the Python script on the command line after setuptools is bootstrapped via import. """ # Note that setuptools gets imported implicitly by the # invocation of this script using python -m setuptools.launch import tokenize import sys def run(): """ Run the script in sys.argv[1] as if it had been...
Swap out hard tabs for spaces
Swap out hard tabs for spaces
Python
mit
pypa/setuptools,pypa/setuptools,pypa/setuptools
5d78a0da7d24eb2dc4af648ece4e21cc2448b76e
app/admin/forms.py
app/admin/forms.py
from flask.ext.wtf import Form from wtforms import StringField, TextAreaField, SubmitField from wtforms.validators import Required, Length, Email, Optional class ProfileForm(Form): name = StringField('Nafn', validators=[Optional(), Length(1,64)]) location = Strin...
from flask.ext.wtf import Form from wtforms import StringField, TextAreaField, SubmitField, SelectField from wtforms.fields.html5 import DateField from wtforms.validators import Required, Length, Email, Optional class ProfileForm(Form): name = StringField('Nafn', validators=[Optional(), ...
Add a PostForm for posting a news story
Add a PostForm for posting a news story
Python
mit
finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is
761b2675471dfee97943e4123e45fc058d8f8153
qsdl/simulator/defaultCostCallbacks.py
qsdl/simulator/defaultCostCallbacks.py
# -*- coding: latin-1 -*- ''' Created on 3.10.2012 @author: Teemu Pkknen ''' def get_callback_map(): AVG_AUTOCOMPLETE_INPUT_LENGTH = 5 def get_current_query_cost( simulation, key_cost, interaction_type ): if "basic" == interaction_type: return float(key_cost) * len( simulation.get_current_query_text()...
# -*- coding: latin-1 -*- ''' Created on 3.10.2012 @author: Teemu Pkknen ''' def get_callback_map(): AVG_AUTOCOMPLETE_INPUT_LENGTH = 5 def get_current_query_cost( simulation, key_cost, interaction_type = "basic" ): if "basic" == interaction_type: return float(key_cost) * len( simulation.get_current_qu...
Change default query cost calculation interaction type to "basic"
Change default query cost calculation interaction type to "basic"
Python
mit
fire-uta/ir-simulation,fire-uta/ir-simulation
0a78f0cc03124662871c27ae2ac8647ecac58457
rasa_nlu/tokenizers/spacy_tokenizer.py
rasa_nlu/tokenizers/spacy_tokenizer.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import typing from typing import Any, List from rasa_nlu.components import Component from rasa_nlu.config import RasaNLUModelConfig from rasa_nlu.tokenizers import Token...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import typing from typing import Any, List from rasa_nlu.components import Component from rasa_nlu.config import RasaNLUModelConfig from rasa_nlu.tokenizers import Token...
Add missing "requires" to spacy tokenizer
Add missing "requires" to spacy tokenizer
Python
apache-2.0
RasaHQ/rasa_nlu,RasaHQ/rasa_nlu,RasaHQ/rasa_nlu
4848dfc9e965f7f82eb1f7aa4d90e8b39489a6a0
recipes/pyglet/display_import_tests.py
recipes/pyglet/display_import_tests.py
# The import tests in here should be only those that # 1. Require an X11 display on linux test_imports = [ 'pyglet.font', 'pyglet.gl', 'pyglet.graphics', 'pyglet.image', 'pyglet.image.codecs', 'pyglet.input', 'pyglet.media', 'pyglet.media.drivers', 'pyglet.media.drivers.directsound'...
# The import tests in here should be only those that # 1. Require an X11 display on linux test_imports = [ 'pyglet.font', 'pyglet.gl', 'pyglet.graphics', 'pyglet.image', 'pyglet.image.codecs', 'pyglet.input', 'pyglet.media', 'pyglet.media.drivers', 'pyglet.media.drivers.directsound'...
Add a tiny bit of output
Add a tiny bit of output
Python
bsd-3-clause
data-exp-lab/staged-recipes,Savvysherpa/staged-recipes,hbredin/staged-recipes,tylere/staged-recipes,johannesring/staged-recipes,shadowwalkersb/staged-recipes,kwilcox/staged-recipes,mcernak/staged-recipes,rvalieris/staged-recipes,barkls/staged-recipes,johanneskoester/staged-recipes,birdsarah/staged-recipes,rmcgibbo/stag...
52058f7ea882d9d62d1003796520387e2a092c6c
volt/hooks.py
volt/hooks.py
"""Hooks for various events.""" # Copyright (c) 2012-2022 Wibowo Arindrarto <contact@arindrarto.dev> # SPDX-License-Identifier: BSD-3-Clause import sys import structlog from typing import Any from . import signals as s __all__ = [ "log", "post_site_load_engines", "post_site_collect_targets", "pre_si...
"""Hooks for various events.""" # Copyright (c) 2012-2022 Wibowo Arindrarto <contact@arindrarto.dev> # SPDX-License-Identifier: BSD-3-Clause import sys import structlog from typing import Any from . import signals as s __all__ = [ "log", "post_site_load_engines", "post_site_collect_targets", "pre_si...
Add hook.name function for inferring hook names
feat: Add hook.name function for inferring hook names
Python
bsd-3-clause
bow/volt
ddb70c43c0b63cb5af74fb059975cac17bf9f7b9
mdot_rest/views.py
mdot_rest/views.py
from django.shortcuts import render from .models import Resource from .serializers import ResourceSerializer from rest_framework import generics class ResourceList(generics.ListCreateAPIView): queryset = Resource.objects.all() serializer_class = ResourceSerializer class ResourceDetail(generics.RetrieveUpdat...
from django.shortcuts import render from .models import Resource from .serializers import ResourceSerializer from rest_framework import generics, permissions class ResourceList(generics.ListCreateAPIView): queryset = Resource.objects.all() serializer_class = ResourceSerializer permission_classes = (permis...
Make the API read only unless authenticated.
Make the API read only unless authenticated.
Python
apache-2.0
uw-it-aca/mdot-rest,uw-it-aca/mdot-rest
925270e5dd8ffcc72b95bf431444bce480fa18bb
simphony/engine/__init__.py
simphony/engine/__init__.py
""" Simphony engine module This module is dynamicaly populated at import with the registered plugins modules. Plugins modules need to be registered at the 'simphony.engine' entry point. """ from ..extension import get_engine_manager from ..extension import create_wrapper __all__ = ['get_supported_engines', 'create_w...
""" Simphony engine module This module is dynamicaly populated at import with the registered plugins modules. Plugins modules need to be registered at the 'simphony.engine' entry point. """ from ..extension import get_engine_manager __all__ = ['get_supported_engines', 'get_supported_engine_names'] def g...
Remove create_wrapper from the API
Remove create_wrapper from the API
Python
bsd-2-clause
simphony/simphony-common
a7ead6577d885475e82a1c18872eb55e9d39c8b0
rwt/launch.py
rwt/launch.py
import os import subprocess import sys import signal def _build_env(target): """ Prepend target to PYTHONPATH """ env = dict(os.environ) suffix = env.get('PYTHONPATH', '') prefix = target joined = os.pathsep.join([prefix, suffix]).rstrip(os.pathsep) env['PYTHONPATH'] = joined return env def with_path(targe...
import os import subprocess import sys import signal import itertools def _build_env(target): """ Prepend target and .pth references in target to PYTHONPATH """ env = dict(os.environ) suffix = env.get('PYTHONPATH') prefix = target, items = itertools.chain( prefix, (suffix,) if suffix else (), ) joined = ...
Refactor to better inject values into path items
Refactor to better inject values into path items
Python
mit
jaraco/rwt
9489e8512df9e073ac019c75f827c03fe64242dd
sorts/bubble_sort.py
sorts/bubble_sort.py
""" This is pure python implementation of bubble sort algorithm For doctests run following command: python -m doctest -v bubble_sort.py or python3 -m doctest -v bubble_sort.py For manual testing run: python bubble_sort.py """ from __future__ import print_function def bubble_sort(collection): """Pure implementa...
""" This is pure python implementation of bubble sort algorithm For doctests run following command: python -m doctest -v bubble_sort.py or python3 -m doctest -v bubble_sort.py For manual testing run: python bubble_sort.py """ from __future__ import print_function def bubble_sort(collection): """Pure implementa...
Break if the collection is sorted
Break if the collection is sorted
Python
mit
TheAlgorithms/Python
6182fd214580e517ffe8a59ed89037adf7fd2094
traits/tests/test_dynamic_trait_definition.py
traits/tests/test_dynamic_trait_definition.py
from traits.testing.unittest_tools import unittest from traits.api import Float, HasTraits, Int, List class Foo(HasTraits): x = Float x_changes = List y_changes = List def _x_changed(self, new): self.x_changes.append(new) def _y_changed(self, new): self.y_changes.append(new) ...
from traits.testing.unittest_tools import unittest from traits.api import Float, HasTraits, Int, List class Foo(HasTraits): x = Float y_changes = List def _y_changed(self, new): self.y_changes.append(new) class TestDynamicTraitDefinition(unittest.TestCase): """ Test demonstrating special ...
Remove unused trait definitions in test.
Remove unused trait definitions in test.
Python
bsd-3-clause
burnpanck/traits,burnpanck/traits
399ba60eb17744ea4c45891e29140f1a2b44a4c0
netpyne/analysis/hnn.py
netpyne/analysis/hnn.py
""" analysis/rxd.py Functions to plot and analyze RxD-related results Contributors: salvadordura@gmail.com """ from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.inst...
""" analysis/rxd.py Functions to plot and analyze RxD-related results Contributors: salvadordura@gmail.com """ from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.inst...
Change plotDipole to return html instead of saving it as a file
Change plotDipole to return html instead of saving it as a file
Python
mit
Neurosim-lab/netpyne,Neurosim-lab/netpyne
d8c8b5ffc1f79fc106dc9e41cc6f1ae4f40d0535
src/mpi4py/futures/_core.py
src/mpi4py/futures/_core.py
# Author: Lisandro Dalcin # Contact: dalcinl@gmail.com # pylint: disable=unused-import # pylint: disable=redefined-builtin # pylint: disable=missing-module-docstring try: from concurrent.futures import ( FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED, CancelledError, Tim...
# Author: Lisandro Dalcin # Contact: dalcinl@gmail.com # pylint: disable=unused-import # pylint: disable=redefined-builtin # pylint: disable=missing-module-docstring try: from concurrent.futures import ( FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED, CancelledError, Tim...
Fix backward compatibility exception types
mpi4py.futures: Fix backward compatibility exception types
Python
bsd-2-clause
mpi4py/mpi4py,mpi4py/mpi4py,mpi4py/mpi4py
65fcd98e65a5921dabf324e82a5e5925b1279a30
alfred_db/migrations/versions/29a56dc34a2b_add_permissions.py
alfred_db/migrations/versions/29a56dc34a2b_add_permissions.py
"""Add permissions Revision ID: 29a56dc34a2b Revises: 4fdf1059c4ba Create Date: 2012-09-02 14:06:24.088307 """ # revision identifiers, used by Alembic. revision = '29a56dc34a2b' down_revision = '4fdf1059c4ba' from alembic import op import sqlalchemy as sa def upgrade(): op.create_table('permissions', ...
"""Add permissions Revision ID: 29a56dc34a2b Revises: 4fdf1059c4ba Create Date: 2012-09-02 14:06:24.088307 """ # revision identifiers, used by Alembic. revision = '29a56dc34a2b' down_revision = '5245d0b46f8' from alembic import op import sqlalchemy as sa def upgrade(): op.create_table('permissions', s...
Fix permission table creation migration
Fix permission table creation migration
Python
isc
alfredhq/alfred-db
f85001b39f8f8097c20a197f8cbde70d7ec8e88b
tests/test_extension.py
tests/test_extension.py
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...
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...
Test existing config schema members
Test existing config schema members
Python
apache-2.0
jodal/mopidy-spotify,kingosticks/mopidy-spotify,mopidy/mopidy-spotify
71ef5d2994dbbf4aa993ba1110eb5404de1f6ac3
test_graph.py
test_graph.py
from __future__ import unicode_literals import pytest from graph import Graph @pytest.fixture() def graph_empty(): g = Graph() return g @pytest.fixture() def graph_filled(): g = Graph() g.graph = { 5: set([10]), 10: set([5, 20, 15]), 15: set(), 20: set([5]), ...
from __future__ import unicode_literals import pytest from graph import Graph @pytest.fixture() def graph_empty(): g = Graph() return g @pytest.fixture() def graph_filled(): g = Graph() g.graph = { 5: set([10]), 10: set([5, 20, 15]), 15: set(), 20: set([5]), ...
Add further tests for add_node
Add further tests for add_node
Python
mit
jonathanstallings/data-structures,jay-tyler/data-structures
e948fa0c24ebfe83d2df81f729b5bcc9b4b971b4
mygpo/data/models.py
mygpo/data/models.py
from datetime import datetime from django.db import models from mygpo.podcasts.models import Podcast class PodcastUpdateResult(models.Model): """ Results of a podcast update Once an instance is stored, the update is assumed to be finished. """ # The podcast that was updated podcast = models.Foreig...
from datetime import datetime from django.db import models from mygpo.core.models import UUIDModel from mygpo.podcasts.models import Podcast class PodcastUpdateResult(UUIDModel): """ Results of a podcast update Once an instance is stored, the update is assumed to be finished. """ # The podcast that wa...
Use UUID as primary key of PodcastUpdateResult
Use UUID as primary key of PodcastUpdateResult
Python
agpl-3.0
gpodder/mygpo,gpodder/mygpo,gpodder/mygpo,gpodder/mygpo
5b9bc280a4a5806dbf87ec555fcfdf87ad8bdfd9
raven/contrib/django/utils.py
raven/contrib/django/utils.py
def linebreak_iter(template_source): yield 0 p = template_source.find('\n') while p >= 0: yield p + 1 p = template_source.find('\n', p + 1) yield len(template_source) + 1 def get_data_from_template(source): origin, (start, end) = source template_source = origin.reload() li...
def linebreak_iter(template_source): yield 0 p = template_source.find('\n') while p >= 0: yield p + 1 p = template_source.find('\n', p + 1) yield len(template_source) + 1 def get_data_from_template(source): origin, (start, end) = source template_source = origin.reload() li...
Implement relative path (use loadname) for Templates
Implement relative path (use loadname) for Templates
Python
bsd-3-clause
lepture/raven-python,someonehan/raven-python,dbravender/raven-python,jmp0xf/raven-python,ticosax/opbeat_python,icereval/raven-python,patrys/opbeat_python,tarkatronic/opbeat_python,lepture/raven-python,danriti/raven-python,Photonomie/raven-python,beniwohli/apm-agent-python,dirtycoder/opbeat_python,percipient/raven-pytho...
ca37ff8b08d5b0dd6db1bd48912807aa40872aba
erpnext/patches/v4_0/customer_discount_to_pricing_rule.py
erpnext/patches/v4_0/customer_discount_to_pricing_rule.py
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils.nestedset import get_root_of def execute(): frappe.reload_doc("accounts", "doctype", "pricing_rule") frappe.db.au...
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils.nestedset import get_root_of def execute(): frappe.reload_doc("accounts", "doctype", "pricing_rule") frappe.db.au...
Fix in pricing rule patch
Fix in pricing rule patch
Python
agpl-3.0
indictranstech/buyback-erp,Tejal011089/fbd_erpnext,Tejal011089/fbd_erpnext,indictranstech/phrerp,rohitwaghchaure/digitales_erpnext,indictranstech/biggift-erpnext,mbauskar/helpdesk-erpnext,njmube/erpnext,gangadharkadam/johnerp,gangadhar-kadam/verve_live_erp,fuhongliang/erpnext,rohitwaghchaure/GenieManager-erpnext,gangad...
c64060482a34036615805b13416c78bb78a3058a
swh/web/common/urlsindex.py
swh/web/common/urlsindex.py
# Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information from django.conf.urls import url class UrlsIndex(object): """ ...
# Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information from django.conf.urls import url class UrlsIndex(object): """ ...
Allow to register unnamed django views
common: Allow to register unnamed django views
Python
agpl-3.0
SoftwareHeritage/swh-web-ui,SoftwareHeritage/swh-web-ui,SoftwareHeritage/swh-web-ui
28c8dfd6e3da8525d8379a46244a510db9c34aa5
pytablewriter/writer/text/_spacealigned.py
pytablewriter/writer/text/_spacealigned.py
import copy import dataproperty from ._csv import CsvTableWriter class SpaceAlignedTableWriter(CsvTableWriter): """ A table writer class for space aligned format. :Example: :ref:`example-space-aligned-table-writer` .. py:method:: write_table |write_table| with space aligne...
import copy import dataproperty from ._csv import CsvTableWriter class SpaceAlignedTableWriter(CsvTableWriter): """ A table writer class for space aligned format. :Example: :ref:`example-space-aligned-table-writer` .. py:method:: write_table |write_table| with space aligne...
Fix constructor for SpaceAlignedTableWriter class
Fix constructor for SpaceAlignedTableWriter class
Python
mit
thombashi/pytablewriter
9d70dc1f82fb807c02f4ccfa04bef7f6da36cbc6
cluster/context_processors.py
cluster/context_processors.py
from models import Job def running_jobs(request): if request.user.is_authenticated(): temp = len(Job.get_running_jobs(user=request.user)) return {"running_jobs": temp} else: return {"running_jobs": None}
from models import Job from interface import get_all_jobs def running_jobs(request): if request.user.is_authenticated(): # hack to get numbers to update get_all_jobs(request.user) temp = len(Job.get_running_jobs(user=request.user)) return {"running_jobs": temp} else: re...
Add a hack so that the number of jobs running will update correctly
Add a hack so that the number of jobs running will update correctly
Python
mit
crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp
9ce80d4b4a27e5a32504c6b00ffcff846c53a649
froide/publicbody/widgets.py
froide/publicbody/widgets.py
import json from django import forms from .models import PublicBody class PublicBodySelect(forms.Widget): input_type = "text" template_name = 'publicbody/_chooser.html' initial_search = None class Media: extend = False js = ('js/publicbody.js',) def set_initial_search(self, sea...
import json from django import forms from .models import PublicBody class PublicBodySelect(forms.Widget): input_type = "text" template_name = 'publicbody/_chooser.html' initial_search = None class Media: extend = False js = ('js/publicbody.js',) def set_initial_search(self, sea...
Fix super call for Python 2.7
Fix super call for Python 2.7
Python
mit
fin/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide
fa01bae61830e501e62997f456f9533b654eb425
utils.py
utils.py
import numpy as np def overwrite_labels(y): classes = np.unique(y) y[y==classes[0]] = -1 y[y==classes[1]] = 1 return y
import numpy as np from sklearn import cross_validation def overwrite_labels(y): classes = np.unique(y) y[y==classes[0]] = -1 y[y==classes[1]] = 1 return y def train_test_split(X, y, test_size=0.2): data = cross_validation.train_test_split(X, y, test_size=test_size) training = data[0], data[...
Add data splitter for cross validation
Add data splitter for cross validation
Python
mit
IshitaTakeshi/SCW
86d4aa3e5895d5f7ac029df82c63e2b1e29e8c2d
spc/types.py
spc/types.py
""" All the different types that the compiler handles. """ from collections import namedtuple IntegerType = namedtuple('IntegerType', []) Integer = IntegerType() ByteType = namedtuple('ByteType', []) Byte = ByteType() PointerTo = namedtuple('PointerTo', ['type']) ArrayOf = namedtuple('ArrayOf', ['type', 'count']) Fu...
""" All the different types that the compiler handles. """ from collections import namedtuple IntegerType = namedtuple('IntegerType', []) Integer = IntegerType() ByteType = namedtuple('ByteType', []) Byte = ByteType() PointerTo = namedtuple('PointerTo', ['type']) ArrayOf = namedtuple('ArrayOf', ['type', 'count']) Fu...
Add note that Struct's field collection is an OrderedDict
Add note that Struct's field collection is an OrderedDict
Python
mit
adamnew123456/spc,adamnew123456/spc
4dceb440069d63133bffe928b5c8aa756574a41c
lowfat/validator.py
lowfat/validator.py
""" Validator functions """ from urllib import request from urllib.error import HTTPError from django.core.exceptions import ValidationError import PyPDF2 def online_document(url): """Check if online document is available.""" try: online_resource = request.urlopen(url) except HTTPError as excepti...
""" Validator functions """ from urllib import request from urllib.error import HTTPError from django.core.exceptions import ValidationError import PyPDF2 def online_document(url): """Check if online document is available.""" try: online_resource = request.urlopen(url) except HTTPError as excepti...
Fix problem with sites that blocks bots
Fix problem with sites that blocks bots
Python
bsd-3-clause
softwaresaved/fat,softwaresaved/fat,softwaresaved/fat,softwaresaved/fat
02a975356d6a6b36cc565e8f4b771497867f09dd
tests/test_factorization.py
tests/test_factorization.py
import random import unittest from algorithms.factorization.pollard_rho import pollard_rho from algorithms.factorization.trial_division import trial_division from algorithms.factorization.fermat import fermat class TestFermat(unittest.TestCase): def test_fermat(self): x = random.randint(1, 100000000) ...
import random import unittest from algorithms.factorization.pollard_rho import pollard_rho from algorithms.factorization.trial_division import trial_division from algorithms.factorization.fermat import fermat class TestFermat(unittest.TestCase): def test_fermat(self): x = random.randint(1, 100000000) ...
Add test case for Pollard's Rho at zero to bump test coverage
Add test case for Pollard's Rho at zero to bump test coverage
Python
bsd-3-clause
stphivos/algorithms
d5d33f9fb77fd0d9bb4410971e0acd54b8cbf084
latest_tweets/management/commands/latest_tweets_update.py
latest_tweets/management/commands/latest_tweets_update.py
from django.conf import settings from django.core.management.base import BaseCommand from django.db import transaction from twitter import OAuth, Twitter from ..models import Tweet from ..utils import update_tweets @transaction.atomic def update_user(user): t = Twitter(auth=OAuth( settings.TWITTER_OAUTH_...
from django.conf import settings from django.core.management.base import BaseCommand from django.db import transaction from twitter import OAuth, Twitter from latest_tweets.models import Tweet from latest_tweets.utils import update_tweets @transaction.atomic def update_user(user): t = Twitter(auth=OAuth( ...
Fix imports for management command
Fix imports for management command
Python
bsd-3-clause
blancltd/django-latest-tweets
6c6f6ec6c5a895f083ff8c9b9a0d76791bb13ce9
app/eve_api/tasks/static.py
app/eve_api/tasks/static.py
from celery.decorators import task from eve_proxy.models import CachedDocument from eve_api.utils import basic_xml_parse_doc from eve_api.models import EVESkill, EVESkillGroup @task() def import_eve_skills(): """ Imports the skill tree and groups """ char_doc = CachedDocument.objects.api_query('/eve/S...
from celery.decorators import task from eve_proxy.models import CachedDocument from eve_api.utils import basic_xml_parse_doc from eve_api.models import EVESkill, EVESkillGroup @task() def import_eve_skills(): """ Imports the skill tree and groups """ char_doc = CachedDocument.objects.api_query('/eve/S...
Support if skill group/types are changed
Support if skill group/types are changed
Python
bsd-3-clause
nikdoof/test-auth
f94110a91db9f0e52209e470b6ed8c4b4b3fe30c
common/helpers.py
common/helpers.py
from django.core.mail import EmailMessage from django.template import loader, Context from django.conf import settings def send_email(to_list, subject, message_template, message_context): message_context.update({ 'BASE_URL': settings.BASE_URL }) context = Context(message_context) message = loa...
from django.core.mail import EmailMessage from django.template import loader, Context from django.conf import settings def send_email(to_list, subject, message_template, message_context): message_context.update({ 'BASE_URL': settings.BASE_URL }) # Turn a single email into a list of one element ...
Allow a single email as the to email field
Allow a single email as the to email field
Python
mit
Socialsquare/RunningCause,Socialsquare/RunningCause,Socialsquare/RunningCause,Socialsquare/RunningCause
94cae9c13ac90a7de50cfaf998b9b423e7a2eaf1
csunplugged/resources/utils/resource_valid_configurations.py
csunplugged/resources/utils/resource_valid_configurations.py
"""Create list of all possible valid resource combinations.""" import itertools from utils.bool_to_yes_no import bool_to_yes_no def resource_valid_configurations(valid_options, header_text=True): """Return list of all possible valid resource combinations. Args: valid_options: A dictionary containing...
"""Create list of all possible valid resource combinations.""" import itertools from utils.bool_to_yes_no import bool_to_yes_no def resource_valid_configurations(valid_options, header_text=True): """Return list of all possible valid resource combinations. Args: valid_options: A dictionary containing...
Fix bug where boolean combination values were not changed to strings
Fix bug where boolean combination values were not changed to strings
Python
mit
uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged
61cf3a2f99c01d5da0d75a5ff6b0b2c4cac83487
plugins/random/plugin.py
plugins/random/plugin.py
import random from cardinal.decorators import command class RandomPlugin: @command('roll') def roll(self, cardinal, user, channel, msg): args = msg.split(' ') args.pop(0) dice = [] for arg in args: try: sides = int(arg) dice.append(...
import random import re from cardinal.decorators import command def parse_roll(arg): # some people might separate with commas arg = arg.rstrip(',') if match := re.match(r'^(\d+)?d(\d+)$', arg): num_dice = match.group(1) sides = match.group(2) elif match := re.match(r'^d?(\d+)$', arg)...
Add support for 5d20 instead of d20
Add support for 5d20 instead of d20
Python
mit
JohnMaguire/Cardinal
86ff9a791290455cd169cca7697587a2ad9f350b
services/flickr.py
services/flickr.py
import foauth.providers class Flickr(foauth.providers.OAuth1): # General info about the provider provider_url = 'http://www.flickr.com/' docs_url = 'http://www.flickr.com/services/api/' category = 'Pictures' # URLs to interact with the API request_token_url = 'http://www.flickr.com/services/o...
import foauth.providers class Flickr(foauth.providers.OAuth1): # General info about the provider provider_url = 'http://www.flickr.com/' docs_url = 'http://www.flickr.com/services/api/' category = 'Pictures' # URLs to interact with the API request_token_url = 'http://www.flickr.com/services/o...
Rewrite Flickr to use the new scope selection system
Rewrite Flickr to use the new scope selection system
Python
bsd-3-clause
foauth/foauth.org,foauth/foauth.org,foauth/oauth-proxy,foauth/foauth.org
452b67fa4fe5d9f34a98971e377bbaa1b978907b
superblock.py
superblock.py
#!/usr/bin/env python2 """ Analyze superblock in ext2 filesystem. Usage: superblock.py <filename> """ import sys import string from binascii import hexlify BLOCKSIZE = 512 def block_printer(filename, offset, block_count): def nonprintable_replace(char): if char not in string.printable: ...
#!/usr/bin/env python2 """ Analyze superblock in ext2 filesystem. Usage: superblock.py <filename> """ import sys import string from binascii import hexlify BLOCKSIZE = 512 def nonprintable_replace(char): if char not in string.printable: return '.' if char in '\n\r\t\x0b\x0c': return '.'...
Print 16 bit per line
Print 16 bit per line
Python
mit
dbrgn/superblock