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
47f1d3bf2ef53fa9fef9eff46497ca02f366e3fb
nap/auth.py
nap/auth.py
from __future__ import unicode_literals # Authentication and Authorisation from functools import wraps from . import http def permit(test_func): '''Decorate a handler to control access''' def decorator(view_func): @wraps(view_func) def _wrapped_view(self, *args, **kwargs): if tes...
from __future__ import unicode_literals # Authentication and Authorisation from functools import wraps from . import http def permit(test_func, response_class=http.Forbidden): '''Decorate a handler to control access''' def decorator(view_func): @wraps(view_func) def _wrapped_view(self, *args...
Allow control of response type for failing permit check
Allow control of response type for failing permit check
Python
bsd-3-clause
limbera/django-nap
a34086d5bbd63d98953919c72d4eb4623063ad0c
piptools/repositories/minimal_upgrade.py
piptools/repositories/minimal_upgrade.py
# coding: utf-8 from __future__ import (absolute_import, division, print_function, unicode_literals) from .base import BaseRepository class MinimalUpgradeRepository(BaseRepository): """ The MinimalUpgradeRepository uses a provided requirements file as a proxy in front of a reposit...
# coding: utf-8 from __future__ import (absolute_import, division, print_function, unicode_literals) from .base import BaseRepository class MinimalUpgradeRepository(BaseRepository): """ The MinimalUpgradeRepository uses a provided requirements file as a proxy in front of a reposit...
Add missing properties to pass through to the proxied repository.
Add missing properties to pass through to the proxied repository.
Python
bsd-2-clause
suutari/prequ,suutari/prequ,suutari-ai/prequ
e2452a46766abdef354d9e04f6fb61eae51bf6ee
yepes/models.py
yepes/models.py
# -*- coding:utf-8 -*- from django import template template.add_to_builtins('yepes.defaultfilters') template.add_to_builtins('yepes.defaulttags')
# -*- coding:utf-8 -*- from __future__ import absolute_import import types from django import template from django.db import connections from django.db.models.manager import Manager from django.db.models.query import QuerySet from django.utils import six template.add_to_builtins('yepes.defaultfilters') template.ad...
Implement truncate() method for Manager and in_batches() method for QuerySet
Implement truncate() method for Manager and in_batches() method for QuerySet
Python
bsd-3-clause
samuelmaudo/yepes,samuelmaudo/yepes,samuelmaudo/yepes,samuelmaudo/yepes
b435f5c07a39874195781d928b7451d2765c3cf9
test-project/testproject/models.py
test-project/testproject/models.py
import datetime, json from sqlalchemy import ( Column, Integer, Text, DateTime, ForeignKey, ) from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import ( scoped_session, sessionmaker, relationship, backref, ) from zope.sqlalchemy import ZopeTransac...
from __future__ import absolute_import, unicode_literals import datetime, json from sqlalchemy import ( Column, Integer, Text, DateTime, ForeignKey, ) from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import ( scoped_session, sessionmaker, relationship,...
Fix to unicode problem in 3.2
Fix to unicode problem in 3.2
Python
mit
RedTurtle/sqlalchemy-datatables,Pegase745/sqlalchemy-datatables
9f1ec5e42d66477fc884bf5ea853d145c0adeb4f
tests/test_fs.py
tests/test_fs.py
from farmfs.fs import normpath as _normalize from farmfs.fs import userPath2Path as up2p from farmfs.fs import Path def test_normalize_abs(): assert _normalize("/") == "/" assert _normalize("/a") == "/a" assert _normalize("/a/") == "/a" assert _normalize("/a/b") == "/a/b" assert _normalize(...
from farmfs.fs import normpath as _normalize from farmfs.fs import userPath2Path as up2p from farmfs.fs import Path def test_normalize_abs(): assert _normalize("/") == "/" assert _normalize("/a") == "/a" assert _normalize("/a/") == "/a" assert _normalize("/a/b") == "/a/b" assert _normalize(...
Add test case for “/“
Add test case for “/“
Python
mit
andrewguy9/farmfs,andrewguy9/farmfs
379e99a672537776ac0e160999967b5efce29305
tweepy/media.py
tweepy/media.py
# Tweepy # Copyright 2009-2021 Joshua Roesslein # See LICENSE for details. from tweepy.mixins import DataMapping class Media(DataMapping): __slots__ = ( "data", "media_key", "type", "duration_ms", "height", "non_public_metrics", "organic_metrics", "preview_image_url", "promoted_metrics",...
# Tweepy # Copyright 2009-2021 Joshua Roesslein # See LICENSE for details. from tweepy.mixins import DataMapping class Media(DataMapping): __slots__ = ( "data", "media_key", "type", "duration_ms", "height", "non_public_metrics", "organic_metrics", "preview_image_url", "promoted_metrics",...
Add alt_text field for Media
Add alt_text field for Media
Python
mit
svven/tweepy,tweepy/tweepy
09d78bb23ffba9d1d709a3ba5cbabbe84a9b1978
server/macros/currency_usd_to_cad.py
server/macros/currency_usd_to_cad.py
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import os im...
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import os im...
Delete the desks settings for macro
fix(macro): Delete the desks settings for macro
Python
agpl-3.0
pavlovicnemanja/superdesk,amagdas/superdesk,verifiedpixel/superdesk,mdhaman/superdesk-aap,sivakuna-aap/superdesk,plamut/superdesk,marwoodandrew/superdesk,petrjasek/superdesk,fritzSF/superdesk,petrjasek/superdesk-ntb,verifiedpixel/superdesk,marwoodandrew/superdesk,superdesk/superdesk-aap,verifiedpixel/superdesk,superdes...
a80069cb364e4802321aaba918ef671daebcff50
elephantblog/admin.py
elephantblog/admin.py
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from elephantblog.models import Entry, EntryAdmin, Category, CategoryTranslation from feincms.translations import admin_translationinline, short_language_code CategoryTranslationInline = admin_translationinline(CategoryTranslat...
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from elephantblog.models import Entry, EntryAdmin, Category, CategoryTranslation from feincms.translations import admin_translationinline, short_language_code CategoryTranslationInline = admin_translationinline(CategoryTranslat...
Remove the broken translations extension autodetection
Remove the broken translations extension autodetection
Python
bsd-3-clause
joshuajonah/feincms-elephantblog,matthiask/feincms-elephantblog,sbaechler/feincms-elephantblog,michaelkuty/feincms-elephantblog,joshuajonah/feincms-elephantblog,matthiask/feincms-elephantblog,michaelkuty/feincms-elephantblog,michaelkuty/feincms-elephantblog,feincms/feincms-elephantblog,sbaechler/feincms-elephantblog,sb...
494fd9dd3cb526682e5cb6fabc12ce4263875aea
flask_slacker/__init__.py
flask_slacker/__init__.py
""" flask_slacker ~~~~~~~~~~~~~ A Flask extension for using Slacker. :copyright: (c) 2017 Matheus Rosa :license: MIT, see LICENSE for more details. """ from slacker import Slacker as BaseSlacker __version__ = '0.0.1' class Slacker(object): def __init__(self, app=None, **kwargs): ""...
""" flask_slacker ~~~~~~~~~~~~~ A Flask extension for using Slacker. :copyright: (c) 2017 Matheus Rosa :license: MIT, see LICENSE for more details. """ from slacker import Slacker as BaseSlacker, DEFAULT_TIMEOUT __version__ = '0.0.1' class Slacker(object): def __init__(self, app=None): ...
Load app configs for Slacker
Load app configs for Slacker
Python
mit
mdsrosa/flask-slacker
ebfdde13ef464104b744d6eff41ebe181861603a
froide/helper/widgets.py
froide/helper/widgets.py
from django import forms from django.core.urlresolvers import reverse from django.utils.safestring import mark_safe class EmailInput(forms.TextInput): input_type = 'email' class DateInput(forms.DateInput): input_type = 'date' class AgreeCheckboxInput(forms.CheckboxInput): def __init__(self, attrs=None...
from django import forms from django.core.urlresolvers import reverse from django.utils.safestring import mark_safe class EmailInput(forms.TextInput): input_type = 'email' class DateInput(forms.DateInput): input_type = 'date' class AgreeCheckboxInput(forms.CheckboxInput): def __init__(self, attrs=None...
Change widget to Bootstrap form
Change widget to Bootstrap form
Python
mit
stefanw/froide,okfse/froide,catcosmo/froide,CodeforHawaii/froide,ryankanno/froide,okfse/froide,stefanw/froide,LilithWittmann/froide,catcosmo/froide,stefanw/froide,catcosmo/froide,ryankanno/froide,okfse/froide,LilithWittmann/froide,stefanw/froide,CodeforHawaii/froide,LilithWittmann/froide,CodeforHawaii/froide,okfse/froi...
469b7e8a83308b4ea6ad84d49d7a8aa42274a381
projects/views.py
projects/views.py
from django.contrib.auth.decorators import login_required from django.shortcuts import render from .models import Project from .forms import ProjectForm @login_required def add_project(request): data = request.POST if request.POST else None form = ProjectForm(data, user=request.user) if form.is_valid():...
from django.contrib.auth.decorators import login_required from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect, Http404 from .models import Project from .forms import ProjectForm def can_edit_projects(user): return user.is_authenticated() and user.has_perm('project...
Add restrictioins for who can edit the project and who cannot
Add restrictioins for who can edit the project and who cannot
Python
mit
Hackfmi/Diaphanum,Hackfmi/Diaphanum
274f5b738386e8a7ad0a7fd5ae46719fe15712de
clowder/clowder/cli/stash_controller.py
clowder/clowder/cli/stash_controller.py
from cement.ext.ext_argparse import expose from clowder.cli.abstract_base_controller import AbstractBaseController class StashController(AbstractBaseController): class Meta: label = 'stash' stacked_on = 'base' stacked_type = 'nested' description = 'Stash current changes' @exp...
from cement.ext.ext_argparse import expose from clowder.cli.abstract_base_controller import AbstractBaseController from clowder.commands.util import ( filter_groups, filter_projects_on_project_names, run_group_command, run_project_command ) from clowder.util.decorators import ( print_clowder_repo_s...
Add `clowder stash` logic to Cement controller
Add `clowder stash` logic to Cement controller
Python
mit
JrGoodle/clowder,JrGoodle/clowder,JrGoodle/clowder
b8de9355e0c592b1c57f91e3980544bab7cbfb0f
app/assets.py
app/assets.py
from flask_assets import Bundle, Environment js = Bundle( 'node_modules/jquery/dist/jquery.js', 'node_modules/jquery-pjax/jquery.pjax.js', 'node_modules/bootbox/bootbox.js', 'node_modules/bootstrap/dist/js/bootstrap.min.js', 'js/application.js', filters='jsmin', output='gen/packed.js' ) css...
from flask_assets import Bundle, Environment, Filter # fixes missing semicolon in last statement of jquery.pjax.js class ConcatFilter(Filter): def concat(self, out, hunks, **kw): out.write(';'.join([h.data() for h, info in hunks])) js = Bundle( 'node_modules/jquery/dist/jquery.js', 'node_modules/j...
Add concat filter to fix issue with jquery-pjax
Add concat filter to fix issue with jquery-pjax jquery-pjax makes use of IIFEs but does not terminate its last statement with a semicolon, causing syntax errors after asset concatenation. See also: https://github.com/miracle2k/webassets/issues/100#issuecomment-388461033
Python
mit
cburmeister/flask-bones,cburmeister/flask-bones,cburmeister/flask-bones
5168d4256bdfac937be62c8dc509a79a4ba9101c
pythran/tests/rosetta/average_loop_length.py
pythran/tests/rosetta/average_loop_length.py
#from http://rosettacode.org/wiki/Average_loop_length#Python #pythran export analytical(int) #pythran export testing(int, int) #runas analytical(10) #runas testing(10, 100) #from __future__ import division # Only necessary for Python 2.X from math import factorial from random import randrange def analytical(n): retu...
#from http://rosettacode.org/wiki/Average_loop_length#Python #pythran export analytical(int) #pythran export testing(int, int) #runas analytical(10) #runas avg = testing(10, 10**5); theory = analytical(10); abs((avg / theory - 1) * 100) < 0.1 #from __future__ import division # Only necessary for Python 2.X from math i...
Fix test to have less random result
Fix test to have less random result
Python
bsd-3-clause
hainm/pythran,artas360/pythran,pombredanne/pythran,serge-sans-paille/pythran,artas360/pythran,pombredanne/pythran,pombredanne/pythran,pbrunet/pythran,hainm/pythran,pbrunet/pythran,pbrunet/pythran,artas360/pythran,serge-sans-paille/pythran,hainm/pythran
bd5f6ac7a9b801b53e7f7e0d4d84301a8f8652ef
program.py
program.py
import json import csv import requests import secret base_url = https://www.mysportsfeeds.com/api/feed/pull/nfl/2016-2017-regular/ def main(): division_standings() playoff_standings() playoff_standings() player_stats() points_for() tiebreaker() player_score() # Get Division Standings f...
import json import csv import requests from requests.auth import HTTPBasicAuth import secret base_url = 'https://www.mysportsfeeds.com/api/feed/pull/nfl/2016-2017-regular/' def main(): division_standings() playoff_standings() playoff_standings() player_stats() points_for() tiebreaker() pl...
Update function to get player stats using base_url
Update function to get player stats using base_url
Python
mit
prcutler/nflpool,prcutler/nflpool
52d9ed9c08ef0686a891e3428349b70d74a7ecf8
scripts/munge_fah_data.py
scripts/munge_fah_data.py
import numpy as np import os import glob import mdtraj as md import fahmunge import pandas as pd projects = pd.read_csv("./projects.csv", index_col=0) output_path = "/data/choderalab/fah/munged/" for (project, location, pdb) in projects.itertuples(): print(project, location, pdb) allatom_output_path = os.path...
import numpy as np import os import glob import mdtraj as md import fahmunge import pandas as pd projects = pd.read_csv("./projects.csv", index_col=0) output_path = "/data/choderalab/fah/munged/" for (project, location, pdb) in projects.itertuples(): print(project, location, pdb) allatom_output_path = os.path...
Change output data structure to support faster rsync
Change output data structure to support faster rsync
Python
lgpl-2.1
steven-albanese/FAHMunge,kyleabeauchamp/FAHMunge,choderalab/FAHMunge
5ecde010ed93f5017a15899c53dbfdfc054d907f
indra/sources/hume/api.py
indra/sources/hume/api.py
__all__ = ['process_jsonld_file', 'process_jsonld'] import json import logging from indra.sources.hume import processor logger = logging.getLogger(__name__) def process_jsonld_file(fname): """Process a JSON-LD file in the new format to extract Statements. Parameters ---------- fname : str T...
__all__ = ['process_jsonld_file', 'process_jsonld'] import json import logging from indra.sources.hume import processor logger = logging.getLogger(__name__) def process_jsonld_file(fname): """Process a JSON-LD file in the new format to extract Statements. Parameters ---------- fname : str T...
Add encoding parameter to open jsonld
Add encoding parameter to open jsonld
Python
bsd-2-clause
johnbachman/belpy,sorgerlab/belpy,bgyori/indra,sorgerlab/indra,johnbachman/indra,johnbachman/indra,johnbachman/indra,sorgerlab/indra,sorgerlab/belpy,sorgerlab/indra,bgyori/indra,johnbachman/belpy,sorgerlab/belpy,bgyori/indra,johnbachman/belpy
2ab74cdb6adc979195f6ba60d5f8e9bf9dd4b74d
scikits/learn/__init__.py
scikits/learn/__init__.py
""" Machine Learning module in python ================================= scikits.learn is a Python module integrating classique machine learning algorithms in the tightly-nit world of scientific Python packages (numpy, scipy, matplotlib). It aims to provide simple and efficient solutions to learning problems that are ...
""" Machine Learning module in python ================================= scikits.learn is a Python module integrating classique machine learning algorithms in the tightly-nit world of scientific Python packages (numpy, scipy, matplotlib). It aims to provide simple and efficient solutions to learning problems that are ...
Add a tester to the scikit.
ENH: Add a tester to the scikit.
Python
bsd-3-clause
alexsavio/scikit-learn,joernhees/scikit-learn,shikhardb/scikit-learn,poryfly/scikit-learn,costypetrisor/scikit-learn,treycausey/scikit-learn,stylianos-kampakis/scikit-learn,alexsavio/scikit-learn,bigdataelephants/scikit-learn,costypetrisor/scikit-learn,stylianos-kampakis/scikit-learn,liangz0707/scikit-learn,nmayorov/sc...
ce2c22fb3616fbfdaf3a5c1f1de3f2fa1fc9f76f
proselint/checks/lilienfeld/terms_to_avoid.py
proselint/checks/lilienfeld/terms_to_avoid.py
# -*- coding: utf-8 -*- """Psychological and psychiatric terms to avoid. --- layout: post source: Scott O. Lilienfeld, et al. source_url: http://dx.doi.org/10.3389/fpsyg.2015.01100 title: psychological and psychiatric terms to avoid date: 2014-06-10 12:31:19 categories: writing --- Psychological an...
# -*- coding: utf-8 -*- """Psychological and psychiatric terms to avoid. --- layout: post source: Scott O. Lilienfeld, et al. source_url: http://dx.doi.org/10.3389/fpsyg.2015.01100 title: psychological and psychiatric terms to avoid date: 2014-06-10 12:31:19 categories: writing --- Psychological an...
Check for p = 0.00
Check for p = 0.00 #149
Python
bsd-3-clause
jstewmon/proselint,amperser/proselint,amperser/proselint,jstewmon/proselint,amperser/proselint,jstewmon/proselint,amperser/proselint,amperser/proselint
2abf0e6b9009abd7c34b459ad9e3f2c6223bb043
polyaxon/db/getters/experiment_groups.py
polyaxon/db/getters/experiment_groups.py
import logging from db.models.experiment_groups import ExperimentGroup _logger = logging.getLogger('polyaxon.db') def get_valid_experiment_group(experiment_group_id): try: return ExperimentGroup.objects.get(id=experiment_group_id) except ExperimentGroup.DoesNotExist: _logger.info('Experiment...
import logging from db.models.experiment_groups import ExperimentGroup _logger = logging.getLogger('polyaxon.db') def get_valid_experiment_group(experiment_group_id): try: return ExperimentGroup.objects.get(id=experiment_group_id) except ExperimentGroup.DoesNotExist: _logger.info('Experiment...
Add condition to check if experiment group exists before checking status
Add condition to check if experiment group exists before checking status
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
fbf25d0e190e660c0be31b615c0753d62358ad46
settings/settings.py
settings/settings.py
from django.utils import timezone from settings.models import Setting from utils.dates import string_to_datetime class Settings: def __init__(self, values=None): if values is None: return settings = Setting.objects.filter(name__in=values) self.__dict__['settings'] = dict((o.na...
from django.utils import timezone from settings.models import Setting from utils.dates import string_to_datetime class Settings: def __init__(self, values=None): if values is None: return settings = Setting.objects.filter(name__in=values) self.__dict__['settings'] = dict((o.na...
Simplify Settings code a little bit
Simplify Settings code a little bit - Fixes error 500 on homepage with clean database
Python
agpl-3.0
m4tx/egielda,m4tx/egielda,m4tx/egielda
e289c48727573a43a062213fd52bc43a2781bd8b
indra/trips/trips_api.py
indra/trips/trips_api.py
import sys import trips_client from processor import TripsProcessor def process_text(text): html = trips_client.send_query(text) xml = trips_client.get_xml(html) trips_client.save_xml(xml, 'test.xml') return process_xml(xml) def process_xml(xml_string): tp = TripsProcessor(xml_string) tp.get...
import sys import trips_client from processor import TripsProcessor def process_text(text, save_xml_name='trips_output.xml'): html = trips_client.send_query(text) xml = trips_client.get_xml(html) if save_xml_name: trips_client.save_xml(xml, save_xml_name) return process_xml(xml) def process_...
Add save xml name argument to TRIPS API
Add save xml name argument to TRIPS API
Python
bsd-2-clause
jmuhlich/indra,pvtodorov/indra,bgyori/indra,sorgerlab/indra,johnbachman/indra,sorgerlab/indra,sorgerlab/belpy,pvtodorov/indra,sorgerlab/indra,johnbachman/belpy,pvtodorov/indra,bgyori/indra,johnbachman/indra,jmuhlich/indra,jmuhlich/indra,johnbachman/indra,bgyori/indra,sorgerlab/belpy,sorgerlab/belpy,johnbachman/belpy,jo...
62e5867f9dc5a758e3803e66043255881c8250c2
democracy_club/apps/dc_members/forms.py
democracy_club/apps/dc_members/forms.py
from django.forms import ModelForm from localflavor.gb.forms import GBPostcodeField from .models import Member class MemberUpdateForm(ModelForm): class Meta: model = Member exclude = ['token', 'user', 'constituency', 'mapit_json'] postcode = GBPostcodeField(required=True)
from django.forms import ModelForm from localflavor.gb.forms import GBPostcodeField from .models import Member class MemberUpdateForm(ModelForm): class Meta: model = Member exclude = [ 'token', 'user', 'constituency', 'mapit_json', 'sour...
Exclude most fields from User Profiles
Exclude most fields from User Profiles
Python
bsd-3-clause
DemocracyClub/Website,DemocracyClub/Website,DemocracyClub/Website,DemocracyClub/Website
c608e7c88c4971e647171014ac5c8e77ecb0df34
braid/info.py
braid/info.py
from fabric.api import run, quiet from braid import succeeds, cacheInEnvironment @cacheInEnvironment def distroName(): """ Get the name of the distro. """ with quiet(): lsb = run('/usr/bin/lsb_release --id --short', warn_only=True) if lsb.succeeded: return lsb.lower() ...
from fabric.api import run, quiet from braid import succeeds, cacheInEnvironment @cacheInEnvironment def distroName(): """ Get the name of the distro. """ with quiet(): lsb = run('/usr/bin/lsb_release --id --short', warn_only=True) if lsb.succeeded: return lsb.lower() ...
Add a helper to detect the architecture.
Add a helper to detect the architecture.
Python
mit
alex/braid,alex/braid
8026e6b21aacffc6f08d634103bc32b1775882ae
devicehive/transports/base_transport.py
devicehive/transports/base_transport.py
class BaseTransport(object): """Base transport class.""" def __init__(self, name, data_format_class, data_format_options, handler_class, handler_options): self._name = name self._data_format = data_format_class(**data_format_options) self._handler = handler_class(**hand...
class BaseTransport(object): """Base transport class.""" def __init__(self, name, data_format_class, data_format_options, handler_class, handler_options): self._name = name self._data_format = data_format_class(**data_format_options) self._handler = handler_class(self, ...
Remove transport from handler methods
Remove transport from handler methods
Python
apache-2.0
devicehive/devicehive-python
22dcc9ee23841ecfbb23f76f2f8fd5c5c5bfb8cb
app/models.py
app/models.py
from app import db class Base(db.Model): __abstract__ = True id = db.Column(db.Integer, primary_key=True) created_at = db.Column(db.DateTime, default=db.func.current_timestamp()) updated_at = db.Column(db.DateTime, default=db.func.current_timestamp()) class Route(Base): __tablename__ = 'route...
from app import db class Base(db.Model): __abstract__ = True id = db.Column(db.Integer, primary_key=True) created_at = db.Column(db.DateTime, default=db.func.current_timestamp()) updated_at = db.Column(db.DateTime, default=db.func.current_timestamp()) class Route(Base): __tablename__ = 'route...
Remove unecessary initialization from Route model
Remove unecessary initialization from Route model
Python
mit
mdsrosa/routes_api_python
424fc74377ba4385e4c25fe90f888d39d5f14abd
runtests.py
runtests.py
#!/usr/bin/env python from os.path import dirname, abspath import sys from django.conf import settings if not settings.configured: from django import VERSION settings_dict = dict( INSTALLED_APPS=( 'localeurl', 'localeurl.tests', 'django.contrib.sites', # for sitema...
#!/usr/bin/env python from os.path import dirname, abspath import sys from django.conf import settings if not settings.configured: from django import VERSION settings_dict = dict( INSTALLED_APPS=( 'localeurl', 'localeurl.tests', 'django.contrib.sites', # for sitema...
Add SITE_ID to test settings since contrib.sites is in INSTALLED_APPS.
Add SITE_ID to test settings since contrib.sites is in INSTALLED_APPS.
Python
mit
extertioner/django-localeurl,carljm/django-localeurl,gonnado/django-localeurl
fe5d330fd809285576b1696ccb9807910f5778ce
numscons/__init__.py
numscons/__init__.py
from core.misc import get_scons_path, get_scons_build_dir, \ get_scons_configres_dir, get_scons_configres_filename from core.numpyenv import GetNumpyEnvironment from core.libinfo_scons import NumpyCheckLibAndHeader from checkers import CheckF77BLAS, CheckCBLAS, CheckCLAPACK, CheckF77LAPACK, Chec...
# XXX those are needed by the scons command only... from core.misc import get_scons_path, get_scons_build_dir, \ get_scons_configres_dir, get_scons_configres_filename # XXX those should not be needed by the scons command only... from core.extension import get_python_inc, get_pythonlib_dir # Thos...
Mark things to clean up later in global import
Mark things to clean up later in global import
Python
bsd-3-clause
cournape/numscons,cournape/numscons,cournape/numscons
adfe28a11fea94b207eea0417123a4155c909f05
gpiocrust/__init__.py
gpiocrust/__init__.py
""" Object oriented wrapper around RPi.GPIO. Falls back to mock objects if RPi.GPIO is not found. """ try: import RPi.GPIO from .raspberry_pi import * except RuntimeError: print( '----------------------------------------------------------------------------') print( ' WARNING: RPi.GPIO can only ...
""" Object oriented wrapper around RPi.GPIO. Falls back to mock objects if RPi.GPIO is not found. """ try: import RPi.GPIO from .raspberry_pi import * except RuntimeError: print( '----------------------------------------------------------------------------') print( ' WARNING: RPi.GPIO can only ...
Fix import errors on non-RPi platforms
Fix import errors on non-RPi platforms
Python
mit
zourtney/gpiocrust
da2dc4e6f905356a705e2f75701f9d23c4b008ba
signac/contrib/errors.py
signac/contrib/errors.py
# Copyright (c) 2017 The Regents of the University of Michigan # All rights reserved. # This software is licensed under the BSD 3-Clause License. from ..core.errors import Error class WorkspaceError(Error, OSError): "Raised when there is an issue to create or access the workspace." def __init__(self, error): ...
# Copyright (c) 2017 The Regents of the University of Michigan # All rights reserved. # This software is licensed under the BSD 3-Clause License. from ..core.errors import Error class WorkspaceError(Error, OSError): "Raised when there is an issue to create or access the workspace." def __init__(self, error): ...
Fix OSError not printing bug
Fix OSError not printing bug
Python
bsd-3-clause
csadorf/signac,csadorf/signac
dad58aa0162290627e9d96a5047a507237a49b76
calculate.py
calculate.py
operators = {'+', '-', '*', '/', '(', ')'} def parse_formula(text): tokens = [] buffer = '' for c in text: if '0' <= c <= '9': buffer += c elif c in operators: if buffer: tokens.append(int(buffer)) tokens.append(c) buffer =...
# List of operators along with their associated precedence operators = {None: 100, '+': 3, '-': 3, '*': 2, '/': 2, '(': 1, ')': 1} def operation(v1, v2, operator): if item == '+': return v1 + v2 elif item == '-': return v1 - v2 elif item == '*': return v1 * v2 elif item == '/':...
Add support for basic binary operations
Add support for basic binary operations
Python
mit
MichaelAquilina/Simple-Calculator
b6b1117df271dae8adefa8cb8d3413b73fb393ce
touchpad_listener/touchpad_listener.py
touchpad_listener/touchpad_listener.py
import serial import sonic sonic_pi = sonic.SonicPi() connection = serial.Serial('/dev/tty.usbmodem1421', 115200) while True: line = connection.readline() command, argument = line.strip().split(' ', 1) if command == 'pad': number = int(argument) sonic_pi.run('cue :pad, number: {}'.format...
import serial import sonic import glob sonic_pi = sonic.SonicPi() connection = serial.Serial(glob.glob('/dev/tty.usbmodem*')[0], 115200) while True: line = connection.readline() command, argument = line.strip().split(' ', 1) if command == 'pad': number = int(argument) sonic_pi.run('cue :...
Use `glob` to find an appropriate serial ttry
Use `glob` to find an appropriate serial ttry
Python
bsd-2-clause
CoderDojoScotland/coderdojo-sequencer,jonathanhogg/coderdojo-sequencer
3372bade0c5aee8c30c507832c842d6533608f61
porunga/tests/test_main.py
porunga/tests/test_main.py
import unittest from porunga import get_manager from porunga.commands.test import PorungaTestCommand class TestManager(unittest.TestCase): def test_manager_has_proper_commands(self): manager = get_manager() commands = manager.get_commands() self.assertIn('test', commands) test_co...
import unittest from porunga import get_manager from porunga.commands.test import PorungaTestCommand class TestManager(unittest.TestCase): def test_manager_has_proper_commands(self): manager = get_manager() commands = manager.get_commands() self.assertTrue('test' in commands) tes...
Test updated to work with Python 2.6
Test updated to work with Python 2.6
Python
bsd-2-clause
lukaszb/porunga,lukaszb/porunga
805c52698b3fed8df98462c15045f5de3822e241
edx_repo_tools/dev/clone_org.py
edx_repo_tools/dev/clone_org.py
"""Clone an entire GitHub organization.""" import os.path import click from git.repo.base import Repo from edx_repo_tools.auth import pass_github @click.command() @click.option( '--forks/--no-forks', is_flag=True, default=False, help="Should forks be included?" ) @click.option( '--depth', type=int, def...
"""Clone an entire GitHub organization.""" import os.path import click from git.repo.base import Repo from edx_repo_tools.auth import pass_github @click.command() @click.option( '--forks/--no-forks', is_flag=True, default=False, help="Should forks be included?" ) @click.option( '--depth', type=int, defa...
Fix to work in python 3.
Fix to work in python 3.
Python
apache-2.0
edx/repo-tools,edx/repo-tools
40edb65ee751dfe4cf6e04ee59891266d8b14f30
spacy/tests/regression/test_issue1380.py
spacy/tests/regression/test_issue1380.py
import pytest from ...language import Language def test_issue1380_empty_string(): nlp = Language() doc = nlp('') assert len(doc) == 0 @pytest.mark.models('en') def test_issue1380_en(EN): doc = EN('') assert len(doc) == 0
from __future__ import unicode_literals import pytest from ...language import Language def test_issue1380_empty_string(): nlp = Language() doc = nlp('') assert len(doc) == 0 @pytest.mark.models('en') def test_issue1380_en(EN): doc = EN('') assert len(doc) == 0
Make test work for Python 2.7
Make test work for Python 2.7
Python
mit
recognai/spaCy,aikramer2/spaCy,honnibal/spaCy,aikramer2/spaCy,recognai/spaCy,aikramer2/spaCy,spacy-io/spaCy,explosion/spaCy,aikramer2/spaCy,explosion/spaCy,recognai/spaCy,recognai/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,aikramer2/spaCy,recognai/spaCy,honnibal/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spa...
66cb548c0d609e6364f9ec934814911760023d92
ehriportal/urls.py
ehriportal/urls.py
from django.conf import settings from django.conf.urls.defaults import * from django.views.generic.simple import direct_to_template from django.contrib import admin admin.autodiscover() from pinax.apps.account.openid_consumer import PinaxConsumer handler500 = "pinax.views.server_error" urlpatterns = patterns("", ...
from django.conf import settings from django.conf.urls.defaults import * from django.views.generic.simple import direct_to_template from django.contrib import admin admin.autodiscover() from pinax.apps.account.openid_consumer import PinaxConsumer handler500 = "pinax.views.server_error" urlpatterns = patterns("", ...
Allow site_media/media to be served by staticfiles
Allow site_media/media to be served by staticfiles
Python
mit
mikesname/ehri-collections,mikesname/ehri-collections,mikesname/ehri-collections
f40da1b097d900c0c435d7550e891b0ece99bd91
lib/torque_accounting.py
lib/torque_accounting.py
# torque_accounting.py # Functions for working with Torque accounting files def parse_line(line): event = line.split(';') job_name = event[2] event_type = event[1] event_time = event[0] properties={} prop_strings = event.split(" ") for p in prop_strings: prop=p.split("=") ...
# torque_accounting.py # Functions for working with Torque accounting files def parse_line(line): event = line.split(';') job_name = event[2] event_type = event[1] event_time = event[0] properties={} prop_strings = event.split(" ") for p in prop_strings: prop=p.split("=") ...
Add parse_files method to loop through a bunch of files
Add parse_files method to loop through a bunch of files
Python
mit
ajdecon/torque_qhistory,ajdecon/torque_qhistory
62e40ee27413b170d40791912d8509e26b981398
examples/tools/print_devices.py
examples/tools/print_devices.py
# import PyOpenCL and Numpy. An OpenCL-enabled GPU is not required, # OpenCL kernels can be compiled on most CPUs thanks to the Intel SDK for OpenCL # or the AMD APP SDK. import pyopencl as cl def main(): dev_type_str = {} for dev_type in ['ACCELERATOR', 'ALL', 'CPU', 'CUSTOM', 'DEFAULT', 'GPU']: dev_t...
# import PyOpenCL and Numpy. An OpenCL-enabled GPU is not required, # OpenCL kernels can be compiled on most CPUs thanks to the Intel SDK for OpenCL # or the AMD APP SDK. import pyopencl as cl def main(): dev_type_str = {} for dev_type in ['ACCELERATOR', 'ALL', 'CPU', 'CUSTOM', 'DEFAULT', 'GPU']: dev_t...
Print devices example - change out format
Print devices example - change out format
Python
mit
openre/openre,openre/openre
0f0a9eda5be7cfe0a2076dc2dd8a4d24068f75e0
benchmarks/step_detect.py
benchmarks/step_detect.py
try: from asv import step_detect except ImportError: pass class Simple: def setup(self): self.y = ([1]*20 + [2]*30)*50 def time_detect_regressions(self): step_detect.detect_regressions(self.y) def time_solve_potts_approx(self): step_detect.solve_potts_approx(self.y, 0.3, ...
try: from asv import step_detect except ImportError: pass class Simple: def setup(self): self.y = ([1]*20 + [2]*30)*50 if hasattr(step_detect, 'detect_steps'): def time_detect_regressions(self): steps = step_detect.detect_steps(self.y) step_detect.detect_regres...
Fix benchmarks vs. changes in b1cc0a9aa5107
Fix benchmarks vs. changes in b1cc0a9aa5107
Python
bsd-3-clause
qwhelan/asv,qwhelan/asv,pv/asv,pv/asv,spacetelescope/asv,spacetelescope/asv,airspeed-velocity/asv,spacetelescope/asv,airspeed-velocity/asv,airspeed-velocity/asv,qwhelan/asv,pv/asv,airspeed-velocity/asv,spacetelescope/asv,qwhelan/asv,pv/asv
89975de83d82695ba4615c72d17ac85baa39593d
invar/utils/ocr.py
invar/utils/ocr.py
# -*- coding: utf-8 -*- from baluhn import generate as baluhn_generate, verify as baluhn_verify from django.conf import settings def generate(reference, check_length=settings.INVAR_OCR_CHECK_LENGTH): reference = str(reference) assert check_length == 1 or check_length == 2 if check_length == 1: re...
# -*- coding: utf-8 -*- from baluhn import generate as baluhn_generate, verify as baluhn_verify from django.conf import settings def generate(reference, check_length=settings.INVAR_OCR_CHECK_LENGTH): reference = str(reference) assert check_length == 1 or check_length == 2 if check_length == 1: re...
Fix for empty reference bug
Fix for empty reference bug
Python
mit
ovidner/bitket,ovidner/bitket,ovidner/bitket,ovidner/bitket
860ef2b11774bc6acab848a6b37b808938086973
pylibui/core.py
pylibui/core.py
""" Python wrapper for libui. """ from . import libui class App: def __init__(self): """ Creates a new pylibui app. """ options = libui.uiInitOptions() libui.uiInit(options) def __enter__(self): self.start() def start(self): """ S...
""" Python wrapper for libui. """ from . import libui class App: def __init__(self): """ Creates a new pylibui app. """ options = libui.uiInitOptions() libui.uiInit(options) def start(self): """ Starts the application main loop. :return: N...
Revert "Make App a context manager"
Revert "Make App a context manager"
Python
mit
superzazu/pylibui,superzazu/pylibui,joaoventura/pylibui,joaoventura/pylibui
d84f42d45bb16820fb0077c9f0f92ba88e24d5de
cabot/cabotapp/jenkins.py
cabot/cabotapp/jenkins.py
from os import environ as env from django.conf import settings import requests from datetime import datetime from django.utils import timezone from celery.utils.log import get_task_logger logger = get_task_logger(__name__) auth = (settings.JENKINS_USER, settings.JENKINS_PASS) def get_job_status(jobname): ret =...
from os import environ as env from django.conf import settings import requests from datetime import datetime from django.utils import timezone from celery.utils.log import get_task_logger logger = get_task_logger(__name__) if settings.JENKINS_USER: auth = (settings.JENKINS_USER, settings.JENKINS_PASS) else: ...
Fix Jenkins tests when no user is set
Fix Jenkins tests when no user is set
Python
mit
Affirm/cabot,Affirm/cabot,Affirm/cabot,Affirm/cabot
51059ae476ca0dd553220cf25c73a0eb14a099de
RecorderFactory.py
RecorderFactory.py
from Recorders import Recorder, PrintRecorder, FileRecorder factory = dict([ ('print', create_print_recorder), ('file', create_file_recorder)]) def create_recorder(config): return factory[config.type](config.config) def create_print_recorder(config): return PrintRecorder(config) def create_file_reco...
from Recorders import Recorder, PrintRecorder, FileRecorder def create_print_recorder(config): return PrintRecorder(config) def create_file_recorder(config): return FileRecorder(config) recorderInitializers = dict([ ('print', create_print_recorder), ('file', create_file_recorder)]) def create_record...
Define initializers before use them
Define initializers before use them
Python
mit
hectortosa/py-temperature-recorder
e40985c1ecba1529987ed9551210677ea93b9614
test/unit/builtins/test_install.py
test/unit/builtins/test_install.py
from .common import BuiltinTest from bfg9000.builtins import default, install # noqa from bfg9000 import file_types from bfg9000.path import Path, Root class TestInstall(BuiltinTest): def test_install_none(self): self.assertEqual(self.builtin_dict['install'](), None) def test_install_single(self): ...
import mock from .common import BuiltinTest from bfg9000.builtins import default, install # noqa from bfg9000 import file_types from bfg9000.path import Path, Root class TestInstall(BuiltinTest): def test_install_none(self): self.assertEqual(self.builtin_dict['install'](), None) def test_install_s...
Add tests for unset installation dirs
Add tests for unset installation dirs
Python
bsd-3-clause
jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000
260cd3b96df3a4746560db0032d7b6042c55d7fc
integration-test/976-fractional-pois.py
integration-test/976-fractional-pois.py
# https://www.openstreetmap.org/way/147689077 # Apple Store, SF assert_has_feature( 15, 5242, 12664, 'pois', { 'id': 147689077, 'min_zoom': 15.68 })
# https://www.openstreetmap.org/way/147689077 # Apple Store, SF assert_has_feature( 15, 5242, 12664, 'pois', { 'id': 147689077, 'min_zoom': 15.68 }) # Test that source and min_zoom are set properly for boundaries, roads, transit, and water assert_has_feature( 5, 9, 12, 'boundaries', { 'min_zoom': 0 , '...
Add tests for source and min_zoom
Add tests for source and min_zoom
Python
mit
mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource
633969d8d53d28db48bb2478820e90315329542c
tiddlywebplugins/prettyerror/instance.py
tiddlywebplugins/prettyerror/instance.py
store_contents = {} store_structure = {} store_contents['_default_errors'] = [ 'src/_errors/index.recipe', ] store_structure['recipes'] = {} store_structure['bags'] = {} store_structure['recipes']['_errors'] = { 'desc': 'Pretty Errors Error Tiddlers', 'recipe': [ ('_defau...
""" Establish the data structures representing the bags and recipes needed by this plugin. """ store_contents = {} store_structure = {} store_contents['_default_errors'] = [ 'src/_errors/index.recipe', ] store_structure['recipes'] = {} store_structure['bags'] = {} store_structure['recipes']['_errors...
Correct set policy on bag.
Correct set policy on bag. Had been missing create constraint.
Python
bsd-3-clause
tiddlyweb/tiddlywebplugins.prettyerror
fe37ef9248f8658296e6f465d380d639d6047a5d
aspen/server/diesel_.py
aspen/server/diesel_.py
import diesel from aspen.server import BaseEngine from diesel.protocols import wsgi class Engine(BaseEngine): app = None # a diesel app instance def bind(self): self.app = wsgi.WSGIApplication( self.website , self.website.address[1] ...
import diesel from aspen.server import BaseEngine from diesel.protocols import wsgi class Engine(BaseEngine): diesel_app = None # a diesel diesel_app instance def bind(self): self.diesel_app = wsgi.WSGIApplication( self.website , self.website.address[1] ...
Reduce log spam from diesel.
Reduce log spam from diesel.
Python
mit
gratipay/aspen.py,gratipay/aspen.py
cc08fcbb513224aafe6c04143a150d1019c032ef
setup_py2exe.py
setup_py2exe.py
#!/usr/bin/env python # C:\Python27_32\python.exe setup_py2exe.py py2exe from distutils.core import setup from glob import glob import os import py2exe from setup import SSLYZE_SETUP data_files = [("Microsoft.VC90.CRT", glob(r'C:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT\*.*'))] # T...
#!/usr/bin/env python # C:\Python27_32\python.exe setup_py2exe.py py2exe from distutils.core import setup from glob import glob import os import py2exe from setup import SSLYZE_SETUP data_files = [("Microsoft.VC90.CRT", glob(r'C:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT\*.*'))] # T...
Fix trust stores paths for py2exe builds
Fix trust stores paths for py2exe builds
Python
agpl-3.0
nabla-c0d3/sslyze
013d0e3b2d8fdc212ae63f635a1e8def988672fa
tests/structures/test_sequences.py
tests/structures/test_sequences.py
import unittest from ..utils import TranspileTestCase class SequenceTests(TranspileTestCase): def test_unpack_sequence(self): self.assertCodeExecution(""" x = [1, 2, 3] a, b, c = x print(a) print(b) print(c) """) @unittest.skip(...
import unittest from ..utils import TranspileTestCase class SequenceTests(TranspileTestCase): def test_unpack_sequence(self): self.assertCodeExecution(""" x = [1, 2, 3] a, b, c = x print(a) print(b) print(c) """) @unittest.expec...
Convert some skips to expected failures.
Convert some skips to expected failures.
Python
bsd-3-clause
glasnt/voc,freakboy3742/voc,ASP1234/voc,ASP1234/voc,Felix5721/voc,pombredanne/voc,pombredanne/voc,Felix5721/voc,cflee/voc,cflee/voc,gEt-rIgHt-jR/voc,glasnt/voc,gEt-rIgHt-jR/voc,freakboy3742/voc
9639cb7607d301abbc7ad6c8b22aa97e6a0eb5cb
tests/examples/test_examples_run.py
tests/examples/test_examples_run.py
import pytest from os.path import abspath, basename, dirname, join import subprocess import glob import sys cwd = abspath(dirname(__file__)) examples_dir = join(cwd, "..", "..", "examples") example_files = glob.glob("%s/*.py" % examples_dir) @pytest.fixture(params=[pytest.param(f, marks=pytest.mark.xfail(reason="un...
import pytest from os.path import abspath, basename, dirname, join import subprocess import glob import sys cwd = abspath(dirname(__file__)) examples_dir = join(cwd, "..", "..", "examples") example_files = glob.glob("%s/*.py" % examples_dir) @pytest.fixture(params=glob.glob("%s/*.py" % examples_dir), ...
Remove pytest flag for xfails
Remove pytest flag for xfails
Python
mit
firedrakeproject/gusto,firedrakeproject/dcore
ce6685d18492fe0787ded92939f52916e0d9cbaa
lc046_permutations.py
lc046_permutations.py
"""Leetcode 46. Permutations Medium URL: https://leetcode.com/problems/permutations/ Given a collection of distinct integers, return all possible permutations. Example: Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ] """ class Solution(object): def _backtrack(self, pe...
"""Leetcode 46. Permutations Medium URL: https://leetcode.com/problems/permutations/ Given a collection of distinct integers, return all possible permutations. Example: Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ] """ class Solution(object): def _backtrack(self, pe...
Refactor adding temp to permutations
Refactor adding temp to permutations
Python
bsd-2-clause
bowen0701/algorithms_data_structures
6ba67b7090bbbb7a19e3a6c5623c1e63c0452428
dmoj/executors/OCTAVE.py
dmoj/executors/OCTAVE.py
from .base_executor import ScriptExecutor class Executor(ScriptExecutor): ext = '.m' name = 'OCTAVE' command = 'octave' address_grace = 131072 test_program = "disp(input('', 's'))" fs = ['.*\.m', '/lib/', '/etc/nsswitch\.conf$', '/etc/passwd$', '/usr/share/', '/etc/fltk/'] def get_cmdlin...
from .base_executor import ScriptExecutor class Executor(ScriptExecutor): ext = '.m' name = 'OCTAVE' command = 'octave' address_grace = 131072 test_program = "disp(input('', 's'))" fs = ['.*\.m', '/lib/', '/etc/nsswitch\.conf$', '/etc/passwd$', '/usr/share/', '/etc/fltk/'] def get_cmdlin...
Address execve protection fault in Octave autoconfig
Address execve protection fault in Octave autoconfig `octave-cli` is what we really want
Python
agpl-3.0
DMOJ/judge,DMOJ/judge,DMOJ/judge
011f7fbe66cc226cdd2be2e2eeef44df11733251
scrapyard/kickass.py
scrapyard/kickass.py
import cache import network import scraper import urllib KICKASS_URL = 'http://kickass.so' ################################################################################ def movie(movie_info): return __search('category:{0} imdb:{1}'.format('movies', movie_info['imdb_id'][2:])) #################################...
import cache import network import scraper import urllib KICKASS_URL = 'http://kickass.so' ################################################################################ def movie(movie_info): return __search('category:{0} imdb:{1}'.format('movies', movie_info['imdb_id'][2:])) #################################...
Remove ? from show title when searching
Kickass: Remove ? from show title when searching
Python
mit
sharkone/scrapyard
21bcb3105c9c3884f2a369a75408d91cdca5992e
tests/core/test_extensions.py
tests/core/test_extensions.py
from __future__ import unicode_literals, print_function, division, absolute_import from nose.tools import raises from openfisca_core.parameters import ParameterNode from openfisca_country_template import CountryTaxBenefitSystem tbs = CountryTaxBenefitSystem() def test_extension_not_already_loaded(): assert tbs...
from __future__ import unicode_literals, print_function, division, absolute_import from nose.tools import raises from openfisca_core.parameters import ParameterNode from openfisca_country_template import CountryTaxBenefitSystem tbs = CountryTaxBenefitSystem() def test_extension_not_already_loaded(): assert tbs...
Test extension's parameter access for a given period
Test extension's parameter access for a given period
Python
agpl-3.0
openfisca/openfisca-core,openfisca/openfisca-core
513244c067713a9b87f322c50be43643fdcca056
test/api/test_api.py
test/api/test_api.py
import time import subprocess import pytest import sys SOURCE = "**" if len(sys.argv) == 2: SOURCE = str(sys.argv[1]) start = subprocess.Popen(['make', 'backend']) time.sleep(5) process = subprocess.run("pytest augur/datasources/{}/test_{}_routes.py".format(SOURCE, SOURCE), shell=True) time.sleep(2) subprocess.Po...
import time import subprocess import os import pytest import sys SOURCE = "**" if len(sys.argv) == 2: SOURCE = str(sys.argv[1]) FNULL = open(os.devnull, 'w') start = subprocess.Popen(['augur', 'run'], stdout=FNULL, stderr=subprocess.STDOUT) time.sleep(20) process = subprocess.run("pytest augur/datasources/{}/tes...
Refactor API testing script to be consistent with Travis build
Refactor API testing script to be consistent with Travis build Signed-off-by: Carter Landis <ffc486ac0b21a34cfd7d1170183ed86b0f1b04a2@gmail.com>
Python
mit
OSSHealth/ghdata,OSSHealth/ghdata,OSSHealth/ghdata
c8f1d40f97e0e6be633acec8533f890287ef5200
server/systeminfo.py
server/systeminfo.py
#!/bin/python3 """ This script contains functions to access various system's info. Author: Julien Delplanque """ import subprocess def get_uptime(): """ Return the uptime of the system as a str using the command: $ uptime """ proc = subprocess.Popen(["uptime"], stdout=subprocess.PIPE, shell=True) ...
#!/bin/python3 """ This script contains functions to access various system's info. Author: Julien Delplanque """ import subprocess def get_uptime(): """ Return the uptime of the system as a str using the command: $ uptime """ proc = subprocess.Popen(["uptime"], stdout=subprocess.PIPE, shell=True) ...
Correct get_uptime function. It didn't extract the uptime correctly. Now it does.
Correct get_uptime function. It didn't extract the uptime correctly. Now it does.
Python
mit
juliendelplanque/raspirestmonitor
aae2a298d0f5b6e94d4c7041b1cef0df424666a9
bench_bin.py
bench_bin.py
import socket import time import random import struct NUM = 1024 * 1024 * 4 KEYS = ["test", "foobar", "zipzap"] VALS = [32, 100, 82, 101, 5, 6, 42, 73] BINARY_HEADER = struct.Struct("<BBHd") BIN_TYPES = {"kv": 1, "c": 2, "ms": 3} def format(key, type, val): "Formats a binary message for statsite" key = str(...
import socket import time import random import struct NUM = 1024 * 1024 KEYS = ["test", "foobar", "zipzap"] VALS = [32, 100, 82, 101, 5, 6, 42, 73] BINARY_HEADER = struct.Struct("<BBHd") BIN_TYPES = {"kv": 1, "c": 2, "ms": 3} def format(key, type, val): "Formats a binary message for statsite" key = str(key)...
Change binary benchmark to loop forever too
Change binary benchmark to loop forever too
Python
bsd-3-clause
u-s-p/statsite,statsite/statsite,Instagram/statsite,kuba--/statsite,zeedunk/statsite,nwangtw/statsite,theatrus/statsite,lazybios/statsite,zeedunk/statsite,Instagram/statsite,statsite/statsite,tsunli/statsite,kuba--/statsite,armon/statsite,nspragg/statsite,nspragg/statsite,sleepybishop/statsite,theatrus/statsite,u-s-p/s...
552166a61e66f305b3729718361078558298883b
couchdb/tests/testutil.py
couchdb/tests/testutil.py
# -*- coding: utf-8 -*- # # Copyright (C) 2007-2009 Christopher Lenz # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. import uuid from couchdb import client class TempDatabaseMixin(object): temp_dbs = None _d...
# -*- coding: utf-8 -*- # # Copyright (C) 2007-2009 Christopher Lenz # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. import random import sys from couchdb import client class TempDatabaseMixin(object): temp_dbs ...
Use a random number instead of uuid for temp database name.
Use a random number instead of uuid for temp database name.
Python
bsd-3-clause
ssaavedra/couchdb-python,oliora/couchdb-python,hdmessaging/couchbase-mapping-python
bd11c37a8669bdae2d4561483f50da0891b82627
monsetup/detection/plugins/zookeeper.py
monsetup/detection/plugins/zookeeper.py
import logging import os import yaml import monsetup.agent_config import monsetup.detection log = logging.getLogger(__name__) class Zookeeper(monsetup.detection.Plugin): """Detect Zookeeper daemons and setup configuration to monitor them. """ def _detect(self): """Run detection, set self.ava...
import logging import os import yaml import monsetup.agent_config import monsetup.detection log = logging.getLogger(__name__) class Zookeeper(monsetup.detection.Plugin): """Detect Zookeeper daemons and setup configuration to monitor them. """ def _detect(self): """Run detection, set self.ava...
Fix detection of Zookeeper in monasca-setup
Fix detection of Zookeeper in monasca-setup The Zookeeper detection plugin was looking for zookeeper in the process command-line. This was producing false positives in the detection process because storm uses the zookeeper library and it shows up the command-line for storm. Change-Id: I764a3064003beec55f0e589272855d...
Python
bsd-3-clause
sapcc/monasca-agent,sapcc/monasca-agent,sapcc/monasca-agent
16703454a9334b6667a761bd52b0a5029e5976b2
tests/test_api_views.py
tests/test_api_views.py
import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings") import django from django.test import TestCase from rest_framework.test import APIRequestFactory from api.webview.views import DocumentList django.setup() class APIViewTests(TestCase): def setUp(self): self.factory = APIRequ...
import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings") import pytest import django from django.test import TestCase from rest_framework.test import APIRequestFactory from api.webview.views import DocumentList django.setup() class APIViewTests(TestCase): def setUp(self): self.fac...
Add pytest mark database setup for test
Add pytest mark database setup for test
Python
apache-2.0
erinspace/scrapi,felliott/scrapi,fabianvf/scrapi,CenterForOpenScience/scrapi,erinspace/scrapi,fabianvf/scrapi,mehanig/scrapi,CenterForOpenScience/scrapi,mehanig/scrapi,felliott/scrapi
7cff4344538c59763560a9a86fda0f464f208b66
nightreads/user_manager/user_service.py
nightreads/user_manager/user_service.py
from django.contrib.auth.models import User from nightreads.posts.models import Tag from .models import UserTag def update_user_tags(user, tags): tags_objs = Tag.objects.filter(name__in=tags) user.usertag.tags.add(*tags_objs) user.save() def get_user(email): user, created = User.objects.get_or_crea...
from django.contrib.auth.models import User from nightreads.posts.models import Tag from .models import UserTag def update_user_tags(user, tags): tags_objs = Tag.objects.filter(name__in=tags) if tags_objs: user.usertag.tags.clear() user.usertag.tags.add(*tags_objs) user.save() def get_u...
Clear existing tags before updating
Clear existing tags before updating
Python
mit
avinassh/nightreads,avinassh/nightreads
c31d1b9a50452ae1906eca9735cbfb9acd2580dd
src/parse_user_history/history_parser.py
src/parse_user_history/history_parser.py
import os.path import json import urlparse ACCEPTED_FILETYPES = [ 'json', # 'csv' ] class HistoryParser(): def __init__(self, path): if not os.path.isfile(path): raise Exception("File not found.") if path.split(".")[-1] not in ACCEPTED_FILETYPES: raise Excep...
import os.path import json import urlparse ACCEPTED_FILETYPES = [ 'json', # 'csv' ] class HistoryParser(): def __init__(self, path): if not os.path.isfile(path): raise Exception("File not found.") if path.split(".")[-1] not in ACCEPTED_FILETYPES: raise Excep...
Prepend http to urls in user history
Prepend http to urls in user history
Python
mit
piatra/ssl-project
1cafb39b6204010d3e17b059254af6042f4a9efc
apts/__init__.py
apts/__init__.py
import os import shutil import configparser from .equipment import Equipment from .observations import Observation from .place import Place from .weather import Weather from .notify import Notify from .catalogs import Catalogs from .utils import Utils user_config = os.path.expanduser("~") + "/.config/apts/apts.ini" ...
import os import shutil import configparser from .equipment import Equipment from .observations import Observation from .place import Place from .weather import Weather from .notify import Notify from .catalogs import Catalogs from .utils import Utils # Default values for configuration values DEFAULTS = { 'weathe...
Add default values for config
Add default values for config
Python
apache-2.0
pozar87/apts
52648b65d5920e3c87cfbdd0d71d4d91302b3991
calaccess_raw/admin/tracking.py
calaccess_raw/admin/tracking.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Custom administration panels for tracking models. """ from __future__ import unicode_literals from django.contrib import admin from calaccess_raw import models from .base import BaseAdmin @admin.register(models.RawDataVersion) class RawDataVersionAdmin(BaseAdmin): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Custom administration panels for tracking models. """ from __future__ import unicode_literals from django.contrib import admin from calaccess_raw import models from .base import BaseAdmin @admin.register(models.RawDataVersion) class RawDataVersionAdmin(BaseAdmin): ...
Update count fields on RawDataVersionAdmin
Update count fields on RawDataVersionAdmin
Python
mit
california-civic-data-coalition/django-calaccess-raw-data
d4c0a8d0077439adb1e074e6f6e1a1e8b751a804
serfnode/handler/config.py
serfnode/handler/config.py
import os import uuid from mischief.actors.pipe import get_local_ip import yaml def read_serfnode_yml(): with open('/serfnode.yml') as input: conf = yaml.load(input) or {} return conf['serfnode'] yml = read_serfnode_yml() role = os.environ.get('ROLE') or yml.get('ROLE') or 'no_role' peer = os...
import os import uuid from mischief.actors.pipe import get_local_ip import yaml def read_serfnode_yml(): with open('/serfnode.yml') as input: conf = yaml.load(input) or {} return conf.get('serfnode', {}) yml = read_serfnode_yml() role = os.environ.get('ROLE') or yml.get('ROLE') or 'no_role' p...
Fix handling of empty file
Fix handling of empty file
Python
mit
waltermoreira/serfnode,waltermoreira/serfnode,waltermoreira/serfnode
e033fa49673cdc1b682edcc2aaf1e140a73ab1b4
src/wirecloud/platform/context/models.py
src/wirecloud/platform/context/models.py
# -*- coding: utf-8 -*- # Copyright 2013 Universidad Politécnica de Madrid # This file is part of Wirecloud. # Wirecloud is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or #...
# -*- coding: utf-8 -*- # Copyright 2013 Universidad Politécnica de Madrid # This file is part of Wirecloud. # Wirecloud is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or #...
Remove scope attribute from Constant
Remove scope attribute from Constant
Python
agpl-3.0
rockneurotiko/wirecloud,rockneurotiko/wirecloud,jpajuelo/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud,jpajuelo/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud
53cae8a7d95832a0f95a537468552254028a0668
tests/system/test_auth.py
tests/system/test_auth.py
import pytest from inbox.models.session import session_scope from client import InboxTestClient from conftest import (timeout_loop, credentials, create_account, API_BASE) @timeout_loop('sync_start') def wait_for_sync_start(client): return True if client.messages.first() else False @timeout_loop('auth') def wai...
import pytest from inbox.models.session import session_scope from client import InboxTestClient from conftest import (timeout_loop, credentials, create_account, API_BASE) from accounts import broken_credentials @timeout_loop('sync_start') def wait_for_sync_start(client): return True if client.messages.first() el...
Add a system test to check for expected broken accounts
Add a system test to check for expected broken accounts Summary: This is the system test for D765 and finishes up the sync engine side of T495 - checking for All Mail folder and failing gracefully if it's absent. This test specifically adds another check in `test_auth` based on a new list of live, bad credentials in ...
Python
agpl-3.0
gale320/sync-engine,Eagles2F/sync-engine,wakermahmud/sync-engine,nylas/sync-engine,ErinCall/sync-engine,wakermahmud/sync-engine,EthanBlackburn/sync-engine,closeio/nylas,jobscore/sync-engine,jobscore/sync-engine,Eagles2F/sync-engine,wakermahmud/sync-engine,closeio/nylas,nylas/sync-engine,EthanBlackburn/sync-engine,waker...
b777c8268ec661539f868937478c3bbc204f2fb3
tests/test_RI_response.py
tests/test_RI_response.py
from addons import * from utils import * tdir = 'Response-Theory' def test_beta(workspace): exe_py(workspace, tdir, 'Self-Consistent-Field/beta') def test_CPHF(workspace): exe_py(workspace, tdir, 'Self-Consistent-Field/CPHF') def test_helper_CPHF(workspace): exe_py(workspace, tdir, 'Self-Consistent-...
from addons import * from utils import * tdir = 'Response-Theory' def test_beta(workspace): exe_py(workspace, tdir, 'Self-Consistent-Field/beta') def test_CPHF(workspace): exe_py(workspace, tdir, 'Self-Consistent-Field/CPHF') def test_helper_CPHF(workspace): exe_py(workspace, tdir, 'Self-Consistent-...
Use integral derivative decorator for test
Use integral derivative decorator for test
Python
bsd-3-clause
dsirianni/psi4numpy,psi4/psi4numpy
429ffd7f41dda00f662167f179aea73b7d018807
pi_setup/system.py
pi_setup/system.py
#!/usr/bin/env python import subprocess def main(): subprocess.call(["apt-get", "update"]) subprocess.call(["apt-get", "-y", "upgrade"]) subprocess.call(["apt-get", "-y", "install", "python-dev"]) subprocess.call(["apt-get", "-y", "install", "python-pip"]) subprocess.call(["apt-get", "-y", "instal...
#!/usr/bin/env python import subprocess from utils.installation import OptionalInstall def main(): subprocess.call(["apt-get", "update"]) subprocess.call(["apt-get", "-y", "upgrade"]) subprocess.call(["apt-get", "-y", "install", "python-dev"]) subprocess.call(["apt-get", "-y", "install", "python-pip"]...
Make upstart an optional install
Make upstart an optional install
Python
mit
projectweekend/Pi-Setup,projectweekend/Pi-Setup
b6ab579fa65f816704142716fbd68645ac5f2ff8
zenaida/contrib/feedback/models.py
zenaida/contrib/feedback/models.py
from django.conf import settings from django.db import models class FeedbackItem(models.Model): timestamp = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL) resolved = models.BooleanField(default=False) content = models.TextField() screenshot = models.File...
from django.conf import settings from django.db import models class FeedbackItem(models.Model): timestamp = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL) resolved = models.BooleanField(default=False) content = models.TextField() screenshot = models.File...
Order feedback items by their timestamp.
Order feedback items by their timestamp.
Python
bsd-3-clause
littleweaver/django-zenaida,littleweaver/django-zenaida,littleweaver/django-zenaida,littleweaver/django-zenaida
fccf1d6562e8d5e1349d1f0826993ec799a5fc07
app/timetables/tests/test_models.py
app/timetables/tests/test_models.py
from django.test import TestCase from django.db import IntegrityError from app.timetables.models import Weekday, Meal class WeekdayTest(TestCase): """Tests the Weekday model.""" def setUp(self): Weekday.objects.create(name='monday') def test_weekday_name_should_be_capitalized_on_save(self): ...
from datetime import datetime from django.test import TestCase from django.db import IntegrityError from app.timetables.models import Weekday, Meal class WeekdayTest(TestCase): """Tests the Weekday model.""" def setUp(self): Weekday.objects.create(name='monday') def test_weekday_name_should_be...
Use time object for model test
Use time object for model test
Python
mit
teamtaverna/core
3be244ab1d7b03648350356dd3d9b6025516def5
capstone/rl/tabularf.py
capstone/rl/tabularf.py
import random class TabularF(dict): ''' Tabular representation for any of the two types of value functions: 1. state value function (V-Functions). e.g. vf = TabularF() vf[state] = 1 2. state-action value functions (Q-functions) e.g. qf = TabularF() qf[(state...
import random _MEAN = 0.0 _STD = 0.3 class TabularF(dict): ''' Tabular representation for any of the two types of value functions: 1. state value function (V-Functions). e.g. vf = TabularF() vf[state] = 1 2. state-action value functions (Q-functions) e.g. qf = Tabu...
Initialize values using a gaussian distribution with mean = 0 and std = 0.3
Initialize values using a gaussian distribution with mean = 0 and std = 0.3
Python
mit
davidrobles/mlnd-capstone-code
11cf68b017f1feccc27fcfacea2c67aafc8e682d
tools/contributer_list.py
tools/contributer_list.py
#!/usr/bin/env python """Print a list of contributors for a particular milestone. Usage: python tools/contributor_list.py MILESTONE """ import sys from gh_api import ( get_milestone_id, get_issues_list, ) if __name__ == "__main__": if len(sys.argv) != 2: print(__doc__) sys.exit(1) ...
#!/usr/bin/env python """Print a list of contributors for a particular milestone. Usage: python tools/contributor_list.py [MILESTONE] [MILESTONE] ... """ import sys from gh_api import ( get_milestones, get_milestone_id, get_issues_list, ) if __name__ == "__main__": if len(sys.argv) < 2: ...
Include multiple milestones and open issues in contributor list
Include multiple milestones and open issues in contributor list [ci skip]
Python
bsd-3-clause
jhamrick/nbgrader,jhamrick/nbgrader,jupyter/nbgrader,jhamrick/nbgrader,jhamrick/nbgrader,jupyter/nbgrader,jupyter/nbgrader,jupyter/nbgrader,jupyter/nbgrader
94b37ba0abacbff53da342574b61c87810f6a5d4
bulletin/tools/plugins/forms/job.py
bulletin/tools/plugins/forms/job.py
from datetimewidget.widgets import DateTimeWidget from django.forms import ModelForm from form_utils.widgets import ImageWidget from ..models import Job job_field_labels = { 'image': 'Image (10Mb Limit)', 'url': 'URL' } job_help_texts = { 'url': 'Provide a full url, e.g., "http://www.example.com/page.htm...
from datetimewidget.widgets import DateTimeWidget from django.forms import ModelForm from form_utils.widgets import ImageWidget from ..models import Job job_field_labels = { 'image': 'Image (10Mb Limit)', 'url': 'URL' } job_help_texts = { 'url': 'Provide a full url, e.g., "http://www.example.com/page.htm...
Make image required on Job submit form.
Make image required on Job submit form.
Python
mit
AASHE/django-bulletin,AASHE/django-bulletin,AASHE/django-bulletin
9a4ea40b2eb164f8c18e9812c27aa430c3c27772
api/serializers.py
api/serializers.py
from django.contrib.auth.models import User from rest_framework import serializers from api.models import UserPreferences class UserPreferencesSummarySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = UserPreferences fields = ( 'id', 'url' ) ...
from django.contrib.auth.models import User from rest_framework import serializers from api.models import UserPreferences class UserPreferencesSummarySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = UserPreferences fields = ( 'id', 'url' ) ...
Include new airport_ui preference in serializer for view
Include new airport_ui preference in serializer for view
Python
apache-2.0
CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend
1dac2942eb9a15517392eebc9aa96dcb658ebfee
src/passgen.py
src/passgen.py
import string import random import argparse def passgen(length=12): """Generate a strong password with *length* characters""" pool = string.ascii_uppercase + string.ascii_lowercase + string.digits return ''.join(random.SystemRandom().choice(pool) for _ in range(length)) def main(): parser = argparse...
import string import random import argparse def passgen(length=12): """Generate a strong password with *length* characters""" pool = string.ascii_uppercase + string.ascii_lowercase + string.digits # Using technique from Stack Overflow answer # http://stackoverflow.com/a/23728630 chars = [random.S...
Make it more clear how password is generated
Make it more clear how password is generated
Python
mit
soslan/passgen
0c22486320b064c078fe009faf41e2d0c7f5e272
passwordless/views.py
passwordless/views.py
from django.shortcuts import render from django.views.generic.edit import FormView from . import forms # Create your views here. def logout(request): return render(request, 'passwordless/logout.html') def authn(request, token): return render(request, 'passwordless/authn.html') class LoginView(FormView): ...
from django.shortcuts import render from django.views.generic.edit import FormView from . import forms # Create your views here. def logout(request): return render(request, 'passwordless/logout.html') def authn(request, token): return render(request, 'passwordless/authn.html') class LoginView(FormView): ...
Refactor RegisterView as subclass of LoginView
Refactor RegisterView as subclass of LoginView They share much of the work, they should share the code as well
Python
mit
Kromey/fbxnano,Kromey/akwriters,Kromey/fbxnano,Kromey/akwriters,Kromey/akwriters,Kromey/fbxnano,Kromey/fbxnano,Kromey/akwriters
1d5b3630d372d763ad445b969eaad97fd569db52
examples/cross_thread.py
examples/cross_thread.py
#!/usr/bin/python """ Example of an Eliot action context spanning multiple threads. """ from threading import Thread from sys import stdout from eliot import to_file, preserve_context, start_action to_file(stdout) def add_in_thread(x, y): with start_action(action_type="in_thread", x=x, y=y) as context: ...
#!/usr/bin/env python """ Example of an Eliot action context spanning multiple threads. """ from __future__ import unicode_literals from threading import Thread from sys import stdout from eliot import to_file, preserve_context, start_action to_file(stdout) def add_in_thread(x, y): with start_action(action_ty...
Fix hashbang, add future import.
Fix hashbang, add future import.
Python
apache-2.0
ScatterHQ/eliot,ScatterHQ/eliot,ScatterHQ/eliot,ClusterHQ/eliot
0f844e44f0b1b8873aa777becf7e7a8fcc48483b
virtool/indexes/models.py
virtool/indexes/models.py
import enum from sqlalchemy import Column, Integer, String, Enum from virtool.pg.utils import Base, SQLEnum class IndexType(str, SQLEnum): """ Enumerated type for index file types """ json = "json" fasta = "fasta" bowtie2 = "bowtie2" class IndexFile(Base): """ SQL model to store n...
import enum from sqlalchemy import Column, Integer, String, Enum from virtool.pg.utils import Base, SQLEnum class IndexType(str, SQLEnum): """ Enumerated type for index file types """ json = "json" fasta = "fasta" bowtie2 = "bowtie2" class IndexFile(Base): """ SQL model to store n...
Make 'name' and 'index' columns non-nullable for IndexFile model
Make 'name' and 'index' columns non-nullable for IndexFile model
Python
mit
virtool/virtool,virtool/virtool,igboyes/virtool,igboyes/virtool
e01571fb8c29b78f16c34bfcd2d806b183224047
opps/containers/forms.py
opps/containers/forms.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import forms from django.conf import settings from opps.db.models.fields.jsonf import JSONFormField from opps.fields.widgets import JSONField from opps.fields.models import Field, FieldOption class ContainerAdminForm(forms.ModelForm): def __init__(self, *...
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import forms from django.conf import settings from opps.db.models.fields.jsonf import JSONFormField from opps.fields.widgets import JSONField from opps.fields.models import Field, FieldOption class ContainerAdminForm(forms.ModelForm): def __init__(self, *...
Fix mirror_channel widget on OPPS_MIRROR_CHANNEL false
Fix mirror_channel widget on OPPS_MIRROR_CHANNEL false
Python
mit
opps/opps,YACOWS/opps,YACOWS/opps,YACOWS/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,williamroot/opps,opps/opps,williamroot/opps,opps/opps,jeanmask/opps,opps/opps,jeanmask/opps,williamroot/opps
d672cbc84ced1af4f7e5f0cf97c5d087a477717c
tools/sharding_supervisor/sharding_supervisor.py
tools/sharding_supervisor/sharding_supervisor.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. from sharding_supervisor_old import * # pylint: disable=W0401,W0614 if __name__ == "__main__": sys.exit(main())
#!/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. """Defer to run_test_cases.py.""" import os import optparse import sys ROOT_DIR = os.path.dirname( os.path.dirname(os.path.di...
Switch over to run_test_cases.py, take 2.
Switch over to run_test_cases.py, take 2. Instead of doing a "Revert r168479 'Revert r168478'", it's using a simpler version based on renaming sharding_supervisor first. Try to enable run_test_cases.py again. R=phajdan.jr@chromium.org BUG=164886 Review URL: https://codereview.chromium.org/11472024 git-svn-id: de01...
Python
bsd-3-clause
markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,anirudhSK/chromium,anirudhSK/chromium,Fireblend/chromium-crosswalk,mogoweb/chromium-crosswalk,hujiajie/pa-chromium,zcbenz/cefode-chromium,dushu1203/chromium.src,hujiajie/pa-chromium,dushu1203/chromium.src,M4sse/chromium.src,mogoweb/chromium...
a42997458baa1c6a1648896ff50f44e79525f8a1
ognskylines/commands/devices/insert.py
ognskylines/commands/devices/insert.py
from ognskylines.dbutils import session from ognskylines.model import Device from ogn.utils import get_ddb, get_trackable from manager import Manager manager = Manager() @manager.command def import_ddb(): """Import registered devices from the DDB (discards all devices before import).""" session.query(Device...
from ognskylines.dbutils import session from ognskylines.model import Device import requests from manager import Manager manager = Manager() DDB_URL = "http://ddb.glidernet.org/download/?j=1" def get_ddb(): devices = requests.get(DDB_URL).json() for device in devices['devices']: device.update({'ide...
Add function to fetch devices from the DDB
Add function to fetch devices from the DDB
Python
agpl-3.0
kerel-fs/ogn-skylines-gateway,kerel-fs/ogn-skylines-gateway
0ac3ab3278e81aebe4717e0f599f752b4fda06d3
examples/swat-s1/tests.py
examples/swat-s1/tests.py
""" swat-s1 tests. """ # from mininet.cli import CLI from mininet.net import Mininet from nose.plugins.skip import SkipTest from utils import STATE, RWT_INIT_LEVEL from utils import TANK_SECTION from topo import SwatTopo from physical_process import RawWaterTank # import subprocess # import sys @SkipTest def tes...
""" swat-s1 tests. """ # from mininet.cli import CLI from mininet.net import Mininet from utils import STATE, RWT_INIT_LEVEL from utils import TANK_SECTION from topo import SwatTopo from physical_process import RawWaterTank # import subprocess # import sys def test_init(): pass def test_topo(): topo =...
Remove examples dep from nose
Remove examples dep from nose
Python
mit
remmihsorp/minicps,scy-phy/minicps,remmihsorp/minicps,scy-phy/minicps
d5ed26ebbd84ed16d8d39607ef138581aa3b9d75
osf/migrations/0145_add_preprint_contenttype_to_collections.py
osf/migrations/0145_add_preprint_contenttype_to_collections.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-11-08 16:56 from __future__ import unicode_literals from django.db import migrations from osf.models import Collection from django.contrib.contenttypes.models import ContentType def reverse_func(state, schema): preprint_content_type = ContentType.obje...
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-11-08 16:56 from __future__ import unicode_literals from django.db import migrations from osf.models import Collection from django.contrib.contenttypes.models import ContentType def reverse_func(state, schema): preprint_content_type = ContentType.obje...
Use the Collection.collected_types through table to bulk add preprints as a valid collected_type for existing collections.
Use the Collection.collected_types through table to bulk add preprints as a valid collected_type for existing collections. - Use the Collection - collected_types through table to remove preprints from collected_types.
Python
apache-2.0
CenterForOpenScience/osf.io,Johnetordoff/osf.io,pattisdr/osf.io,adlius/osf.io,baylee-d/osf.io,brianjgeiger/osf.io,felliott/osf.io,mattclark/osf.io,mfraezz/osf.io,felliott/osf.io,aaxelb/osf.io,brianjgeiger/osf.io,mfraezz/osf.io,CenterForOpenScience/osf.io,brianjgeiger/osf.io,mfraezz/osf.io,CenterForOpenScience/osf.io,aa...
68b86aff3c9004b12dbd05cd1861229e73883e38
quickstart/python/understand/example-2/create_joke_task.6.x.py
quickstart/python/understand/example-2/create_joke_task.6.x.py
# Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) # Create a new task named 't...
# Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) # Provide actions for the ne...
Update to include actions in Create
Update to include actions in Create
Python
mit
TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets
4349e65c1c353f8808e139c57439a3dfe2e2846e
armstrong/core/arm_sections/views.py
armstrong/core/arm_sections/views.py
from django.core.urlresolvers import reverse from django.views.generic import DetailView from django.contrib.syndication.views import Feed from django.shortcuts import get_object_or_404 from .models import Section class SimpleSectionView(DetailView): context_object_name = 'section' model = Section def g...
from django.core.urlresolvers import reverse from django.views.generic import DetailView from django.contrib.syndication.views import Feed from django.shortcuts import get_object_or_404 from .models import Section class SimpleSectionView(DetailView): context_object_name = 'section' model = Section def g...
Call get_section from get_object for backwards compatibility
Call get_section from get_object for backwards compatibility
Python
apache-2.0
texastribune/armstrong.core.tt_sections,armstrong/armstrong.core.arm_sections,texastribune/armstrong.core.tt_sections,texastribune/armstrong.core.tt_sections,armstrong/armstrong.core.arm_sections
7e0030eb22671897a80633d57056ba0f26f15a77
src/coordinators/models.py
src/coordinators/models.py
from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from locations.models import District class Coordinator(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) is_manage...
from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from locations.models import District class Coordinator(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) is_manage...
Make filter_by_district more strict - don't show anything to unconfigured users
Make filter_by_district more strict - don't show anything to unconfigured users
Python
mit
mrts/foodbank-campaign,mrts/foodbank-campaign,mrts/foodbank-campaign,mrts/foodbank-campaign
347038c528b07f2553f09daab6915828ab2a6113
tests/__init__.py
tests/__init__.py
# -*- coding: utf-8 -*- # Copyright 2011-2012 Antoine Bertin <diaoulael@gmail.com> # # This file is part of subliminal. # # subliminal is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by # the Free Software Foundation; either version 3 of...
# -*- coding: utf-8 -*- # Copyright 2011-2012 Antoine Bertin <diaoulael@gmail.com> # # This file is part of subliminal. # # subliminal is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by # the Free Software Foundation; either version 3 of...
Add test_videos to the main test suite
Add test_videos to the main test suite
Python
mit
oxan/subliminal,t4lwh/subliminal,h3llrais3r/subliminal,getzze/subliminal,bogdal/subliminal,hpsbranco/subliminal,ravselj/subliminal,nvbn/subliminal,fernandog/subliminal,goll/subliminal,ratoaq2/subliminal,Elettronik/subliminal,neo1691/subliminal,juanmhidalgo/subliminal,SickRage/subliminal,Diaoul/subliminal,kbkailashbagar...
a18e29b492cefaac64b2bd217a897aff7ebd8466
tests/__init__.py
tests/__init__.py
# tests.__init__ import os import os.path import shutil import tempfile import yvs.shared as yvs temp_dir = tempfile.gettempdir() yvs.LOCAL_DATA_DIR_PATH = os.path.join(temp_dir, 'yvs-data') yvs.LOCAL_CACHE_DIR_PATH = os.path.join(temp_dir, 'yvs-cache') def set_up(): try: os.mkdir(yvs.LOCAL_DATA_DIR_PA...
# tests.__init__ import os import os.path import shutil import tempfile import yvs.shared as yvs from mock import patch temp_dir = tempfile.gettempdir() local_data_dir_patcher = patch( 'yvs.shared.LOCAL_DATA_DIR_PATH', os.path.join(temp_dir, 'yvs-data')) local_cache_dir_patcher = patch( 'yvs.shared.LOCAL...
Use patchers for overriding data/cache directories
Use patchers for overriding data/cache directories
Python
mit
caleb531/youversion-suggest,caleb531/youversion-suggest
341dcac3331a21c1b747075ab73601cb08d4868d
compliance_checker/tests/helpers.py
compliance_checker/tests/helpers.py
from netCDF4 import Dataset import tempfile class MockNetCDF(Dataset): """ Wrapper object around NetCDF Dataset to write data only to memory. """ def __init__(self): # taken from test/tst_diskless.py NetCDF library # even though we aren't persisting data to disk, the constructor ...
from netCDF4 import Dataset import tempfile class MockNetCDF(Dataset): """ Wrapper object around NetCDF Dataset to write data only to memory. """ def __init__(self): # taken from test/tst_diskless.py NetCDF library # even though we aren't persisting data to disk, the constructor ...
Add name and dimensions attributes to MockVariable class
Add name and dimensions attributes to MockVariable class
Python
apache-2.0
DanielJMaher/compliance-checker,aodn/compliance-checker,ioos/compliance-checker,lukecampbell/compliance-checker,ocefpaf/compliance-checker
316066b2415861b65d540b822df1b2afea906207
regulations/management/commands/setup_cors.py
regulations/management/commands/setup_cors.py
import boto3 from django.conf import settings from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'Set CORS rules on the Notice and Comment attachment bucket' def handle(self, *args, **options): session = boto3.Session( aws_access_key_id=settings.ATTACHM...
import boto3 from django.conf import settings from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'Set CORS rules on the Notice and Comment attachment bucket' def handle(self, *args, **options): hosts = settings.ALLOWED_HOSTS origins = ['http://' + host for ...
Add protocol to hosts for CORS
Add protocol to hosts for CORS
Python
cc0-1.0
18F/regulations-site,tadhg-ohiggins/regulations-site,eregs/regulations-site,18F/regulations-site,eregs/regulations-site,eregs/regulations-site,tadhg-ohiggins/regulations-site,tadhg-ohiggins/regulations-site,18F/regulations-site,eregs/regulations-site,18F/regulations-site,tadhg-ohiggins/regulations-site
cdfa65efbb9c97f060a51aa5613a2788c437e0a1
pal/services/__init__.py
pal/services/__init__.py
from pal.services.bonapp_service import BonAppService from pal.services.dictionary_service import DictionaryService from pal.services.directory_service import DirectoryService from pal.services.joke_service import JokeService from pal.services.movie_service import MovieService from pal.services.service import wrap_resp...
from pal.services.bonapp_service import BonAppService from pal.services.dictionary_service import DictionaryService from pal.services.directory_service import DirectoryService from pal.services.joke_service import JokeService from pal.services.movie_service import MovieService from pal.services.service import wrap_resp...
Put JokeService in the right place alphabetically
Put JokeService in the right place alphabetically
Python
bsd-3-clause
Machyne/pal,Machyne/pal,Machyne/pal,Machyne/pal
6fe588ea915d65fdab00b53f883b0a72ef6cf564
tests/test_apd.py
tests/test_apd.py
import json from sforparser.apd import scraper INPUT_FILE = 'data/apd/input.txt' def test_output_strips_email_spaces(): json_str = scraper(open(INPUT_FILE)) data = json.loads(json_str) offensive_field = data[70]["locations"][0]["emails"] expected = [ "ronald.sanders@sfdph.org", "jua...
import json import os import pytest from sforparser.apd import scraper INPUT_FILE = 'data/apd/input.txt' @pytest.fixture def data(): json_str = scraper(open(INPUT_FILE)) artifact_dir = os.getenv('CIRCLE_ARTIFACTS') if artifact_dir: artifact_file = os.path.join(artifact_dir, 'apd.json') ...
Switch to pytest fixture and generate artifact for circle ci
Switch to pytest fixture and generate artifact for circle ci
Python
mit
sfbrigade/sf-openreferral-datalib
c67864e50b92c38cbcc0e4e8ae630ff9e7194a55
profiles/views.py
profiles/views.py
from django.conf import settings from django.contrib.auth.decorators import login_required from django.contrib.sites.models import Site from django.core.urlresolvers import reverse from django.utils.datastructures import MultiValueDictKeyError from django.views.generic import TemplateView, UpdateView from incuna.utils ...
from django.conf import settings from django.contrib.auth.decorators import login_required from django.contrib.sites.models import Site from django.core.urlresolvers import reverse from django.views.generic import TemplateView, UpdateView from incuna.utils import get_class_from_path from profiles.models import Profile...
Remove the exception handling code for getting the success url
Remove the exception handling code for getting the success url
Python
bsd-2-clause
incuna/django-extensible-profiles
48902df1fb9b8b299155cd7e2f9a2bf3444abdc8
awsom/__init__.py
awsom/__init__.py
#!/usr/bin/python from awsom.entity import Entity, Factory from awsom.config import AccountEntity, config class ModelRootFactory(Factory): def __init__(self, entity): super(ModelRootFactory, self).__init__(entity) def populate(self): # Attach all configuration-defined accounts as children of th...
#!/usr/bin/python from awsom.entity import Entity, Factory from awsom.config import AccountEntity, config class ModelRootFactory(Factory): def __init__(self, entity): super(ModelRootFactory, self).__init__(entity) def populate(self): # Attach all configuration-defined accounts as children of th...
Fix bug with account additions using old Entity API
Fix bug with account additions using old Entity API
Python
mit
tuxpiper/awsom
dff2b0cb2b425217435deaa7c33d54f168f1a9d7
playground/testing.py
playground/testing.py
import numpy as np import matplotlib.pyplot as plt def takeFFT(data): data = data / np.linalg.norm(data) data_squared = np.square(data) fft_out = np.fft.fft(data_squared) fft_shape = np.fft.fftfreq(data_squared.shape[-1]) plt.stem(fft_shape, fft_out) #plt.stem(fft_shape, np.fft.fftshift(fft_ou...
import numpy as np import matplotlib.pyplot as plt import seaborn as sns def takeFFT(data): data = data / np.linalg.norm(data) data_squared = np.square(data) fft_out = np.fft.fft(data_squared) fft_shape = np.fft.fftfreq(data_squared.shape[-1]) a = np.absolute(fft_out).argmax() print(fft_out[a]...
Fix frequency and phase offset
Fix frequency and phase offset
Python
mit
williamalu/mimo_usrp
4c23e08172f3a1dfc64e32fce53f8f7188a0bf0c
pubsubpull/api.py
pubsubpull/api.py
""" APIs exposed by pubsubpull. """ from __future__ import absolute_import from async.api import schedule from django.db import connection from pubsubpull import _join_with_project_path def add_trigger_function(): """Used for older versions of Postres, or test runs where there are no migrations. ...
""" APIs exposed by pubsubpull. """ from __future__ import absolute_import from async.api import schedule from django.db import connection from pubsubpull import _join_with_project_path def add_trigger_function(): """Used for older versions of Postres, or test runs where there are no migrations. ...
Return the SQL we've just tried to run
Return the SQL we've just tried to run
Python
mit
KayEss/django-pubsubpull,KayEss/django-pubsubpull,KayEss/django-pubsubpull
c39c362e949a7d89f92207d0b26bc9f6d61eacae
ibmcnx/doc/DataSources.py
ibmcnx/doc/DataSources.py
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Appli...
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Appli...
Create script to save documentation to a file
4: Create script to save documentation to a file Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/4
Python
apache-2.0
stoeps13/ibmcnx2,stoeps13/ibmcnx2
4d06890ae7223a61147da857d8cdfb6c208dfc52
lib/pegasus/python/Pegasus/cli/pegasus-init.py
lib/pegasus/python/Pegasus/cli/pegasus-init.py
#!/usr/bin/env python3 import sys import os import subprocess # Use pegasus-config to find our lib path bin_dir = os.path.normpath(os.path.join(os.path.dirname(sys.argv[0]))) pegasus_config = os.path.join(bin_dir, "pegasus-config") + " --python-dump" exec(subprocess.Popen(pegasus_config, stdout=subprocess.PIPE, shell=...
#!/usr/bin/env python3 import os from pathlib import Path from Pegasus.init import main pegasus_share_dir = (Path(os.environ["PEGASUS_HOME"]) / "share" / "pegasus").resolve() main(str(pegasus_share_dir))
Remove call to p-config, as it is handled in p-python-wrapper
Remove call to p-config, as it is handled in p-python-wrapper
Python
apache-2.0
pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus
e2efb3855cd7888b778c3c7ff343c2bdcb942ab0
pushmanager/testing/__init__.py
pushmanager/testing/__init__.py
#!/usr/bin/env python import testify # don't want all of testify's modules, just its goodies from testify.__init__ import * from mocksettings import MockedSettings from testservlet import AsyncTestCase from testservlet import ServletTestMixin from testservlet import TemplateTestCase from testdb import * __all__ = ...
#!/usr/bin/python # don't want all of testify's modules, just its goodies from testify import TestCase from testify import teardown from testify import class_teardown from testify import class_setup_teardown from testify import setup_teardown from testify import setup from testify import class_setup from testify impor...
Make pushmanager.testing more explicit in imports
Make pushmanager.testing more explicit in imports
Python
apache-2.0
Yelp/pushmanager,YelpArchive/pushmanager,asottile/pushmanager,Yelp/pushmanager,asottile/pushmanager,YelpArchive/pushmanager,YelpArchive/pushmanager,asottile/pushmanager,Yelp/pushmanager,Yelp/pushmanager,YelpArchive/pushmanager