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
582edd6bd36e8b40a37a8aaaa013704b5cd73ad6
dotbot/config.py
dotbot/config.py
import yaml import json import os.path from .util import string class ConfigReader(object): def __init__(self, config_file_path): self._config = self._read(config_file_path) def _read(self, config_file_path): try: _, ext = os.path.splitext(config_file_path) with open(co...
import yaml import json import os.path from .util import string class ConfigReader(object): def __init__(self, config_file_path): self._config = self._read(config_file_path) def _read(self, config_file_path): try: _, ext = os.path.splitext(config_file_path) with open(co...
Fix compatibility with Python 3
Fix compatibility with Python 3 This patch removes a stray print statement that was causing problems with Python 3.
Python
mit
bchretien/dotbot,imattman/dotbot,imattman/dotbot,anishathalye/dotbot,anishathalye/dotbot,bchretien/dotbot,bchretien/dotbot,imattman/dotbot
01c9de35395495e35113e5f9bbee8ebc88e1c0f1
evaluation/packages/project.py
evaluation/packages/project.py
"""@package Project This module defines an interface to read and use InputGen projects See C++ InputGen project for more details on Projects """ import xml.etree.ElementTree as ET import displacementKernels as kernels class PyProject: """Main class of the module """ def __init__(self, path): """...
"""@package Project This module defines an interface to read and use InputGen projects See C++ InputGen project for more details on Projects """ import xml.etree.ElementTree as ET import displacementKernels as kernels class PyProject(object): """Main class of the module """ def __init__(self, path): ...
Change loading function to take a path instead of a python file
Change loading function to take a path instead of a python file
Python
apache-2.0
NUAAXXY/globOpt,amonszpart/globOpt,amonszpart/globOpt,amonszpart/globOpt,NUAAXXY/globOpt,NUAAXXY/globOpt,amonszpart/globOpt,NUAAXXY/globOpt,amonszpart/globOpt,amonszpart/globOpt,NUAAXXY/globOpt,NUAAXXY/globOpt
a040d06de7624371122960788aff241994ae08f8
metadata/SnowDegreeDay/hooks/pre-stage.py
metadata/SnowDegreeDay/hooks/pre-stage.py
import os import shutil from wmt.config import site from wmt.models.submissions import prepend_to_path from wmt.utils.hook import find_simulation_input_file from topoflow_utils.hook import assign_parameters file_list = ['rti_file', 'pixel_file'] def execute(env): """Perform pre-stage tasks for run...
import os import shutil from wmt.config import site from wmt.utils.hook import find_simulation_input_file from topoflow_utils.hook import assign_parameters, scalar_to_rtg_file file_list = [] def execute(env): """Perform pre-stage tasks for running a component. Parameters ---------- env : dict ...
Update hook for SnowDegreeDay component
Update hook for SnowDegreeDay component
Python
mit
csdms/wmt-metadata
0c83621f80ad8a1c014cc2ee79ea024f6d073749
src/smif/__init__.py
src/smif/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """smif """ from __future__ import division, print_function, absolute_import import pkg_resources import warnings __author__ = "Will Usher, Tom Russell" __copyright__ = "Will Usher, Tom Russell" __license__ = "mit" try: __version__ = pkg_resources.get_distribution(_...
#!/usr/bin/env python # -*- coding: utf-8 -*- """smif """ from __future__ import division, print_function, absolute_import import pkg_resources import warnings __author__ = "Will Usher, Tom Russell" __copyright__ = "Will Usher, Tom Russell" __license__ = "mit" try: __version__ = pkg_resources.get_distribution(_...
Comment to explain numpy warnings filter
Comment to explain numpy warnings filter
Python
mit
willu47/smif,nismod/smif,tomalrussell/smif,tomalrussell/smif,tomalrussell/smif,willu47/smif,willu47/smif,nismod/smif,nismod/smif,willu47/smif,nismod/smif,tomalrussell/smif
cc2b00f60029f50106af586d9a43895ef84133fa
__init__.py
__init__.py
#!/usr/bin/env python # coding=utf-8 # flake8: noqa # pylint: disable=missing-docstring # # 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 https://mozilla.org/MPL/2.0/. from __future__ import absolu...
#!/usr/bin/env python # coding=utf-8 # flake8: noqa # pylint: disable=missing-docstring # # 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 https://mozilla.org/MPL/2.0/. from __future__ import absolu...
Remove useless "unused-wildcard-import" pylint suppression.
Remove useless "unused-wildcard-import" pylint suppression.
Python
mpl-2.0
MozillaSecurity/lithium,MozillaSecurity/lithium,nth10sd/lithium,nth10sd/lithium
3aac735425c532bdb565f31feab203a36205df4f
__main__.py
__main__.py
#!/usr/bin/env python3 import sys import lexer as l import parser as p import evaluator as e import context as c import object as o def main(): if len(sys.argv) == 1: ctx = c.Context() while True: try: string = input("⧫ ") + ";" ...
#!/usr/bin/env python3 import sys import readline import lexer as l import parser as p import evaluator as e import context as c import object as o def main(): if len(sys.argv) == 1: ctx = c.Context() while True: try: string = input("⧫...
Use the readline module to allow arrow key movement in the REPL
Use the readline module to allow arrow key movement in the REPL
Python
mit
Zac-Garby/pluto-lang
7223bf0bf3ecf3459e5e7c9f01af61a8236eaffd
espei/__init__.py
espei/__init__.py
from ._version import get_versions __version__ = get_versions()['version'] del get_versions import os import yaml from cerberus import Validator MODULE_DIR = os.path.dirname(os.path.abspath(__file__)) # extension for iseven class ESPEIValidator(Validator): def _validate_iseven(self, iseven, field, value): ...
from ._version import get_versions __version__ = get_versions()['version'] del get_versions import os import yaml from cerberus import Validator MODULE_DIR = os.path.dirname(os.path.abspath(__file__)) # extension for iseven class ESPEIValidator(Validator): def _validate_iseven(self, iseven, field, value): ...
Hide permissible NumPy warnings from users
ENH: Hide permissible NumPy warnings from users
Python
mit
PhasesResearchLab/ESPEI
30c9359e33f6ec85ffad227dd8b68f3352f92c36
Assignment_5_partial_differentials/P440_Assign5_Exp1.py
Assignment_5_partial_differentials/P440_Assign5_Exp1.py
''' Kaya Baber Physics 440 - Computational Physics Assignment 5 - PDEs Exploration 1 - Parabolic PDEs: Thermal Diffusion ''' import numpy as np from numpy import linalg as LA import matplotlib.pyplot as plt import math
''' Kaya Baber Physics 440 - Computational Physics Assignment 5 - PDEs Exploration 1 - Parabolic PDEs: Thermal Diffusion ''' import numpy as np from numpy import linalg as LA import matplotlib.pyplot as plt import math #make banded matrix #initialize column vector #matrix multiply #modifiy boundaries #repeat ...
Set up the procedure to code out
Set up the procedure to code out
Python
mit
KayaBaber/Computational-Physics
e39430a8d1870c744fcfb479a15c1a7eacca8a32
psi/data/sinks/api.py
psi/data/sinks/api.py
import enaml with enaml.imports(): from .bcolz_store import BColzStore from .display_value import DisplayValue from .event_log import EventLog from .epoch_counter import EpochCounter, GroupedEpochCounter from .text_store import TextStore
import enaml with enaml.imports(): from .bcolz_store import BColzStore from .display_value import DisplayValue from .event_log import EventLog from .epoch_counter import EpochCounter, GroupedEpochCounter from .text_store import TextStore from .sdt_analysis import SDTAnalysis
Fix missing import to API
Fix missing import to API
Python
mit
bburan/psiexperiment
0cfd63816706531646bf496798bf093f8ee081ff
psqlextra/__init__.py
psqlextra/__init__.py
default_app_config = "psqlextra.apps.PostgresExtraAppConfig"
import django if django.VERSION < (3, 2): # pragma: no cover default_app_config = "psqlextra.apps.PostgresExtraAppConfig"
Remove default_app_config for Django 3.2 and newer
Remove default_app_config for Django 3.2 and newer RemovedInDjango41Warning: 'psqlextra' defines default_app_config = 'psqlextra.apps.PostgresExtraAppConfig'. Django now detects this configuration automatically. You can remove default_app_config.
Python
mit
SectorLabs/django-postgres-extra
c2b5b1458a521b39fbefb9f13428587991d5e3e9
packages/pcl-reference-assemblies.py
packages/pcl-reference-assemblies.py
import glob import os import shutil class PCLReferenceAssembliesPackage(Package): def __init__(self): Package.__init__(self, name='PortableReferenceAssemblies-2014-04-14', version='2014-04-14', sources=['http://storage.bos.xamarin....
import glob import os import shutil class PCLReferenceAssembliesPackage(Package): def __init__(self): Package.__init__(self, name='PortableReferenceAssemblies', version='2014-04-14', sources=['http://storage.bos.xamarin.com/bot-pro...
Fix package name for PCL ref assemblies
Fix package name for PCL ref assemblies
Python
mit
BansheeMediaPlayer/bockbuild,mono/bockbuild,mono/bockbuild,BansheeMediaPlayer/bockbuild,BansheeMediaPlayer/bockbuild
b2c2c5ea21b7f14820937276148c280303db241b
froide/frontpage/models.py
froide/frontpage/models.py
from django.db import models from django.utils.translation import ugettext as _ from django.contrib.auth.models import User from django.contrib.sites.models import Site from django.contrib.sites.managers import CurrentSiteManager from foirequest.models import FoiRequest class FeaturedRequestManager(CurrentSiteManage...
from django.db import models from django.utils.translation import ugettext as _ from django.contrib.auth.models import User from django.contrib.sites.models import Site from django.contrib.sites.managers import CurrentSiteManager from foirequest.models import FoiRequest class FeaturedRequestManager(CurrentSiteManage...
Add IndexError to getFeatured call
Add IndexError to getFeatured call
Python
mit
stefanw/froide,LilithWittmann/froide,stefanw/froide,ryankanno/froide,ryankanno/froide,CodeforHawaii/froide,catcosmo/froide,CodeforHawaii/froide,stefanw/froide,ryankanno/froide,stefanw/froide,fin/froide,ryankanno/froide,okfse/froide,catcosmo/froide,CodeforHawaii/froide,catcosmo/froide,stefanw/froide,okfse/froide,okfse/f...
db81eaa5f05309be69f7b8d3aa12023c75387194
fellowms/forms.py
fellowms/forms.py
from django.forms import ModelForm, widgets from .models import Fellow, Event, Expense, Blog class FellowForm(ModelForm): class Meta: model = Fellow fields = '__all__' class EventForm(ModelForm): class Meta: model = Event exclude = [ "status", ...
from django.forms import ModelForm, widgets from .models import Fellow, Event, Expense, Blog class FellowForm(ModelForm): class Meta: model = Fellow fields = '__all__' class EventForm(ModelForm): class Meta: model = Event exclude = [ "status", ...
Fix public fields from Event
Fix public fields from Event
Python
bsd-3-clause
softwaresaved/fat,softwaresaved/fat,softwaresaved/fat,softwaresaved/fat
480d15042af807cea3e7e182d4588dc3a2f93e92
website/members/signals.py
website/members/signals.py
from django.conf import settings from django.core.mail import EmailMultiAlternatives from django.dispatch import receiver from django.template import loader from simple_email_confirmation import unconfirmed_email_created @receiver(unconfirmed_email_created, dispatch_uid='send_email_confirmation') def send_confirmati...
import datetime from django.conf import settings from django.core.mail import EmailMultiAlternatives from django.db.models.signals import pre_save from django.dispatch import receiver from django.template import loader from django.utils import timezone from simple_email_confirmation import unconfirmed_email_created fr...
Check membership when a Member is saved
Check membership when a Member is saved
Python
agpl-3.0
UTNkar/moore,Dekker1/moore,Dekker1/moore,UTNkar/moore,Dekker1/moore,UTNkar/moore,UTNkar/moore,Dekker1/moore
a7b247d7fc44518b58a91eeadc12ac418daf3889
syncplay/__init__.py
syncplay/__init__.py
version = '1.6.7' revision = ' development' milestone = 'Yoitsu' release_number = '92' projectURL = 'https://syncplay.pl/'
version = '1.6.7' revision = ' beta 1' milestone = 'Yoitsu' release_number = '93' projectURL = 'https://syncplay.pl/'
Mark as 1.6.7 beta 1
Mark as 1.6.7 beta 1
Python
apache-2.0
alby128/syncplay,Syncplay/syncplay,Syncplay/syncplay,alby128/syncplay
fdf7f92a76fb6848f86194507b9a6fe8f0ab0171
hours_slept_time_series.py
hours_slept_time_series.py
import plotly as py import plotly.graph_objs as go from datetime import datetime from sys import argv import names from csvparser import parse data_file = argv[1] raw_data = parse(data_file) sleep_durations = [] sleep_dates = [] nap_durations = [] nap_dates = [] for date, rests in raw_data.items(): sleep_total =...
import plotly as py import plotly.graph_objs as go from datetime import datetime from sys import argv import names from csvparser import parse data_file = argv[1] raw_data = parse(data_file) sleep_durations = [] nap_durations = [] for date, rests in raw_data.items(): sleep_total = nap_total = 0 for r in rest...
Remove unused |date| array variables
Remove unused |date| array variables
Python
mit
f-jiang/sleep-pattern-grapher
22db373a8b33b201a8964b3f518434289b2a57af
app/__init__.py
app/__init__.py
from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.mail import Mail from flask.ext.moment import Moment from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from config import config bootstrap = Bootstrap() mail = Mail() moment = Moment() db = SQLAlchemy() ...
from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.mail import Mail from flask.ext.moment import Moment from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from config import config bootstrap = Bootstrap() mail = Mail() moment = Moment() db = SQLAlchemy() ...
Remove duplicate Flask-Login session protection setting
Remove duplicate Flask-Login session protection setting
Python
mit
richgieg/flask-now,richgieg/flask-now
6321d2e86db0de359886f5e69509dad428778bbf
shop/management/commands/shopcustomers.py
shop/management/commands/shopcustomers.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from optparse import make_option from django.core.management.base import BaseCommand from django.utils.translation import ugettext_lazy as _ class Command(BaseCommand): help = _("Collect information about all customers which accessed this shop.") ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from optparse import make_option from django.core.management.base import BaseCommand from django.utils.translation import ugettext_lazy as _ class Command(BaseCommand): help = _("Collect information about all customers which accessed this shop.") ...
Use the new django management commands definition (ArgumentParser)
Use the new django management commands definition (ArgumentParser)
Python
bsd-3-clause
jrief/django-shop,jrief/django-shop,divio/django-shop,awesto/django-shop,nimbis/django-shop,nimbis/django-shop,khchine5/django-shop,awesto/django-shop,jrief/django-shop,nimbis/django-shop,awesto/django-shop,khchine5/django-shop,nimbis/django-shop,jrief/django-shop,divio/django-shop,khchine5/django-shop,divio/django-sho...
4647183697170ce22910bd6cde27746297543514
python3_tools/get_edx_webservices.py
python3_tools/get_edx_webservices.py
import github from get_repos import * webservices = [] for repo in expanded_repos_list(orgs): try: metadata = get_remote_yaml(repo, 'openedx.yaml') except github.GithubException: continue if 'tags' in metadata and 'webservice' in metadata['tags']: print("{}".format(repo.html_url))...
import github from get_repos import orgs, expanded_repos_list, get_remote_yaml webservices = [] for repo in expanded_repos_list(orgs): try: metadata = get_remote_yaml(repo, 'openedx.yaml') except github.GithubException: continue if 'tags' in metadata and 'webservice' in metadata['tags']: ...
Add tooling to get all of edx's web services.
Add tooling to get all of edx's web services.
Python
apache-2.0
edx/repo-tools,edx/repo-tools
e1985056a11ca3fff3896d2e4126b6cdf048336d
scrape_affiliation.py
scrape_affiliation.py
import requests from lxml import html, etree def scrape_acm(page): tree = html.fromstring(page.content) author_affiliations = [] authors = tree.xpath('//td/a[@title="Author Profile Page"]') for a in authors: affiliation = a.getparent().getnext().find("a/small") # If we don't find it und...
import requests from lxml import html, etree def scrape_acm(page): tree = html.fromstring(page.content) author_affiliations = [] # The ACM author affiliations are stored in a kind of nasty table layout, # best to view source or inspect element on their page for an explanation of this. authors = tre...
Add comment on ACM affil structure
Add comment on ACM affil structure
Python
mit
Twinklebear/dataviscourse-pr-collaboration-networks,Twinklebear/dataviscourse-pr-collaboration-networks,Twinklebear/dataviscourse-pr-collaboration-networks
457e220ec4a401325b5078c6561c4ca8634d8b60
projecteuler/problems/problem_12.py
projecteuler/problems/problem_12.py
"""Problem 12 of https://projecteuler.net""" from projecteuler.maths_functions import factor_count from itertools import count def problem_12(): """Solution to problem 12.""" # Triangle number can be defined as n(n+1)/2. # n and n+1 share only the factor 1. # Therefore the total number of factors of ...
"""Problem 12 of https://projecteuler.net""" from projecteuler.maths_functions import factor_count from itertools import count def problem_12(): """Solution to problem 12.""" # Triangle number can be defined as n(n+1)/2. # n and n+1 share only the factor 1. # Therefore the total number of factors of ...
Refactor problem 12 to increase test coverage
Refactor problem 12 to increase test coverage
Python
mit
hjheath/ProjectEuler,heathy/ProjectEuler
88393283ff5e7f7720a98eda5eec8fa53b30f700
grains/grains.py
grains/grains.py
# File: grains.py # Purpose: Write a program that calculates the number of grains of wheat # on a chessboard given that the number on each square doubles. # Programmer: Amal Shehu # Course: Exercism # Date: Sunday 18 September 2016, 05:25 PM import itertools square = [x for x in r...
# File: grains.py # Purpose: Write a program that calculates the number of grains of wheat # on a chessboard given that the number on each square doubles. # Programmer: Amal Shehu # Course: Exercism # Date: Sunday 18 September 2016, 05:25 PM import itertools square = [x for x in r...
Add condition to avoid index error
Add condition to avoid index error
Python
mit
amalshehu/exercism-python
9accbde96f493ba795eef3d102a41aeecc039dce
grep_sal_code.py
grep_sal_code.py
#!/usr/bin/python import argparse import subprocess import sys EXCLUSIONS = ['*.pyc', '*.log', 'venv*', 'static/*', 'site_static/*', 'datatableview/*', '*.db'] def main(): args = parse_args() # Normally we like to build subprocess commands in lists, but it's # a lot easier to do all of the globbing we...
#!/usr/bin/python import argparse import os import subprocess import sys EXCLUSIONS = ['*.pyc', '*.log', 'venv*', 'static/*', 'site_static/*', 'datatableview/*', '*.db'] def main(): args = parse_args() # Normally we like to build subprocess commands in lists, but it's # a lot easier to do all of the g...
Add straight-to-editor feature to grep script.
Add straight-to-editor feature to grep script.
Python
apache-2.0
sheagcraig/sal,salopensource/sal,salopensource/sal,salopensource/sal,sheagcraig/sal,sheagcraig/sal,sheagcraig/sal,salopensource/sal
647707293524440f014ed0a3ef7d4322a96775e4
tests/example_app/flask_app.py
tests/example_app/flask_app.py
import flask from pale.adapters import flask as pale_flask_adapter from tests.example_app import api def create_pale_flask_app(): """Creates a flask app, and registers a blueprint bound to pale.""" blueprint = flask.Blueprint('api', 'tests.example_app') pale_flask_adapter.bind_blueprint(api, blueprint) ...
import flask from pale.adapters import flask as pale_flask_adapter from pale.config import authenticator, context_creator from tests.example_app import api @authenticator def authenticate_pale_context(context): """Don't actually authenticate anything in this test.""" return context @context_creator def cre...
Add authenticator and context creator to example app
Add authenticator and context creator to example app
Python
mit
Loudr/pale
1df4a955e80fc82cc88c049e2d9a606845cfb326
azure-mgmt-resource/azure/mgmt/resource/__init__.py
azure-mgmt-resource/azure/mgmt/resource/__init__.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # --------------------------------------------------------------------...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # --------------------------------------------------------------------...
Update alias ManagedApplicationClient to ApplicationClient
Update alias ManagedApplicationClient to ApplicationClient
Python
mit
Azure/azure-sdk-for-python,AutorestCI/azure-sdk-for-python,Azure/azure-sdk-for-python,Azure/azure-sdk-for-python,Azure/azure-sdk-for-python,lmazuel/azure-sdk-for-python
1ec5327918e11f76cb3d0dd2699585433d4d6058
reddit_adzerk/__init__.py
reddit_adzerk/__init__.py
from r2.lib.plugin import Plugin from r2.lib.js import Module class Adzerk(Plugin): needs_static_build = True js = { 'reddit': Module('reddit.js', 'adzerk/adzerk.js', ) } def load_controllers(self): # replace the standard Ads view with an Adzerk specific one. ...
from r2.lib.plugin import Plugin from r2.lib.js import Module class Adzerk(Plugin): needs_static_build = True js = { 'reddit-init': Module('reddit-init.js', 'adzerk/adzerk.js', ) } def load_controllers(self): # replace the standard Ads view with an Adzerk specific...
Move adzerk.js into reddit-init to fix race condition.
Move adzerk.js into reddit-init to fix race condition. This should ensure that the Adzerk postMessage receiver is loaded before Adzerk gets its payloads.
Python
bsd-3-clause
madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk
4227b5fb52c58304f993d2def11aeb1ed4d5a157
src/urldecorators/urlresolvers.py
src/urldecorators/urlresolvers.py
import types from django.core import urlresolvers as django_urlresolvers from django.utils.functional import curry class DecoratorMixin(object): """ Mixin class to return decorated views from RegexURLPattern/RegexURLResolver """ def __init__(self, *args, **kwargs): super(DecoratorMixin, s...
import types from django.core import urlresolvers as django_urlresolvers from django.utils.functional import curry class DecoratorMixin(object): """ Mixin class to return decorated views from RegexURLPattern/RegexURLResolver """ def __init__(self, *args, **kwargs): super(DecoratorMixin, s...
Fix for the new ResolverMatch object in Django 1.3.
Fix for the new ResolverMatch object in Django 1.3.
Python
bsd-3-clause
mila/django-urldecorators,mila/django-urldecorators
48f281127eb1adf2c1a88dee3759cec41fb95924
gears/finders.py
gears/finders.py
import os from .exceptions import ImproperlyConfigured from .utils import safe_join class BaseFinder(object): def find(self, path, all=False): raise NotImplementedError() class FileSystemFinder(BaseFinder): def __init__(self, directories): self.locations = [] if not isinstance(dire...
import os from .exceptions import ImproperlyConfigured from .utils import safe_join class BaseFinder(object): def find(self, path, all=False): raise NotImplementedError() class FileSystemFinder(BaseFinder): def __init__(self, directories): self.locations = [] if not isinstance(dire...
Fix FileSystemFinder's find return value if not all
Fix FileSystemFinder's find return value if not all
Python
isc
gears/gears,gears/gears,gears/gears
9aafe3ded97aee0f8f3623f0de1c13cfb555d7a6
getwork_store.py
getwork_store.py
import time class Getwork_store: def __init__(self): self.data = {} def add(self, server, merkle_root): self.data[merkle_root] = {'name':server["name"], 'timestamp':time.time()} return def get_server(self, merkle_root): if self.data.has_key(merkle_...
#License# #bitHopper by Colin Rice is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. #Based on a work at github.com. import time from twisted.internet.task import LoopingCall class Getwork_store: def __init__(self): self.data = {} cal...
Update getwork to prune itself and use a list instead of a dictionary
Update getwork to prune itself and use a list instead of a dictionary
Python
mit
c00w/bitHopper,c00w/bitHopper
b16016994f20945a8a2bbb63b9cb920d856ab66f
web/attempts/migrations/0008_add_submission_date.py
web/attempts/migrations/0008_add_submission_date.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2017-05-09 09:24 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('attempts', '0007_auto_20161004_0927'), ] operations = [ migrations.AddField(...
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2017-05-09 09:24 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('attempts', '0007_auto_20161004_0927'), ] operations = [ migrations.AddField(...
Revert "Make migration SQLite compatible"
Revert "Make migration SQLite compatible" This reverts commit 768d85cccb17c8757dd8d14dad220d0b87568264.
Python
agpl-3.0
ul-fmf/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo,ul-fmf/projekt-tomo,ul-fmf/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo,matijapretnar/projekt-tomo,matijapretnar/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo
5283bddb36bf4016609c130ddbe63cb234dceb73
tools/ocd_restore.py
tools/ocd_restore.py
#!/usr/bin/env python from pupa.utils import JSONEncoderPlus from contextlib import contextmanager from pymongo import Connection import argparse import json import os parser = argparse.ArgumentParser(description='Re-convert a jurisdiction.') parser.add_argument('--server', type=str, help='Mongo Server', ...
#!/usr/bin/env python from pupa.utils import JSONEncoderPlus from contextlib import contextmanager from pymongo import Connection import argparse import json import sys import os parser = argparse.ArgumentParser(description='Re-convert a jurisdiction.') parser.add_argument('--server', type=str, help='Mongo Server', ...
Add more to the restore script.
Add more to the restore script.
Python
bsd-3-clause
influence-usa/pupa,datamade/pupa,influence-usa/pupa,rshorey/pupa,opencivicdata/pupa,mileswwatkins/pupa,opencivicdata/pupa,rshorey/pupa,mileswwatkins/pupa,datamade/pupa
9663799d57a2790417e7d2fb9b1672de4d3a0059
search.py
search.py
import io import getopt import sys def usage(): print("usage: " + sys.argv[0] + " -d dictionary-file -p postings-file -q file-of-queries -o output-file-of-results") if __name__ == '__main__': dict_file = postings_file = query_file = output_file = None try: opts, args = getopt.getopt(sys.argv[1:], 'd:p:q:o:') ex...
import io import getopt import sys import pickle def usage(): print("usage: " + sys.argv[0] + " -d dictionary-file -p postings-file -q file-of-queries -o output-file-of-results") if __name__ == '__main__': dict_file = postings_file = query_file = output_file = None try: opts, args = getopt.getopt(sys.argv[1:], '...
Implement loading of dictionary and postings list
Implement loading of dictionary and postings list
Python
mit
ikaruswill/vector-space-model,ikaruswill/boolean-retrieval
231902d06b1f7fe3bcd7318f933427cdd3c17d6e
trace_viewer/trace_viewer_project.py
trace_viewer/trace_viewer_project.py
# Copyright (c) 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. import sys import os from tvcm import project as project_module class TraceViewerProject(project_module.Project): trace_viewer_path = os.path.abspat...
# Copyright (c) 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. import sys import os from tvcm import project as project_module class TraceViewerProject(project_module.Project): trace_viewer_path = os.path.abspat...
Allow other_paths to be passed into TraceViewerProject
Allow other_paths to be passed into TraceViewerProject This allows external embedders to subclass TraceViewerProject and thus use trace viewer. git-svn-id: 3a56fcae908c7e16d23cb53443ea4795ac387cf2@1198 0e6d7f2b-9903-5b78-7403-59d27f066143
Python
bsd-3-clause
bpsinc-native/src_third_party_trace-viewer,bpsinc-native/src_third_party_trace-viewer,bpsinc-native/src_third_party_trace-viewer,bpsinc-native/src_third_party_trace-viewer
d924576329c4a1d7814be2ed7da3ddd96a108c47
TotalFile.py
TotalFile.py
# -*- coding: utf-8 -*- import re import sublime, sublime_plugin class TotalFileCommand(sublime_plugin.TextCommand): def run(self, edit): cleaned = [] numbers = [] region = sublime.Region(0, self.view.size()); for lineRegion in self.view.lines(region): line = self.view.substr(lineRegion) if (line == ...
# -*- coding: utf-8 -*- import re import sublime, sublime_plugin class TotalFileCommand(sublime_plugin.TextCommand): def run(self, edit): cleaned = [] numbers = [] region = sublime.Region(0, self.view.size()); for lineRegion in self.view.lines(region): line = self.view.substr(lineRegion) if (line == ...
Handle non-matching lines which don't cause match errors and don't clean the empty lines if there are no cleaned lines
Handle non-matching lines which don't cause match errors and don't clean the empty lines if there are no cleaned lines
Python
mit
RichardHyde/SublimeText.Packages
02b87b94e07626a5db5ef548b234c270e5fb05e0
kboard/board/urls.py
kboard/board/urls.py
# Created by JHJ on 2016. 10. 5. from django.conf.urls import url from . import views app_name = 'board' urlpatterns = [ url(r'^$', views.board_list, name='board_list'), url(r'^(?P<board_slug>[-\w]+)/$', views.post_list, name='post_list'), url(r'^(?P<board_slug>[-\w]+)/new/$', views.new_post, name='new_p...
# Created by JHJ on 2016. 10. 5. from django.conf.urls import url from . import views app_name = 'board' urlpatterns = [ url(r'^$', views.board_list, name='board_list'), url(r'^(?P<board_slug>[-\w]+)/$', views.post_list, name='post_list'), url(r'^(?P<board_slug>[-\w]+)/new/$', views.new_post, name='new_p...
Delete board_slug parameter on 'delete_post' url
Delete board_slug parameter on 'delete_post' url
Python
mit
guswnsxodlf/k-board,cjh5414/kboard,hyesun03/k-board,hyesun03/k-board,cjh5414/kboard,hyesun03/k-board,kboard/kboard,guswnsxodlf/k-board,kboard/kboard,cjh5414/kboard,darjeeling/k-board,kboard/kboard,guswnsxodlf/k-board
f0a20db6da65b82ddafd22effbc0d5a7bb17f9e6
Roman-Numerals/Roman.py
Roman-Numerals/Roman.py
class Roman(object): def __init__(self, number): self.number = number self.modern_convert() convert_table = {} def modern_convert(self): number = self.number solution = [] while True: if number >= 1000: solution.append("M") number -= 1000 elif number >= 500: ...
class Roman(object): def __init__(self, number): self.number = int(number) choice = raw_input("Type Y or N for modern Roman Numeral Convert: ").lower() while True: if choice == "y": print "You made it" elif choice == "n": self.old_roman_convert() break else: ...
Add loops in __init__ for continuous convert
Add loops in __init__ for continuous convert
Python
mit
Bigless27/Python-Projects
9e4ca0829bcd7b3d5181bb452c80fb99c41f9820
source/tyr/tyr/rabbit_mq_handler.py
source/tyr/tyr/rabbit_mq_handler.py
# encoding=utf-8 from kombu import Exchange, Connection, Producer import logging class RabbitMqHandler(object): def __init__(self, connection, exchange_name, type='direct', durable=True): self._logger = logging.getLogger(__name__) try: self._connection = Connection(connection) ...
# encoding=utf-8 from kombu import Exchange, Connection, Producer import logging class RabbitMqHandler(object): def __init__(self, connection, exchange_name, type='direct', durable=True): self._logger = logging.getLogger(__name__) try: self._connection = Connection(connection) ...
Fix error message 'ChannelError: channel disconnected'
Fix error message 'ChannelError: channel disconnected'
Python
agpl-3.0
patochectp/navitia,ballouche/navitia,ballouche/navitia,CanalTP/navitia,patochectp/navitia,kinnou02/navitia,antoine-de/navitia,antoine-de/navitia,patochectp/navitia,pbougue/navitia,xlqian/navitia,pbougue/navitia,xlqian/navitia,Tisseo/navitia,CanalTP/navitia,CanalTP/navitia,ballouche/navitia,Tisseo/navitia,ballouche/navi...
4f7a64f3060c196a434e504847efc511e34537f6
asyncssh/crypto/__init__.py
asyncssh/crypto/__init__.py
# Copyright (c) 2014-2015 by Ron Frederick <ronf@timeheart.net>. # All rights reserved. # # This program and the accompanying materials are made available under # the terms of the Eclipse Public License v1.0 which accompanies this # distribution and is available at: # # http://www.eclipse.org/legal/epl-v10.html # #...
# Copyright (c) 2014-2015 by Ron Frederick <ronf@timeheart.net>. # All rights reserved. # # This program and the accompanying materials are made available under # the terms of the Eclipse Public License v1.0 which accompanies this # distribution and is available at: # # http://www.eclipse.org/legal/epl-v10.html # #...
Allow Curve25519DH import to fail in crypto package
Allow Curve25519DH import to fail in crypto package With the refactoring to avoid pylint warnings, a problem was introduced in importing the crypto module when the curve25519 dependencies were unavailable. This commit fixes that problem.
Python
epl-1.0
jonathanslenders/asyncssh
d85b58a0edce8321312eff66f16fc72439e4426a
app/sense.py
app/sense.py
#!/usr/bin/env python3 from Sensor import SenseController from KeyDispatcher import KeyDispatcher from Display import Display from DataLogger import SQLiteLogger DEVICE = "PiSense" class Handler: def __init__(self, display, logger, sensor): self.display = display self.logger = logger se...
#!/usr/bin/env python3 from Sensor import SenseController from KeyDispatcher import KeyDispatcher from Display import Display from DataLogger import SQLiteLogger import time DEVICE = "PiSense" DELAY = 0.0 class Handler: def __init__(self, display, logger, sensor): self.display = display self.lo...
Add ability to control read rate
Add ability to control read rate
Python
mit
thelonious/g2x,gizmo-cda/g2x,gizmo-cda/g2x,gizmo-cda/g2x,gizmo-cda/g2x,thelonious/g2x
4a476e31d16273afc99abed408efba37936af620
virtool/hmm/utils.py
virtool/hmm/utils.py
import semver import virtool.github def format_hmm_release(updated, release, installed): # The release dict will only be replaced if there is a 200 response from GitHub. A 304 indicates the release # has not changed and `None` is returned from `get_release()`. if updated is None: return None ...
import semver import virtool.github def format_hmm_release(updated, release, installed): # The release dict will only be replaced if there is a 200 response from GitHub. A 304 indicates the release # has not changed and `None` is returned from `get_release()`. if updated is None: return None ...
Fix HMM release formatting bug
Fix HMM release formatting bug
Python
mit
virtool/virtool,virtool/virtool,igboyes/virtool,igboyes/virtool
93873f19a651b786f2413b073a9372dae7bb67a9
codecademy/Car.py
codecademy/Car.py
class Car(object): condition = "new" def __init__(self, model, color, mpg): self.model = model self.color = color self.mpg = mpg def display_car(self): print "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg)) my_car = Car("DeLorean", "silver", 88) pri...
class Car(object): condition = "new" def __init__(self, model, color, mpg): self.model = model self.color = color self.mpg = mpg def display_car(self): print "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg)) def drive_car(self): self.condi...
Add a sub class for car
Add a sub class for car
Python
apache-2.0
haozai309/hello_python
9171777c3945b3a1324d9b20ff607fd340747b58
cinder/version.py
cinder/version.py
# Copyright 2011 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
# Copyright 2011 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
Remove runtime dep on python-pbr, python-d2to1
Remove runtime dep on python-pbr, python-d2to1 Requires RPM spec to fill in REDHATCINDERVERSION.
Python
apache-2.0
redhat-openstack/cinder,redhat-openstack/cinder
2a4891506f02e20d6a6f0e10a346b8fb30d54767
mozaik_membership_payment/models/account_payment.py
mozaik_membership_payment/models/account_payment.py
# Copyright 2018 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, models class AccountPayment(models.Model): _inherit = "account.payment" @api.depends("journal_id", "partner_id", "partner_type", "is_internal_transfer") def _compute_destination_account_i...
# Copyright 2018 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, models from odoo.fields import first class AccountPayment(models.Model): _inherit = "account.payment" @api.depends("journal_id", "partner_id", "partner_type", "is_internal_transfer") def ...
Fix the account for memberships payements
Fix the account for memberships payements
Python
agpl-3.0
mozaik-association/mozaik,mozaik-association/mozaik
2b0a11a1adf4167fb55f9b90fc87a8b8518a24a7
atmo/apps.py
atmo/apps.py
from django.apps import AppConfig from django.conf import settings import session_csrf class AtmoAppConfig(AppConfig): name = 'atmo' def ready(self): # The app is now ready. Include any monkey patches here. # Monkey patch CSRF to switch to session based CSRF. Session # based CSRF wi...
from django.apps import AppConfig from django.conf import settings import session_csrf class AtmoAppConfig(AppConfig): name = 'atmo' def ready(self): # The app is now ready. Include any monkey patches here. # Monkey patch CSRF to switch to session based CSRF. Session # based CSRF wi...
Fix rq jobs registration check
Fix rq jobs registration check
Python
mpl-2.0
mozilla/telemetry-analysis-service,mozilla/telemetry-analysis-service,mozilla/telemetry-analysis-service,mozilla/telemetry-analysis-service
57773d37b20285eba15cc78f4de4e3e344097624
game-log.py
game-log.py
from bs4 import BeautifulSoup, Tag import requests class YahooGameLog: def __init__(self, player_id): page = requests.get('http://sports.yahoo.com/nba/players/' + player_id + '/gamelog/') self.soup = BeautifulSoup(page.text, 'lxml')
from bs4 import BeautifulSoup, Tag import requests class YahooGameLog: def __init__(self, player_id): page = requests.get('http://sports.yahoo.com/nba/players/' + player_id + '/gamelog/') self.soup = BeautifulSoup(page.text, 'lxml') self.column_names = self.get_headers() def get_header...
Add yahoo game log header parsing
Add yahoo game log header parsing
Python
mit
arosenberg01/asdata
f4f4d799409e4869276b84f032e60cdf516fcaf6
src/subcmds/init.py
src/subcmds/init.py
#! /usr/bin/env python import os import subprocess import config NAME="init" HELP="give git issues" def execute(args): # Check to see if the .ghi directories have already been created # If it doesn't exist, create it. if os.path.isdir(config.GHI_DIR) == False: os.makedirs(config.GHI_DIR) os.makedirs(config.IS...
#! /usr/bin/env python import config import os NAME="init" HELP="give git issues" def execute(args): # Check to see if the .ghi directories have already been created # If it doesn't exist, create it. if os.path.isdir(config.GHI_DIR) == False: os.makedirs(config.GHI_DIR) os.makedirs(config.ISSUES_DIR) elif os...
Remove no longer needed import
Remove no longer needed import
Python
apache-2.0
lorneliechty/ghi,lorneliechty/ghi
37defc61f5722a8e988386cb4eed883f2205feb5
luminoso_api/save_token.py
luminoso_api/save_token.py
import argparse import os import sys from urllib.parse import urlparse from .v5_client import LuminosoClient, get_token_filename from .v5_constants import URL_BASE def main(): default_domain_base = urlparse(URL_BASE).netloc default_token_filename = get_token_filename() parser = argparse.ArgumentParser( ...
import argparse import os import sys from urllib.parse import urlparse from .v5_client import LuminosoClient, get_token_filename from .v5_constants import URL_BASE def _main(argv): default_domain_base = urlparse(URL_BASE).netloc default_token_filename = get_token_filename() parser = argparse.ArgumentPars...
Move main() into _main() to make testing easier
Move main() into _main() to make testing easier
Python
mit
LuminosoInsight/luminoso-api-client-python
128a0ae97e86d6dec6c149a7d3f8bccd7f8c499d
agents/DiffAgentBase.py
agents/DiffAgentBase.py
class DiffAgentBase(object): diff = [] noise_reduction = [] latest_observation = 0 current_prediction = [] name = '' behaviour = None working_behaviour_size = 2 def __init__(self, experience, knowledge, space): self.space = space self.experience = experience sel...
class DiffAgentBase(object): diff = [] noise_reduction = [] latest_observation = 0 current_prediction = [] name = '' behaviour = None working_behaviour_size = 2 def __init__(self, experience, knowledge, space): self.space = space self.experience = experience sel...
Break when done copying the working behaviour
Break when done copying the working behaviour
Python
apache-2.0
sergiuionescu/gym-agents
cdefb1fdb304939b35f8c881662fa220a57573dc
members/urls.py
members/urls.py
from django.conf.urls import patterns, url from django.contrib import auth urlpatterns = patterns('members.views', url(r'^login/$', 'login', name='login'), url(r'^logout/$', 'logout', name='logout'), url(r'^search/(?P<name>.*)/$', 'search', name='search'), url(r'^archive/$', 'archive_student_council', ...
from django.conf.urls import patterns, url from django.contrib import auth urlpatterns = patterns('members.views', url(r'^login/$', 'login', name='login'), url(r'^logout/$', 'logout', name='logout'), url(r'^search/(?P<name>.*)/$', 'search', name='search'), url(r'^archive/$', 'archive_student_council', ...
Add url for user's profile
Add url for user's profile
Python
mit
Hackfmi/Diaphanum,Hackfmi/Diaphanum
6d5a37ef127f2b1822645fcad6636880e92d5489
helusers/models.py
helusers/models.py
import uuid import logging from django.db import models from django.contrib.auth.models import AbstractUser as DjangoAbstractUser logger = logging.getLogger(__name__) class AbstractUser(DjangoAbstractUser): uuid = models.UUIDField(primary_key=True) department_name = models.CharField(max_length=50, null=True,...
import uuid import logging from django.db import models from django.contrib.auth.models import AbstractUser as DjangoAbstractUser logger = logging.getLogger(__name__) class AbstractUser(DjangoAbstractUser): uuid = models.UUIDField(primary_key=True) department_name = models.CharField(max_length=50, null=True,...
Remove primary_sid from common fields
Remove primary_sid from common fields
Python
bsd-2-clause
City-of-Helsinki/django-helusers,City-of-Helsinki/django-helusers
8382ee65c87c5eee976d4488ef91bdd5f801c06b
apitestcase/testcase.py
apitestcase/testcase.py
import requests class TestCase(object): """ Add assetion methods for HTTP Requests to TestCase """ def assertRequest(self, method="GET", url="", status_code=200, contains=None, **kwargs): """ Asserts requests on a given endpoint """ if contains is None: ...
import requests class TestCase(object): """ Add assetion methods for HTTP Requests to TestCase """ def assertRequest(self, method="GET", url="", status_code=200, contains=None, **kwargs): """ Asserts requests on a given endpoint """ if contains is None: ...
Remove return statements from assert methods
Remove return statements from assert methods
Python
mit
bramwelt/apitestcase
6e61c41a24e35e66d941b67945f135392b27397d
list_ami_datasets.py
list_ami_datasets.py
""" Groups AMI datasets by pointing direction, then dumps them in JSON format. """ import ami import json ami_rootdir = '/opt/ami' r = ami.Reduce(ami_rootdir) named_groups = r.group_pointings() json.dump(named_groups, open('groups.json', 'w'), sort_keys=True, indent=4)
#!/usr/bin/python """ Groups AMI datasets by pointing direction, then dumps them in JSON format. """ import json import optparse import sys import ami def main(): options, outputfilename = handle_args(sys.argv[1:]) r = ami.Reduce(options.amidir) named_groups = r.group_pointings() json.dump(named_grou...
Make listings script executable, add argument handling.
Make listings script executable, add argument handling.
Python
bsd-3-clause
timstaley/drive-ami
31c360fbdb3aa1393715e53ec4dfd86e59d68249
staticgen_demo/staticgen_views.py
staticgen_demo/staticgen_views.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.utils import translation from cms.models import Title from staticgen.staticgen_pool import staticgen_pool from staticgen.staticgen_views import StaticgenView class StaicgenDemoStaticViews(StaticgenView): ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.dispatch import receiver from django.utils import translation from cms.models import Title from cms.signals import page_moved, post_publish, post_unpublish from staticgen.models import Page from staticgen.st...
Mark CMS pages as changed .. using CMS publisher signals.
Mark CMS pages as changed .. using CMS publisher signals.
Python
bsd-3-clause
mishbahr/staticgen-demo,mishbahr/staticgen-demo,mishbahr/staticgen-demo
50d447a546cd939594aeb8fda84167cef27f0d5e
msmbuilder/scripts/msmb.py
msmbuilder/scripts/msmb.py
"""Statistical models for biomolecular dynamics""" from __future__ import print_function, absolute_import, division import sys from ..cmdline import App from ..commands import * from ..version import version # the commands register themselves when they're imported class MSMBuilderApp(App): def _subcommands(self):...
"""Statistical models for biomolecular dynamics""" from __future__ import print_function, absolute_import, division import sys from ..cmdline import App from ..commands import * from ..version import version # the commands register themselves when they're imported # Load external commands which register themselves # w...
Load plugins from entry point
Load plugins from entry point
Python
lgpl-2.1
brookehus/msmbuilder,stephenliu1989/msmbuilder,peastman/msmbuilder,brookehus/msmbuilder,dr-nate/msmbuilder,dotsdl/msmbuilder,peastman/msmbuilder,msultan/msmbuilder,mpharrigan/mixtape,stephenliu1989/msmbuilder,cxhernandez/msmbuilder,rmcgibbo/msmbuilder,cxhernandez/msmbuilder,msultan/msmbuilder,brookehus/msmbuilder,steph...
f9d63b418f69c77b01f9bed1d05fecdf8c028e7e
mvw/generator.py
mvw/generator.py
import os class Generator: def run(self, sourcedir, outputdir): sourcedir = os.path.normpath(sourcedir) outputdir = os.path.normpath(outputdir) prefix = len(sourcedir)+len(os.path.sep) for root, dirs, files in os.walk(sourcedir): relpath = os.path.join(outputdir, root[pr...
import os class Generator: def run(self, sourcedir, outputdir): sourcedir = os.path.normpath(sourcedir) outputdir = os.path.normpath(outputdir) prefix = len(sourcedir)+len(os.path.sep) for root, dirs, files in os.walk(sourcedir): destpath = os.path.join(outputdir, root[...
Call parse with markdown files, copy otherwise
Call parse with markdown files, copy otherwise
Python
mit
kevinbeaty/mvw
931024e081d380a5f754920c7992b359ce2cd2de
celery_progress/__init__.py
celery_progress/__init__.py
from django.conf import settings from django.utils.module_loading import import_by_path BACKEND = getattr(settings, 'CELERY_PROGRESS_BACKEND', 'celery_progress.backends.CeleryBackend') def get_backend(): return import_by_path(BACKEND) backend = get_backend()()
from django.conf import settings from django.utils.module_loading import import_by_path BACKEND = getattr(settings.configure(), 'CELERY_PROGRESS_BACKEND', 'celery_progress.backends.CeleryBackend') def get_backend(): return import_by_path(BACKEND) backend = get_backend()()
Call configure() on settings to ensure that the CELERY_PROGRESS_BACKEND variable can be picked up
Call configure() on settings to ensure that the CELERY_PROGRESS_BACKEND variable can be picked up
Python
bsd-3-clause
annaisystems/django-celery-progress,annaisystems/django-celery-progress,annaisystems/django-celery-progress
18cbf5c9b357dc2941fd268b87a65649a086ab01
IPython/html/widgets/widget_output.py
IPython/html/widgets/widget_output.py
"""Output class. Represents a widget that can be used to display output within the widget area. """ # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from .widget import DOMWidget import sys from IPython.utils.traitlets import Unicode, List from IPython.display im...
"""Output class. Represents a widget that can be used to display output within the widget area. """ # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from .widget import DOMWidget import sys from IPython.utils.traitlets import Unicode, List from IPython.display im...
Add doc string to Output widget
Add doc string to Output widget
Python
bsd-3-clause
ipython/ipython,ipython/ipython
b6b9c6f3f8faaade428d044f93acd25edade075d
tools/pdtools/pdtools/__main__.py
tools/pdtools/pdtools/__main__.py
""" Paradrop command line utility. Environment Variables: PDSERVER_URL Paradrop controller URL [default: https://paradrop.org]. """ import os import click from . import chute from . import device from . import routers from . import store PDSERVER_URL = os.environ.get("PDSERVER_URL", "https://paradrop.org") ...
""" Paradrop command line utility. Environment Variables: PDSERVER_URL Paradrop controller URL [default: https://paradrop.org]. """ import os import click from . import chute from . import device from . import routers from . import store PDSERVER_URL = os.environ.get("PDSERVER_URL", "https://paradrop.org") ...
Enable '-h' help option from the pdtools root level.
Enable '-h' help option from the pdtools root level.
Python
apache-2.0
ParadropLabs/Paradrop,ParadropLabs/Paradrop,ParadropLabs/Paradrop
d546d6901859a5fee8a16ffea6df560ecbb1e280
tests/unit_tests.py
tests/unit_tests.py
#!/usr/bin/env python import os import sys import unittest parentDir = os.path.join(os.path.dirname(__file__), "../") sys.path.insert(0, parentDir) from oxyfloat import OxyFloat class DataTest(unittest.TestCase): def setUp(self): self.of = OxyFloat() def test_get_oxyfloats(self): float_list ...
#!/usr/bin/env python import os import sys import unittest parentDir = os.path.join(os.path.dirname(__file__), "../") sys.path.insert(0, parentDir) from oxyfloat import OxyFloat class DataTest(unittest.TestCase): def setUp(self): self.of = OxyFloat() def test_get_oxyfloats(self): self.oga_fl...
Add tests for reading profile data
Add tests for reading profile data
Python
mit
biofloat/biofloat,MBARIMike/biofloat,biofloat/biofloat,MBARIMike/biofloat,MBARIMike/oxyfloat,MBARIMike/oxyfloat
39f44c926eb16f2cd57fa344318bce652b158a3a
tests/shape/test_basic.py
tests/shape/test_basic.py
import pytest from unittest import TestCase from stylo.shape import Ellipse, Circle, Rectangle, Square from stylo.testing.shape import BaseShapeTest @pytest.mark.shape class TestEllipse(TestCase, BaseShapeTest): """Tests for the :code:`Ellipse` shape.""" def setUp(self): self.shape = Ellipse(0, 0, 1...
import pytest from unittest import TestCase from stylo.shape import Ellipse, Circle, Rectangle, Square, Triangle from stylo.testing.shape import BaseShapeTest @pytest.mark.shape class TestEllipse(TestCase, BaseShapeTest): """Tests for the :code:`Ellipse` shape.""" def setUp(self): self.shape = Ellip...
Add Triangle to shape tests
Add Triangle to shape tests
Python
mit
alcarney/stylo,alcarney/stylo
ca641bb6bfc65d82564cee684bc3192986806b71
vdb/flu_download.py
vdb/flu_download.py
import os,datetime from download import download from download import get_parser class flu_download(download): def __init__(self, **kwargs): download.__init__(self, **kwargs) if __name__=="__main__": parser = get_parser() args = parser.parse_args() fasta_fields = ['strain', 'virus', 'accession...
import os,datetime from download import download from download import get_parser class flu_download(download): def __init__(self, **kwargs): download.__init__(self, **kwargs) if __name__=="__main__": parser = get_parser() args = parser.parse_args() fasta_fields = ['strain', 'virus', 'accession...
Revise flu fasta fields to interface with nextflu.
Revise flu fasta fields to interface with nextflu.
Python
agpl-3.0
blab/nextstrain-db,nextstrain/fauna,nextstrain/fauna,blab/nextstrain-db
215401f586a6960c4165debf698f3a95c75a178b
comrade/views/simple.py
comrade/views/simple.py
from django.http import HttpResponse, HttpResponseServerError from django.template import RequestContext, loader from django.conf import settings from maintenancemode.http import HttpResponseTemporaryUnavailable import logging logger = logging.getLogger('comrade.views.simple') def status(request): logger.info("R...
from django.http import HttpResponse, HttpResponseServerError from django.template import RequestContext, loader from django.conf import settings from maintenancemode.http import HttpResponseTemporaryUnavailable import logging logger = logging.getLogger('comrade.views.simple') def status(request): logger.info("R...
Make status the last optional arg.
Make status the last optional arg.
Python
mit
bueda/django-comrade
80347266377f01932fe8277c7a12ce87663b9018
comtypes/messageloop.py
comtypes/messageloop.py
import ctypes from ctypes import WinDLL, byref, WinError from ctypes.wintypes import MSG _user32 = WinDLL("user32") GetMessage = _user32.GetMessageA GetMessage.argtypes = [ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint, ctypes.c_uint, ] TranslateMessage = _user32.TranslateMessage Dispatc...
import ctypes from ctypes import WinDLL, byref, WinError from ctypes.wintypes import MSG _user32 = WinDLL("user32") GetMessage = _user32.GetMessageA GetMessage.argtypes = [ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint, ctypes.c_uint, ] TranslateMessage = _user32.TranslateMessage Dispatc...
Use any for concise code
Use any for concise code
Python
mit
denfromufa/comtypes,denfromufa/comtypes,denfromufa/comtypes,denfromufa/comtypes,denfromufa/comtypes
c326becad43949999d151cd1e10fcb75f9d2b148
lib/constants.py
lib/constants.py
SQL_PORT = 15000 JSON_RPC_PORT = 15598 HTTP_PORT = 15597 JSON_PUBSUB_PORT = 15596
SQL_PORT = 15000 JSON_RPC_PORT = 15598 HTTP_PORT = 15597 HTTPS_PORT = 443 JSON_PUBSUB_PORT = 15596
Add missing constant for ssl listener.
Add missing constant for ssl listener.
Python
apache-2.0
MediaMath/qasino,MediaMath/qasino
cd6752a2866631eeea0dcbcf37f24d825f5e4a50
vpc/vpc_content/search_indexes.py
vpc/vpc_content/search_indexes.py
import datetime from haystack.indexes import SearchIndex, CharField, DateTimeField from haystack import site from models import Author, Material class AuthorIndex(SearchIndex): # the used template contains fullname and author bio # Zniper thinks this line below also is OK: # text = CharField(document=True...
import datetime from haystack.indexes import SearchIndex, RealTimeSearchIndex from haystack.indexes import CharField, DateTimeField from haystack import site from models import Author, Material class AuthorIndex(RealTimeSearchIndex): # the used template contains fullname and author bio # Zniper thinks this li...
Make indexing on real time
Make indexing on real time
Python
agpl-3.0
voer-platform/vp.repo,voer-platform/vp.repo,voer-platform/vp.repo,voer-platform/vp.repo
611165bccb307611945f7a44ecb8f66cf4381da6
dbconnect.py
dbconnect.py
import MySQLdb def connection(): conn = MySQLdb.connect(host="localhost", user="root", passwd="gichin124", db="tripmeal") c = conn.cursor() return c, conn
import MySQLdb import urlparse import os urlparse.uses_netloc.append('mysql') try: if 'DATABASES' not in locals(): DATABASES = {} if 'DATABASE_URL' in os.environ: url = urlparse.urlparse(os.environ['DATABASE_URL']) # Ensure default database exists. DATABASES['default'] = DATA...
Add the new settings for the database
Add the new settings for the database
Python
mit
DanielAndreasen/TripMeal,DanielAndreasen/TripMeal
d0c8968766a06e8c426e75edddb9c6ce88d080a0
fsspec/implementations/tests/test_common.py
fsspec/implementations/tests/test_common.py
import datetime import pytest from fsspec import AbstractFileSystem from fsspec.implementations.tests.conftest import READ_ONLY_FILESYSTEMS TEST_FILE = 'file' @pytest.mark.parametrize("fs", ['local'], indirect=["fs"]) def test_created(fs: AbstractFileSystem): try: fs.touch(TEST_FILE) created = ...
import datetime import pytest from fsspec import AbstractFileSystem from fsspec.implementations.tests.conftest import READ_ONLY_FILESYSTEMS TEST_FILE = 'file' @pytest.mark.parametrize("fs", ['local'], indirect=["fs"]) def test_created(fs: AbstractFileSystem): try: fs.touch(TEST_FILE) created = ...
Fix typo in test assertion
Fix typo in test assertion
Python
bsd-3-clause
fsspec/filesystem_spec,intake/filesystem_spec,fsspec/filesystem_spec
80e5af1599303cd012a348c7d5503bdfca433ce2
tests/test_manager.py
tests/test_manager.py
def test_ensure_authority(manager_transaction): authority1 = manager_transaction.ensure_authority( name='Test Authority', rank=0, cardinality=1234 ) assert authority1.name == 'Test Authority' assert authority1.rank == 0 assert authority1.cardinality == 1234 authority2 = ...
def test_ensure_authority(manager_transaction): authority1 = manager_transaction.ensure_authority( name='Test Authority', cardinality=1234 ) assert authority1.name == 'Test Authority' assert authority1.cardinality == 1234 authority2 = manager_transaction.ensure_authority( na...
Fix the one measly test
Fix the one measly test
Python
mit
scolby33/OCSPdash,scolby33/OCSPdash,scolby33/OCSPdash
4a838a3e1df1f832a013b3e8a18e5474b06d0f9a
easy_bake.py
easy_bake.py
import RPi.GPIO as gpio import time #use board numbering on the pi gpio.setmode(gpio.BOARD) gpio.setup(40, gpio.OUT) gpio.setup(38, gpio.OUT) #true and 1 are the same gpio.output(40, True) gpio.output(38, 1) while True: gpio.output(40, True) gpio.output(38, False) time.sleep(4) gpio.output(40, 0) gpio.ou...
import RPi.GPIO as gpio import time #use board numbering on the pi gpio.setmode(gpio.BOARD) output_pins = [40, 38] gpio.setup(output_pins, gpio.OUT) #true and 1 are the same # gpio.output(40, True) # gpio.output(38, 1) while True: gpio.output(output_pins, (True, False)) # gpio.output(40, True) # gpio.output(...
Add in array or tuple of pins
Add in array or tuple of pins
Python
mit
emgreen33/easy_bake,emgreen33/easy_bake
f542b05f9a344c6a39b6ed3b163deddc3086be26
pybinding/model.py
pybinding/model.py
import _pybinding from scipy.sparse import csr_matrix as _csrmatrix class Model(_pybinding.Model): def __init__(self, *params): super().__init__() self.add(*params) def add(self, *params): for param in params: if param is None: continue if isin...
import _pybinding from scipy.sparse import csr_matrix as _csrmatrix from .system import System as _System from .hamiltonian import Hamiltonian as _Hamiltonian from .solver.solver_ex import SolverEx as _Solver class Model(_pybinding.Model): def __init__(self, *params): super().__init__() self.add(*...
Annotate return types of Model properties
Annotate return types of Model properties
Python
bsd-2-clause
MAndelkovic/pybinding,dean0x7d/pybinding,dean0x7d/pybinding,MAndelkovic/pybinding,MAndelkovic/pybinding,dean0x7d/pybinding
259a4377b19f1140d46a5c8f7389121806fe7e01
pombola/south_africa/urls.py
pombola/south_africa/urls.py
from django.conf.urls import patterns, include, url from pombola.south_africa.views import LatLonDetailView, SAPlaceDetailSub, SAOrganisationDetailView urlpatterns = patterns('pombola.south_africa.views', url(r'^place/latlon/(?P<lat>[0-9\.-]+),(?P<lon>[0-9\.-]+)/', LatLonDetailView.as_view(), name='latlon'), ...
from django.conf.urls import patterns, include, url from pombola.south_africa.views import LatLonDetailView, SAPlaceDetailSub, SAOrganisationDetailView from pombola.core.urls import organisation_patterns # Override the organisation url so we can vary it depending on the organisation type. for index, pattern in enumer...
Use a different method to override the url in SA
Use a different method to override the url in SA This is not an ideal solution, but seems to do the job. The problem with the way it was previously was that it the /organisation/all route way getting skipped as the /organisation/:slug route was always matching.
Python
agpl-3.0
mysociety/pombola,ken-muturi/pombola,patricmutwiri/pombola,patricmutwiri/pombola,mysociety/pombola,ken-muturi/pombola,mysociety/pombola,ken-muturi/pombola,patricmutwiri/pombola,mysociety/pombola,hzj123/56th,geoffkilpin/pombola,hzj123/56th,mysociety/pombola,geoffkilpin/pombola,ken-muturi/pombola,geoffkilpin/pombola,geof...
0b1d2a43e4f9858bcb9d9bf9edf3dfae417f133d
satchless/util/__init__.py
satchless/util/__init__.py
from decimal import Decimal from django.http import HttpResponse from django.utils import simplejson def decimal_format(value, min_decimal_places=0): decimal_tuple = value.as_tuple() have_decimal_places = -decimal_tuple.exponent digits = list(decimal_tuple.digits) while have_decimal_places < min_decima...
from decimal import Decimal from django.http import HttpResponse from django.utils import simplejson def decimal_format(value, min_decimal_places=0): decimal_tuple = value.as_tuple() have_decimal_places = -decimal_tuple.exponent digits = list(decimal_tuple.digits) while have_decimal_places < min_decima...
Add a huge hack to treat Decimals like floats
Add a huge hack to treat Decimals like floats This commit provided to you by highly trained professional stuntmen, do not try to reproduce any of this at home!
Python
bsd-3-clause
taedori81/satchless,fusionbox/satchless,fusionbox/satchless,fusionbox/satchless
17080ab6511d045b0bc27b3c04102fbcefa5c330
modules/icons.py
modules/icons.py
import sublime from os import path _plugin_name = "Git Conflict Resolver" _icon_folder = path.join(_plugin_name, "gutter") _icons = { "ours": "ours", "ancestor": "ancestor", "theirs": "theirs" } def get(group): base = "" extension = "" if int(sublime.version()) < 3000: base = path.j...
import sublime _plugin_name = "Git Conflict Resolver" _icon_folder = "/".join([_plugin_name, "gutter"]) _icons = { "ours": "ours", "ancestor": "ancestor", "theirs": "theirs" } def get(group): base = "" extension = "" if int(sublime.version()) < 3000: base = "/".join(["..", _icon_fold...
Fix sublime icon pathing by using "/" instead of os.path.join
Fix sublime icon pathing by using "/" instead of os.path.join
Python
mit
Zeeker/sublime-GitConflictResolver,Zeeker/sublime-GitConflictResolver
5cf8f3326b6995a871df7f2b61b25ff529216103
recordpeeker/command_line.py
recordpeeker/command_line.py
import argparse import os import json import sys def parse_args(argv): parser = argparse.ArgumentParser("Test") parser.add_argument("--port", "-p", type=int, default=8080, help="Specify the port recordpeeker runs on") parser.add_argument("--verbosity", "-v", default=0, type=int, choices=[0,1,2,3], help="Sp...
import argparse import os import json import sys def parse_args(argv): parser = argparse.ArgumentParser("Test") parser.add_argument("--port", "-p", type=int, default=8080, help="Specify the port recordpeeker runs on") parser.add_argument("--verbosity", "-v", default=0, type=int, choices=[0,1,2,3], help="Sp...
Fix bustage for script calls
Fix bustage for script calls
Python
mit
jonchang/recordpeeker
f3875b1d9aed5f847b11846a27f7652e4c548b6c
modules/karma.py
modules/karma.py
import discord from modules.botModule import BotModule class Karma(BotModule): name = 'karma' description = 'Monitors messages for reactions and adds karma accordingly.' help_text = 'This module has no callable functions' trigger_string = '!reddit' listen_for_reaction = True...
import discord from modules.botModule import BotModule class Karma(BotModule): name = 'karma' description = 'Monitors messages for reactions and adds karma accordingly.' help_text = 'This module has no callable functions' trigger_string = '!reddit' module_db = 'karma.json' ...
Add logic and code for database operations (untested)
Add logic and code for database operations (untested)
Python
mit
suclearnub/scubot
cd8fe432077bdd65122189dd9191d7a5b8788e48
reinforcement-learning/play.py
reinforcement-learning/play.py
"""This is the agent which currently takes the action with highest immediate reward.""" import env import time env.make("pygame") for episode in range(10): env.reset() episode_reward = 0 for t in range(100): episode_reward += env.actual_reward if env.done: print( ...
"""This is the agent which currently takes the action with highest immediate reward.""" import time start = time.time() import env import rl env.make("text") for episode in range(1000): env.reset() episode_reward = 0 for t in range(100): episode_reward += env.actual_reward if env.done: ...
Use proper q learning for agent.
Use proper q learning for agent.
Python
mit
danieloconell/Louis
fd6cc34c682c773273bcdd9d09d2f7f2e4d91700
ocr/tfhelpers.py
ocr/tfhelpers.py
# -*- coding: utf-8 -*- """ Loading and using trained models from tensorflow """ import tensorflow as tf class Graph(): """ Loading and running isolated tf graph """ def __init__(self, loc): self.graph = tf.Graph() self.sess = tf.Session(graph=self.graph) with self.graph.as_default(): ...
# -*- coding: utf-8 -*- """ Loading and using trained models from tensorflow """ import tensorflow as tf class Graph(): """ Loading and running isolated tf graph """ def __init__(self, loc, operation='activation', input_name='x'): """ loc: location of file containing saved model operati...
Update Graph class for loading saved models Requires renaming operations in models -> re-train them
Update Graph class for loading saved models Requires renaming operations in models -> re-train them
Python
mit
Breta01/handwriting-ocr
bb4c1375082d68a78e194d3d1d3399eadc0d1b12
dlstats/errors.py
dlstats/errors.py
class DlstatsException(Exception): def __init__(self, *args, **kwargs): self.provider_name = kwargs.pop("provider_name", None) self.dataset_code = kwargs.pop("dataset_code", None) super().__init__(*args, **kwargs) class RejectFrequency(DlstatsException): def __init__(self, *args,...
class DlstatsException(Exception): def __init__(self, *args, **kwargs): self.provider_name = kwargs.pop("provider_name", None) self.dataset_code = kwargs.pop("dataset_code", None) self.comments = kwargs.pop("comments", None) super().__init__(*args, **kwargs) class RejectFreque...
Add exception for interrupt data process
Add exception for interrupt data process
Python
agpl-3.0
Widukind/dlstats,Widukind/dlstats
aa8117c288fc45743554450448178c47246b088f
devicehive/transport.py
devicehive/transport.py
def init(name, data_format_class, data_format_options, handler_class, handler_options): transport_class_name = '%sTransport' % name.title() transport_module = __import__('devicehive.transports.%s_transport' % name, fromlist=[transport_class_name]) return getattr(tr...
def init(name, data_format_class, data_format_options, handler_class, handler_options): transport_class_name = '%sTransport' % name.title() transport_module = __import__('devicehive.transports.%s_transport' % name, fromlist=[transport_class_name]) return getattr(tr...
Remove Request and Response classes
Remove Request and Response classes
Python
apache-2.0
devicehive/devicehive-python
a626e97bdb8816ed46760c55ad402b64e391538a
revenue/admin.py
revenue/admin.py
from django.contrib import admin from django.core.exceptions import ValidationError from django.forms import BaseInlineFormSet, ModelForm from django.utils.translation import ugettext_lazy as _ from revenue.models import Receipt, FeeLine class FeeLinesInlineFormSet(BaseInlineFormSet): def clean(self): su...
from django.contrib import admin from django.core.exceptions import ValidationError from django import forms from django.utils.translation import ugettext_lazy as _ from revenue.models import Receipt, FeeLine class FeeLinesInlineFormSet(forms.BaseInlineFormSet): def clean(self): super(FeeLinesInlineFormS...
Fix how we calculate total to really account for deleted objects
Fix how we calculate total to really account for deleted objects
Python
mpl-2.0
jackbravo/condorest-django,jackbravo/condorest-django,jackbravo/condorest-django
c2a3d8621e01d453da0043f5fe9afeba0a064224
presets/icons.py
presets/icons.py
import os import bpy import bpy.utils.previews from .. import util asset_previews = bpy.utils.previews.new() def load_previews(lib, start=0): global asset_previews enum_items = [] lib_dir = presets_library = util.get_addon_prefs().presets_library.path for i,asset in enumerate(lib.presets): p...
import os import bpy import bpy.utils.previews from .. import util asset_previews = bpy.utils.previews.new() def get_presets_for_lib(lib): items = list(lib.presets) for sub_group in lib.sub_groups: items.extend(get_presets_for_lib(sub_group)) return items def load_previews(lib): global asset_...
Fix order in icon preview.
Fix order in icon preview.
Python
mit
prman-pixar/RenderManForBlender,adminradio/RenderManForBlender,prman-pixar/RenderManForBlender
0298ace270749a6de89595a5bb566739dc63b16e
jsk_apc2016_common/scripts/install_trained_data.py
jsk_apc2016_common/scripts/install_trained_data.py
#!/usr/bin/env python from jsk_data import download_data def main(): PKG = 'jsk_apc2016_common' download_data( pkg_name=PKG, path='trained_data/vgg16_96000.chainermodel', url='https://drive.google.com/uc?id=0B9P1L--7Wd2vOTdzOGlJcGM1N00', md5='3c993d333cf554684b5162c9f69b20cf'...
#!/usr/bin/env python from jsk_data import download_data def main(): PKG = 'jsk_apc2016_common' download_data( pkg_name=PKG, path='trained_data/vgg16_96000.chainermodel', url='https://drive.google.com/uc?id=0B9P1L--7Wd2vOTdzOGlJcGM1N00', md5='3c993d333cf554684b5162c9f69b20cf'...
Add vgg16 trained_data to download
Add vgg16 trained_data to download
Python
bsd-3-clause
pazeshun/jsk_apc,pazeshun/jsk_apc,pazeshun/jsk_apc,pazeshun/jsk_apc,pazeshun/jsk_apc
7bcc78cd428fa6d76c11b2f19886ec5e798411c6
pavement.py
pavement.py
from paver.easy import * @task def release_unix(): sh('python setup.py clean') sh('rm -f h5py_config.pickle') sh('python setup.py build --hdf5-version=1.8.4 --mpi=no') sh('python setup.py test') sh('python setup.py sdist') print("Unix release done. Distribution tar file is in dist/") @task de...
from paver.easy import * @task def release_unix(): sh('python setup.py clean') sh('rm -f h5py_config.pickle') sh('python setup.py build --hdf5-version=1.8.4 --mpi=no') sh('python setup.py test') sh('python setup.py sdist') print("Unix release done. Distribution tar file is in dist/") @task de...
Add pre-release git paver task
Add pre-release git paver task
Python
bsd-3-clause
h5py/h5py,h5py/h5py,h5py/h5py
3e81a2bfd026475b9ab0548c3127aa102066707d
guest-talks/20170828-oo-intro/exercises/test_square_grid.py
guest-talks/20170828-oo-intro/exercises/test_square_grid.py
import unittest from square_grid import SquareGrid class TestSquareGrid(unittest.TestCase): def setUp(self): a = [0] * 3 b = [1] * 3 c = [2] * 3 self.matrix= [a,b,c] self.good_grid = SquareGrid(self.matrix) def test_error_on_mixed_dimensions(self): """Test objec...
import unittest from square_grid import SquareGrid class TestSquareGrid(unittest.TestCase): def setUp(self): a = [0] * 3 b = [1] * 3 c = [2] * 3 self.matrix= [a,b,c] self.good_grid = SquareGrid(self.matrix) def test_error_on_mixed_dimensions(self): """Test objec...
Use literals in tests instead of code ;)
Use literals in tests instead of code ;)
Python
mit
noisebridge/PythonClass,razzius/PyClassLessons,PyClass/PyClassLessons,PyClass/PyClassLessons,noisebridge/PythonClass,razzius/PyClassLessons,noisebridge/PythonClass,razzius/PyClassLessons,noisebridge/PythonClass,PyClass/PyClassLessons,razzius/PyClassLessons
b57be89c94d050dd1e5f4279f91170982b00cc2e
polyaxon/clusters/management/commands/clean_experiments.py
polyaxon/clusters/management/commands/clean_experiments.py
from django.core.management import BaseCommand from experiments.models import Experiment from spawner import scheduler from spawner.utils.constants import ExperimentLifeCycle class Command(BaseCommand): def handle(self, *args, **options): for experiment in Experiment.objects.filter( exper...
from django.core.management import BaseCommand from experiments.models import Experiment from spawner import scheduler from spawner.utils.constants import ExperimentLifeCycle class Command(BaseCommand): def handle(self, *args, **options): for experiment in Experiment.objects.filter( exper...
Update status when stopping experiments
Update status when stopping experiments
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
48ee32acb12519dc644dce5b4f95d285a3176242
flocker/restapi/_logging.py
flocker/restapi/_logging.py
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ This module defines the Eliot log events emitted by the API implementation. """ __all__ = [ "JSON_REQUEST", "REQUEST", ] from eliot import Field, ActionType LOG_SYSTEM = u"api" METHOD = Field.forTypes( u"method", [unicode, bytes], u"T...
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ This module defines the Eliot log events emitted by the API implementation. """ __all__ = [ "JSON_REQUEST", "REQUEST", ] from eliot import Field, ActionType LOG_SYSTEM = u"api" METHOD = Field(u"method", lambda method: method, ...
Address review comment: Just pass through fields we aren't changing.
Address review comment: Just pass through fields we aren't changing.
Python
apache-2.0
Azulinho/flocker,lukemarsden/flocker,mbrukman/flocker,agonzalezro/flocker,achanda/flocker,Azulinho/flocker,1d4Nf6/flocker,runcom/flocker,LaynePeng/flocker,moypray/flocker,lukemarsden/flocker,achanda/flocker,wallnerryan/flocker-profiles,AndyHuu/flocker,Azulinho/flocker,runcom/flocker,1d4Nf6/flocker,adamtheturtle/flocker...
c9ca005e8129c784e108bb77719f201e110433f1
settings/models.py
settings/models.py
from django.db import models # Create your models here. class GlobalSettings(models.Model): DOMAIN_NAME = 'FQDN' FORCE_HTTPS = 'HTTPS' ADMIN_MAIL = 'ADM_MAIL' ADMIN_NAME = 'ADM_NAME' KEY_CHOICES = ( (DOMAIN_NAME, 'Domain Name'), (FORCE_HTTPS, 'Force HTTPS'), (ADMIN_MAIL, 'Admin de-mail'), (ADMIN_NAME, ...
from django.db import models # Create your models here. class GlobalSettings(models.Model): DOMAIN_NAME = 'FQDN' FORCE_HTTPS = 'HTTPS' ADMIN_MAIL = 'ADM_MAIL' ADMIN_NAME = 'ADM_NAME' KEY_CHOICES = ( (DOMAIN_NAME, 'Domain Name'), (FORCE_HTTPS, 'Force HTTPS'), (ADMIN_MAIL, 'Admin de-mail'), (ADMIN_NAME, ...
Fix uniqueness for voting systems
Fix uniqueness for voting systems
Python
mit
kuboschek/jay,OpenJUB/jay,kuboschek/jay,kuboschek/jay,OpenJUB/jay,OpenJUB/jay
7938589c950b9b36d215aa85224c931a080c104e
statsd/gauge.py
statsd/gauge.py
import statsd import decimal class Gauge(statsd.Client): '''Class to implement a statsd gauge ''' def send(self, subname, value): '''Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :keyword...
import statsd from . import compat class Gauge(statsd.Client): '''Class to implement a statsd gauge ''' def send(self, subname, value): '''Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :...
Use compat.NUM_TYPES due to removal of long in py3k
Use compat.NUM_TYPES due to removal of long in py3k
Python
bsd-3-clause
wolph/python-statsd
9e62292ed25860a2e376c5d98c8ff7762bc1346b
scripts/slave/chromium/dart_buildbot_run.py
scripts/slave/chromium/dart_buildbot_run.py
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Entry point for the dartium buildbots. This script is called from buildbot and reports results using the buildbot annotation sc...
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Entry point for the dartium buildbots. This script is called from buildbot and reports results using the buildbot annotation sc...
Use the annotated steps from the dart dir
Use the annotated steps from the dart dir TBR=whesse Review URL: https://codereview.chromium.org/352223009 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@280292 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
eunchong/build,eunchong/build,eunchong/build,eunchong/build
10009f8a19b417359d41a5e83ff5083e6862b891
algorithms/math/sieve_eratosthenes.py
algorithms/math/sieve_eratosthenes.py
""" sieve_eratosthenes.py Implementation of the Sieve of Eratosthenes algorithm. Depth First Search Overview: ------------------------ Is a simple, ancient algorithm for finding all prime numbers up to any given limit. It does so by iteratively marking as composite (i.e. not prime) the m...
""" sieve_eratosthenes.py Implementation of the Sieve of Eratosthenes algorithm. Sieve of Eratosthenes Overview: ------------------------ Is a simple, ancient algorithm for finding all prime numbers up to any given limit. It does so by iteratively marking as composite (i.e. not prime) th...
Fix Sieve of Eratosthenes Overview header
Fix Sieve of Eratosthenes Overview header
Python
bsd-3-clause
rexshihaoren/algorithms,stphivos/algorithms
0701e34c76a4ea55b1334c9b48c88fd346f49fa2
nazs/apps.py
nazs/apps.py
# -*- coding: utf-8 -*- # # NAZS # Copyright (C) 2014 Carlos Pérez-Aradros Herce <exekias@gmail.com> # # 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...
# -*- coding: utf-8 -*- # # NAZS # Copyright (C) 2014 Carlos Pérez-Aradros Herce <exekias@gmail.com> # # 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...
Stop auto creation of shm database
Stop auto creation of shm database
Python
agpl-3.0
exekias/droplet,exekias/droplet,exekias/droplet
5e7daffadbd523e1d2a457d10977b1c8a2880d9d
docs/example-plugins/directAPIcall.py
docs/example-plugins/directAPIcall.py
from __future__ import unicode_literals from client import slack_client as sc for user in sc.api_call("users.list")["members"]: print(user["name"], user["id"])
from __future__ import unicode_literals from client import slack_client as sc def process_message(data): '''If a user passes 'print users' in a message, print the users in the slack team to the console. (Don't run this in production probably)''' if 'print users' in data['text']: for user in sc.ap...
Add a bit more info into the example plugin.
Add a bit more info into the example plugin.
Python
mit
erynofwales/ubot2,aerickson/python-rtmbot,jammons/python-rtmbot,slackhq/python-rtmbot,ChihChengLiang/python-rtmbot,erynofwales/ubot2
9883a1ac995816160a35fd66107a576289062123
apis/betterself/v1/events/views.py
apis/betterself/v1/events/views.py
from apis.betterself.v1.events.serializers import SupplementEventSerializer from apis.betterself.v1.utils.views import BaseGenericListCreateAPIViewV1 from events.models import SupplementEvent class SupplementEventView(BaseGenericListCreateAPIViewV1): serializer_class = SupplementEventSerializer model = Supple...
from apis.betterself.v1.events.serializers import SupplementEventSerializer from apis.betterself.v1.utils.views import BaseGenericListCreateAPIViewV1 from events.models import SupplementEvent class SupplementEventView(BaseGenericListCreateAPIViewV1): serializer_class = SupplementEventSerializer model = Supple...
Add queryset, but debate if better options
Add queryset, but debate if better options
Python
mit
jeffshek/betterself,jeffshek/betterself,jeffshek/betterself,jeffshek/betterself
a397f781751536f07e41644f8331990f5e0e8803
aiofiles/__init__.py
aiofiles/__init__.py
"""Utilities for asyncio-friendly file handling.""" from .threadpool import open __version__ = "0.7.0dev0" __all__ = ["open"]
"""Utilities for asyncio-friendly file handling.""" from .threadpool import open from . import tempfile __version__ = "0.7.0dev0" __all__ = ['open', 'tempfile']
Add files via upload Rebase
Add files via upload Rebase
Python
apache-2.0
Tinche/aiofiles
f83a2dd996ad8f1f0807e4ef877df52d62a4ce45
tests/test_particle_restart/test_particle_restart.py
tests/test_particle_restart/test_particle_restart.py
#!/usr/bin/env python import os from subprocess import Popen, STDOUT, PIPE pwd = os.path.dirname(__file__) def setup(): os.putenv('PWD', pwd) os.chdir(pwd) def test_run(): proc = Popen([pwd + '/../../src/openmc'], stderr=STDOUT, stdout=PIPE) returncode = proc.wait() print(proc.communicate()[0])...
#!/usr/bin/env python import os from subprocess import Popen, STDOUT, PIPE pwd = os.path.dirname(__file__) def setup(): os.putenv('PWD', pwd) os.chdir(pwd) def test_run(): proc = Popen([pwd + '/../../src/openmc'], stderr=PIPE, stdout=PIPE) stdout, stderr = proc.communicate() assert stderr != ''...
Change particle restart test to check for output on stderr rather than checking the return status.
Change particle restart test to check for output on stderr rather than checking the return status.
Python
mit
wbinventor/openmc,shenqicang/openmc,sxds/opemmc,shikhar413/openmc,liangjg/openmc,smharper/openmc,walshjon/openmc,kellyrowland/openmc,amandalund/openmc,samuelshaner/openmc,johnnyliu27/openmc,bhermanmit/cdash,bhermanmit/openmc,mit-crpg/openmc,keadyk/openmc_mg_prepush,smharper/openmc,johnnyliu27/openmc,shenqicang/openmc,a...
9d14c70b68eb1b00b8b6826ee6fc2e58fb4a0ab6
settings_test.py
settings_test.py
# These settings will always be overriding for all test runs EMAIL_FROM_ADDRESS = 'doesnt@matter.com'
# These settings will always be overriding for all test runs EMAIL_FROM_ADDRESS = 'doesnt@matter.com' PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.MD5PasswordHasher', )
Use only md5 to hash passwords when running tests
Use only md5 to hash passwords when running tests
Python
bsd-3-clause
peterbe/airmozilla,ehsan/airmozilla,lcamacho/airmozilla,anu7495/airmozilla,anu7495/airmozilla,anu7495/airmozilla,blossomica/airmozilla,lcamacho/airmozilla,EricSekyere/airmozilla,Nolski/airmozilla,tannishk/airmozilla,ehsan/airmozilla,blossomica/airmozilla,anjalymehla/airmozilla,ehsan/airmozilla,zofuthan/airmozilla,chiri...
52c78b7498f52d26cd5dc2ea27c6c0f2dc6db117
pytips/models.py
pytips/models.py
# -*- coding: utf-8 -*- """Defines the model 'layer' for PyTips.""" from __future__ import print_function from __future__ import unicode_literals from __future__ import absolute_import from __future__ import division from sqlalchemy import func from flask.ext.sqlalchemy import BaseQuery from pytips import db clas...
# -*- coding: utf-8 -*- """Defines the model 'layer' for PyTips.""" from __future__ import print_function from __future__ import unicode_literals from __future__ import absolute_import from __future__ import division from sqlalchemy import func from flask.ext.sqlalchemy import BaseQuery from pytips import db clas...
Add a helper for retrieving the newest Tip.
Add a helper for retrieving the newest Tip.
Python
isc
gthank/pytips,gthank/pytips,gthank/pytips,gthank/pytips
17fd955a3b4abe5ca751ea05e0cdb30429a9ce04
ghettoq/backends/pyredis.py
ghettoq/backends/pyredis.py
from Queue import Empty from redis import Redis from ghettoq.backends.base import BaseBackend DEFAULT_PORT = 6379 DEFAULT_DB = 0 class RedisBackend(BaseBackend): def __init__(self, host=None, port=None, user=None, password=None, database=None, timeout=None): if not isinstance(database, int...
from Queue import Empty from redis import Redis from ghettoq.backends.base import BaseBackend DEFAULT_PORT = 6379 DEFAULT_DB = 0 class RedisBackend(BaseBackend): def __init__(self, host=None, port=None, user=None, password=None, database=None, timeout=None): if not isinstance(database, int...
Throw Empty exception if BRPOP returns None. Add priority argument so it works with the latest version.
Throw Empty exception if BRPOP returns None. Add priority argument so it works with the latest version.
Python
bsd-3-clause
ask/ghettoq
91c3eb57ea3b2cd12654cbd6925a681d3450e77e
go/apps/jsbox/definition.py
go/apps/jsbox/definition.py
from go.vumitools.conversation.definition import ( ConversationDefinitionBase, ConversationAction) class ViewLogsAction(ConversationAction): action_name = 'view_logs' action_display_name = 'View Sandbox Logs' redirect_to = 'jsbox_logs' class ConversationDefinition(ConversationDefinitionBase): co...
from go.vumitools.conversation.definition import ( ConversationDefinitionBase, ConversationAction) class ViewLogsAction(ConversationAction): action_name = 'view_logs' action_display_name = 'View Sandbox Logs' redirect_to = 'jsbox_logs' class ConversationDefinition(ConversationDefinitionBase): co...
Add start of hook for extra jsbox endpoints.
Add start of hook for extra jsbox endpoints.
Python
bsd-3-clause
praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go
0b8aa961cb8aa6646aa1b660f6f669cf82492225
helper/windows.py
helper/windows.py
""" Windows platform support for running the application as a detached process. """ import subprocess import sys DETACHED_PROCESS = 8 class Daemon(object): """Daemonize the helper application, putting it in a forked background process. """ def __init__(self, controller): raise NotImplemente...
""" Windows platform support for running the application as a detached process. """ import platform import subprocess import sys DETACHED_PROCESS = 8 def operating_system(): """Return a string identifying the operating system the application is running on. :rtype: str """ return '%s %s (%s)' %...
Implement the operating_system() method for Windows
Implement the operating_system() method for Windows
Python
bsd-3-clause
dave-shawley/helper,gmr/helper,gmr/helper