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
b3b67fe0e68423fc2f85bccf1f20acdb779a38ba
pylxd/deprecated/tests/utils.py
pylxd/deprecated/tests/utils.py
# Copyright (c) 2015 Canonical Ltd # # 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 law or ...
# Copyright (c) 2015 Canonical Ltd # # 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 law or ...
Remove unused testing utility function
Remove unused testing utility function Signed-off-by: Dougal Matthews <8f24f2c0fd825cfb6716a36822888c4a01678c88@dougalmatthews.com>
Python
apache-2.0
lxc/pylxd,lxc/pylxd
57bb37d7579620005a49613ff90f0a2eec55a77e
backend/offers_web.py
backend/offers_web.py
import falcon import json import rethinkdb as r MAX_OFFERS = 100 class OfferListResource: def __init__(self): self._db = r.connect('localhost', 28015) def on_get(self, req, resp): """Returns all offers available""" try: limit, page = map(int, (req.params.get('limit', MAX_O...
import falcon import json import rethinkdb as r MAX_OFFERS = 100 class OfferListResource: def __init__(self): self._db = r.connect('localhost', 28015) def on_get(self, req, resp): """Returns all offers available""" try: limit, page = map(int, (req.params.get('limit', MAX_O...
Fix max elements in header
Fix max elements in header
Python
agpl-3.0
jilljenn/voyageavecmoi,jilljenn/voyageavecmoi,jilljenn/voyageavecmoi
fac7e7d8759aab7e2bea666e55d71e35da45c334
groundstation/gref.py
groundstation/gref.py
import os class Gref(object): def __init__(self, store, channel, identifier): self.store = store self.channel = channel.replace("/", "_") self.identifier = identifier self._node_path = os.path.join(self.store.gref_path(), self.channel, ...
import os class Gref(object): def __init__(self, store, channel, identifier): self.store = store self.channel = channel.replace("/", "_") self.identifier = identifier self._node_path = os.path.join(self.store.gref_path(), self.channel, ...
Implement Gref.tips() to fetch it's tips.
Implement Gref.tips() to fetch it's tips.
Python
mit
richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation
06a19b5c693b2b5b808f8e7b00136bef6b1a04c3
base/relengapi/app.py
base/relengapi/app.py
from flask import current_app from flask import Flask from flask import g from flask import jsonify from flask import redirect from flask import url_for from relengapi import celery from relengapi import db import pkg_resources def create_app(cmdline=False): app = Flask('relengapi') app.config.from_envvar('REL...
import os from flask import current_app from flask import Flask from flask import g from flask import jsonify from flask import redirect from flask import url_for from relengapi import celery from relengapi import db import pkg_resources def create_app(cmdline=False): app = Flask('relengapi') app.config.from_e...
Set a random session key if none is configured
Set a random session key if none is configured
Python
mpl-2.0
mozilla-releng/services,andrei987/services,srfraser/services,andrei987/services,srfraser/services,lundjordan/services,mozilla/build-relengapi,garbas/mozilla-releng-services,garbas/mozilla-releng-services,lundjordan/services,andrei987/services,andrei987/services,garbas/mozilla-releng-services,srfraser/services,hwine/bui...
1af37551cd8e68e84a25f77dc57e5c94b10d3b87
btcx/common.py
btcx/common.py
from twisted.words.xish.utility import EventDispatcher USER_AGENT = 'btcx-bot' class ExchangeEvent(EventDispatcher): def __init__(self, **kwargs): EventDispatcher.__init__(self, **kwargs) def listen(self, msg, cb): event = "%s/%s" % (self.prefix, msg) self.addObserver(event, cb) ...
import os from twisted.words.xish.utility import EventDispatcher USER_AGENT = 'btcx-bot' class ExchangeEvent(EventDispatcher): def __init__(self, **kwargs): EventDispatcher.__init__(self, **kwargs) self.listener = {} def listen(self, msg, cb): event = "%s/%s" % (self.prefix, msg) ...
Support for removing listeners by means of a listener id.
Support for removing listeners by means of a listener id.
Python
mit
knowitnothing/btcx,knowitnothing/btcx
a419f6dcb7968d6af1e3ef8eae29b723d96b5fd2
stayput/jinja2/__init__.py
stayput/jinja2/__init__.py
from jinja2 import Environment, FileSystemLoader from stayput import Templater class Jinja2Templater(Templater): def __init__(self, site, *args, **kwargs): self.site = site self.env = Environment(loader=FileSystemLoader(site.templates_path)) def template(self, item): return self.env...
from jinja2 import Environment, FileSystemLoader from stayput import Templater class Jinja2Templater(Templater): def __init__(self, site, *args, **kwargs): self.site = site self.env = Environment(loader=FileSystemLoader(site.templates_path)) def template(self, item, site, *args, **kwargs): ...
Update for stayput master and ensure forward compatibility
Update for stayput master and ensure forward compatibility
Python
mit
veeti/stayput_jinja2
df690e4c2f19e30c619db90b8b2dfd77dab54159
sympy/printing/__init__.py
sympy/printing/__init__.py
"""Printing subsystem""" from pretty import * from latex import latex, print_latex from mathml import mathml, print_mathml from python import python, print_python from ccode import ccode, print_ccode from fcode import fcode, print_fcode from jscode import jscode, print_jscode from gtk import * from preview import prev...
"""Printing subsystem""" from pretty import pager_print, pretty, pretty_print, pprint, \ pprint_use_unicode, pprint_try_use_unicode from latex import latex, print_latex from mathml import mathml, print_mathml from python import python, print_python from ccode import ccode, print_ccode from fcode import fcode, prin...
Remove glob imports from sympy.printing.
Remove glob imports from sympy.printing.
Python
bsd-3-clause
Designist/sympy,emon10005/sympy,farhaanbukhsh/sympy,mafiya69/sympy,kaushik94/sympy,atreyv/sympy,kmacinnis/sympy,Mitchkoens/sympy,aktech/sympy,sunny94/temp,grevutiu-gabriel/sympy,wanglongqi/sympy,AunShiLord/sympy,jamesblunt/sympy,emon10005/sympy,shikil/sympy,rahuldan/sympy,diofant/diofant,yashsharan/sympy,kmacinnis/symp...
5d01c58aef7f101531ecc7a44a83d225fa2fdcc8
npc/linters/__init__.py
npc/linters/__init__.py
from . import changeling
""" Linters for verifying the correctness of certain character types The `commands.lint` function can lint all basic files, but special character types sometimes need extra checks. The linters in this package encapsulate that logic. All linter packages have a single main entry point `lint` which accepts a character i...
Add docstring to linters package
Add docstring to linters package
Python
mit
aurule/npc,aurule/npc
42389e796acba99fe12e30e6ca08672b889bd5f2
infrastructure/serializers.py
infrastructure/serializers.py
from rest_framework import serializers from . import models from scorecard.serializers import GeographySerializer class FinancialYearSerializer(serializers.ModelSerializer): class Meta: model = models.FinancialYear fields = ["budget_year"] class BudgetPhaseSerializer(serializers.ModelSerializer...
from rest_framework import serializers from . import models from scorecard.serializers import GeographySerializer class FinancialYearSerializer(serializers.ModelSerializer): class Meta: model = models.FinancialYear fields = ["budget_year"] read_only_fields = ["budget_year"] class Budget...
Make fields readonly, skips rest_framework, validation, speeds up queries
Make fields readonly, skips rest_framework, validation, speeds up queries
Python
mit
Code4SA/municipal-data,Code4SA/municipal-data,Code4SA/municipal-data,Code4SA/municipal-data
0f12f4a2e8b68cf48b9768a6b18a1a560068eac2
app/timetables/models.py
app/timetables/models.py
from __future__ import unicode_literals from django.db import models class Weekday(models.Model): """Model representing the day of the week.""" name = models.CharField(max_length=60, unique=True) def clean(self): """ Capitalize the first letter of the first word to avoid case in...
from __future__ import unicode_literals from django.db import models class Weekday(models.Model): """Model representing the day of the week.""" name = models.CharField(max_length=60, unique=True) def clean(self): """ Capitalize the first letter of the first word to avoid case in...
Change meal name to charfield
Change meal name to charfield
Python
mit
teamtaverna/core
8883f1a45595219ae843b3400df1f56ab07aa4fe
corehq/apps/userreports/document_stores.py
corehq/apps/userreports/document_stores.py
from corehq.form_processor.document_stores import ReadonlyFormDocumentStore, ReadonlyCaseDocumentStore from corehq.form_processor.utils import should_use_sql_backend from corehq.util.couch import get_db_by_doc_type from pillowtop.dao.couch import CouchDocumentStore def get_document_store(domain, doc_type): use_sq...
from corehq.apps.locations.models import SQLLocation from corehq.form_processor.document_stores import ReadonlyFormDocumentStore, ReadonlyCaseDocumentStore from corehq.form_processor.utils import should_use_sql_backend from corehq.util.couch import get_db_by_doc_type from pillowtop.dao.couch import CouchDocumentStore f...
Add document store for locations
Add document store for locations
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
7fd3e82c449ebf46e369d2a8c2bf534cb6b17607
notebook/lib/pos_tags.py
notebook/lib/pos_tags.py
import nltk class PosTags: def tag(self, t): ''' With a list of tokens, mark their part of speech and return a list dicts (no native tuple type in dataframes it seems). ''' pos = nltk.pos_tag(t) retval = [] for p in pos: retval.append({"word": p[...
import nltk class PosTags: def tag(self, t, as_dicts=True): ''' With a list of tokens, mark their part of speech and return a list dicts (no native tuple type in dataframes it seems). ''' pos = nltk.pos_tag(t) if as_dicts: return self.to_dicts(pos) ...
Change return to allow for original tuples to come out since we'll need them for chunking
Change return to allow for original tuples to come out since we'll need them for chunking
Python
mit
mjcollin/2016spr,mjcollin/2016spr,mjcollin/2016spr
138aa351b3dbe95f3cdebf01dbd3c75f1ce3fac2
src/ggrc/fulltext/sql.py
src/ggrc/fulltext/sql.py
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: david@reciprocitylabs.com # Maintained By: david@reciprocitylabs.com from ggrc import db from . import Indexer class SqlIndexer(Indexer): def cr...
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: david@reciprocitylabs.com # Maintained By: david@reciprocitylabs.com from ggrc import db from . import Indexer class SqlIndexer(Indexer): def cr...
Fix test broken due to delete_record change
Fix test broken due to delete_record change
Python
apache-2.0
kr41/ggrc-core,uskudnik/ggrc-core,vladan-m/ggrc-core,AleksNeStu/ggrc-core,prasannav7/ggrc-core,josthkko/ggrc-core,vladan-m/ggrc-core,hyperNURb/ggrc-core,vladan-m/ggrc-core,uskudnik/ggrc-core,jmakov/ggrc-core,NejcZupec/ggrc-core,hyperNURb/ggrc-core,andrei-karalionak/ggrc-core,hasanalom/ggrc-core,selahssea/ggrc-core,Alek...
756c9ae9487ac5c35f069b79e792043bca0af27e
panoptes_client/utils.py
panoptes_client/utils.py
import functools ITERABLE_TYPES = ( list, set, tuple, ) try: from numpy import ndarray ITERABLE_TYPES = ITERABLE_TYPES + (ndarray,) except ImportError: pass def isiterable(v): return isinstance(v, ITERABLE_TYPES) def batchable(func=None, batch_size=100): def do_batch(*args, **kwar...
import functools ITERABLE_TYPES = ( list, set, tuple, ) try: from numpy import ndarray ITERABLE_TYPES = ITERABLE_TYPES + (ndarray,) except ImportError: pass def isiterable(v): return isinstance(v, ITERABLE_TYPES) def batchable(func=None, batch_size=100): def do_batch(*args, **kwar...
Fix passing sets to batchable methods
Fix passing sets to batchable methods Sets don't support indexing, so convert them to lists.
Python
apache-2.0
zooniverse/panoptes-python-client
e170666cbbc1f2a61c0ffa077c66da4556a6c5bb
app/packages/views.py
app/packages/views.py
import requests from . import packages from models import Package, Downloads from flask import jsonify from datetime import timedelta from app import cache from utils import cache_timeout @packages.route('/stats', methods=['GET']) @cache_timeout @cache.cached() def stats(): resp = dict() resp["count"] = Packa...
import requests from . import packages from models import Package, Downloads from flask import jsonify from datetime import timedelta from app import cache from utils import cache_timeout @packages.route('/stats', methods=['GET']) @cache_timeout @cache.cached() def stats(): resp = dict() resp["count"] = Packa...
Add my packages to featured list
Add my packages to featured list
Python
bsd-2-clause
NikhilKalige/atom-website,NikhilKalige/atom-website,NikhilKalige/atom-website
33f2636e1de536a633cec9332362252b0b614817
serpent/templates/SerpentGamePlugin/files/serpent_game.py
serpent/templates/SerpentGamePlugin/files/serpent_game.py
from serpent.game import Game from .api.api import MyGameAPI from serpent.utilities import Singleton from serpent.input_controller import InputControllers from serpent.game_launchers.web_browser_game_launcher import WebBrowser class SerpentGame(Game, metaclass=Singleton): def __init__(self, **kwargs): ...
from serpent.game import Game from .api.api import MyGameAPI from serpent.utilities import Singleton from serpent.game_launchers.web_browser_game_launcher import WebBrowser class SerpentGame(Game, metaclass=Singleton): def __init__(self, **kwargs): kwargs["platform"] = "PLATFORM" kwargs["wind...
Remove kwargs["input_controller"] from the Game plugin template
Remove kwargs["input_controller"] from the Game plugin template
Python
mit
SerpentAI/SerpentAI
d6433001f3660c9c4506fe5e1f62c0a52edd02f7
project/djenerator/tests.py
project/djenerator/tests.py
#!/usr/bin/env python """ This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.test import TestCase
#!/usr/bin/env python """ This module contains tests for djenerator app. """ from django.test import TestCase from model_reader import is_instance_of_model from models import ExtendingModel from models import NotExtendingModel from models import TestModel0 from models import TestModel1 from models import TestModelA fro...
Test Cases for is instance of Model function
Test Cases for is instance of Model function
Python
mit
mostafa-mahmoud/djenerator,aelguindy/djenerator,mostafa-mahmoud/djenerator
6631906fc126eadc114a7ee673194da4880dc960
flask_admin/contrib/geoa/typefmt.py
flask_admin/contrib/geoa/typefmt.py
from flask_admin.contrib.sqla.typefmt import DEFAULT_FORMATTERS as BASE_FORMATTERS import json from jinja2 import Markup from wtforms.widgets import html_params from geoalchemy2.shape import to_shape from geoalchemy2.elements import WKBElement from sqlalchemy import func from flask import current_app def geom_formatt...
from flask_admin.contrib.sqla.typefmt import DEFAULT_FORMATTERS as BASE_FORMATTERS from jinja2 import Markup from wtforms.widgets import html_params from geoalchemy2.shape import to_shape from geoalchemy2.elements import WKBElement from sqlalchemy import func def geom_formatter(view, value): params = html_params(...
Remove Flask-SQLAlchemy dependency It should be noted that the declarative base still has to be configured like this:
Remove Flask-SQLAlchemy dependency It should be noted that the declarative base still has to be configured like this: ```python MyBase: query = session.query_property() ``` Also decreased code duplication and removed unused imports.
Python
bsd-3-clause
torotil/flask-admin,likaiguo/flask-admin,iurisilvio/flask-admin,toddetzel/flask-admin,mikelambert/flask-admin,lifei/flask-admin,likaiguo/flask-admin,rochacbruno/flask-admin,ArtemSerga/flask-admin,closeio/flask-admin,betterlife/flask-admin,jschneier/flask-admin,torotil/flask-admin,toddetzel/flask-admin,closeio/flask-adm...
e35ff2f0e45289c40a57c9488156829c60f9d3a0
vumi_http_proxy/clickme.py
vumi_http_proxy/clickme.py
#!/usr/bin/env python import click from vumi_http_proxy import http_proxy @click.command() @click.option('--interface', default="0.0.0.0", help='eg 0.0.0.0') @click.option('--port', default=8080, help='eg 80') def cli(interface, port): cli.interface = str(interface) cli.port = port """This script runs vu...
#!/usr/bin/env python import click from vumi_http_proxy import http_proxy @click.command() @click.option('--interface', default="0.0.0.0", help='eg 0.0.0.0') @click.option('--port', default=8080, help='eg 80') def cli(interface, port): """This script runs vumi-http-proxy on <interface>:<port>""" interface = ...
Change unicode ip to string
Change unicode ip to string
Python
bsd-3-clause
praekelt/vumi-http-proxy,praekelt/vumi-http-proxy
435b989d75b9e57cf2fe5fec6892c481a278a102
examples/capabilities/selenoid_cap_file.py
examples/capabilities/selenoid_cap_file.py
# Desired capabilities example file for Selenoid Grid # # The same result can be achieved on the command-line with: # --cap-string='{"selenoid:options": {"enableVNC": true}}' capabilities = { "screenResolution": "1280x1024x24", "selenoid:options": { "enableVNC": True, "enableVideo": False, ...
# Desired capabilities example file for Selenoid Grid # # The same result can be achieved on the command-line. Eg: # --cap-string='{"selenoid:options": {"enableVNC": true}}' capabilities = { "acceptSslCerts": True, "acceptInsecureCerts": True, "screenResolution": "1920x1080x24", "selenoid:options":...
Update an example capabilities file
Update an example capabilities file
Python
mit
mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase
a26f3ee3df1f70302bc524e3a8decb1a1266aadd
devito/data/meta.py
devito/data/meta.py
from devito.tools import Tag __all__ = ['DOMAIN', 'OWNED', 'HALO', 'NOPAD', 'FULL', 'LEFT', 'RIGHT', 'CENTER'] class DataRegion(Tag): pass DOMAIN = DataRegion('domain') OWNED = DataRegion('owned') # within DOMAIN HALO = DataRegion('halo') NOPAD = DataRegion('nopad') # == DOMAIN+HALO FULL = DataReg...
from devito.tools import Tag __all__ = ['DOMAIN', 'OWNED', 'HALO', 'NOPAD', 'FULL', 'LEFT', 'RIGHT', 'CENTER'] class DataRegion(Tag): pass DOMAIN = DataRegion('domain') OWNED = DataRegion('owned') # within DOMAIN HALO = DataRegion('halo') NOPAD = DataRegion('nopad') # == DOMAIN+HALO FULL = DataReg...
Add static value to LEFT, CENTER, RIGHT
data: Add static value to LEFT, CENTER, RIGHT
Python
mit
opesci/devito,opesci/devito
220748a5cc481b8df76af6a1301af94def603ee2
paci/helpers/display_helper.py
paci/helpers/display_helper.py
"""Helper to output stuff""" from tabulate import tabulate def print_list(header, entries): """Prints out a list""" print(tabulate(entries, header, tablefmt="grid")) def print_table(entries): """Prints out a table""" print(tabulate(entries, tablefmt="plain")) def std_input(text, default): """...
"""Helper to output stuff""" from tabulate import tabulate import os def print_list(header, entries): """Prints out a list""" print(tabulate(fix_descriptions(entries), header, tablefmt="presto")) def print_table(entries): """Prints out a table""" print(tabulate(cleanup_entries(entries), tablefmt="p...
Fix how tables are printed on smaller screens
Fix how tables are printed on smaller screens
Python
mit
tradebyte/paci,tradebyte/paci
e42f77d374bab66fb1a90322c3b36c8f75f2499c
pft/errors.py
pft/errors.py
"""Module that contains error handlers.""" from flask import render_template, Blueprint error = Blueprint('error', __name__) @error.app_errorhandler(404) def page_not_found(e): """Return page not found HTML page.""" return render_template('404.html'), 404 @error.app_errorhandler(500) def internal_server_er...
"""Module that contains error handlers.""" from flask import render_template, Blueprint from .database import db error = Blueprint('error', __name__) @error.app_errorhandler(404) def page_not_found(e): """Return page not found HTML page.""" return render_template('404.html'), 404 @error.app_errorhandler(50...
Add database rollback to error handler
Add database rollback to error handler
Python
unknown
gregcowell/PFT,gregcowell/BAM,gregcowell/BAM,gregcowell/PFT
b728253a668c7ff2fba12678d77344bfc645e40b
dusty/daemon.py
dusty/daemon.py
import os import atexit import logging import socket from .preflight import preflight_check from .log import configure_logging from .notifier import notify from .constants import SOCKET_PATH, SOCKET_TERMINATOR def _clean_up_existing_socket(): try: os.unlink(SOCKET_PATH) except OSError: if os.p...
import os import atexit import logging import socket from .preflight import preflight_check from .log import configure_logging from .notifier import notify from .constants import SOCKET_PATH, SOCKET_TERMINATOR def _clean_up_existing_socket(socket_path): try: os.unlink(socket_path) except OSError: ...
Make this easier to test, which we'll get to a bit later
Make this easier to test, which we'll get to a bit later
Python
mit
gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty
fca363dec1ff73e34e25084322d5a31dd6fbc1ee
simplestatistics/statistics/coefficient_of_variation.py
simplestatistics/statistics/coefficient_of_variation.py
from .standard_deviation import standard_deviation from .mean import mean def coefficient_of_variation(data): """ The `coefficient_of_variation`_ is the ratio of the standard deviation to the mean .. _`coefficient of variation`: https://en.wikipedia.org/wiki/Coefficient_of_variation Args: data...
from .standard_deviation import standard_deviation from .mean import mean def coefficient_of_variation(data, sample = True): """ The `coefficient of variation`_ is the ratio of the standard deviation to the mean. .. _`coefficient of variation`: https://en.wikipedia.org/wiki/Coefficient_of_variation A...
Add sample param to CV function
Add sample param to CV function Boolean param to make possible to calculate coefficient of variation for population (default is sample).
Python
unknown
tmcw/simple-statistics-py,sheriferson/simplestatistics,sheriferson/simple-statistics-py
b62415c19459d9e5819b82f464731b166157811d
gym/envs/tests/test_registration.py
gym/envs/tests/test_registration.py
# -*- coding: utf-8 -*- from gym import error, envs from gym.envs import registration from gym.envs.classic_control import cartpole def test_make(): env = envs.make('CartPole-v0') assert env.spec.id == 'CartPole-v0' assert isinstance(env, cartpole.CartPoleEnv) def test_spec(): spec = envs.spec('CartPo...
# -*- coding: utf-8 -*- from gym import error, envs from gym.envs import registration from gym.envs.classic_control import cartpole def test_make(): env = envs.make('CartPole-v0') assert env.spec.id == 'CartPole-v0' assert isinstance(env, cartpole.CartPoleEnv) def test_spec(): spec = envs.spec('CartPo...
Fix exception message formatting in Python3
Fix exception message formatting in Python3
Python
mit
d1hotpep/openai_gym,machinaut/gym,machinaut/gym,d1hotpep/openai_gym,dianchen96/gym,Farama-Foundation/Gymnasium,dianchen96/gym,Farama-Foundation/Gymnasium
c0ed918e09bcb0c0eb1aec20e375c7da8c7466ef
tests/NongeneratingSymbolsRemove/RecursiveTest.py
tests/NongeneratingSymbolsRemove/RecursiveTest.py
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy-transforms """ from unittest import TestCase, main from grammpy import * from grammpy_transforms import * class RecursiveTest(TestCase): pass if __name__ == '__main__': main()
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy-transforms """ from unittest import TestCase, main from grammpy import * from grammpy_transforms import * class A(Nonterminal): pass class B(Nonterminal): pass class C(Nonterminal): pass clas...
Add grammar for test of recursive grammar
Add grammar for test of recursive grammar
Python
mit
PatrikValkovic/grammpy
1e078b88b4eecaa5a9d0a2ada9a64237fe3c4f09
users/management/commands/social_auth_migrate.py
users/management/commands/social_auth_migrate.py
from allauth.socialaccount.models import SocialAccount from django.core.management.base import BaseCommand from django.db import IntegrityError from social_django.models import UserSocialAuth class Command(BaseCommand): help = 'Migrate allauth social logins to social auth' def handle(self, *args, **options):...
from allauth.socialaccount.models import SocialAccount, SocialApp from django.core.management.base import BaseCommand from django.db import IntegrityError from social_django.models import UserSocialAuth class Command(BaseCommand): help = 'Migrate allauth social logins to social auth' def add_arguments(self, ...
Implement app secret printing to social_auth migration tool
Implement app secret printing to social_auth migration tool
Python
mit
mikkokeskinen/tunnistamo,mikkokeskinen/tunnistamo
2d067d0dbf4f04203c9bda2d8fb48d58fae3913d
datapoints/sql_queries.py
datapoints/sql_queries.py
## this should show in red if the COUNT is less than the total ## number of regions that exist for that relationshiop show_region_aggregation = ''' SELECT i.name , SUM(d.value) as value , r.full_name FROM region_relationship rr INNER JOIN datapoint d ...
## this should show in red if the COUNT is less than the total ## number of regions that exist for that relationshiop show_region_aggregation = ''' SELECT i.name , SUM(d.value) as value , r.name FROM region_relationship rr INNER JOIN datapoint d ...
Fix a bug in the region aggregation query.
Fix a bug in the region aggregation query. There is no full_name column for regions; it is just name.
Python
agpl-3.0
SeedScientific/polio,unicef/rhizome,unicef/polio,unicef/polio,unicef/rhizome,unicef/rhizome,SeedScientific/polio,unicef/rhizome,SeedScientific/polio,SeedScientific/polio,unicef/polio,unicef/polio,SeedScientific/polio
9a9ecde6f88a6c969f23dbcfc5bbc7e611f7f138
version_info/get_version.py
version_info/get_version.py
import git import version_info.exceptions __all__ = ( 'get_git_version', 'find_versions', ) def get_git_version(path): repo = git.Repo(path) head_commit = repo.head.ref.commit for tag in repo.tags: if tag.commit == head_commit: return tag.name, head_commit.hexsha return ...
import collections import git import version_info.exceptions __all__ = ( 'get_git_version', 'find_versions', ) VersionSpec = collections.namedtuple('VersionSpec', ('name', 'tag', 'commit')) def get_git_version(path): repo = git.Repo(path) head_commit = repo.head.ref.commit for tag in repo.ta...
Make find_versions return a namedtuple as documented
Make find_versions return a namedtuple as documented
Python
mit
TyMaszWeb/python-version-info
01036133ed749d96a74bafb6b3f8670c06c63a84
1selfOpenDashboardCommand.py
1selfOpenDashboardCommand.py
import sublime, sublime_plugin, webbrowser QD_URL = "https://app.1self.co" class GoTo1selfDashboardCommand(sublime_plugin.TextCommand): def run(self,edit): SETTINGS = {} SETTINGS_FILE = "1self.sublime-settings" SETTINGS = sublime.load_settings(SETTINGS_FILE) stream_id = SETTINGS.ge...
import sublime, sublime_plugin, webbrowser QD_URL = "http://www.1self.co" class GoTo1selfDashboardCommand(sublime_plugin.TextCommand): def run(self,edit): SETTINGS = {} SETTINGS_FILE = "1self.sublime-settings" SETTINGS = sublime.load_settings(SETTINGS_FILE) stream_id = SETTINGS.get...
Change landing URLs to website
Change landing URLs to website
Python
apache-2.0
1self/sublime-text-plugin,1self/sublime-text-plugin,1self/sublime-text-plugin
c5609fe1b48cdd5740215c1d0783eaafdfe2e76b
listen/__init__.py
listen/__init__.py
#!/usr/bin/python # -*- coding: utf8 -*- """ The MIT License (MIT) Copyright (c) 2014 Jarl Stefansson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limit...
#!/usr/bin/python # -*- coding: utf8 -*- """ The MIT License (MIT) Copyright (c) 2014 Jarl Stefansson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limit...
Remove requirement on python > 2.7
Remove requirement on python > 2.7
Python
mit
antevens/listen,antevens/listen
1b179405245bc7d7d6157528bd64e2b399491090
quantecon/optimize/__init__.py
quantecon/optimize/__init__.py
""" Initialization of the optimize subpackage """ from .scalar_maximization import brent_max from .root_finding import *
""" Initialization of the optimize subpackage """ from .scalar_maximization import brent_max from .root_finding import newton, newton_halley, newton_secant, bisect, brentq
Fix import to list items
Fix import to list items
Python
bsd-3-clause
oyamad/QuantEcon.py,QuantEcon/QuantEcon.py,oyamad/QuantEcon.py,QuantEcon/QuantEcon.py
fa7172a5e3231e738d85df3baba130fdec7497d1
derrida/outwork/views.py
derrida/outwork/views.py
from django.views.generic import ListView from haystack.query import SearchQuerySet from haystack.inputs import Clean from derrida.outwork.models import Outwork class OutworkListView(ListView): model = Outwork template_name = 'outwork/outwork_list.html' paginate_by = 16 def get_queryset(self): ...
from django.views.generic import ListView from haystack.query import SearchQuerySet from haystack.inputs import Clean, Raw from derrida.outwork.models import Outwork class OutworkListView(ListView): model = Outwork template_name = 'outwork/outwork_list.html' paginate_by = 16 def get_queryset(self): ...
Fix outwork list view to properly filter on published=true in Solr
Fix outwork list view to properly filter on published=true in Solr
Python
apache-2.0
Princeton-CDH/derrida-django,Princeton-CDH/derrida-django,Princeton-CDH/derrida-django,Princeton-CDH/derrida-django
0c8ab03600fa806a109861f0e560e3b3a6850a66
nbgrader/apps/formgradeapp.py
nbgrader/apps/formgradeapp.py
from IPython.config.loader import Config from IPython.utils.traitlets import Unicode from nbgrader.apps.customnbconvertapp import CustomNbConvertApp from nbgrader.apps.customnbconvertapp import aliases as base_aliases from nbgrader.apps.customnbconvertapp import flags as base_flags from nbgrader.templates import get_t...
from IPython.config.loader import Config from IPython.utils.traitlets import Unicode from nbgrader.apps.customnbconvertapp import CustomNbConvertApp from nbgrader.apps.customnbconvertapp import aliases as base_aliases from nbgrader.apps.customnbconvertapp import flags as base_flags from nbgrader.templates import get_t...
Use default IPython profile when converting to HTML
Use default IPython profile when converting to HTML
Python
bsd-3-clause
ellisonbg/nbgrader,ellisonbg/nbgrader,jupyter/nbgrader,modulexcite/nbgrader,jhamrick/nbgrader,jdfreder/nbgrader,jhamrick/nbgrader,ellisonbg/nbgrader,jupyter/nbgrader,EdwardJKim/nbgrader,EdwardJKim/nbgrader,MatKallada/nbgrader,alope107/nbgrader,jupyter/nbgrader,jhamrick/nbgrader,dementrock/nbgrader,dementrock/nbgrader,j...
037e15f383c326f1f4e7de59bc3ec3520ac6ce40
pystachio/__init__.py
pystachio/__init__.py
__author__ = 'Brian Wickman' __version__ = '0.5.2' __license__ = 'MIT' from pystachio.typing import ( Type, TypeCheck, TypeFactory) from pystachio.base import Environment from pystachio.parsing import MustacheParser from pystachio.naming import Namable, Ref from pystachio.basic import ( Float, Integer, S...
__author__ = 'Brian Wickman' __version__ = '0.5.2' __license__ = 'MIT' import sys if sys.version_info < (2, 6, 5): raise ImportError("pystachio requires Python >= 2.6.5") from pystachio.typing import ( Type, TypeCheck, TypeFactory) from pystachio.base import Environment from pystachio.parsing import Mustache...
Add check for minimum Python version
Add check for minimum Python version
Python
mit
wickman/pystachio
d5b8018d1d722f3b1e980425af79934265b0f3eb
tests/test_navigation.py
tests/test_navigation.py
def test_right_arrows(page): page.goto("index.html") while(True): # Keeps going to the next page until there is no right arrow right_arrow = page.query_selector("//*[@id='relations-next']/a") if(right_arrow): page.click("//*[@id='relations-next']/a") page.wait_for...
def get_menu_titles(page) -> list: page.goto("index.html") page.wait_for_load_state() menu_list = page.query_selector_all("//*[@class='toctree-wrapper compound']/ul/li/a") menu_titles = [] for i in menu_list: menu_item = i.as_element().inner_text() menu_titles.append(menu_item) ...
Implement assertions and a for instead of a while loop
Implement assertions and a for instead of a while loop
Python
agpl-3.0
PyAr/PyZombis,PyAr/PyZombis,PyAr/PyZombis
c709c58fc128076af5f58d33dcd0983436573d79
tests/test_parsingapi.py
tests/test_parsingapi.py
from __future__ import unicode_literals, division, absolute_import from flexget.plugin import get_plugin_by_name, get_plugins from flexget.plugins.parsers import plugin_parsing class TestParsingAPI(object): def test_all_types_handled(self): declared_types = set(plugin_parsing.PARSER_TYPES) method...
from __future__ import unicode_literals, division, absolute_import from flexget.plugin import get_plugin_by_name, get_plugins from flexget.plugins.parsers import plugin_parsing class TestParsingAPI(object): def test_all_types_handled(self): declared_types = set(plugin_parsing.PARSER_TYPES) method...
Add a test to verify plugin_parsing clears selected parsers after task
Add a test to verify plugin_parsing clears selected parsers after task
Python
mit
tobinjt/Flexget,Flexget/Flexget,jawilson/Flexget,sean797/Flexget,OmgOhnoes/Flexget,poulpito/Flexget,antivirtel/Flexget,ianstalk/Flexget,JorisDeRieck/Flexget,tarzasai/Flexget,Pretagonist/Flexget,malkavi/Flexget,dsemi/Flexget,sean797/Flexget,tobinjt/Flexget,Pretagonist/Flexget,crawln45/Flexget,Danfocus/Flexget,tobinjt/Fl...
278b17859e4ad7464098a715777fcb755acf258c
doTranscode.py
doTranscode.py
#!/usr/bin/env python import encoders import decoders import config import tempfile import os def transcode(inF, outF, options, type=None): "Transcodes a file" if type == None: type = os.path.splitext(outF)[1][1:].lower() #Get the file's metadata meta = decoders.getMetadata(inF) #Decode the...
#!/usr/bin/env python import encoders import decoders import config import tempfile import os def transcode(inF, outF, options, type=None): "Transcodes a file" if type == None: type = os.path.splitext(outF)[1][1:].lower() #Get the file's metadata meta = decoders.getMetadata(inF) #Decode the...
Make sure that the temporary file has a `wav` extension because a certain encoder was designed for Windows and thinks that you would never possibly have a file without an extension so adds `.wav` if it's not there on the input file
Make sure that the temporary file has a `wav` extension because a certain encoder was designed for Windows and thinks that you would never possibly have a file without an extension so adds `.wav` if it's not there on the input file
Python
isc
jeffayle/Transcode
81069682d724c0a1e2cd292e286e4148cd9c3d9d
scraping/IEEE/main.py
scraping/IEEE/main.py
"""IEEE Xplore API Request. Usage: IEEE/main.py -h [-au AUTHOR] [-ti TITLE] [-ab ABSTRACT] [-py YEAR] [-hc NUMBER] Options: -h --help show this -au AUTHOR Terms to search for in Author [default: ""] -ti TITLE Terms to search for in Title [default: ""] -...
"""IEEE Xplore API Request. Usage: IEEE/main.py -h [-au AUTHOR] [-ti TITLE] [-ab ABSTRACT] [-py YEAR] [-hc NUMBER] Options: -h --help show this -au AUTHOR Terms to search for in Author [default: ""] -ti TITLE Terms to search for in Title [default: ""] -...
Fix loop to delete branches from xml.
Fix loop to delete branches from xml.
Python
mit
ArcasProject/Arcas
ae897509ecc7f190b31cc34085aacf81e45bc36e
nflpool/data/secret-config.py
nflpool/data/secret-config.py
from nflpool.data.dbsession import DbSessionFactory # You will need an account from MySportsFeed to access their API. They offer free access to developers # Edit below with your credentials and then save as secret.py msf_username = 'YOURUSERNAME' msf_pw = 'YOURPASSWORD' su_email = '' slack_webhook_url = ''
from nflpool.data.dbsession import DbSessionFactory # You will need an account from MySportsFeed to access their API. They offer free access to developers # Edit below with your credentials and then save as secret.py msf_username = 'YOURUSERNAME' msf_pw = 'YOURPASSWORD' su_email = '' slack_webhook_url = '' msf_a...
Add the MSF API key and password fields
Add the MSF API key and password fields
Python
mit
prcutler/nflpool,prcutler/nflpool
df4c12d9e2b07db9aa9a1406f61020eb78998bef
nickenbot/command/__init__.py
nickenbot/command/__init__.py
import os import string import importlib import traceback from .. import irc def execute(**kwargs): module_string = string.join([__name__, kwargs['command']], '.') module = None try: module = importlib.import_module(module_string) except ImportError as e: traceback.print_exc() ...
import os import fnmatch import string import importlib import traceback from .. import irc def get_all(): files = os.listdir('./nickenbot/command') files.remove('__init__.py') commands = [os.path.splitext(f)[0] for f in files if fnmatch.fnmatch(f, '*.py')] commands = [string.replace(c, '_', '-') for c...
Add support for hyphens, and list of commands
Add support for hyphens, and list of commands Adds a function to retrieve all commands, and converts incoming commands from hyphenated to underscored form.
Python
mit
brlafreniere/nickenbot,brlafreniere/nickenbot
18059a0515ea5f6edf87e8485200f001503459cd
info-txt.py
info-txt.py
# XML Parsing import xml.etree.ElementTree as ET # HTML output import dominate as dom from dominate.tags import * # Interact with user machine import datetime from sys import argv import os import time import webbrowser second = 1000 minute = 60000 hour = 3600000 class SMS: '''base SMS class to store a single mess...
# XML Parsing import xml.etree.ElementTree as ET # HTML output import dominate as dom from dominate.tags import * # Interact with user machine import datetime from sys import argv import os import time import webbrowser second = 1000 minute = 60000 hour = 3600000 class SMS: '''base SMS class to store a single mess...
Determine response time for messages
Determine response time for messages
Python
mit
2nd47/info-txt
d9b06edb63d20550c4b3fa0fa6924d99724dc11a
examples/image_resize.py
examples/image_resize.py
from __future__ import print_function from transloadit.client import Transloadit tl = Transloadit('TRANSLOADIT_KEY', 'TRANSLOADIT_SECRET') ass = tl.new_assembly() ass.add_file(open('fixtures/lol_cat.jpg', 'rb')) ass.add_step('resize', '/image/resize', {'width': 70, 'height': 70}) response = ass.create(wait=True) res...
from transloadit.client import Transloadit tl = Transloadit("TRANSLOADIT_KEY", "TRANSLOADIT_SECRET") ass = tl.new_assembly() ass.add_file(open("fixtures/lol_cat.jpg", "rb")) ass.add_step("resize", "/image/resize", {"width": 70, "height": 70}) response = ass.create(wait=True) result_url = response.data.get("results")....
Update example syntax to python3
Update example syntax to python3
Python
mit
ifedapoolarewaju/transloadit-python-sdk
3dcece1bb4e2490168b21d4298e297e61bdde901
corehq/ex-submodules/casexml/apps/case/fixtures.py
corehq/ex-submodules/casexml/apps/case/fixtures.py
from casexml.apps.case.xml.generator import safe_element from casexml.apps.phone.xml import get_casedb_element class CaseDBFixture(object): """Used to provide a casedb-like structure as a fixture Does not follow the standard FixtureGenerator pattern since it is currently not used during a regular sync op...
from casexml.apps.case.xml.generator import safe_element from casexml.apps.phone.xml import get_casedb_element class CaseDBFixture(object): """Used to provide a casedb-like structure as a fixture Does not follow the standard FixtureGenerator pattern since it is currently not used during a regular sync op...
Add links to fixture and casedb specs
Add links to fixture and casedb specs
Python
bsd-3-clause
qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq
28e67e04a88b0195184bf43f013c11ea7f320c4f
conveyor/processor.py
conveyor/processor.py
from __future__ import absolute_import from __future__ import division from xmlrpc2 import client as xmlrpc2 class BaseProcessor(object): def __init__(self, index, *args, **kwargs): super(BaseProcessor, self).__init__(*args, **kwargs) self.index = index self.client = xmlrpc2.Client(sel...
from __future__ import absolute_import from __future__ import division from xmlrpc2 import client as xmlrpc2 class BaseProcessor(object): def __init__(self, index, *args, **kwargs): super(BaseProcessor, self).__init__(*args, **kwargs) self.index = index self.client = xmlrpc2.Client(sel...
Add a method for getting a list of releases to fetch
Add a method for getting a list of releases to fetch
Python
bsd-2-clause
crateio/carrier
c694ac630f36c53c130a63908c6c3576f220a6bd
django-openstack/django_openstack/auth/__init__.py
django-openstack/django_openstack/auth/__init__.py
import django_openstack.urls class Roles: USER = 'user' PROJECT_ADMIN = 'projadmin' SOFTWARE_ADMIN = 'softadmin' HARDWARE_ADMIN = 'hardadmin' ALL_ROLES = (HARDWARE_ADMIN, SOFTWARE_ADMIN, PROJECT_ADMIN, USER) @staticmethod def get_max_role(roles): if not roles: ...
import django_openstack.urls class Roles: USER = 'user' PROJECT_ADMIN = 'projadmin' SOFTWARE_ADMIN = 'softadmin' HARDWARE_ADMIN = 'hardadmin' ALL_ROLES = (HARDWARE_ADMIN, SOFTWARE_ADMIN, PROJECT_ADMIN, USER) @staticmethod def get_max_role(roles): if not roles: ...
Return 'user' role as default value
Return 'user' role as default value
Python
apache-2.0
griddynamics/osc-robot-openstack-dashboard,griddynamics/osc-robot-openstack-dashboard,griddynamics/osc-robot-openstack-dashboard
2a986d7c0bab1612e96cace5ce54a188e22af2aa
services/wordpress.py
services/wordpress.py
import json import foauth class Wordpress(foauth.providers.OAuth2): # General info about the provider provider_url = 'https://www.wordpress.com/' favicon_url = 'http://s2.wp.com/i/favicon.ico' docs_url = 'http://developer.wordpress.com/docs/api/' # URLs to interact with the API authorize_url...
import json import foauth.providers class Wordpress(foauth.providers.OAuth2): # General info about the provider provider_url = 'https://www.wordpress.com/' favicon_url = 'http://s2.wp.com/i/favicon.ico' docs_url = 'http://developer.wordpress.com/docs/api/' # URLs to interact with the API aut...
Fix the import for Wordpress
Fix the import for Wordpress
Python
bsd-3-clause
foauth/foauth.org,foauth/foauth.org,foauth/foauth.org
fbad3c0b80258b02cc2ba81ff1408d24cd69c69d
src/iconclassserver/util.py
src/iconclassserver/util.py
import redis import json from django.conf import settings import iconclass import requests import time def handle_githubpushes(): redis_c = redis.StrictRedis() while True: data = redis_c.lpop(settings.REDIS_PREFIX + '_gitpushes') if not data: break data = json.loads(data) ...
import redis import json from django.conf import settings import iconclass import requests import time import os def handle_githubpushes(): redis_c = redis.StrictRedis() while True: data = redis_c.lpop(settings.REDIS_PREFIX + '_gitpushes') if not data: break data = json.loads(data) ...
Handle filenames with path prefixes in git commit logs
Handle filenames with path prefixes in git commit logs
Python
mit
epoz/iconclass-server,epoz/iconclass-server
78ebec64e51c43005488bc1b9ce84fca65d069e4
planet_alignment/app/app_factory.py
planet_alignment/app/app_factory.py
""" .. module:: app_factory :platform: linux :synopsis: .. moduleauthor:: Paul Fanelli <paul.fanelli@gmail.com> .. modulecreated:: 6/27/15 """ from zope.interface import implements from planet_alignment.app.app import App from planet_alignment.app.interface import IAppFactory from planet_alignment.config.bunc...
""" .. module:: app_factory :platform: linux :synopsis: .. moduleauthor:: Paul Fanelli <paul.fanelli@gmail.com> .. modulecreated:: 6/27/15 """ from zope.interface import implements from planet_alignment.app.app import App from planet_alignment.app.interface import IAppFactory from planet_alignment.config.bunc...
Document the AppFactory, add the doc headers.
Document the AppFactory, add the doc headers.
Python
mit
paulfanelli/planet_alignment
edad01902f8c9d23da106c538d118e28da286821
lesion/lifio.py
lesion/lifio.py
import javabridge as jv import bioformats as bf def start(max_heap_size='8G'): """Start the Java Virtual Machine, enabling bioformats IO. Parameters ---------- max_heap_size : string, optional The maximum memory usage by the virtual machine. Valid strings include '256M', '64k', and '2G...
import numpy as np import javabridge as jv import bioformats as bf def start(max_heap_size='8G'): """Start the Java Virtual Machine, enabling bioformats IO. Parameters ---------- max_heap_size : string, optional The maximum memory usage by the virtual machine. Valid strings include '25...
Add function to determine metadata length
Add function to determine metadata length
Python
bsd-3-clause
jni/lesion
6a7a61d514ac738f8de29efe280ecfedfaf72685
ttrss/auth.py
ttrss/auth.py
from requests.auth import AuthBase import requests import json from exceptions import raise_on_error class TTRAuth(AuthBase): def __init__(self, user, password): self.user = user self.password = password def response_hook(self, r, **kwargs): j = json.loads(r.content) if int(j[...
from requests.auth import AuthBase import requests import json from exceptions import raise_on_error class TTRAuth(AuthBase): def __init__(self, user, password): self.user = user self.password = password def response_hook(self, r, **kwargs): j = json.loads(r.content) if int(j[...
Clean up cookie lookup in TTRAuth
Clean up cookie lookup in TTRAuth
Python
mit
Vassius/ttrss-python
3aff93b43f880eab72ca205e1f354e7179907132
fix_removal.py
fix_removal.py
import os from distutils import sysconfig # Check to see if the previous version was installed and clean up # installed-files.txt prune = ['var/', 'var/run/', 'var/log/'] python_lib_dir = sysconfig.get_python_lib() fixed = False for dir_path, dir_names, file_names in os.walk(python_lib_dir): for dir_name in dir_na...
import os import site # Check to see if the previous version was installed and clean up # installed-files.txt prune = ['var/', 'var/run/', 'var/log/'] package_directories = site.PREFIXES if site.USER_SITE: package_directories.append(site.USER_SITE) for package_dir in package_directories: print 'Checking %s ...
Make the script check all the site package directories
Make the script check all the site package directories
Python
bsd-3-clause
notnmeyer/newrelic-plugin-agent,whiteear/newrelic-plugin-agent,alonisser/newrelic-plugin-agent,NewRelic-Python-Plugins/newrelic-python-agent,alonisser/newrelic-plugin-agent,whiteear/newrelic-plugin-agent,NewRelic-Python-Plugins/newrelic-python-agent,MeetMe/newrelic-plugin-agent,rounds/newrelic-plugin-agent,whiteear/new...
a275068193c87c5a27758c17d7699e963a0bdfa8
llvmpy/src/Support/FormattedStream.py
llvmpy/src/Support/FormattedStream.py
from binding import * from ..namespace import llvm from raw_ostream import raw_ostream @llvm.Class(raw_ostream) class formatted_raw_ostream: _include_ = 'llvm/Support/FormattedStream.h' new = Constructor(ref(raw_ostream), cast(bool, Bool))
from binding import * from ..namespace import llvm from raw_ostream import raw_ostream @llvm.Class(raw_ostream) class formatted_raw_ostream: _include_ = 'llvm/Support/FormattedStream.h' _new = Constructor(ref(raw_ostream), cast(bool, Bool)) @CustomPythonStaticMethod def new(stream, destroy=False): ...
Fix formatted_raw_ostream ownership error with the underlying stream.
Fix formatted_raw_ostream ownership error with the underlying stream.
Python
bsd-3-clause
llvmpy/llvmpy,llvmpy/llvmpy,llvmpy/llvmpy,llvmpy/llvmpy,llvmpy/llvmpy,llvmpy/llvmpy
4f8aed6ed3491e62911619eaa9aa4b86b30065e4
leonardo/module/leonardo_auth/widget/userlogin/models.py
leonardo/module/leonardo_auth/widget/userlogin/models.py
# -#- coding: utf-8 -#- from django.db import models from django.utils.translation import ugettext_lazy as _ from leonardo.module.web.models import Widget LOGIN_TYPE_CHOICES = ( (1, _("Admin")), (2, _("Public")), ) class UserLoginWidget(Widget): type = models.PositiveIntegerField(verbose_name=_( ...
# -#- coding: utf-8 -#- from django.db import models from django.utils.translation import ugettext_lazy as _ from leonardo.module.web.models import Widget LOGIN_TYPE_CHOICES = ( (1, _("Admin")), (2, _("Public")), ) class UserLoginWidget(Widget): type = models.PositiveIntegerField(verbose_name=_( ...
Fix missing next in context.
Fix missing next in context.
Python
bsd-3-clause
django-leonardo/django-leonardo,django-leonardo/django-leonardo,django-leonardo/django-leonardo,django-leonardo/django-leonardo
3c12a453a9686e998662fea822f85fb307f1d746
emma2/msm/flux/__init__.py
emma2/msm/flux/__init__.py
from .api import *
r""" =================================================================== flux - Reactive flux an transition pathways (:mod:`emma2.msm.flux`) =================================================================== .. currentmodule:: emma2.msm.flux This module contains functions to compute reactive flux networks and find ...
Include flux package in doc
[msm/flux] Include flux package in doc
Python
bsd-2-clause
arokem/PyEMMA,trendelkampschroer/PyEMMA,trendelkampschroer/PyEMMA,arokem/PyEMMA
79bb94f51cd2dca65479cb39f6c365c4c372b0ca
forumuser/models.py
forumuser/models.py
from django.contrib.auth.models import AbstractUser, Group from django.db import models class ForumUser(AbstractUser): def __unicode__(self): return '%(username)s (%(email)s)' % { 'username': self.username, 'email': self.email }
from django.contrib.auth.models import AbstractUser, Group from django.db import models class ForumUser(AbstractUser): items_per_page = models.PositiveSmallIntegerField(blank=True, null=True) def __unicode__(self): return '%(username)s (%(email)s)' % { 'username': self.username, ...
Add items per page as a preference to the forumm user model
Add items per page as a preference to the forumm user model
Python
mit
hellsgate1001/thatforum_django,hellsgate1001/thatforum_django,hellsgate1001/thatforum_django
e77c5acd4fcdb16f17245122212458baf5195064
bookworm/settings_mobile.py
bookworm/settings_mobile.py
from settings import * import settings TEMPLATE_DIRS_BASE = TEMPLATE_DIRS TEMPLATE_DIRS = ( '%s/library/templates/mobile/auth' % ROOT_PATH, '%s/library/templates/mobile' % ROOT_PATH, ) TEMPLATE_DIRS += TEMPLATE_DIRS_BASE MOBILE = True
from settings import * import settings TEMPLATE_DIRS_BASE = TEMPLATE_DIRS TEMPLATE_DIRS = ( '%s/library/templates/mobile/auth' % ROOT_PATH, '%s/library/templates/mobile' % ROOT_PATH, ) TEMPLATE_DIRS += TEMPLATE_DIRS_BASE MOBILE = True SESSION_COOKIE_NAME = 'bookworm_mobile'
Change cookie name for mobile setting
Change cookie name for mobile setting
Python
bsd-3-clause
google-code-export/threepress,anselmorenato/threepress,anselmorenato/threepress,anselmorenato/threepress,google-code-export/threepress,google-code-export/threepress,lizadaly/threepress,anselmorenato/threepress,lizadaly/threepress,google-code-export/threepress,lizadaly/threepress,lizadaly/threepress
d3caf69dfe98aa2fd0f9046c01035cdd7e4e359e
opps/articles/tests/models.py
opps/articles/tests/models.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.test import TestCase from opps.articles.models import Article, Post class ArticleModelTest(TestCase): fixtures = ['tests/initial_data.json'] def setUp(self): self.article = Article.objects.get(id=1) def test_child_class(self): s...
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.test import TestCase from opps.articles.models import Article, Post class ArticleModelTest(TestCase): fixtures = ['tests/initial_data.json'] def setUp(self): self.article = Article.objects.get(id=1) def test_child_class(self): s...
Test recommendation via article class
Test recommendation via article class
Python
mit
williamroot/opps,jeanmask/opps,opps/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,YACOWS/opps,opps/opps,williamroot/opps,YACOWS/opps,opps/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,opps/opps
a86eaffa53a18389ea628f37c76900cc24c701f6
opps/contrib/logging/admin.py
opps/contrib/logging/admin.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.contrib import admin from .models import Logging class LoggingAdmin(admin.ModelAdmin): model = Logging raw_id_fields = ('user',) exclude = ('site_iid', 'site_domain') admin.site.register(Logging, LoggingAdmin)
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.contrib import admin from .models import Logging class LoggingAdmin(admin.ModelAdmin): model = Logging raw_id_fields = ('user',) exclude = ('site_iid', 'site_domain', 'mirror_site') admin.site.register(Logging, LoggingAdmin)
Add field mirror_site at exclude on LoggingAdmin
Add field mirror_site at exclude on LoggingAdmin
Python
mit
YACOWS/opps,williamroot/opps,YACOWS/opps,williamroot/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,YACOWS/opps,opps/opps,opps/opps,williamroot/opps,opps/opps,jeanmask/opps,jeanmask/opps,YACOWS/opps,opps/opps
714fd7d0c173672f636e8d051b24046b10d3f481
format_json.py
format_json.py
#! /usr/bin/env python import sys import json for filepath in sys.argv[1:]: with open(filepath) as f: try: oyster = json.load(f) except ValueError: sys.stderr.write("In file: {}\n".format(filepath)) raise with open(filepath, 'w') as f: json.dump(oyst...
#! /usr/bin/env python3 import sys import json for filepath in sys.argv[1:]: with open(filepath) as f: try: oyster = json.load(f) except ValueError: sys.stderr.write("In file: {}\n".format(filepath)) raise with open(filepath, 'w') as f: json.dump(oys...
Make this work for non-ASCII chars as well.
Make this work for non-ASCII chars as well.
Python
mit
nbeaver/cmd-oysters,nbeaver/cmd-oysters
4de23cffa16c71e287efba7d32ba375feeb9bc13
format_json.py
format_json.py
#! /usr/bin/env python3 import sys import json import argparse def format_json(fp): try: data = json.load(fp) except ValueError: sys.stderr.write("In file: {}\n".format(fp.name)) raise # Jump back to the beginning of the file before overwriting it. fp.seek(0) json.dump(data...
#! /usr/bin/env python3 import sys import json import argparse def format_json(fp): try: data = json.load(fp) except ValueError: sys.stderr.write("In file: {}\n".format(fp.name)) raise # Jump back to the beginning of the file before overwriting it. fp.seek(0) fp.truncate(0)...
Truncate the file before writing more data.
Truncate the file before writing more data.
Python
mit
nbeaver/cmd-oysters,nbeaver/cmd-oysters
860cea2b6d183414d794eb2e2d44beb7728e2d4b
hasjob/models/location.py
hasjob/models/location.py
# -*- coding: utf-8 -*- from . import db, BaseScopedNameMixin from flask import url_for from .board import Board __all__ = ['Location'] class Location(BaseScopedNameMixin, db.Model): """ A location where jobs are listed, using geonameid for primary key. Scoped to a board """ __tablename__ = 'locatio...
# -*- coding: utf-8 -*- from . import db, BaseScopedNameMixin from flask import url_for from .board import Board __all__ = ['Location'] class Location(BaseScopedNameMixin, db.Model): """ A location where jobs are listed, using geonameid for primary key. Scoped to a board """ __tablename__ = 'locatio...
Fix parent synonym for Location model
Fix parent synonym for Location model
Python
agpl-3.0
hasgeek/hasjob,hasgeek/hasjob,hasgeek/hasjob,hasgeek/hasjob
401f98ad74792e9a5d9354dec8c24dc9637d1f5e
tests/gsim/pezeshk_2011_test.py
tests/gsim/pezeshk_2011_test.py
# The Hazard Library # Copyright (C) 2013 GEM Foundation # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # Th...
# The Hazard Library # Copyright (C) 2013 GEM Foundation # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # Th...
Add implementation of gmpe Pezeshk et al 2011 for ENA
Add implementation of gmpe Pezeshk et al 2011 for ENA
Python
agpl-3.0
vup1120/oq-hazardlib,gem/oq-engine,g-weatherill/oq-hazardlib,gem/oq-hazardlib,gem/oq-hazardlib,g-weatherill/oq-hazardlib,gem/oq-engine,gem/oq-engine,rcgee/oq-hazardlib,mmpagani/oq-hazardlib,g-weatherill/oq-hazardlib,gem/oq-hazardlib,ROB-Seismology/oq-hazardlib,silviacanessa/oq-hazardlib,vup1120/oq-hazardlib,ROB-Seismol...
87771bda7fbf46519097ba433a7b4fd3f2cbaa7e
office_lunch_order/office_lunch_order_app/tests.py
office_lunch_order/office_lunch_order_app/tests.py
from django.test import TestCase, Client c = Client() response = c.get('/officelunchorder/') response.status_code # 200 response.content response = c.post('/officelunchorder/login/') response.status_code # 200 response.content response = c.get('/officelunchorder/logout/') response.status_code # 200 response.content re...
from django.test import TestCase, Client c = Client() response = c.get('/officelunchorder/') response.status_code # 200 response.content response = c.post('/officelunchorder/login/') response.status_code # 200 response.content response = c.get('/officelunchorder/logout/') response.status_code # 200 response.content re...
Test add_order and order details with existing order_id url
Test add_order and order details with existing order_id url
Python
epl-1.0
MariuszKorotko/Office_Lunch_Order,MariuszKorotko/Office_Lunch_Order
4c60e42af4b37c260e2a9f00eb82dbd44ee53799
__init__.py
__init__.py
# imports for Pyrge package __all__ = ['effects', 'emitter', 'entity', 'gameloop', 'mixin', 'music', 'point', 'quadtree', 'sound', 'spritesheet', 'text', 'tiledimage', 'tilemap', ...
# imports for Pyrge package __all__ = ['effects', 'emitter', 'entity', 'gameloop', 'mixin', 'music', 'point', 'quadtree', 'sound', 'spritesheet', 'text', 'tiledimage', 'tilemap', ...
Put Image and Entity into __all__
Put Image and Entity into __all__
Python
lgpl-2.1
momikey/pyrge
c01a858306d31a5b12e42f30ff01bdbdb2240092
froide/publicbody/tests.py
froide/publicbody/tests.py
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 a...
from django.test import TestCase from django.core.urlresolvers import reverse from publicbody.models import PublicBody class PublicBodyTest(TestCase): fixtures = ['auth.json', 'publicbodies.json', 'foirequest.json'] def test_web_page(self): response = self.client.get(reverse('publicbody-list')) ...
Test public body showing, json view and csv export
Test public body showing, json view and csv export
Python
mit
okfse/froide,ryankanno/froide,catcosmo/froide,ryankanno/froide,okfse/froide,LilithWittmann/froide,okfse/froide,LilithWittmann/froide,ryankanno/froide,CodeforHawaii/froide,stefanw/froide,stefanw/froide,LilithWittmann/froide,CodeforHawaii/froide,catcosmo/froide,catcosmo/froide,stefanw/froide,ryankanno/froide,fin/froide,f...
076f8cf27d3a1b52a1b597e224d23bd2ba18fcd7
kalamarsite.py
kalamarsite.py
import os import kalamar.site from kalamar.access_point.cache import Cache from kalamar.access_point.xml.rest import Rest, RestProperty, TITLE from kalamar.access_point.filesystem import FileSystem from sitenco import PROJECTS_PATH page = Rest( FileSystem( PROJECTS_PATH, r'(.*)/pages/(.*)\.rst', (...
import os import kalamar.site from kalamar.access_point.cache import Cache from kalamar.access_point.xml.rest import Rest, RestProperty, TITLE from kalamar.access_point.filesystem import FileSystem from sitenco import PROJECTS_PATH page = Rest( FileSystem( PROJECTS_PATH, r'([a-z]*)/pages/(.*)\.rst...
Use [a-z]* pattern to match project ids
Use [a-z]* pattern to match project ids
Python
bsd-3-clause
Kozea/sitenco
696010e636f7e30ba331b103ba051422780edf4b
bluebottle/funding/utils.py
bluebottle/funding/utils.py
from babel.numbers import get_currency_name, get_currency_symbol from bluebottle.utils.exchange_rates import convert from django.db.models import Sum from djmoney.money import Money from bluebottle.funding.models import PaymentProvider def get_currency_settings(): result = [] for provider in PaymentProvider....
from babel.numbers import get_currency_name, get_currency_symbol from bluebottle.utils.exchange_rates import convert from django.db.models import Sum from djmoney.money import Money from bluebottle.funding.models import PaymentProvider def get_currency_settings(): result = [] for provider in PaymentProvider....
USe payout amount to calculate total
USe payout amount to calculate total
Python
bsd-3-clause
onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle
1f250c6113ed69dc3373afbc40a93bdc7d8e7894
pages_scrape.py
pages_scrape.py
import logging import requests def scrape(url, extractor): """ Function to request and parse a given URL. Returns only the "relevant" text. Parameters ---------- url : String. URL to request and parse. extractor : Goose class instance. An instance of Goose th...
import logging import requests def scrape(url, extractor): """ Function to request and parse a given URL. Returns only the "relevant" text. Parameters ---------- url : String. URL to request and parse. extractor : Goose class instance. An instance of Goose th...
Handle UTF errors with invalid bytes.
Handle UTF errors with invalid bytes.
Python
mit
openeventdata/scraper,chilland/scraper
38746e4f4891f7ad87ce678776be15556d1db449
gcl/to_json.py
gcl/to_json.py
import argparse import json import sys import gcl from gcl import query from gcl import util def main(argv=None, stdin=None): parser = argparse.ArgumentParser(description='Convert (parts of) a GCL model file to JSON.') parser.add_argument('file', metavar='FILE', type=str, nargs='?', help='F...
import argparse import json import sys import gcl from gcl import query from gcl import util def select(dct, path): for part in path: if not hasattr(dct, 'keys'): raise RuntimeError('Value %r cannot be indexed with %r' % (dct, part)) if part not in dct: raise RuntimeError('Value %r has no key %...
Add proper root selector to gcl2json
Add proper root selector to gcl2json
Python
mit
rix0rrr/gcl
3c3e9b5f584c23c9359ca9dce71b89635fffd043
LiSE/LiSE/tests/test_load.py
LiSE/LiSE/tests/test_load.py
import os import shutil import pytest from LiSE.engine import Engine from LiSE.examples.kobold import inittest def test_keyframe_load_init(tempdir): """Can load a keyframe at start of branch, including locations""" eng = Engine(tempdir) inittest(eng) eng.branch = 'new' eng.snap_keyframe() e...
import os import shutil import pytest from LiSE.engine import Engine from LiSE.examples.kobold import inittest def test_keyframe_load_init(tempdir): """Can load a keyframe at start of branch, including locations""" eng = Engine(tempdir) inittest(eng) eng.branch = 'new' eng.snap_keyframe() e...
Make test_multi_keyframe demonstrate what it's supposed to
Make test_multi_keyframe demonstrate what it's supposed to I was testing a cache that wasn't behaving correctly for unrelated reasons.
Python
agpl-3.0
LogicalDash/LiSE,LogicalDash/LiSE
972cb7c234729d2ce8bbab0937f8efbfe18a2eeb
lab_members/models.py
lab_members/models.py
from django.db import models class Position(models.Model): class Meta: verbose_name = "Position" verbose_name_plural = "Positions" title = models.CharField(u'title', blank=False, default='', help_text=u'Please enter a title for this position', max_length=64, ...
from django.db import models class Position(models.Model): class Meta: verbose_name = "Position" verbose_name_plural = "Positions" title = models.CharField(u'title', blank=False, default='', help_text=u'Please enter a title for this position', max_length=64, ...
Fix error: __str__ returned non-string (type NoneType)
Fix error: __str__ returned non-string (type NoneType)
Python
bsd-3-clause
mfcovington/django-lab-members,mfcovington/django-lab-members,mfcovington/django-lab-members
9ad049bdac489e5f500f8bf8ec0cd615ccacadbf
stack/logs.py
stack/logs.py
from troposphere import Join, iam, logs from .common import arn_prefix from .template import template container_log_group = logs.LogGroup( "ContainerLogs", template=template, RetentionInDays=365, DeletionPolicy="Retain", ) logging_policy = iam.Policy( PolicyName="LoggingPolicy", PolicyDocume...
from troposphere import Join, iam, logs from .common import arn_prefix from .template import template container_log_group = logs.LogGroup( "ContainerLogs", template=template, RetentionInDays=365, DeletionPolicy="Retain", ) logging_policy = iam.Policy( PolicyName="LoggingPolicy", PolicyDocume...
Add logging permissions needed by aws-for-fluent-bit
Add logging permissions needed by aws-for-fluent-bit
Python
mit
tobiasmcnulty/aws-container-basics,caktus/aws-web-stacks
e1ad3190e124163c0e7e0e7fc03cfea6f43f0cf8
stack/vpc.py
stack/vpc.py
from troposphere.ec2 import ( VPC, ) from .template import template vpc = VPC( "Vpc", template=template, CidrBlock="10.0.0.0/16", )
from troposphere import ( Ref, ) from troposphere.ec2 import ( InternetGateway, VPC, VPCGatewayAttachment, ) from .template import template vpc = VPC( "Vpc", template=template, CidrBlock="10.0.0.0/16", ) # Allow outgoing to outside VPC internet_gateway = InternetGateway( "InternetG...
Attach an `InternetGateway` to the `VPC`
Attach an `InternetGateway` to the `VPC`
Python
mit
tobiasmcnulty/aws-container-basics,caktus/aws-web-stacks
92aeffe058bfd724309ddcdbdab9226057074afe
masters/master.chromium.lkgr/master_source_cfg.py
masters/master.chromium.lkgr/master_source_cfg.py
# Copyright (c) 2011 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 buildbot.changes.pb import PBChangeSource def Update(config, active_master, c): # Polls config.Master.trunk_url for changes c['change_source']....
# 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. from master.url_poller import URLPoller LKGR_URL = 'https://chromium-status.appspot.com/lkgr' def Update(config, active_master, c): c['change_source...
Switch master.chromium.lkgr to poll the chromium-status app.
Switch master.chromium.lkgr to poll the chromium-status app. Using a PBChangeSource is silly, opaque, and potentially dangerous. We already have a URLPoller for exactly this use-case (already in use by chromium.endure) so let's use it here too. This also has the advantage of making sure the LKGR waterfall picks up *al...
Python
bsd-3-clause
eunchong/build,eunchong/build,eunchong/build,eunchong/build
7fa20f228a673ee983af47910f10851c126a9308
src/foremast/plugin_manager.py
src/foremast/plugin_manager.py
from pluginbase import PluginBase class PluginManager: def __init__(self, paths, provider): self.paths = [paths] self.provider = provider plugin_base = PluginBase(package='foremast.plugins') self.plugin_source = plugin_base.make_plugin_source(searchpath=self.paths) def plugin...
"""Manager to handle plugins""" from pluginbase import PluginBase class PluginManager: """Class to manage and create Spinnaker applications Args: paths (str): Path of plugin directory. provider (str): The name of the cloud provider. """ def __init__(self, paths, provider): se...
Add docstring to plugin manager
chore: Add docstring to plugin manager
Python
apache-2.0
gogoair/foremast,gogoair/foremast
a2ced7a752c033cef1a1da1fb246b99f0895f86a
src/objectdictionary.py
src/objectdictionary.py
import collections class ObjectDictionary(collections.Mapping): def __init__(self): self.names = {} self.ids = {} @classmethod def initialize(edsPath): pass def __setitem__(self,key,value): pass def __getitem__(self,key): pass def __iter__(): ...
import collections class ObjectDictionary(collections.Mapping): def __init__(self): self.names = {} self.ids = {} @classmethod def initialize(edsPath): pass def __setitem__(self,key,value): if type(key) is str: self.names[key] = value else: ...
Add Mapping methods to ObjectDictionary
Add Mapping methods to ObjectDictionary
Python
mit
aceofwings/Evt-Gateway,aceofwings/Evt-Gateway
f0861ff6c817f1f683e69cf362336545ff3d9148
ledger/admin.py
ledger/admin.py
from django.contrib import admin from ledger.models import Account, Entry class EntryAdmin(admin.ModelAdmin): list_display = ['date', 'amount', 'details', 'debit_account', 'credit_account'] list_filter = ['date'] admin.site.register(Entry, EntryAdmin) admin.site.register(Account)
from django.contrib import admin from ledger.models import Account, Entry class EntryAdmin(admin.ModelAdmin): list_display = ['date', 'amount', 'details', 'debit_account', 'credit_account'] list_filter = ['date', 'debit_account', 'credit_account'] search_fields = ['details', 'debit_account__name', 'credit...
Add a little more functionality to EntryAdmin
Add a little more functionality to EntryAdmin
Python
mpl-2.0
jackbravo/condorest-django,jackbravo/condorest-django,jackbravo/condorest-django
1e7361f46f551a2e897040ae47b43cdd5263d328
dataactcore/models/field.py
dataactcore/models/field.py
class FieldType: """ Acts as an enum for field types """ INTEGER = "INTEGER" TEXT = "TEXT" class FieldConstraint: """ Acts a an enum for field constraints """ NONE = "" PRIMARY_KEY = "PRIMARY KEY" NOT_NULL = "NOT NULL"
class FieldType: """ Acts as an enum for field types """ INTEGER = "INTEGER" TEXT = "TEXT"
Remove FieldConstraint class (not used)
Remove FieldConstraint class (not used)
Python
cc0-1.0
fedspendingtransparency/data-act-broker-backend,fedspendingtransparency/data-act-broker-backend
07ee6957d20a1c02b22ed5d91d20211506e7ca54
partner_feeds/templatetags/partner_feed_tags.py
partner_feeds/templatetags/partner_feed_tags.py
from django import template from partner_feeds.models import Partner register = template.Library() @register.assignment_tag def get_partners(*args): partners = [] for name in args: try: partner = Partner.objects.get(name=name) except Partner.DoesNotExist: continue ...
from django import template from partner_feeds.models import Partner, Post register = template.Library() @register.assignment_tag def get_partners(*partner_names): """ Given a list of partner names, return those partners with posts attached to them in the order that they were passed to this function ...
Update `get_partners` assignment tag to reduce the number of queries
Update `get_partners` assignment tag to reduce the number of queries Maintains the same interface so no other changes should be required
Python
bsd-2-clause
theatlantic/django-partner-feeds
7dbc1359ea4fb1b725fd53869a218856e4dec701
lswapi/httpie/__init__.py
lswapi/httpie/__init__.py
""" LswApi auth plugin for HTTPie. """ from json import loads, dumps from time import time from os import path from lswapi import __auth_token_url__, __token_store__, fetch_access_token from requests import post from httpie.plugins import AuthPlugin class LswApiAuth(object): def __init__(self, client_id, client_s...
""" LswApi auth plugin for HTTPie. """ from json import loads, dumps from time import time from os import path from lswapi import __auth_token_url__, __token_store__, fetch_access_token from requests import post from httpie.plugins import AuthPlugin class LswApiAuth(object): def __init__(self, client_id, client_s...
Fix for function signature change in 0.4.0 in fetch_access_token
Fix for function signature change in 0.4.0 in fetch_access_token
Python
apache-2.0
nrocco/lswapi
c0ec6a6a799ab86562b07326eeaf21da4fd23dff
rejected/log.py
rejected/log.py
""" Logging Related Things """ import logging class CorrelationFilter(logging.Formatter): """Filter records that have a correlation_id""" def __init__(self, exists=None): super(CorrelationFilter, self).__init__() self.exists = exists def filter(self, record): if self.exists: ...
""" Logging Related Things """ import logging class CorrelationFilter(logging.Formatter): """Filter records that have a correlation_id""" def __init__(self, exists=None): super(CorrelationFilter, self).__init__() self.exists = exists def filter(self, record): if self.exists: ...
Add the consumer name to the extra values
Add the consumer name to the extra values
Python
bsd-3-clause
gmr/rejected,gmr/rejected
63db2005911abae96eb170af0dd93093cbfeae38
nimp/utilities/ue4.py
nimp/utilities/ue4.py
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------- import socket import random import string import time import contextlib import shutil import os from nimp.utilities.build import * from nimp.utilities.deployment import * #----------------------------------------...
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------- import socket import random import string import time import contextlib import shutil import os from nimp.utilities.build import * from nimp.utilities.deployment import * #----------------------------------------...
Build UE4 projects by name rather than by full path.
Build UE4 projects by name rather than by full path.
Python
mit
dontnod/nimp
11cb3adf0beb19abebbf8345b9244dbcc0f51ca7
autopoke.py
autopoke.py
#!/bin/env python from selenium import webdriver from selenium.common.exceptions import StaleElementReferenceException from time import sleep from getpass import getpass if __name__ == '__main__': driver = webdriver.phantomjs.webdriver.WebDriver() driver.get('https://facebook.com') driver.find_element_by_...
#!/bin/env python from selenium import webdriver from selenium.common.exceptions import StaleElementReferenceException from time import sleep from getpass import getpass if __name__ == '__main__': driver = webdriver.phantomjs.webdriver.WebDriver() driver.get('https://facebook.com') driver.find_element_by_...
Add notice on page reload
Add notice on page reload
Python
mit
matthewbentley/autopoke
ccfc5e8681eef5e382b6c31abce540cbe179f7b2
tests/factories/user.py
tests/factories/user.py
# -*- coding: utf-8 -*- # Copyright (c) 2016 The Pycroft Authors. See the AUTHORS file. # This file is part of the Pycroft project and licensed under the terms of # the Apache License, Version 2.0. See the LICENSE file for details. import factory from factory.faker import Faker from pycroft.model.user import User, Roo...
# -*- coding: utf-8 -*- # Copyright (c) 2016 The Pycroft Authors. See the AUTHORS file. # This file is part of the Pycroft project and licensed under the terms of # the Apache License, Version 2.0. See the LICENSE file for details. import factory from factory.faker import Faker from pycroft.model.user import User, Roo...
Allow adjusting of RoomHistoryEntry attributes in UserFactory
Allow adjusting of RoomHistoryEntry attributes in UserFactory
Python
apache-2.0
agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft
e86f62edb2edf9dd5d20eb2bf89b09c76807de50
tests/cupy_tests/core_tests/test_array_function.py
tests/cupy_tests/core_tests/test_array_function.py
import unittest import numpy import six import cupy from cupy import testing @testing.gpu class TestArrayFunction(unittest.TestCase): @testing.with_requires('numpy>=1.17.0') def test_array_function(self): a = numpy.random.randn(100, 100) a_cpu = numpy.asarray(a) a_gpu = cupy.asarray...
import unittest import numpy import six import cupy from cupy import testing @testing.gpu class TestArrayFunction(unittest.TestCase): @testing.with_requires('numpy>=1.17.0') def test_array_function(self): a = numpy.random.randn(100, 100) a_cpu = numpy.asarray(a) a_gpu = cupy.asarray...
Add tests for NumPy _implementation usage
Add tests for NumPy _implementation usage
Python
mit
cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy
a9a2c13cf947de9bc8ed50a38da5f7191b86ae23
accounts/tests/test_views.py
accounts/tests/test_views.py
"""accounts app unittests for views """ from django.test import TestCase from django.urls import reverse class WelcomePageTest(TestCase): """Tests relating to the welcome_page view. """ def test_uses_welcome_template(self): """The root url should respond with the welcome page template. ...
"""accounts app unittests for views """ from django.test import TestCase from django.core import mail from django.urls import reverse class WelcomePageTest(TestCase): """Tests relating to the welcome_page view. """ def test_uses_welcome_template(self): """The root url should respond with the wel...
Add trivial test for the view to send an email
Add trivial test for the view to send an email
Python
mit
randomic/aniauth-tdd,randomic/aniauth-tdd
018f8e7c7c69eefeb121c8552eb319b4b550f251
backslash/error_container.py
backslash/error_container.py
from sentinels import NOTHING class ErrorContainer(object): def add_error(self, exception, exception_type, traceback, timestamp=NOTHING): return self.client.api.call_function('add_error', {self._get_id_key(): self.id, 'exception': exception, ...
from sentinels import NOTHING class ErrorContainer(object): def add_error(self, message, exception_type=NOTHING, traceback=NOTHING, timestamp=NOTHING): return self.client.api.call_function('add_error', {self._get_id_key(): self.id, 'message': mes...
Unify errors and failures in API
Unify errors and failures in API
Python
bsd-3-clause
vmalloc/backslash-python,slash-testing/backslash-python
75a27c416effd2958182b1401e49d6613a28857d
sana_builder/webapp/models.py
sana_builder/webapp/models.py
from django.db import models from django.contrib.auth.models import User class Procedure(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=50) uuid = models.IntegerField(null=True) version = models.CharField(max_length=50, null=True) owner = models.ForeignK...
from django.db import models from django.contrib.auth.models import User class Procedure(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=50) uuid = models.IntegerField(null=True, unique=True) version = models.CharField(max_length=50, null=True) owner = mo...
Make uuid on procedures unique
Make uuid on procedures unique
Python
bsd-3-clause
SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder
ad1203b9b93d1be499698807e2307413c20bb573
cisco_olt_http/tests/test_operations.py
cisco_olt_http/tests/test_operations.py
from cisco_olt_http import operations
from cisco_olt_http import operations from cisco_olt_http.client import Client def test_get_data(): client = Client('http://base-url') show_equipment_op = operations.ShowEquipmentOp(client) op_data = show_equipment_op.get_data() assert op_data
Add simple test for operation get_data
Add simple test for operation get_data
Python
mit
beezz/cisco-olt-http-client,Vnet-as/cisco-olt-http-client
f3eeb19249fae51a5537735cd5966596194cdc36
pages/widgets_registry.py
pages/widgets_registry.py
__all__ = ('register_widget',) from django.utils.translation import ugettext as _ class WidgetAlreadyRegistered(Exception): """ An attempt was made to register a widget for Django page CMS more than once. """ pass class WidgetNotFound(Exception): """ The requested widget was not found ...
__all__ = ('register_widget',) from django.utils.translation import ugettext as _ class WidgetAlreadyRegistered(Exception): """ An attempt was made to register a widget for Django page CMS more than once. """ pass class WidgetNotFound(Exception): """ The requested widget was not found ...
Fix widget registry exception handling code
Fix widget registry exception handling code
Python
bsd-3-clause
batiste/django-page-cms,remik/django-page-cms,batiste/django-page-cms,oliciv/django-page-cms,oliciv/django-page-cms,akaihola/django-page-cms,remik/django-page-cms,remik/django-page-cms,akaihola/django-page-cms,oliciv/django-page-cms,pombredanne/django-page-cms-1,batiste/django-page-cms,akaihola/django-page-cms,pombreda...
3ac86b4c058f920c9ec774c192d84050d61c8cc3
tests/__init__.py
tests/__init__.py
# -*- coding: utf-8 -*- import os from hycc.util import hycc_main def clean(): for path in os.listdir("tests/resources"): if path not in ["hello.hy", "__init__.py"]: os.remove(os.path.join("tests/resources", path)) def test_build_executable(): hycc_main("tests/resources/hello.hy".split()...
# -*- coding: utf-8 -*- import os from hycc.util import hycc_main def clean(): for path in os.listdir("tests/resources"): if path not in ["hello.hy", "__init__.py"]: path = os.path.join("tests/resources", path) if os.path.isdir(path): os.rmdir(path) else...
Fix bug; os.remove cannot remove directories
Fix bug; os.remove cannot remove directories
Python
mit
koji-kojiro/hylang-hycc
f4cfad2edaa896b471f4f44b2a3fda2bd6b1bb49
tests/conftest.py
tests/conftest.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import pytest from flask import Flask, jsonify @pytest.fixture def app(): app = Flask(__name__) @app.route('/ping') def ping(): return jsonify(ping='pong') return app
#!/usr/bin/env python # -*- coding: utf-8 -*- import pytest from flask import Flask, jsonify @pytest.fixture def app(): app = Flask(__name__) @app.route('/') def index(): return app.response_class('OK') @app.route('/ping') def ping(): return jsonify(ping='pong') return app
Add index route to test application
Add index route to test application This endpoint uses to start :class:`LiveServer` instance with minimum waiting timeout.
Python
mit
amateja/pytest-flask
dff2120a65daacfb1add8da604483f354abcefa2
src/pygrapes/serializer/__init__.py
src/pygrapes/serializer/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from abstract import Abstract from json import Json from msgpack import MsgPack __all__ = ['Abstract', 'Json', 'MsgPack']
#!/usr/bin/env python # -*- coding: utf-8 -*- from pygrapes.serializer.abstract import Abstract from pygrapes.serializer.json import Json from pygrapes.serializer.msgpack import MsgPack __all__ = ['Abstract', 'Json', 'MsgPack']
Load resources by absolute path not relative
Load resources by absolute path not relative
Python
bsd-3-clause
michalbachowski/pygrapes,michalbachowski/pygrapes,michalbachowski/pygrapes
ff37a13d1adec1fe685bd48964ab50ef000f53f5
loom/config.py
loom/config.py
from fabric.api import env, run, sudo, settings, hide # Default system user env.user = 'ubuntu' # Default puppet environment env.environment = 'prod' # Default puppet module directory env.puppet_module_dir = 'modules/' # Default puppet version # If loom_puppet_version is None, loom installs the latest version env.l...
from fabric.api import env, run, settings, hide # Default system user env.user = 'ubuntu' # Default puppet environment env.environment = 'prod' # Default puppet module directory env.puppet_module_dir = 'modules/' # Default puppet version # If loom_puppet_version is None, loom installs the latest version env.loom_pu...
Revert "sudo is required to run which <gem-exec> on arch."
Revert "sudo is required to run which <gem-exec> on arch." This reverts commit 15162c58c27bc84f1c7fc0326f782bd693ca4d7e.
Python
bsd-3-clause
nithinphilips/loom,nithinphilips/loom
22a678488d43f4ca7fc53c7894113b7895893e2a
mpltools/style/__init__.py
mpltools/style/__init__.py
""" This module defines styles redefine matplotlib rc parameters. In addition, you can override pre-defined styles with "mplstyle" files in the current directory and your home directory. The priority of style files is: 1. ./mplstyle 2. ~/.mplstyle 3. mpltools/style/ Style names should be specified as sect...
""" This module defines styles redefine matplotlib rc parameters. In addition, you can override pre-defined styles with "mplstyle" files in the current directory and your home directory. The priority of style files is: 1. ./mplstyle 2. ~/.mplstyle 3. mpltools/style/ Style names should be specified as sect...
Remove outdated function from list.
FIX: Remove outdated function from list.
Python
bsd-3-clause
tonysyu/mpltools,matteoicardi/mpltools
4b88dff3df0c82392314efe9c48379e1ad2b1500
vinotes/apps/api/serializers.py
vinotes/apps/api/serializers.py
from django.contrib.auth.models import User from rest_framework import serializers from .models import Note, Trait, Wine, Winery class WinerySerializer(serializers.ModelSerializer): wines = serializers.PrimaryKeyRelatedField(many=True, queryset=Wine.objects.all()) class Meta: model = Winery ...
from django.contrib.auth.models import User from rest_framework import serializers from .models import Note, Trait, Wine, Winery class WinerySerializer(serializers.ModelSerializer): wines = serializers.PrimaryKeyRelatedField(many=True, queryset=Wine.objects.all()) class Meta: model = Winery ...
Add trait's wines to serializer.
Add trait's wines to serializer.
Python
unlicense
rcutmore/vinotes-api,rcutmore/vinotes-api
a34c594a13a79a864d1b747d84a0074e7711dd42
testanalyzer/pythonanalyzer.py
testanalyzer/pythonanalyzer.py
import re from fileanalyzer import FileAnalyzer class PythonAnalyzer(FileAnalyzer): def get_class_count(self, content): return len( re.findall("class [a-zA-Z0-9_]+\(?[a-zA-Z0-9_, ]*\)?:", content)) def get_function_count(self, content): return len( re.findall("def [a-...
import re from fileanalyzer import FileAnalyzer class PythonAnalyzer(FileAnalyzer): def get_class_count(self, content): return len( re.findall("class +[a-zA-Z0-9_]+ *\(?[a-zA-Z0-9_, ]*\)? *:", content)) def get_function_count(self, content): return len( re.findall("de...
Update regex to allow spaces
Update regex to allow spaces
Python
mpl-2.0
CheriPai/TestAnalyzer,CheriPai/TestAnalyzer,CheriPai/TestAnalyzer
3d8f642460cf5c26dd8f58a5a36786b3ef4069e8
ogusa/tests/test_txfunc.py
ogusa/tests/test_txfunc.py
import pickle from ogusa import txfunc def test_cps_data(): with open("../../regression/cps_test_replace_outliers.pkl", 'rb') as p: param_arr = pickle.load(p) sse_big_mat = pickle.load(p) txfunc.replace_outliers(param_arr, sse_big_mat)
from ogusa import txfunc import numpy as np import pickle import os CUR_PATH = os.path.abspath(os.path.dirname(__file__)) def test_replace_outliers(): """ 4 cases: s is an outlier and is 0 s is an outlier and is in the interior (s > 0 and s < S) s is not an outlier but the first s - 1...
Use simulated data for test
Use simulated data for test
Python
mit
OpenSourcePolicyCenter/dynamic,OpenSourcePolicyCenter/dynamic,OpenSourcePolicyCenter/dynamic,OpenSourcePolicyCenter/dynamic,OpenSourcePolicyCenter/dynamic