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
6c12f97bfed8b8a4749f75e1a508caf0ea310423
docker/update-production.py
docker/update-production.py
#!/usr/bin/env python3 import argparse import subprocess import json import sys parser = argparse.ArgumentParser() args = parser.parse_args() def info(msg): sys.stdout.write('* {}\n'.format(msg)) sys.stdout.flush() info('Determining current production details...') output = subprocess.check_output(['tutum',...
#!/usr/bin/env python3 import argparse import subprocess import json import sys parser = argparse.ArgumentParser() args = parser.parse_args() def info(msg): sys.stdout.write('* {}\n'.format(msg)) sys.stdout.flush() info('Determining current production details...') output = subprocess.check_output(['tutum',...
Make sure to update correct load balancer
Make sure to update correct load balancer
Python
mit
muzhack/musitechhub,muzhack/musitechhub,muzhack/muzhack,muzhack/muzhack,muzhack/musitechhub,muzhack/muzhack,muzhack/musitechhub,muzhack/muzhack
98581828a9e82ff7ebae6abdb4f2c497f22441d1
trex/urls.py
trex/urls.py
# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from django.conf.urls import patterns, include, url from django.contrib import admin from trex.views import project urlpatterns = patterns( '', url(r"^admin/", include(a...
# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from django.conf.urls import patterns, include, url from django.contrib import admin from trex.views import project urlpatterns = patterns( '', url(r"^admin/", include(a...
Use api/1/ as url prefix for all REST interfaces
Use api/1/ as url prefix for all REST interfaces This allows separating the "normal" web code from the rest api.
Python
mit
bjoernricks/trex,bjoernricks/trex
2dba75be67e07a98fb2b7093e0d0d2771fd7146f
satchmo/apps/payment/modules/giftcertificate/processor.py
satchmo/apps/payment/modules/giftcertificate/processor.py
""" GiftCertificate processor """ from django.utils.translation import ugettext as _ from l10n.utils import moneyfmt from models import GiftCertificate from payment.modules.base import BasePaymentProcessor, ProcessorResult, NOTSET class PaymentProcessor(BasePaymentProcessor): def __init__(self, settings): ...
""" GiftCertificate processor """ from django.utils.translation import ugettext as _ from l10n.utils import moneyfmt from models import GiftCertificate from payment.modules.base import BasePaymentProcessor, ProcessorResult, NOTSET class PaymentProcessor(BasePaymentProcessor): def __init__(self, settings): ...
Fix the gift certificate module so that an invalid code won't throw an exception.
Fix the gift certificate module so that an invalid code won't throw an exception.
Python
bsd-3-clause
grengojbo/satchmo,grengojbo/satchmo
46cec51fa3b81da21662da5d36ccaf1f409caaea
gem/personalise/templatetags/personalise_extras.py
gem/personalise/templatetags/personalise_extras.py
from django import template from wagtail_personalisation.adapters import get_segment_adapter register = template.Library() @register.simple_tag def filter_surveys_by_segments(surveys, request): """Filter out surveys not in user's segments.""" user_segments = get_segment_adapter(request).get_segments() us...
from django import template from wagtail_personalisation.adapters import get_segment_adapter register = template.Library() @register.simple_tag def filter_surveys_by_segments(surveys, request): """Filter out surveys not in user's segments.""" user_segments = get_segment_adapter(request).get_segments() us...
Fix error when displaying other types of surveys
Fix error when displaying other types of surveys
Python
bsd-2-clause
praekelt/molo-gem,praekelt/molo-gem,praekelt/molo-gem
780dc99953060113f793c1a0da7058efe8f194fc
kokki/cookbooks/aws/recipes/default.py
kokki/cookbooks/aws/recipes/default.py
import os from kokki import * env.include_recipe("boto") # Mount volumes and format is necessary for vol in env.config.aws.volumes: env.cookbooks.aws.EBSVolume(vol.get('name') or vol['volume_id'], volume_id = vol.get('volume_id'), availability_zone = env.config.aws.availability_zone, dev...
import os from kokki import * env.include_recipe("boto") # Mount volumes and format is necessary for vol in env.config.aws.volumes: env.cookbooks.aws.EBSVolume(vol.get('name') or vol['volume_id'], volume_id = vol.get('volume_id'), availability_zone = env.config.aws.availability_zone, dev...
Revert that last change.. and do a proper fix
Revert that last change.. and do a proper fix
Python
bsd-3-clause
samuel/kokki
ee629fca605b27ee6f34c8fa7584f670ae60b121
whylog/constraints/constraint_manager.py
whylog/constraints/constraint_manager.py
from whylog.constraints import DifferentConstraint, IdenticalConstraint, TimeConstraint from whylog.constraints.exceptions import UnsupportedConstraintTypeError class ConstraintRegistry(object): CONSTRAINTS = { 'identical': IdenticalConstraint, 'time': TimeConstraint, 'different': Differen...
from whylog.constraints import DifferentConstraint, IdenticalConstraint, TimeConstraint from whylog.constraints.exceptions import UnsupportedConstraintTypeError class ConstraintRegistry(object): CONSTRAINTS = { 'identical': IdenticalConstraint, 'time': TimeConstraint, 'different': Differen...
Add constraint from name method
Add constraint from name method
Python
bsd-3-clause
epawlowska/whylog,kgromadzki/whylog,kgromadzki/whylog,konefalg/whylog,9livesdata/whylog,konefalg/whylog,andrzejgorski/whylog,epawlowska/whylog,9livesdata/whylog,andrzejgorski/whylog
6fa6090189e405e57db19b3a77f2adb46aef1242
create_english_superset.py
create_english_superset.py
import optparse import os optparser = optparse.OptionParser() optparser.add_option("-d", "--directory", dest="directory", default="dictionaries/", help="Directory with dictionaries") (opts, _) = optparser.parse_args() full_path = os.path.abspath(opts.directory) all_english_words = set() for filename in os.listdir(fu...
import optparse import os optparser = optparse.OptionParser() optparser.add_option("-d", "--directory", dest="directory", default="dictionaries/", help="Directory with dictionaries") (opts, _) = optparser.parse_args() full_path = os.path.abspath(opts.directory) all_english_words = set() for filename in os.listdir(fu...
Refactor create english superset code to create english superset dictionaries in batches of 10K. Also re-include untranslated words.
Refactor create english superset code to create english superset dictionaries in batches of 10K. Also re-include untranslated words.
Python
mit
brendandc/multilingual-google-image-scraper
421dbe962dae44cad7aa734a397cb16fe9b1632f
reactive/datanode.py
reactive/datanode.py
from charms.reactive import when, when_not, set_state, remove_state from charms.hadoop import get_hadoop_base from jujubigdata.handlers import HDFS from jujubigdata import utils @when('namenode.ready') @when_not('datanode.started') def start_datanode(namenode): hadoop = get_hadoop_base() hdfs = HDFS(hadoop) ...
from charms.reactive import when, when_not, set_state, remove_state from charms.layer.hadoop_base import get_hadoop_base from jujubigdata.handlers import HDFS from jujubigdata import utils @when('namenode.ready') @when_not('datanode.started') def start_datanode(namenode): hadoop = get_hadoop_base() hdfs = HDF...
Update charms.hadoop reference to follow convention
Update charms.hadoop reference to follow convention
Python
apache-2.0
johnsca/layer-apache-hadoop-datanode,juju-solutions/layer-apache-hadoop-datanode
b7b691d82accc012ee4308849a82ba8514e4a156
migrations/versions/20140430220209_4093ccb6d914.py
migrations/versions/20140430220209_4093ccb6d914.py
"""empty message Revision ID: 4093ccb6d914 Revises: None Create Date: 2014-04-30 22:02:09.991428 """ # revision identifiers, used by Alembic. revision = '4093ccb6d914' down_revision = None from alembic import op import sqlalchemy as sa from datetime import datetime def upgrade(): op.create_table('gallery', ...
"""empty message Revision ID: 4093ccb6d914 Revises: None Create Date: 2014-04-30 22:02:09.991428 """ # revision identifiers, used by Alembic. revision = '4093ccb6d914' down_revision = None from alembic import op import sqlalchemy as sa from datetime import datetime def upgrade(): op.create_table('gallery', ...
Allow MySQL to set a default role
Allow MySQL to set a default role
Python
mit
taeram/ineffable,taeram/ineffable,taeram/ineffable
06659d9d92b7f2b51db5905555293d23905cf7a4
sinon/lib/SinonSandbox.py
sinon/lib/SinonSandbox.py
properties = ["SinonSpy", "SinonStub", "SinonMock"] production_properties = ["spy", "stub", "mock"] def _clear_item_in_queue(queue): for item in reversed(queue): item.restore() def sinontest(f): def fn(*args, **kwargs): ret = f(*args, **kwargs) # handle production mode (called by sino...
properties = ["SinonSpy", "SinonStub", "SinonMock", "SinonAssertion"] production_properties = ["spy", "stub", "mock", "assert"] def _clear_assertion_message(obj): setattr(obj, "message", "") def _clear_item_in_queue(queue): for item in reversed(queue): item.restore() def sinontest(f): def fn(*ar...
Reset message into empty string of sinonAssertion
Reset message into empty string of sinonAssertion
Python
bsd-2-clause
note35/sinon,note35/sinon
35255e3c6bda4f862ed3d891b356e383eef02bda
dsppkeras/datasets/dspp.py
dsppkeras/datasets/dspp.py
from ..utils.data_utils import get_file import numpy as np import cPickle as pickle import tarfile def load_data(path='peptone_dspp.tar.gz'): """Loads the MNIST dataset. # Arguments path: path where to cache the dataset locally (relative to ~/.keras/datasets). # Returns Tuple ...
from ..utils.data_utils import get_file import json import tarfile def load_data(path='peptone_dspp.tar.gz'): """Loads the MNIST dataset. # Arguments path: path where to cache the dataset locally (relative to ~/.keras/datasets). # Returns Tuple of Numpy arrays: `(x_train, y_tr...
Switch to JSON containing database.tar.gz
Switch to JSON containing database.tar.gz
Python
agpl-3.0
PeptoneInc/dspp-keras
47f7d42c118a00c94d99981b5b1deb34d67ff04a
mangacork/scripts/check_len_chapter.py
mangacork/scripts/check_len_chapter.py
import os def make_chapter_files(): os.chdir('../static/images') for _, dirs, files in os.walk(os.getcwd()): dirs = [d for d in dirs if not d[0] == '.'] files = [f for f in files if not f[0] == '.'] for directory in dirs: file_path = get_filepath(directory) m...
import os def make_chapter_files(): os.chdir('../static/images') for _, dirs, files in os.walk(os.getcwd()): dirs = [d for d in dirs if not d[0] == '.'] files = [f for f in files if not f[0] == '.'] for directory in dirs: file_path = get_filepath(directory) m...
Write name of last page in txt file
Write name of last page in txt file
Python
mit
ma3lstrom/manga-cork,ma3lstrom/manga-cork,ma3lstrom/manga-cork
5a43c61c0688e2837492e7f034a0dd2c157c6e4d
hypatia/__init__.py
hypatia/__init__.py
"""This module contains all of the important meta-information for Hypatia such as the author's name, the copyright and license, status, and so on. """ __author__ = "Lillian Lemmer" __copyright__ = "Copyright 2015 Lillian Lemmer" __credits__ = ["Lillian Lemmer"] __license__ = "MIT" __maintainer__ = __author...
"""This module contains all of the important meta-information for Hypatia such as the author's name, the copyright and license, status, and so on. """ __author__ = "Lillian Lemmer" __copyright__ = "Copyright 2015 Lillian Lemmer" __credits__ = ["Lillian Lemmer"] __license__ = "MIT" __maintainer__ = __author...
Add a class for representing the current version
[Feature] Add a class for representing the current version This patch implements the `Version` class inside of the `__init__.py` file alongside the rest of Hypatia's meta-data. The class has public integer properties representing the major, minor, and patch portions of the version number. This makes it possible for ...
Python
mit
lillian-lemmer/hypatia,hypatia-software-org/hypatia-engine,brechin/hypatia,lillian-lemmer/hypatia,hypatia-software-org/hypatia-engine,Applemann/hypatia,Applemann/hypatia,brechin/hypatia
28198f5f200fa655b1b509d0c744391eaa714577
python/executeprocess.py
python/executeprocess.py
import subprocess import sys def ExecuteProcess(args, verbose=False, isCSharp=False): if isCSharp and sys.platform.startswith("darwin"): newArgs = ["mono"] newArgs.extend(args) args = newArgs if verbose: print "Executing: '%s'" % " ".join(args) process = subprocess.Popen...
import subprocess import sys def ExecuteProcess(args, verbose=False, isCSharp=False): if sys.platform.startswith("win"): for index,item in enumerate(args): if '\\' in item: args[index] = item.replace('\\', '/') if isCSharp and sys.platform.startswith("darwin"): ...
Convert back slashes to forward slashes before executing Python processes
[trunk] Convert back slashes to forward slashes before executing Python processes
Python
bsd-3-clause
markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation
225ae01e3147bbee5c03462dad7dcfef22297f51
elevator/utils/patterns.py
elevator/utils/patterns.py
from collections import Sequence # Enums beautiful python implementation # Used like this : # Numbers = enum('ZERO', 'ONE', 'TWO') # >>> Numbers.ZERO # 0 # >>> Numbers.ONE # 1 # Found here: http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python def enum(*sequential, **named): en...
from collections import Sequence # Enums beautiful python implementation # Used like this : # Numbers = enum('ZERO', 'ONE', 'TWO') # >>> Numbers.ZERO # 0 # >>> Numbers.ONE # 1 # Found here: http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python def enum(*sequential, **named): en...
Update : try/except in destructurate greatly enhances performances on mass read/write
Update : try/except in destructurate greatly enhances performances on mass read/write
Python
mit
oleiade/Elevator
a3f981006fae846714bdb5aa0de98ac829a57bc0
registration/__init__.py
registration/__init__.py
VERSION = (0, 9, 0, 'beta', 1) def get_version(): from django.utils.version import get_version as django_get_version return django_get_version(VERSION) # pragma: no cover
VERSION = (0, 9, 0, 'beta', 1) def get_version(): try: from django.utils.version import get_version as django_get_version return django_get_version(VERSION) # pragma: no cover except ImportError: return ".".join(str(n) for n in VERSION)
Fix dependency order issue in get_version
Fix dependency order issue in get_version
Python
bsd-3-clause
ildarsamit/django-registration,ildarsamit/django-registration
7d9a85c57deb6a6d89dcf9764ffe8baf3cb2981b
wcontrol/db/db_create.py
wcontrol/db/db_create.py
#!env/bin/python from migrate.versioning import api from config import SQLALCHEMY_DATABASE_URI from config import SQLALCHEMY_MIGRATE_REPO from app import db import os.path db.create_all() if not os.path.exists(SQLALCHEMY_MIGRATE_REPO): api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository') api.version_contr...
#!env/bin/python from migrate.versioning import api from config import SQLALCHEMY_DATABASE_URI from config import SQLALCHEMY_MIGRATE_REPO from app import db import os.path db.create_all() if not os.path.exists(SQLALCHEMY_MIGRATE_REPO): api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository') api.version_co...
Modify config to fit with PEP8 standard
Modify config to fit with PEP8 standard
Python
mit
pahumadad/weight-control,pahumadad/weight-control,pahumadad/weight-control,pahumadad/weight-control
272d0bbc590fefa393317f27d2fa0c5912d654a9
django_cbtp_email/example_project/tests/test_basic.py
django_cbtp_email/example_project/tests/test_basic.py
# -*- encoding: utf-8 -*- # ! python2 from __future__ import (absolute_import, division, print_function, unicode_literals) import os import tempfile from django.test import TestCase from ..tests.mailers import TestMailer class BasicUsageTestCase(TestCase): def test_message_will_be_sent_with_inlined_css(self):...
# -*- encoding: utf-8 -*- # ! python2 from __future__ import (absolute_import, division, print_function, unicode_literals) import os import tempfile from django.test import TestCase from ..tests.mailers import TestMailer class BasicUsageTestCase(TestCase): def test_message_will_be_sent_with_inlined_css(self):...
Use assertIn in tests for better error message.
Use assertIn in tests for better error message.
Python
mit
illagrenan/django-cbtp-email,illagrenan/django-cbtp-email
4601937752f707110d303e403153cc4412bcde58
oshino/util.py
oshino/util.py
from time import time def dynamic_import(path): module, builder = path.rsplit(".", 1) return getattr(__import__(module, fromlist=[builder]), builder) def current_ts(): """ Just gives current timestamp. """ return int(time() * 1000)
from datetime import datetime def dynamic_import(path): module, builder = path.rsplit(".", 1) return getattr(__import__(module, fromlist=[builder]), builder) def current_ts(): """ Just gives current timestamp. """ utcnow = datetime.utcnow() return int(utcnow.timestamp() * 1000)
Use UTC timestamp as timestamp
Use UTC timestamp as timestamp
Python
mit
CodersOfTheNight/oshino
6480a810b66a437ac716eb164c20f5bcc97d0934
src/handlers/admin.py
src/handlers/admin.py
from flask.ext.admin import Admin from flask.ext.admin.contrib.sqla import ModelView import db.schema as schema import db.query as query from handlers.rest import app admin = Admin(app, url="/admin") class RoundModelView(ModelView): def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs): ...
from flask.ext.admin import Admin from flask.ext.admin.contrib.sqla import ModelView import db.schema as schema import db.query as query from handlers.rest import app admin = Admin(app, url="/admin") class RoundModelView(ModelView): column_list = ('id', 'perspective', 'start_time') def __init__(self, name=None, ...
Fix list columns for all models
Fix list columns for all models
Python
apache-2.0
pascalc/narrative-roulette,pascalc/narrative-roulette
c97c07b1f4ccc5798a935bf1bbcfe84986cb9f65
tikplay/tests/test_server.py
tikplay/tests/test_server.py
import unittest import mock from tikplay import server class ServerTestcase(unittest.TestCase): def setUp(self): self.handler_class = mock.MagicMock() self.server_class = mock.MagicMock() self.server_class.serve_forever = mock.MagicMock() self.__server = server.Server(host='127.0.0...
import unittest import mock from tikplay import server class DummyServer(): def __init__(self, *args, **kwargs): self._shutdown = False self._alive = False def serve_forever(self): self._alive = True while not self._shutdown: if self._shutdown: brea...
Add a dummy server - Tests are broken
Add a dummy server - Tests are broken
Python
mit
tietokilta-saato/tikplay,tietokilta-saato/tikplay,tietokilta-saato/tikplay,tietokilta-saato/tikplay
cd2ff46284a8144755b880c035d0a89938474955
salt/grains/extra.py
salt/grains/extra.py
# -*- coding: utf-8 -*- from __future__ import absolute_import # Import python libs import os # Import third party libs import yaml import logging # Import salt libs import salt.utils.files log = logging.getLogger(__name__) def shell(): ''' Return the default shell to use on this system ''' # Pro...
# -*- coding: utf-8 -*- from __future__ import absolute_import # Import python libs import os # Import third party libs import yaml import logging # Import salt libs import salt.utils.files import salt.utils.platform log = logging.getLogger(__name__) def shell(): ''' Return the default shell to use on th...
Return COMSPEC as the shell for Windows
Return COMSPEC as the shell for Windows
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
255b3f645d42464d4f8c80e97200d4dacc513616
keras/preprocessing/__init__.py
keras/preprocessing/__init__.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
Add a toplevel warning against legacy keras.preprocessing utilities
Add a toplevel warning against legacy keras.preprocessing utilities PiperOrigin-RevId: 434866390
Python
apache-2.0
keras-team/keras,keras-team/keras
1e182ec0fd7cf550c809f2e6792629caeb8d5553
sauce/lib/helpers.py
sauce/lib/helpers.py
# -*- coding: utf-8 -*- """WebHelpers used in SAUCE. @author: moschlar """ from datetime import datetime from tg import url as tgurl #from webhelpers import date, feedgenerator, html, number, misc, text import webhelpers as w from webhelpers.html.tags import link_to from webhelpers.text import truncate from webhel...
# -*- coding: utf-8 -*- """WebHelpers used in SAUCE. @author: moschlar """ from datetime import datetime from tg import url as tgurl #from webhelpers import date, feedgenerator, html, number, misc, text import webhelpers as w from webhelpers.html.tags import link_to from webhelpers.text import truncate from webhel...
Use striptags from genshi for striphtml, since we have to have genshi anyway
Use striptags from genshi for striphtml, since we have to have genshi anyway
Python
agpl-3.0
moschlar/SAUCE,moschlar/SAUCE,moschlar/SAUCE,moschlar/SAUCE
b9c66ca635d48c6d6d04d8b68e7befe910cad347
scattergun/scattergun_coreapp/tests.py
scattergun/scattergun_coreapp/tests.py
from django.test import TestCase from .models import Team class TeamTestCase(TestCase): def setUp(self): Team.objects.create(name="Test Team 1", number=1) def test_team_created_correctly(self): test_team_1 = Team.objects.get(number=1) self.assertEqual(test_team_1.name, "Test Team 1") ...
from django.core.urlresolvers import reverse from django.test import Client, TestCase from .models import Team class TeamTestCase(TestCase): def setUp(self): Team.objects.create(name="Test Team 1", number=1) def test_team_created_correctly(self): test_team_1 = Team.objects.get(number=1) ...
Add unit test for team views
Add unit test for team views
Python
mit
Team4761/Scattergun,Team4761/Scattergun,Team4761/Scattergun
28c11c91ad056735952f904c86c2fb726ef90f81
test/util.py
test/util.py
def assert_outcomes(result, **expected): outcomes = result.parseoutcomes() for key in 'seconds', 'pytest-warnings', 'warnings', 'warning': if key in outcomes: del outcomes[key] assert outcomes == expected
def assert_outcomes(result, **expected): outcomes = result.parseoutcomes() for key in 'seconds', 'warnings': if key in outcomes: del outcomes[key] assert outcomes == expected
Remove checks for deprecated keys in outcomes
Remove checks for deprecated keys in outcomes
Python
mit
ropez/pytest-describe
da42140e1620021fda305bbc37f43d1e49ec65da
src/poliastro/examples.py
src/poliastro/examples.py
# coding: utf-8 """Example data. """ from astropy import time from astropy import units as u from poliastro.bodies import Earth from poliastro.twobody import State # Taken from Plyades (c) 2012 Helge Eichhorn (MIT License) iss = State.from_vectors(Earth, [8.59072560e2, -4.13720368e3, 5.2955...
# coding: utf-8 """Example data. """ from astropy import time from astropy import units as u from poliastro.bodies import Sun, Earth from poliastro.twobody import State # Taken from Plyades (c) 2012 Helge Eichhorn (MIT License) iss = State.from_vectors(Earth, [8.59072560e2, -4.13720368e3, 5...
Add 67P/Churyumov–Gerasimenko to example data
Add 67P/Churyumov–Gerasimenko to example data
Python
mit
Juanlu001/poliastro,poliastro/poliastro,Juanlu001/poliastro,newlawrence/poliastro,newlawrence/poliastro,Juanlu001/poliastro,anhiga/poliastro,anhiga/poliastro,anhiga/poliastro,newlawrence/poliastro
59eaf266921d76cf5ef472fa59dbb9e136c800f3
views/main.py
views/main.py
from flask import redirect from flask import render_template from flask import request import database.link from linkr import app from uri.link import * from uri.main import * @app.route(LinkAliasRedirectURI.path, methods=LinkAliasRedirectURI.methods) def alias_route(alias): # Attempt to fetch the link mapping f...
from flask import redirect from flask import render_template from flask import request import database.link from linkr import app from uri.link import * from uri.main import * from util.decorators import require_form_args @app.route(LinkAliasRedirectURI.path, methods=LinkAliasRedirectURI.methods) @require_form_args(...
Support programmatically passing password in alias route
Support programmatically passing password in alias route
Python
mit
LINKIWI/linkr,LINKIWI/linkr,LINKIWI/linkr
aac0f52fa97f75ca6ec5a2744cd1c0942a57c283
src/pybel/struct/utils.py
src/pybel/struct/utils.py
# -*- coding: utf-8 -*- from collections import defaultdict def hash_dict(d): """Hashes a dictionary :param dict d: A dictionary to recursively hash :return: the hash value of the dictionary :rtype: int """ h = 0 for k, v in sorted(d.items()): h += hash(k) if isinstance(...
# -*- coding: utf-8 -*- from collections import defaultdict from ..utils import hash_edge def stratify_hash_edges(graph): """Splits all qualified and unqualified edges by different indexing strategies :param BELGraph graph: A BEL network :rtype dict[tuple, dict[int, int]], dict[tuple, dict[int, set[int...
Cut out old hash function
Cut out old hash function
Python
mit
pybel/pybel,pybel/pybel,pybel/pybel
9d1059bc4cf28b9650bb6386cb5665bfb9b2c138
canopus/views/__init__.py
canopus/views/__init__.py
import os from datetime import date from pyramid.response import FileResponse from pyramid.view import view_config @view_config(route_name='home', renderer='templates/index.html') def index(request): return {'year': date.today().year} @view_config(route_name='robots') def robots(request): here = os.path.ab...
import os from datetime import date from pyramid.httpexceptions import HTTPBadRequest from pyramid.response import FileResponse from pyramid.view import view_config from sqlalchemy.exc import IntegrityError @view_config(route_name='home', renderer='templates/index.html') def index(request): return {'year': date....
Throw 500 error on SQLAlchemy integrity error
Throw 500 error on SQLAlchemy integrity error
Python
mit
josuemontano/pyramid-angularjs-starter,josuemontano/API-platform,josuemontano/pyramid-angularjs-starter,josuemontano/api-starter,josuemontano/pyramid-angularjs-starter,josuemontano/api-starter,josuemontano/API-platform,josuemontano/API-platform,josuemontano/API-platform,josuemontano/api-starter
9195818ef2e7f75528a68a686889721e7f2ff213
idiokit/dns/_hostlookup.py
idiokit/dns/_hostlookup.py
from .. import idiokit from ._iputils import parse_ip from ._conf import hosts from ._dns import DNSError, a, aaaa def _filter_ips(potential_ips): results = [] for ip in potential_ips: try: family, ip = parse_ip(ip) except ValueError: continue else: ...
from .. import idiokit from ._iputils import parse_ip from ._conf import hosts from ._dns import DNSError, a, aaaa def _filter_ips(potential_ips): results = [] for ip in potential_ips: try: family, ip = parse_ip(ip) except ValueError: continue else: ...
Remove an unnecessary class attribute
Remove an unnecessary class attribute
Python
mit
abusesa/idiokit
ab5996b9218ec51b2991bb1fd702885414fce8b0
lib/ansiblelint/rules/CommandsInsteadOfModulesRule.py
lib/ansiblelint/rules/CommandsInsteadOfModulesRule.py
import ansiblelint.utils import os from ansiblelint import AnsibleLintRule class CommandsInsteadOfModulesRule(AnsibleLintRule): id = 'ANSIBLE0006' shortdesc = 'Using command rather than module' description = 'Executing a command when there is an Ansible module ' + \ 'is generally a bad id...
import ansiblelint.utils import os from ansiblelint import AnsibleLintRule class CommandsInsteadOfModulesRule(AnsibleLintRule): id = 'ANSIBLE0006' shortdesc = 'Using command rather than module' description = 'Executing a command when there is an Ansible module ' + \ 'is generally a bad id...
Check whether unzip or tar are used instead of unarchive
Check whether unzip or tar are used instead of unarchive
Python
mit
MatrixCrawler/ansible-lint,dataxu/ansible-lint,charleswhchan/ansible-lint,MiLk/ansible-lint,willthames/ansible-lint,schlueter/ansible-lint
ecac9283bc831a6879f21e80e1b98818683ff6a4
atlas/prodtask/management/commands/pthealthcheck.py
atlas/prodtask/management/commands/pthealthcheck.py
from django.core.management.base import BaseCommand, CommandError import time from django_celery_beat.models import PeriodicTask from django.utils import timezone from datetime import timedelta from atlas.prodtask.views import send_alarm_message class Command(BaseCommand): args = 'None' help = 'Check celery...
from django.core.management.base import BaseCommand, CommandError import time from django_celery_beat.models import PeriodicTask from django.utils import timezone from datetime import timedelta from atlas.prodtask.views import send_alarm_message class Command(BaseCommand): args = 'None' help = 'Check celery...
Add logging for health check
Add logging for health check
Python
apache-2.0
PanDAWMS/panda-bigmon-atlas,PanDAWMS/panda-bigmon-atlas,PanDAWMS/panda-bigmon-atlas,PanDAWMS/panda-bigmon-atlas
64c02a8bb7863ee9606b7927540fbf71d806a6e1
sitecustomize.py
sitecustomize.py
import os import sys def patch_process_for_coverage(): # patch multiprocessing module to get coverage # https://bitbucket.org/ned/coveragepy/issue/117/enable-coverage-measurement-of-code-run-by from coverage.collector import Collector from coverage import coverage import multiprocessing # dete...
import os import sys def patch_process_for_coverage(): # patch multiprocessing module to get coverage # https://bitbucket.org/ned/coveragepy/issue/117/enable-coverage-measurement-of-code-run-by from coverage.collector import Collector from coverage import coverage import multiprocessing # dete...
Fix scope when setting up multiprocessing with coverage
Fix scope when setting up multiprocessing with coverage
Python
apache-2.0
Wattpad/luigi,jamesmcm/luigi,wakamori/luigi,casey-green/luigi,mbruggmann/luigi,adaitche/luigi,rayrrr/luigi,stroykova/luigi,riga/luigi,fabriziodemaria/luigi,mfcabrera/luigi,mfcabrera/luigi,Houzz/luigi,h3biomed/luigi,linsomniac/luigi,soxofaan/luigi,oldpa/luigi,edx/luigi,jw0201/luigi,foursquare/luigi,humanlongevity/luigi,...
d21547637222d6bb2c3c9d03eae771d033ec47f4
lms/djangoapps/api_manager/management/commands/migrate_orgdata.py
lms/djangoapps/api_manager/management/commands/migrate_orgdata.py
import json from django.contrib.auth.models import Group from django.core.management.base import BaseCommand from api_manager.models import GroupProfile, Organization class Command(BaseCommand): """ Migrates legacy organization data and user relationships from older Group model approach to newer concrete Org...
import json from django.contrib.auth.models import Group from django.core.management.base import BaseCommand from api_manager.models import GroupProfile, Organization class Command(BaseCommand): """ Migrates legacy organization data and user relationships from older Group model approach to newer concrete Org...
Tweak to migration in order to accomodate old names for data fields and allow for if data fields were not present
Tweak to migration in order to accomodate old names for data fields and allow for if data fields were not present
Python
agpl-3.0
edx-solutions/edx-platform,edx-solutions/edx-platform,edx-solutions/edx-platform,edx-solutions/edx-platform
721015d5a7ea9745094f06dfcea3625c20555992
inidiff/tests/test_diff.py
inidiff/tests/test_diff.py
import unittest import inidiff INI_1 = '''[test] number=10 ''' INI_2 = '''[test] number=20 ''' class TestDiff(unittest.TestCase): """Test diffs diff things.""" def test_no_differences(self): self.assertEqual([], inidiff.diff(INI_1, INI_1)) def test_some_differences(self): self.assertT...
import unittest import inidiff INI_1 = '''[test] number=10 ''' INI_2 = '''[test] number=20 ''' class TestDiff(unittest.TestCase): """Test diffs diff things.""" def test_no_differences(self): self.assertEqual([], inidiff.diff(INI_1, INI_1)) def test_some_differences(self): self.assertT...
Check number is the field that is different
Check number is the field that is different
Python
mit
kragniz/inidiff
29594c877766c387fe25d2aac09244402cbf41d7
FreeMemory.py
FreeMemory.py
/* * Copyright 2012-2014 inBloom, Inc. and its affiliates. * * 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 appli...
/* * Copyright 2012-2014 inBloom, Inc. and its affiliates. * * 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 appli...
Fix for bug where we were using SwapCached instead of Cached values in availableMemory Calculation
Fix for bug where we were using SwapCached instead of Cached values in availableMemory Calculation
Python
apache-2.0
inbloom/server-density-plugins
ff2b16c5f8c69ccfeb808aeb832a5c6afcecb8ab
sift/models/build.py
sift/models/build.py
import ujson as json from sift.build import DatasetBuilder from sift.models import links, text, embeddings class BuildDocModel(DatasetBuilder): """ Build a model over a corpus of text documents """ @classmethod def providers(cls): return [ links.EntityCounts, links.EntityNam...
import ujson as json from sift.build import DatasetBuilder from sift.models import links, text, embeddings class BuildDocModel(DatasetBuilder): """ Build a model over a corpus of text documents """ @classmethod def providers(cls): return [ links.EntityCounts, links.EntityNam...
Update cli for recently added models
Update cli for recently added models
Python
mit
wikilinks/sift,wikilinks/sift
610bd0fb6f25f790b1ff6e4adb9d87f10233e39e
statirator/core/models.py
statirator/core/models.py
class TranslationsMixin(object): "Helper for getting transalations" SLUG_FIELD_FOR_TRANSLATIONS = 'slug' # Overide in models if needed LANG_FIELD_FOR_TRANSLATIONS = 'language' # Overide in models if needed def get_translations(self): "Query set for the translations" self_slug = ...
class TranslationsMixin(object): "Helper for getting transalations" SLUG_FIELD_FOR_TRANSLATIONS = 'slug' # Overide in models if needed LANG_FIELD_FOR_TRANSLATIONS = 'language' # Overide in models if needed def get_translations(self): "Query set for the translations" self_slug = ...
Add get_language method for TranslationsMixin
Add get_language method for TranslationsMixin
Python
mit
MeirKriheli/statirator,MeirKriheli/statirator,MeirKriheli/statirator
0a8f5b342c0174b712ac895e71d56132c313729f
stonemason/util/tempfn.py
stonemason/util/tempfn.py
# -*- coding:utf-8 -*- """ stonemason.util.tempfn ~~~~~~~~~~~~~~~~~~~~~~ Generate a temp filename """ __author__ = 'ray' __date__ = '8/30/12' import os import errno import tempfile import six def generate_temp_filename(dirname=None, prefix='tmp', suffix=''): """Generate a temporary file name with ...
# -*- coding:utf-8 -*- """ stonemason.util.tempfn ~~~~~~~~~~~~~~~~~~~~~~ Generate a temp filename """ __author__ = 'ray' __date__ = '8/30/12' import os import errno import tempfile import six STONEMASON_TEMP_ROOT = 'stonemason' def generate_temp_filename(dirname=None, prefix='tmp', suffix=''): "...
Add root dir for temp files
FEATURE: Add root dir for temp files
Python
mit
Kotaimen/stonemason,Kotaimen/stonemason
e67bbc3aa791947d24895ba5b0286e27323a4074
plugins/mtg.py
plugins/mtg.py
import urllib from util import hook, http def card_search(query): base_url = "https://api.deckbrew.com" name = urllib.quote_plus(query) search_url = base_url + "/mtg/cards?name=" + name return http.get_json(search_url) @hook.command def mtg(inp, say=None): '''.mtg <name> - Searches for Magic t...
import urllib from util import hook, http def card_search(query): base_url = "https://api.deckbrew.com" name = urllib.quote_plus(query) search_url = base_url + "/mtg/cards?name=" + name return http.get_json(search_url) @hook.command def mtg(inp, say=None): '''.mtg <name> - Searches for Magic t...
Replace {T} with a unicode tap symbol approximation and replace {S} with a unicode snowflake, how exiting. More symbol replacements to follow
Replace {T} with a unicode tap symbol approximation and replace {S} with a unicode snowflake, how exiting. More symbol replacements to follow
Python
unlicense
rmmh/skybot,TeamPeggle/ppp-helpdesk,parkrrr/skybot,jmgao/skybot,crisisking/skybot,olslash/skybot,ddwo/nhl-bot
888fd2a46783be37f00412f3b7e5d720722a1afc
test_tinymce/models.py
test_tinymce/models.py
from __future__ import absolute_import from django.db import models from tinymce import HTMLField class TestModel(models.Model): """ A model for testing TinyMCE 4 rendering """ content = HTMLField(verbose_name='HTML Content') class TestChildModel(models.Model): """ A model for testing TinyMC...
from __future__ import absolute_import from django.db import models from tinymce import HTMLField class TestModel(models.Model): """ A model for testing TinyMCE 4 rendering """ content = HTMLField(verbose_name='HTML Content') class TestChildModel(models.Model): """ A model for testing TinyMC...
Fix tests with Django 2.0
Fix tests with Django 2.0
Python
mit
romanvm/django-tinymce4-lite,romanvm/django-tinymce4-lite,romanvm/django-tinymce4-lite
8ccaed4590cb89d95b949d71934ee198f1b0574e
ideas/admin.py
ideas/admin.py
from .models import Idea, Outstanding from django.contrib import admin from django.contrib.admin import AdminSite from django.contrib.auth.models import User, Group class MyAdminSite(AdminSite): site_header = "Hackatrix Backend" site_title = "Hackatrix Backend" index_title = "Administrator" class IdeaAd...
from .models import Idea, Outstanding from django.contrib import admin from django.contrib.admin import AdminSite from django.contrib.auth.admin import UserAdmin, GroupAdmin from django.contrib.auth.models import User, Group class MyAdminSite(AdminSite): site_header = "Hackatrix Backend" site_title = "Hackatr...
Add UserAdmin and GroupAdmin to custom AdminSite
Add UserAdmin and GroupAdmin to custom AdminSite
Python
mit
neosergio/vote_hackatrix_backend
118ca7981db7443ef3cd6247e699799548cd883a
pydir/utils.py
pydir/utils.py
import os import subprocess import sys def shellcmd(command, echo=True): if echo: print '[cmd]', command if not isinstance(command, str): command = ' '.join(command) stdout_result = subprocess.check_output(command, shell=True) if echo: sys.stdout.write(stdout_result) return stdout_result ...
import os import subprocess import sys def shellcmd(command, echo=True): if not isinstance(command, str): command = ' '.join(command) if echo: print '[cmd]', command stdout_result = subprocess.check_output(command, shell=True) if echo: sys.stdout.write(stdout_result) return stdout_result ...
Change the echoing in shellcmd().
Subzero: Change the echoing in shellcmd(). This makes it much easier to copy/paste the output. BUG= none R=jvoung@chromium.org Review URL: https://codereview.chromium.org/611983003
Python
apache-2.0
google/swiftshader,google/swiftshader,bkaradzic/SwiftShader,bkaradzic/SwiftShader,bkaradzic/SwiftShader,bkaradzic/SwiftShader,google/swiftshader,bkaradzic/SwiftShader
7aaef53e5547abfca8eb64ceb4ac477a14b79536
tensorflow_datasets/core/visualization/__init__.py
tensorflow_datasets/core/visualization/__init__.py
# coding=utf-8 # Copyright 2020 The TensorFlow Datasets Authors. # # 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 appl...
# coding=utf-8 # Copyright 2020 The TensorFlow Datasets Authors. # # 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 appl...
Add show_statistics to public API
Add show_statistics to public API PiperOrigin-RevId: 322842576
Python
apache-2.0
tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets
802beba31c832a045c38961ef4add2531193a6db
src/prefill.py
src/prefill.py
import pywikibot import sys import requests from app import get_proposed_edits, app def prefill_cache(max_pages=5000, starting_page=None): site = pywikibot.Site() cs1 = pywikibot.Page(site, 'Module:Citation/CS1') count = 0 starting_page_seen = starting_page is None for p in cs1.embeddedin(namespace...
import pywikibot import sys import requests from app import get_proposed_edits, app import threading from time import sleep def worker(title=None): try: get_proposed_edits(title, False, True) except: pass def prefill_cache(max_pages=5000, starting_page=None): site = pywikibot.Site() cs...
Add multithreading with threading module, run until the end
Add multithreading with threading module, run until the end The template has over 3M usages, so 5M should be a safe number.
Python
mit
dissemin/oabot,dissemin/oabot,dissemin/oabot
c537f40c4c56dc8a52e284bd9c03d09d191e77eb
tests/test_dungeon.py
tests/test_dungeon.py
from game.models import (Dungeon, Deck, Player, make_standard_deck) import pytest @pytest.fixture def dungeon(): return Dungeon(make_standard_deck(), seed=123456789) def test_dungeon_handle_input_valid(dungeon): dungeon.handle_input(...
from game.models import (Dungeon, Deck, Player, make_standard_deck) import pytest @pytest.fixture def dungeon(): return Dungeon(make_standard_deck(), seed=123456789) def test_deck_order(dungeon): """this check ensures that we can pla...
Add tests for Dungeon class
Add tests for Dungeon class
Python
mit
setphen/Donsol
2dac0f9825b58c5c9af9958d6f0cb0337649cf76
wsgi_general.py
wsgi_general.py
import DQXUtils import DQXDbTools def application(environ, start_response): #For the root we do a relative redirect to index.html, hoping the app has one if environ['PATH_INFO'] == '/': start_response('301 Moved Permanently', [('Location', 'index.html'),]) return with DQXDbTools.DBCursor()...
import DQXUtils import DQXDbTools def application(environ, start_response): #For the root we do a relative redirect to index.html, hoping the app has one if environ['PATH_INFO'] == '/': start_response('301 Moved Permanently', [('Location', 'index.html'),]) return with DQXDbTools.DBCursor()...
Add routing exception for docs
Add routing exception for docs
Python
agpl-3.0
cggh/DQXServer
c008171b93371c72a2f2a2698f514d267e312837
tests/testapp/urls.py
tests/testapp/urls.py
from django.conf.urls import url from django.contrib import admin from .views import ArticleView, PageView urlpatterns = [ url(r"^admin/", admin.site.urls), url(r"^articles/(?P<pk>\d+)/$", ArticleView.as_view(), name="article_detail"), url(r"^pages/(?P<pk>\d+)/$", PageView.as_view(), name="page_detail"),...
from django.urls import re_path from django.contrib import admin from .views import ArticleView, PageView urlpatterns = [ re_path(r"^admin/", admin.site.urls), re_path(r"^articles/(?P<pk>\d+)/$", ArticleView.as_view(), name="article_detail"), re_path(r"^pages/(?P<pk>\d+)/$", PageView.as_view(), name="pag...
Switch from url() to re_path()
Switch from url() to re_path()
Python
bsd-3-clause
matthiask/django-content-editor,matthiask/feincms2-content,matthiask/feincms2-content,matthiask/django-content-editor,matthiask/feincms2-content,matthiask/django-content-editor,matthiask/django-content-editor
eb0362c489f63d94d082ee4700dfdc871f68f916
tests/dal/await_syntax.py
tests/dal/await_syntax.py
from umongo import Document # Await syntax related tests are stored in a separate file in order to # catch a SyntaxError when Python doesn't support it async def test_await_syntax(db): class Doc(Document): class Meta: collection = db.doc async def test_cursor(cursor): await curso...
from umongo import Document from umongo.dal.motor_asyncio import MotorAsyncIOReference # Await syntax related tests are stored in a separate file in order to # catch a SyntaxError when Python doesn't support it async def test_await_syntax(db): class Doc(Document): class Meta: collection = db....
Add test for MotorAsyncIOReference await support
Add test for MotorAsyncIOReference await support
Python
mit
Scille/umongo
cd792dd6ab60b1976225c01d5071a925f0f185b7
tests/test_linestyles2.py
tests/test_linestyles2.py
#!/usr/bin/env python from boomslang import Line, Plot from ImageComparisonTestCase import ImageComparisonTestCase import unittest class LineStyles2Test(ImageComparisonTestCase, unittest.TestCase): def __init__(self, testCaseName): super(LineStyles2Test, self).__init__(testCaseName) self.imageName...
#!/usr/bin/env python from boomslang import Line, Plot from ImageComparisonTestCase import ImageComparisonTestCase import unittest class LineStyles2Test(ImageComparisonTestCase, unittest.TestCase): def __init__(self, testCaseName): super(LineStyles2Test, self).__init__(testCaseName) self.imageName...
Make linestyles2 test runnable (should probably fix this for other tests)
Make linestyles2 test runnable (should probably fix this for other tests)
Python
bsd-3-clause
alexras/boomslang
fb08d35b8470cb659e9a9f80d58d15c18faeaf9c
testinfra/backend/base.py
testinfra/backend/base.py
# -*- coding: utf8 -*- # Copyright © 2015 Philippe Pepiot # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
# -*- coding: utf8 -*- # Copyright © 2015 Philippe Pepiot # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
Fix safe_ssh command without arguments
backend: Fix safe_ssh command without arguments
Python
apache-2.0
philpep/testinfra,Leibniz137/testinfra
273999eeedee551a4490c89928650fbfebeb4a22
tests/_test.py
tests/_test.py
import unittest class TestCase(unittest.TestCase): pass
import random import unittest import autograd.numpy as anp import numpy as np import tensorflow as tf import torch class TestCase(unittest.TestCase): @classmethod def testSetUp(cls): seed = 42 random.seed(seed) anp.random.seed(seed) np.random.seed(seed) torch.manual_se...
Fix random seed in unit tests
Fix random seed in unit tests Signed-off-by: Niklas Koep <342d5290239d9c5264c8f98185afedb99596601a@gmail.com>
Python
bsd-3-clause
pymanopt/pymanopt,pymanopt/pymanopt
4392a87f9ebb5c6d2c2623089b3216837d6efb6b
test/418-wof-l10n_name.py
test/418-wof-l10n_name.py
# Hollywood (wof neighbourhood) # https://whosonfirst.mapzen.com/data/858/260/37/85826037.geojson assert_has_feature( 16, 11227, 26157, 'places', { 'id': 85826037, 'kind': 'neighbourhood', 'source': "whosonfirst.mapzen.com", 'name': 'Hollywood', 'name:ko': '\xed\x97\x90\xeb\xa6\xac\xec\x9a\xb0...
# Hollywood (wof neighbourhood) # https://whosonfirst.mapzen.com/data/858/260/37/85826037.geojson assert_has_feature( 16, 11227, 26157, 'places', { 'id': 85826037, 'kind': 'neighbourhood', 'source': "whosonfirst.mapzen.com", 'name': 'Hollywood', 'name:kor': '\xed\x97\x90\xeb\xa6\xac\xec\x9a\xb...
Update tests for new l10n behavior
Update tests for new l10n behavior
Python
mit
mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource
2833a895e8a7d0ba879598222c83bc5a4cd88853
desc/geometry/__init__.py
desc/geometry/__init__.py
from .curve import FourierRZCurve, FourierXYZCurve, FourierPlanarCurve from .surface import FourierRZToroidalSurface, ZernikeRZToroidalSection __all__ = [ "FourierRZCurve", "FourierXYZCurve", "FourierPlanarCurve", "FourierRZToroidalSurface", "ZernikeRZToroidalSection", ]
from .curve import FourierRZCurve, FourierXYZCurve, FourierPlanarCurve from .surface import FourierRZToroidalSurface, ZernikeRZToroidalSection from .core import Surface, Curve __all__ = [ "FourierRZCurve", "FourierXYZCurve", "FourierPlanarCurve", "FourierRZToroidalSurface", "ZernikeRZToroidalSectio...
Add geometry ABCs to init
Add geometry ABCs to init
Python
mit
PlasmaControl/DESC,PlasmaControl/DESC
700b1681162210e00afc1a7ca22bff5a82522077
tests/DdlTextWrterTest.py
tests/DdlTextWrterTest.py
import os import unittest from pyddl import * from pyddl.enum import * __author__ = "Jonathan Hale" class DdlTextWriterTest(unittest.TestCase): def tearDown(self): try: os.remove("test.oddl") except FileNotFoundError: pass # test_empty failed? def test_empty(self): ...
import os import unittest from pyddl import * from pyddl.enum import * __author__ = "Jonathan Hale" class DdlTextWriterTest(unittest.TestCase): def tearDown(self): try: os.remove("test.oddl") except FileNotFoundError: pass # test_empty failed? def test_empty(self): ...
Add more structures to test_full() document
Add more structures to test_full() document Signed-off-by: Squareys <0f6a03d4883e012ba4cb2c581a68f35544703cd6@googlemail.com>
Python
mit
Squareys/PyDDL
435ac02a320582fb8ede698da579d5c4fdd2d600
summary_footnotes.py
summary_footnotes.py
""" Summary Footnotes ------------- Fix handling of footnotes inside article summaries. Option to either remove them or make them link to the article page. """ from pelican import signals from pelican.contents import Content, Article from BeautifulSoup import BeautifulSoup from six import text_type def summary_footn...
""" Summary Footnotes ------------- Fix handling of footnote links inside article summaries. Option to either remove them or make them link to the article page. """ from pelican import signals from pelican.contents import Content, Article from BeautifulSoup import BeautifulSoup from six import text_type def initiali...
Rewrite summary as late as possible.
Rewrite summary as late as possible. Fixes issue where {filename} links would sometimes not work.
Python
agpl-3.0
dperelman/summary_footnotes
6fa6203ce412ec1f9f50d07fce0a8c279878a3f1
examples/visual_testing/layout_test.py
examples/visual_testing/layout_test.py
from seleniumbase import BaseCase class VisualLayoutTest(BaseCase): def test_applitools_helloworld(self): self.open('https://applitools.com/helloworld?diff1') print('Creating baseline in "visual_baseline" folder...') self.check_window(name="helloworld", baseline=True) self.click('...
from seleniumbase import BaseCase class VisualLayoutTest(BaseCase): def test_applitools_helloworld(self): self.open('https://applitools.com/helloworld?diff1') print('Creating baseline in "visual_baseline" folder...') self.check_window(name="helloworld", baseline=True) self.click('...
Update comments in the layout test
Update comments in the layout test
Python
mit
mdmintz/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase
8ce2882f365f24bcdb4274f78809afdda602083a
tests/test_meetup_loto.py
tests/test_meetup_loto.py
import tests.context import unittest from meetup_loto import Loto class TestMeetupLoto(unittest.TestCase): def setUp(self): self.api = FakeApi() self.loto = Loto(self.api, "Docker-Montreal", 240672864) def test_meetup_loto_participants(self): nb_participants = self.loto.number_of_part...
import tests.context import unittest from meetup_loto import Loto class TestMeetupLoto(unittest.TestCase): def setUp(self): self.api = FakeApi() self.loto = Loto(self.api, "Docker-Montreal", 240672864) def test_meetup_loto_participants(self): nb_participants = self.loto.number_of_part...
Use list comprehensions to generate test data
Use list comprehensions to generate test data
Python
mit
ghislainbourgeois/meetup_loto,ghislainbourgeois/meetup_loto,ghislainbourgeois/meetup_loto
275090f49fde702bb0189845afc322ec728907d6
app/models.py
app/models.py
from flask_login import UserMixin import spotify import spotipy import db_utils import application as app class User(UserMixin): ''' User class for Flask-Login ''' def __init__(self, user_id, username=None): self.id = int(user_id) self.username = username self._spotify = None @pro...
from flask_login import UserMixin import spotify import spotipy import db_utils import application as app class User(UserMixin): ''' User class for Flask-Login ''' def __init__(self, user_id, username=None): self.id = int(user_id) self.username = username self._spotify = None @pro...
Fix token refresh for spotify credentials
Fix token refresh for spotify credentials
Python
mit
DropMuse/DropMuse,DropMuse/DropMuse
248ed7b2d273fc044652af78388127f2fa31641c
test.py
test.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import unittest from romajitools import * class RTTestCase(unittest.TestCase): def test_lemma_tables(self): # sanity test self.assertEqual(len(LEMMAS), 233) def test_hiragana_table(self): # chec...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import unittest from romajitools import * class RTTestCase(unittest.TestCase): def test_lemma_tables(self): # sanity test self.assertEqual(len(LEMMAS), 233) def test_hiragana_table(self): # chec...
Use TO_HIRAGANA to get lemmas from Hiragana table.
Use TO_HIRAGANA to get lemmas from Hiragana table.
Python
bsd-3-clause
khanson679/romaji-tools
0662cd31d0c49c85460200093311eea6fa86f09e
mwikiircbot.py
mwikiircbot.py
import ircbotframe import sys class Handler: def __init__(self, host, port=6667, name="MediaWiki", description="MediaWiki recent changes bot", channels=[]): self.channels = channels self.bot = ircbotframe.ircBot(host, port, name, description) self.bot.bind("376", self.endMOTD) self....
import ircbotframe import sys class Handler: def __init__(self, host, port=6667, name="MediaWiki", description="MediaWiki recent changes bot", channels=[]): self.channels = channels self.bot = ircbotframe.ircBot(host, port, name, description) self.bot.bind("376", self.endMOTD) self....
Remove a redundant if and fix a syntax error
Remove a redundant if and fix a syntax error
Python
mit
fenhl/mwikiircbot
1d4ac6431e91b04a5a11bd7add78c512e3fe68d8
aiodocker/jsonstream.py
aiodocker/jsonstream.py
import asyncio import json import logging import aiohttp.errors log = logging.getLogger(__name__) class JsonStreamResult: def __init__(self, response, transform=None): self.response = response self.transform = transform or (lambda x: x) async def fetch(self): while True: ...
import asyncio import json import logging import aiohttp.errors log = logging.getLogger(__name__) class JsonStreamResult: def __init__(self, response, transform=None): self.response = response self.transform = transform or (lambda x: x) async def fetch(self): while True: ...
Fix indefinite hangs when closing streaming results.
Fix indefinite hangs when closing streaming results. * See https://github.com/KeepSafe/aiohttp/issues/739
Python
mit
paultag/aiodocker,gaopeiliang/aiodocker,barrachri/aiodocker,gaopeiliang/aiodocker,barrachri/aiodocker,gaopeiliang/aiodocker,barrachri/aiodocker
48267661a046f04ec2274b53919e013fe47bd9fd
enactiveagents/model/perceptionhandler.py
enactiveagents/model/perceptionhandler.py
""" Module that holds classes that represent an agent's perception handler. """ import abc import world import structure class PerceptionHandler(object): @abc.abstractmethod def perceive(self, agent, world): """ Generates a percept given an agent and a world. :param agent: The agent ...
""" Module that holds classes that represent an agent's perception handler. """ import abc import world import structure class PerceptionHandler(object): """ Abstract perception handler class. """ @abc.abstractmethod def perceive(self, agent, world): """ Generates a percept given ...
Document classes in the perception handler module.
Document classes in the perception handler module.
Python
mit
Beskhue/enactive-agents,Beskhue/enactive-agents,Beskhue/enactive-agents
d50fecebfc9e4e94fc8c0dd0c848030bf5e1ae6c
analytics/middleware.py
analytics/middleware.py
import uuid from django.conf import settings from django.utils import timezone from django.utils.deprecation import MiddlewareMixin from analytics.models import AnalyticsRecord from analytics.utils import ( should_ignore, status_code_invalid, get_tracking_params, ) class AnalyticsMiddleware(MiddlewareMi...
import uuid from django.conf import settings from django.utils import timezone from django.utils.deprecation import MiddlewareMixin from analytics.models import AnalyticsRecord from analytics.utils import ( should_ignore, status_code_invalid, get_tracking_params, ) class AnalyticsMiddleware(MiddlewareMi...
Use session instead of cookie for tracking visitor UUID
Use session instead of cookie for tracking visitor UUID session ID is only recorded after this layer of middleware, hence the need for a new UUID
Python
bsd-2-clause
praekelt/nurseconnect,praekelt/nurseconnect,praekelt/nurseconnect
6b07caaf86e0fbbf81c7b583ebd93c3ccfbd7c60
api/v2/serializers/details/project_application.py
api/v2/serializers/details/project_application.py
from core.models import ProjectApplication, Project, Application from rest_framework import serializers from api.v2.serializers.summaries import ProjectSummarySerializer from .application import ApplicationSerializer class ProjectRelatedField(serializers.PrimaryKeyRelatedField): def get_queryset(self): r...
from core.models import ProjectApplication, Project, Application from rest_framework import serializers from api.v2.serializers.summaries import ProjectSummarySerializer from .application import ApplicationSerializer class ProjectRelatedField(serializers.PrimaryKeyRelatedField): def get_queryset(self): r...
Rename 'public_fields' Application->Image to avoid confusion with the UI
Rename 'public_fields' Application->Image to avoid confusion with the UI
Python
apache-2.0
CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend
07c36f71850c5b9a2fc7a56e2b3cedeb833f83ab
oxyio/settings/__init__.py
oxyio/settings/__init__.py
# oxy.io # File: oxyio/settings/__init__.py # Desc: settings classmodule allowing for defaults + modules applied at runtime import sys from . import defaults class OxyioSettings(object): def __init__(self): # Apply the defaults to this self.apply_attrs(defaults) def load_module(self, name):...
# oxy.io # File: oxyio/settings/__init__.py # Desc: settings classmodule allowing for defaults + modules applied at runtime import sys from . import defaults class OxyioSettings(object): def __init__(self): # Apply the defaults to this self.apply_attrs(defaults) def load_module(self, name)...
Add comment about import in function.
Add comment about import in function.
Python
mit
oxyio/oxyio,oxyio/oxyio,oxyio/oxyio,oxyio/oxyio
4d3ba43ae00833ca19c5945285050af342b00046
abelfunctions/__init__.py
abelfunctions/__init__.py
""" abelfunctions is a Python library for computing with Abelian functions, algebraic curves, and solving integrable Partial Differential Equations. The code is available as a git repository at https://github.com/cswiercz/abelfunctions """ from .abelmap import AbelMap, Jacobian from .riemann_surface import Riema...
""" abelfunctions is a Python library for computing with Abelian functions, algebraic curves, and solving integrable Partial Differential Equations. The code is available as a git repository at https://github.com/cswiercz/abelfunctions """ from .abelmap import AbelMap, Jacobian from .puiseux import puiseux from ...
Include puiseux.puiseux in global namespace
Include puiseux.puiseux in global namespace Because it's useful, we include puiseux.puiseux() in the project __init__.py.
Python
mit
abelfunctions/abelfunctions,cswiercz/abelfunctions,abelfunctions/abelfunctions,cswiercz/abelfunctions,cswiercz/abelfunctions,abelfunctions/abelfunctions
968247875e0be421205a924a8d1325c0c9aeb2c6
zebra/forms.py
zebra/forms.py
from django import forms from django.core.exceptions import NON_FIELD_ERRORS from django.utils.dates import MONTHS from zebra.conf import options from zebra.widgets import NoNameSelect, NoNameTextInput class MonospaceForm(forms.Form): def addError(self, message): self._errors[NON_FIELD_ERRORS] = self.err...
from django import forms from django.core.exceptions import NON_FIELD_ERRORS from django.utils.dates import MONTHS from zebra.conf import options from zebra.widgets import NoNameSelect, NoNameTextInput class MonospaceForm(forms.Form): def addError(self, message): self._errors[NON_FIELD_ERRORS] = self.err...
Improve end-user labels, values, help text.
Improve end-user labels, values, help text.
Python
mit
amjoconn/django-zebra,GoodCloud/django-zebra,blag/django-zebra,blag/django-zebra,gumob/django-stripe,gumob/django-stripe,amjoconn/django-zebra,gumob/django-stripe,blag/django-zebra,amjoconn/django-zebra,GoodCloud/django-zebra
b30ba90aec5b7e6e4fa875ce7fb24b0135d9b0ef
tools/skp/page_sets/skia_googlespreadsheet_desktop.py
tools/skp/page_sets/skia_googlespreadsheet_desktop.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 import story from telemetry.page import page as page_module from telemetry.page import shared_page_state clas...
# 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 import story from telemetry.page import page as page_module from telemetry.page import shared_page_state clas...
Fix spreadsheets page set for RecreateSKPs bot
Fix spreadsheets page set for RecreateSKPs bot NoTry: true Bug: skia:9380 Change-Id: Iab05b1baab58032a8053242fd2a8b6e8799c35cc Reviewed-on: https://skia-review.googlesource.com/c/skia/+/238037 Reviewed-by: Eric Boren <0e499112533c8544f0505ea0d08394fb5ad7d8fa@google.com> Commit-Queue: Ravi Mistry <9fa2e7438b8cb730f96b7...
Python
bsd-3-clause
HalCanary/skia-hc,google/skia,HalCanary/skia-hc,aosp-mirror/platform_external_skia,HalCanary/skia-hc,aosp-mirror/platform_external_skia,google/skia,aosp-mirror/platform_external_skia,HalCanary/skia-hc,google/skia,google/skia,aosp-mirror/platform_external_skia,HalCanary/skia-hc,google/skia,aosp-mirror/platform_external_...
3cd3aa7b5f6a04a6d25d0f919c7dc38aa6c2a499
raven/contrib/django/__init__.py
raven/contrib/django/__init__.py
""" raven.contrib.django ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from .client import *
""" raven.contrib.django ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from raven.contrib.django.client import *
Switch to absolute import for Python 2.5 (fixes GH-64)
Switch to absolute import for Python 2.5 (fixes GH-64)
Python
bsd-3-clause
ewdurbin/raven-python,Goldmund-Wyldebeast-Wunderliebe/raven-python,akalipetis/raven-python,recht/raven-python,arthurlogilab/raven-python,dirtycoder/opbeat_python,someonehan/raven-python,Goldmund-Wyldebeast-Wunderliebe/raven-python,hzy/raven-python,dbravender/raven-python,danriti/raven-python,percipient/raven-python,Pho...
8f96c4e1852edb1ec2c35733611e86b4d89abf1a
legislators/urls.py
legislators/urls.py
from . import views from django.conf.urls import url urlpatterns = [ url(r'^find_legislator/', views.find_legislator), url(r'^get_latlon/', views.get_latlon, name="get_latlon"), url(r'^latest_latlon/', views.latest_latlon, name="latest_latlon"), url(r'^detail/(?P<legislator_id>(.*))/$', views.legislat...
from . import views from django.conf.urls import url urlpatterns = [ url(r'^find_legislator/', views.find_legislator, name="find_legislator"), url(r'^get_latlon/', views.get_latlon, name="get_latlon"), url(r'^latest_latlon/', views.latest_latlon, name="latest_latlon"), url(r'^detail/(?P<legislator_id>...
Add name to legislator detail page
Add name to legislator detail page
Python
mit
jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot
8d86d70739cbd4640faf17ca28686c3b04d5ec9c
migrations/versions/0336_broadcast_msg_content_2.py
migrations/versions/0336_broadcast_msg_content_2.py
""" Revision ID: 0336_broadcast_msg_content_2 Revises: 0335_broadcast_msg_content Create Date: 2020-12-04 15:06:22.544803 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql from sqlalchemy.orm.session import Session from app.models import BroadcastMessage revision = '0336_...
""" Revision ID: 0336_broadcast_msg_content_2 Revises: 0335_broadcast_msg_content Create Date: 2020-12-04 15:06:22.544803 """ from alembic import op import sqlalchemy as sa from notifications_utils.template import BroadcastMessageTemplate from sqlalchemy.dialects import postgresql from sqlalchemy.orm.session import S...
Rewrite previous migration in raw SQL
Rewrite previous migration in raw SQL We shouldn’t import models into migrations because if the model changes later down the line then the migration can’t be re-run at a later date (for example to rebuild a database from scratch). We don’t need to encode the content before storing it (we’ll always do that before rend...
Python
mit
alphagov/notifications-api,alphagov/notifications-api
0529c91443fa2948514a21933de00f4c146c9764
data_api/snapshot_scheduler/src/test_snapshot_scheduler.py
data_api/snapshot_scheduler/src/test_snapshot_scheduler.py
# -*- encoding: utf-8 -*- import datetime as dt import os import mock from unittest.mock import patch import snapshot_scheduler class patched_datetime(dt.datetime): @classmethod def utcnow(cls): return dt.datetime(2011, 6, 21, 0, 0, 0, 0) @mock.patch('datetime.datetime', patched_datetime) def tes...
# -*- encoding: utf-8 -*- import datetime as dt import os import mock from unittest.mock import patch import snapshot_scheduler class patched_datetime(dt.datetime): @classmethod def utcnow(cls): return dt.datetime(2011, 6, 21, 0, 0, 0, 0) @mock.patch('datetime.datetime', patched_datetime) def tes...
Use the correctly named env vars
snapshot_scheduler: Use the correctly named env vars
Python
mit
wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api
ae4ad35270a5daaa58b4988820da9d342d8e4751
examples/basic_example.py
examples/basic_example.py
# -*- coding: utf-8 -*- from chatterbot import ChatBot # Create a new chat bot named Charlie chatbot = ChatBot('Charlie') # Get a response to the input text 'How are you?' response = chatbot.get_response('How are you?') print(response)
# -*- coding: utf-8 -*- from chatterbot import ChatBot # Create a new chat bot named Charlie chatbot = ChatBot( 'Charlie', trainer='chatterbot.trainers.ListTrainer' ) chatbot.train([ "Hi, can I help you?", "Sure, I'd to book a flight to Iceland.", "Your flight has been booked." ]) # Get a respons...
Add training to basic example
Add training to basic example
Python
bsd-3-clause
vkosuri/ChatterBot,gunthercox/ChatterBot
93f2ed85d32efd88f38b3b123bc99e6afe120ae3
apps/payment/appconfig.py
apps/payment/appconfig.py
from django.apps import AppConfig class PaymentConfig(AppConfig): name = 'apps.payment' verbose_name = 'Payment' def ready(self): super(PaymentConfig, self).ready() from reversion import revisions as reversion from apps.payment.models import PaymentPrice, PaymentTransaction ...
from django.apps import AppConfig class PaymentConfig(AppConfig): name = 'apps.payment' verbose_name = 'Payment' def ready(self): super(PaymentConfig, self).ready() from reversion import revisions as reversion from apps.payment.models import PaymentTransaction reversion...
Fix registering for already registered model
Fix registering for already registered model
Python
mit
dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4
bab2056ea9e47eec1d0bd15f86ff9cf08f8dbafc
tweets/tasks.py
tweets/tasks.py
from datetime import timedelta from django.conf import settings from django.core.management import call_command from celery.task import periodic_task @periodic_task(run_every=timedelta(minutes=settings.TWEET_INTERVAL_MINUTES)) def tweet_next_task(): call_command('tweet_next', verbose=True, interactive=False)
from django.core.management import call_command from celery import shared_task @shared_task() def tweet_next_task(): call_command('tweet_next', verbose=True, interactive=False)
Use shared_task instead of deprecated periodic_task
Use shared_task instead of deprecated periodic_task
Python
mit
gwhigs/tweeter,gwhigs/tweeter,gwhigs/tweeter,gwhigs/tweeter
556545432af2b6d7d2c04e97fb86be308069d03a
plugins/backtothefuture.py
plugins/backtothefuture.py
"""!backtothefuture <date> returns the delorean dashboard with the specified <date>""" import re import parsedatetime p = parsedatetime.Calendar() def backtothefutureday(datestr): dt = p.parse(datestr)[0] return 'http://www.itsbacktothefutureday.com/images/{year}/{month}/{day}.jpg'.format(year=dt.tm_year, ...
"""!backtothefuture <date> returns the delorean dashboard with the specified <date>""" import re import time import parsedatetime p = parsedatetime.Calendar() def backtothefutureday(datestr): dt, result = p.parse(datestr) if result == 0: return "I'm not eating that bogus date." if not isinstance...
Fix some bugs with date parsing, as well as zero pad month and day in URL
Fix some bugs with date parsing, as well as zero pad month and day in URL
Python
mit
akatrevorjay/slask,kesre/slask,joshshadowfax/slask
1560bf7112652cbbc06d6d58031cd268d293ee13
atmo/users/factories.py
atmo/users/factories.py
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at http://mozilla.org/MPL/2.0/. import factory from django.contrib.auth.models import User, Group class GroupFactory(factory.django.DjangoModelFactory...
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at http://mozilla.org/MPL/2.0/. import factory from django.contrib.auth.models import User, Group from django.contrib.auth.hashers import make_password ...
Fix incompatibility with recent factory_boy postgeneration.
Fix incompatibility with recent factory_boy postgeneration.
Python
mpl-2.0
mozilla/telemetry-analysis-service,mozilla/telemetry-analysis-service,mozilla/telemetry-analysis-service,mozilla/telemetry-analysis-service
0018ee9534ebf5b695971b936dd56cf45a6b4769
tests/packages/CommandCasing/plugin.py
tests/packages/CommandCasing/plugin.py
from sublime_plugin import ApplicationCommand class not_pascal_case_command(ApplicationCommand): def run(self): print("not_pascal_case") class not_PascalCaseCommand(ApplicationCommand): def run(self): print("not_PascalCaseCommand") class not_PASCALcase_command(ApplicationCommand): d...
from sublime_plugin import ApplicationCommand # The print calls show what sublime_plugin.Command.name # translates the class names to. class not_pascal_case_command(ApplicationCommand): def run(self): print("not_pascal_case") class not_PascalCaseCommand(ApplicationCommand): def run(self): ...
Clarify on command class casing
Clarify on command class casing
Python
mit
packagecontrol/package_reviewer,packagecontrol/st_package_reviewer
a48e2a2f9f367994ab131201db2f07eee5788642
interleaving/interleaving_method.py
interleaving/interleaving_method.py
class InterleavingMethod(object): ''' Interleaving ''' def interleave(self, a, b): ''' a: a list of document IDs b: a list of document IDs Return an instance of Ranking ''' raise NotImplementedError() def multileave(self, *lists): ''' ...
class InterleavingMethod(object): ''' Interleaving ''' def interleave(self, k, a, b): ''' k: the maximum length of resultant interleaving a: a list of document IDs b: a list of document IDs Return an instance of Ranking ''' raise NotImplementedErr...
Add a length argument for InterleavingMethod.interleave and multileave
Add a length argument for InterleavingMethod.interleave and multileave
Python
mit
mpkato/interleaving
e7a124628ce06d423425e3012d1b19b25562bdef
Discord/cogs/duelyst.py
Discord/cogs/duelyst.py
from discord.ext import commands from utilities import checks def setup(bot): bot.add_cog(Duelyst(bot)) class Duelyst(commands.Cog): def __init__(self, bot): self.bot = bot async def cog_check(self, ctx): return await checks.not_forbidden().predicate(ctx) @commands.group(invoke_without_command = True,...
from discord.ext import commands from utilities import checks def setup(bot): bot.add_cog(Duelyst()) class Duelyst(commands.Cog): async def cog_check(self, ctx): return await checks.not_forbidden().predicate(ctx) @commands.group(invoke_without_command = True, case_insensitive = True) async def duelyst(sel...
Remove unused bot attribute from Duelyst cog
[Discord] Remove unused bot attribute from Duelyst cog
Python
mit
Harmon758/Harmonbot,Harmon758/Harmonbot
f66f8b84a4092cce1f9f7e4e29a4fc483c51602f
whistleblower/tasks.py
whistleblower/tasks.py
import json import logging import os import subprocess from celery import Celery from celery.schedules import crontab from .targets.facebook_messenger import Post as MessengerPost from .targets.twitter import Post as TwitterPost import whistleblower.queue HOUR = 3600 ENABLED_TARGETS = [ TwitterPost, Messenge...
import json import logging import os import subprocess from celery import Celery from celery.schedules import crontab from .targets.facebook_messenger import Post as MessengerPost from .targets.twitter import Post as TwitterPost import whistleblower.queue HOUR = 3600 ENABLED_TARGETS = [ TwitterPost, Messenge...
Remove task for updating data
Remove task for updating data Not sure if this is the best method to have it. Since for now is not needed, droping it from the codebase.
Python
unlicense
datasciencebr/whistleblower
b16409f5c0771d3d4440b5152971e9659fa23eb9
application.py
application.py
#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager application = create_app(os.getenv('FLASH_CONFIG') or 'default') manager = Manager(application) if __name__ == '__main__': manager.run()
#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager, Server application = create_app(os.getenv('FLASH_CONFIG') or 'default') manager = Manager(application) manager.add_command("runserver", Server(port=5003)) if __name__ == '__main__': manager.run()
Update to run on port 5003
Update to run on port 5003 For development we will want to run multiple apps, so they should each bind to a different port number.
Python
mit
alphagov/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,alphag...
96104472462e78853969ab5bef87592fe479e4b9
bin/server.py
bin/server.py
""" Simple server scripts that spawns the Jupyter notebook server process. """ import subprocess subprocess.call([ 'jupyter', 'notebook', '--no-browser', '--ip=0.0.0.0', '--port=5000', '--notebook-dir=../workspace' ])
""" Simple server scripts that spawns the Jupyter notebook server process. """ import os import subprocess # Check if code runs in SourceLair and change current directory to project # root directory, if so. if (os.environ.get('SL_ENV') == '1'): os.chdir('/mnt/project') # Try to import jupyter. If this fails, ins...
Add automatic installation of dependencies if not found.
Add automatic installation of dependencies if not found.
Python
mit
parisk/jupyter-starter
4ac0458e114809c82b42bc0f058aa382fd4f9daf
src/fabfile.py
src/fabfile.py
import os # pylint: disable=unused-wildcard-import,unused-import,wildcard-import SRC_DIR = os.path.dirname(os.path.abspath(__file__)) # elife-builder/src/ # once called 'THIS_DIR', now deprecated as confusing. PROJECT_DIR = os.path.dirname(SRC_DIR) # elife-builder/ from cfn import * import aws import metrics im...
import os # pylint: disable=unused-wildcard-import,unused-import,wildcard-import SRC_DIR = os.path.dirname(os.path.abspath(__file__)) # elife-builder/src/ # once called 'THIS_DIR', now deprecated as confusing. PROJECT_DIR = os.path.dirname(SRC_DIR) # elife-builder/ from cfn import * import aws import metrics im...
Remove import of dead module
Remove import of dead module
Python
mit
elifesciences/builder,elifesciences/builder
04a738253bbd0018784ce6ad81480b38a61b006f
etc/bin/xcode_bots/testflight/before_integration.py
etc/bin/xcode_bots/testflight/before_integration.py
# This script should be copied into the Run Script trigger of an Xcode Bot # Utilizes `cavejohnson` for Xcode Bot scripting # https://github.com/drewcrawford/CaveJohnson #!/bin/bash PATH=/Library/Frameworks/Python.framework/Versions/3.4/bin:$PATH # Set unique Build Number prior to TestFlight upload cavejohnson setBu...
# This script should be copied into the Run Script trigger of an Xcode Bot # Utilizes `cavejohnson` for Xcode Bot scripting # https://github.com/drewcrawford/CaveJohnson #!/bin/bash PATH=/Library/Frameworks/Python.framework/Versions/3.4/bin:$PATH # Set unique Build Number prior to TestFlight upload cavejohnson setBu...
Use the correct Info.plist in the new version of FeedbackDemo
Use the correct Info.plist in the new version of FeedbackDemo
Python
bsd-3-clause
Jawbone/apptentive-ios,ALHariPrasad/apptentive-ios,apptentive/apptentive-ios,hibu/apptentive-ios,sahara108/apptentive-ios,Jawbone/apptentive-ios,hibu/apptentive-ios,apptentive/apptentive-ios,sahara108/apptentive-ios,apptentive/apptentive-ios,hibu/apptentive-ios,ALHariPrasad/apptentive-ios
cd9cb42c16d443a26c7054e27c3ebc254142fbfb
python/ligscore/__init__.py
python/ligscore/__init__.py
import saliweb.backend class Job(saliweb.backend.Job): runnercls = saliweb.backend.SGERunner def run(self): libs = {'PoseScore': 'protein_ligand_pose_score.lib', 'RankScore': 'protein_ligand_rank_score.lib'} pdb, mol2, lib = open('input.txt').readline().strip().split(' ') ...
import saliweb.backend class Job(saliweb.backend.Job): runnercls = saliweb.backend.WyntonSGERunner def run(self): libs = {'PoseScore': 'protein_ligand_pose_score.lib', 'RankScore': 'protein_ligand_rank_score.lib'} pdb, mol2, lib = open('input.txt').readline().strip().split(' ')...
Switch to new Wynton cluster
Switch to new Wynton cluster
Python
lgpl-2.1
salilab/ligscore,salilab/ligscore
f6748408ecbbd1550b47a5975bdff135229acd11
tests/test_itunes.py
tests/test_itunes.py
""" test_itunes.py Copyright © 2015 Alex Danoff. All Rights Reserved. 2015-08-02 This file tests the functionality provided by the itunes module. """ import unittest from itunes.itunes import parse_value class ITunesTests(unittest.TestCase): """ Test cases for iTunes functionality. """ def test_pa...
""" test_itunes.py Copyright © 2015 Alex Danoff. All Rights Reserved. 2015-08-02 This file tests the functionality provided by the itunes module. """ import unittest from itunes.itunes import parse_value class ITunesTests(unittest.TestCase): """ Test cases for iTunes functionality. """ def test_pa...
Add test case for `parse_value`
Add test case for `parse_value` The new test case handles the string '""' as input.
Python
mit
adanoff/iTunesTUI
9de4ba984ce009c310e201ff3d00958f56c96d55
tests/test_length.py
tests/test_length.py
import pytest # type: ignore from ppb_vector import Vector @pytest.mark.parametrize( "x, y, expected", [(6, 8, 10), (8, 6, 10), (0, 0, 0), (-6, -8, 10), (1, 2, 2.23606797749979)], ) def test_length(x, y, expected): vector = Vector(x, y) assert vector.length == expected
from math import sqrt import pytest # type: ignore from hypothesis import given from ppb_vector import Vector from utils import isclose, vectors @pytest.mark.parametrize( "x, y, expected", [(6, 8, 10), (8, 6, 10), (0, 0, 0), (-6, -8, 10), (1, 2, 2.23606797749979)], ) def test_le...
Add comparison to (the square root of) the dot product
tests/length: Add comparison to (the square root of) the dot product
Python
artistic-2.0
ppb/ppb-vector,ppb/ppb-vector
e21e3dec9a238785fefe275f600ff43991f3737c
nntpserver.py
nntpserver.py
#!/usr/bin/python import socket, sys, os, signal import nntp signal.signal(signal.SIGCHLD, signal.SIG_IGN) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 4321)) s.listen(1) while True: conn, addr = s.accept() pid = os.fork() if pid > 0: conn.close() else: nntp.NN...
#!/usr/bin/python import socket, sys, os, signal import nntp signal.signal(signal.SIGCHLD, signal.SIG_IGN) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('', 4321)) s.listen(1) while True: conn, addr = s.accept() pid = os.fork() if...
Set SO_REUSADDR on the listening socket
Set SO_REUSADDR on the listening socket So that nntpserver.py can be killed and restarted wothout delay.
Python
mit
dpw/pnntprss
e8cd061ca203fa886757bdbf215b83c5ab2e43aa
geotrek/outdoor/migrations/0032_course_points_reference.py
geotrek/outdoor/migrations/0032_course_points_reference.py
# Generated by Django 3.1.13 on 2021-10-13 13:05 import django.contrib.gis.db.models.fields from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('outdoor', '0031_course_parent_sites'), ] operations = [ migrations.AddField( model_name='cou...
# Generated by Django 3.1.13 on 2021-10-13 13:05 from django.conf import settings import django.contrib.gis.db.models.fields from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('outdoor', '0031_course_parent_sites'), ] operations = [ migrations.AddF...
Use settings SRID in migration
Use settings SRID in migration
Python
bsd-2-clause
GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek
390f585994f6d021405de9aee3c174b054fb64a7
ietfparse/compat/parse.py
ietfparse/compat/parse.py
""" Exports related to URL parsing. This module exports standard library functionality so that it matches :mod:`urllib.parse` from the Python 3 standard library. """ __all__ = ( 'quote', 'splitnport', 'urlencode', 'urlsplit', 'urlunsplit', ) try: from urllib.parse import ( quote, spli...
""" Exports related to URL parsing. This module exports standard library functionality so that it matches :mod:`urllib.parse` from the Python 3 standard library. """ __all__ = ( 'quote', 'splitnport', 'urlencode', 'urlsplit', 'urlunsplit', ) try: from urllib.parse import ( quote, spli...
Fix urlencode for Python < 3.0.
compat: Fix urlencode for Python < 3.0. The urlencode function handles encoding in Python 3.x so our compatibility layer should do so to.
Python
bsd-3-clause
dave-shawley/ietfparse
67e47e0179352e9d5206fe7196762481d0bcaba4
aspen/server.py
aspen/server.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from algorithm import Algorithm def main(): Server().main() class Server(object): def __init__(self, argv=None): self.argv = argv def get_algor...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from algorithm import Algorithm def main(): Server().main() class Server(object): def __init__(self, argv=None): self.argv = argv def get_algor...
Drop back to state as return val
Drop back to state as return val If we store state on Algorithm then we're not thread-safe.
Python
mit
gratipay/aspen.py,gratipay/aspen.py
94d4cb6a5c5d0c43e056bec73584d798f88ff70e
bnw_handlers/command_login.py
bnw_handlers/command_login.py
# -*- coding: utf-8 -*- #from twisted.words.xish import domish from base import * from bnw_core.base import get_webui_base import bnw_core.bnw_objects as objs from twisted.internet import defer @require_auth def cmd_login(request): """ Логин-ссылка """ return dict( ok=True, desc='%s/login?key=...
# -*- coding: utf-8 -*- #from twisted.words.xish import domish from base import * from bnw_core.base import get_webui_base import bnw_core.bnw_objects as objs from twisted.internet import defer @require_auth def cmd_login(request): """ Логин-ссылка """ return dict( ok=True, desc='%s/login?key=...
Fix 500 error on empty passlogin values
Fix 500 error on empty passlogin values
Python
bsd-2-clause
stiletto/bnw,un-def/bnw,stiletto/bnw,ojab/bnw,stiletto/bnw,ojab/bnw,un-def/bnw,stiletto/bnw,ojab/bnw,un-def/bnw,ojab/bnw,un-def/bnw
743b678a2113f7f93d4c0cc27aa73745700a460a
bazaar/listings/filters.py
bazaar/listings/filters.py
from __future__ import unicode_literals import django_filters from .models import Listing class ListingFilter(django_filters.FilterSet): title = django_filters.CharFilter(lookup_type="icontains") class Meta: model = Listing fields = ['title', "publishings__store", "publishings__available_un...
from __future__ import unicode_literals from django import forms import django_filters from ..filters import BaseFilterSet from .models import Listing class LowStockListingFilter(django_filters.Filter): field_class = forms.BooleanField def filter(self, qs, value): if value: qs = qs.fil...
Add filter for low stock listings
Add filter for low stock listings
Python
bsd-2-clause
meghabhoj/NEWBAZAAR,meghabhoj/NEWBAZAAR,evonove/django-bazaar,meghabhoj/NEWBAZAAR,evonove/django-bazaar,evonove/django-bazaar
8ba164dca3d55d18e6b65c6f1e326fb3c0a2c11d
jarn/mkrelease/process.py
jarn/mkrelease/process.py
from __future__ import absolute_import import os from .tee import run from .exit import trace catch_keyboard_interrupts = True class Process(object): """Process related functions using the tee module.""" rc_keyboard_interrupt = 54321 def __init__(self, quiet=False, env=None): self.quiet = qui...
from __future__ import absolute_import import os from .tee import run from .exit import trace catch_keyboard_interrupts = True class Process(object): """Process related functions using the tee module.""" rc_keyboard_interrupt = 54321 def __init__(self, quiet=False, env=None, runner=run): self...
Allow to pass a runner to Process.
Allow to pass a runner to Process.
Python
bsd-2-clause
Jarn/jarn.mkrelease
1180767250af525f9d11c6b3b7f45c3d9b1e00f0
skyfield/tests/test_searchlib.py
skyfield/tests/test_searchlib.py
from numpy import add, array, diff, flatnonzero, reshape, sign def _remove_adjacent_duplicates(indices): return indices[diff(indices, prepend=-1) != 0] def _choose_brackets(y): dsd = diff(sign(diff(y))) indices = flatnonzero(dsd < 0) left = reshape(add.outer(indices, [0, 1]), -1) left = _remove_ad...
from numpy import add, append, array, diff, flatnonzero, reshape, sign def _remove_adjacent_duplicates(indices): mask = diff(indices) != 0 mask = append(mask, [True]) return indices[mask] def _choose_brackets(y): dsd = diff(sign(diff(y))) indices = flatnonzero(dsd < 0) left = reshape(add.outer...
Fix use of a too-recent NumPy feature
Fix use of a too-recent NumPy feature
Python
mit
skyfielders/python-skyfield,skyfielders/python-skyfield
7809a22a67f9c9d67d4765c2029d9b30656606bc
hello.py
hello.py
#!/usr/bin/python3.4 print("hello")
#!/usr/bin/python3.4 def greeting(msg): print(msg) if __name__=='__main__': greeting("hello")
Add function to print a message
Add function to print a message
Python
mit
ag4ml/cs3240-labdemo
faa1d74ccbfea43697c08db59db467b7a99ccb62
optimize/py/main.py
optimize/py/main.py
from scipy import optimize as o import clean as c def minimize(func, guess): return o.minimize(func, guess) def minimize_scalar(func, bracket=None, bounds=None, args=(), method='brent', tol=None, options=None): return o.minimize_scalar(func, bracket, bounds, args, method, tol, options)
from scipy import optimize as o import clean as c def minimize(func, guess): return o.minimize(func, guess) def minimize_scalar(func, options): bracket = options['bracket'] bounds = options['bounds'] method = options['method'] tol = options['tol'] options = options['options'] retu...
Allow options to be passed into minimization
Allow options to be passed into minimization
Python
mit
acjones617/scipy-node,acjones617/scipy-node