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
872875ecb3b5a09c14da8836cdd4b7a6f6610675
vumi/transports/mxit/responses.py
vumi/transports/mxit/responses.py
import re from twisted.web.template import Element, renderer, XMLFile from twisted.python.filepath import FilePath class ResponseParser(object): HEADER_PATTERN = r'^(.*)[\r\n]{1,2}\d?' ITEM_PATTERN = r'^(\d+)\. (.+)$' def __init__(self, content): header_match = re.match(self.HEADER_PATTERN, con...
import re from twisted.web.template import Element, renderer, XMLFile from twisted.python.filepath import FilePath from vumi.utils import PkgResources MXIT_RESOURCES = PkgResources(__name__) class ResponseParser(object): HEADER_PATTERN = r'^(.*)[\r\n]{1,2}\d?' ITEM_PATTERN = r'^(\d+)\. (.+)$' def __...
Use PkgResources helper to load response templates.
Use PkgResources helper to load response templates.
Python
bsd-3-clause
TouK/vumi,TouK/vumi,TouK/vumi,harrissoerja/vumi,harrissoerja/vumi,vishwaprakashmishra/xmatrix,vishwaprakashmishra/xmatrix,harrissoerja/vumi,vishwaprakashmishra/xmatrix
4719401819a877ceebfcc49f1084fb01395a3f4d
nyuki/bus/persistence/mongo_backend.py
nyuki/bus/persistence/mongo_backend.py
from datetime import datetime import logging from motor.motor_asyncio import AsyncIOMotorClient from pymongo.errors import AutoReconnect log = logging.getLogger(__name__) class MongoBackend(object): def __init__(self, name): self.name = name self.host = None self._collection = None ...
from datetime import datetime import logging from motor.motor_asyncio import AsyncIOMotorClient from pymongo.errors import AutoReconnect log = logging.getLogger(__name__) class MongoBackend(object): def __init__(self, name): self.name = name self.host = None self._collection = None ...
Add failsafe mongo calls
Add failsafe mongo calls [ci skip]
Python
apache-2.0
optiflows/nyuki,gdraynz/nyuki,gdraynz/nyuki,optiflows/nyuki
eb7201789bc5ce03ca415fc4c208ce5a41bfc249
sha1.py
sha1.py
#!/usr/bin/env python """ usage: python -m sha1 <filename> """ import sys import hashlib # --- these fields are required for packaging __version__ = '1.0' __author__ = 'anatoly techtonik <techtonik@gmail.com>' __license__ = 'Public Domain' __url__ = 'https://gist.github.com/techtonik/df09baeacbebc52d234b' # /-- these ...
#!/usr/bin/env python """ usage: python -m sha1 <filename> """ import sys import hashlib # --- these fields are required for packaging __version__ = '1.0' __author__ = 'anatoly techtonik <techtonik@gmail.com>' __license__ = 'Public Domain' __url__ = 'https://github.com/techtonik/sha1' # /-- these fields are required f...
Move from Gist to GitHub
Move from Gist to GitHub
Python
unlicense
techtonik/sha1
75e0c323871d6eae6959523b105a06cfe8460a28
etk2/etk.py
etk2/etk.py
import json class ETK(object): def __init__(self): pass def get_glossary(self, file_path): res = dict() with open(file_path) as fp: line = fp.readline().rstrip('\n') while line: res[line] = line line = fp.readline().rstrip('\n') ...
from typing import List import json class ETK(object): def __init__(self): pass def get_glossary(self, file_path) -> List[str]: """ A glossary is a text file, one entry per line. Args: file_path (str): path to a text file containing a glossary. Returns: L...
Add comments and typing annotations
Add comments and typing annotations
Python
mit
usc-isi-i2/etk,usc-isi-i2/etk,usc-isi-i2/etk
3f1c988830b7b5128c8da141326ecbf7234a791a
kolibri/core/content/utils/content_types_tools.py
kolibri/core/content/utils/content_types_tools.py
from django.db.models import Q from le_utils.constants import content_kinds from kolibri.core.content.hooks import ContentRendererHook from kolibri.core.content.models import ContentNode # Start with an empty queryset, as we'll be using OR to add conditions renderable_contentnodes_without_topics_q_filter = ContentNod...
from django.db.models import Q from le_utils.constants import content_kinds from kolibri.core.content.hooks import ContentRendererHook # Start with an empty Q object, as we'll be using OR to add conditions renderable_contentnodes_without_topics_q_filter = Q() # loop through all the registered content renderer hooks...
Use Q object instead of empty queryset
Use Q object instead of empty queryset
Python
mit
mrpau/kolibri,lyw07/kolibri,lyw07/kolibri,learningequality/kolibri,mrpau/kolibri,learningequality/kolibri,indirectlylit/kolibri,learningequality/kolibri,indirectlylit/kolibri,mrpau/kolibri,lyw07/kolibri,indirectlylit/kolibri,lyw07/kolibri,learningequality/kolibri,indirectlylit/kolibri,mrpau/kolibri
756456992247bf8dbb0731556e37ecd0cf32e3ab
scripts/splitfa.py
scripts/splitfa.py
#!/usr/bin/env python from __future__ import print_function, absolute_import, division import screed import docopt CLI = """ USAGE: fasplit <fasta> <prefix> """ opts = docopt.docopt(CLI) prefix = opts['<prefix>'] with screed.open(opts['<fasta>']) as fh: for record in fh: fname = "{}{}.fasta".format(p...
#!/usr/bin/env python from __future__ import print_function, absolute_import, division import screed import docopt CLI = """ USAGE: fasplit <fasta> <prefix> """ opts = docopt.docopt(CLI) prefix = opts['<prefix>'] with screed.open(opts['<fasta>']) as fh: for record in fh: fname = "{}{}.fasta".format(p...
Remove gaps from individual genomes
Remove gaps from individual genomes
Python
mit
kdmurray91/kwip-experiments,kdmurray91/kwip-experiments,kdmurray91/kwip-experiments
e8880d6a4fb96722551bdc50274cdfddc2bd41d2
corehq/ex-submodules/casexml/apps/case/tests/test_signals.py
corehq/ex-submodules/casexml/apps/case/tests/test_signals.py
from django.test import TestCase from casexml.apps.case.mock import CaseFactory from casexml.apps.case.signals import cases_received from casexml.apps.case.xform import process_cases_with_casedb from corehq.form_processor.backends.sql.dbaccessors import FormAccessorSQL from corehq.form_processor.interfaces.processor im...
from django.test import TestCase from casexml.apps.case.mock import CaseFactory from casexml.apps.case.signals import cases_received from casexml.apps.case.xform import process_cases_with_casedb from corehq.form_processor.backends.sql.dbaccessors import FormAccessorSQL from corehq.form_processor.interfaces.processor im...
Refactor test to not use global variable
Refactor test to not use global variable
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
081b1cd60e363adf941ba511c7683c0ed2843a97
gubernator/appengine_config.py
gubernator/appengine_config.py
# Copyright 2016 The Kubernetes Authors All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
# Copyright 2016 The Kubernetes Authors All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
Increase Gubernator's url fetch deadline -- 5 seconds is too fast!
Increase Gubernator's url fetch deadline -- 5 seconds is too fast! This should avoid a lot of refreshes because some directory listing or download takes slightly too long.
Python
apache-2.0
mikedanese/test-infra,gmarek/test-infra,mindprince/test-infra,shashidharatd/test-infra,cblecker/test-infra,rmmh/kubernetes-test-infra,mikedanese/test-infra,jlowdermilk/test-infra,shyamjvs/test-infra,mikedanese/test-infra,girishkalele/test-infra,grodrigues3/test-infra,monopole/test-infra,foxish/test-infra,mikedanese/tes...
e8e326fe39623ea04082553d1293b1e79c3611f6
proto/ho.py
proto/ho.py
#!/usr/bin/env python import sys from board import Board, BoardView from utils import clear, getch def main(): board = Board(19, 19) view = BoardView(board) def move(): board.move(*view.cursor) view.redraw() def exit(): sys.exit(0) KEYS = { 'w': view.cursor_up,...
#!/usr/bin/env python import sys from board import Board, BoardView from utils import clear, getch def main(): board = Board(19, 19) view = BoardView(board) err = None def move(): board.move(*view.cursor) view.redraw() def exit(): sys.exit(0) KEYS = { 'w': ...
Add error handling to main game loop
Add error handling to main game loop
Python
mit
davesque/go.py
bc399ed6902f6ba3d24e1ce1a8ff88a259793c3a
Artifactorial/urls.py
Artifactorial/urls.py
# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2014 Rémi Duraffort # This file is part of Artifactorial. # # Artifactorial 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 L...
# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2014 Rémi Duraffort # This file is part of Artifactorial. # # Artifactorial 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 L...
Use the new url pattern
Use the new url pattern
Python
mit
ivoire/Artifactorial,ivoire/Artifactorial,ivoire/Artifactorial
ff2d9b276928d2bf06ae81b1fa243ee2816cd694
seawater/__init__.py
seawater/__init__.py
# -*- coding: utf-8 -*- __all__ = ["csiro", "extras"] __authors__ = 'Filipe Fernandes' __created_ = "14-Jan-2010" __email__ = "ocefpaf@gmail.com" __license__ = "MIT" __maintainer__ = "Filipe Fernandes" __modified__ = "16-Mar-2013" __status__ = "Production" __version__ = "2.0.0" import csiro import extras
# -*- coding: utf-8 -*- from csiro import *
Update to reflect some small re-factoring.
Update to reflect some small re-factoring.
Python
mit
ocefpaf/python-seawater,pyoceans/python-seawater,pyoceans/python-seawater,ocefpaf/python-seawater
0d135a746dd79ad1b703570e2bb3b27a694c67b0
simuvex/procedures/stubs/NoReturnUnconstrained.py
simuvex/procedures/stubs/NoReturnUnconstrained.py
import simuvex ###################################### # NoReturnUnconstrained # Use in places you would put ReturnUnconstrained as a default action # But the function shouldn't actually return ###################################### use_cases = {'exit_group', 'exit', 'abort', 'longjmp', 'pthread_exit', 'siglongjmp'} ...
import simuvex ###################################### # NoReturnUnconstrained # Use in places you would put ReturnUnconstrained as a default action # But the function shouldn't actually return ###################################### class NoReturnUnconstrained(simuvex.SimProcedure): #pylint:disable=redefined-builtin ...
Move use_cases into the class
Move use_cases into the class
Python
bsd-2-clause
iamahuman/angr,iamahuman/angr,f-prettyland/angr,chubbymaggie/simuvex,chubbymaggie/angr,schieb/angr,angr/angr,tyb0807/angr,f-prettyland/angr,tyb0807/angr,axt/angr,tyb0807/angr,chubbymaggie/angr,angr/angr,angr/angr,iamahuman/angr,axt/angr,f-prettyland/angr,chubbymaggie/angr,angr/simuvex,chubbymaggie/simuvex,zhuyue1314/si...
4e5825b732597d7adcfcf8eaea3468c893b86347
src/akllt/tests.py
src/akllt/tests.py
# coding: utf-8 import pkg_resources from django.test.testcases import TransactionTestCase from homophony import BrowserTestCase, Browser def import_pages(directory): pass class SmokeTest(TransactionTestCase): def test_nothing(self): self.client.get('/') class FoobarTestCase(BrowserTestCase): ...
# coding: utf-8 import pkg_resources from django.test.testcases import TransactionTestCase from homophony import BrowserTestCase, Browser from akllt.models import StandardPage def import_pages(directory): pass def import_pages(directory): pass class SmokeTest(TransactionTestCase): def test_nothing(s...
Create functional test for data import
Create functional test for data import
Python
agpl-3.0
python-dirbtuves/akl.lt,python-dirbtuves/akl.lt,python-dirbtuves/akl.lt,python-dirbtuves/akl.lt,python-dirbtuves/akl.lt
983e4fc9c5fafcfb60996c73571fc9ae9dd6b307
app/__init__.py
app/__init__.py
from flask import Flask from flask_login import LoginManager from flask_bcrypt import Bcrypt from flask_admin import Admin from flask_admin.contrib.peewee import ModelView from playhouse.flask_utils import FlaskDB app = Flask(__name__) app.config.from_object('config') @app.before_request def _db_connect(): db.co...
from flask import Flask from flask_login import LoginManager from flask_bcrypt import Bcrypt from flask_admin import Admin from flask_admin.contrib.peewee import ModelView from playhouse.flask_utils import FlaskDB app = Flask(__name__) app.config.from_object('config') @app.before_request def _db_connect(): db.co...
Fix table names in flask-admin
Fix table names in flask-admin
Python
mpl-2.0
teknologkoren/teknologkoren-se,teknologkoren/teknologkoren-se,teknologkoren/teknologkoren-se,teknologkoren/teknologkoren-se
d617ce484c1c85032f6c792b7f03d7710df97acf
GoldenDictMedia/2.1/golden_dict_media/__init__.py
GoldenDictMedia/2.1/golden_dict_media/__init__.py
import aqt from golden_dict_media.AddonInitializer import init_addon if aqt.mw is not None: init_addon()
import aqt from .AddonInitializer import init_addon if aqt.mw is not None: init_addon()
Use relative paths in golden_dict_media
Use relative paths in golden_dict_media
Python
mit
searene/Anki-Addons,searene/Anki-Addons
5e736819e35efaad8568bb0782af3d256d55963d
game/quests/__init__.py
game/quests/__init__.py
# -*- coding: utf-8 -*- """ Quests - questcache.wdb """ from .. import * class Quest(Model): def getTooltip(self): return QuestTooltip(self) class QuestTooltip(Tooltip): def tooltip(self): self.append("name", self.obj.getName(), color=YELLOW) ret = self.values self.values = [] return ret class Q...
# -*- coding: utf-8 -*- """ Quests - questcache.wdb """ from .. import * class Quest(Model): def getTooltip(self): return QuestTooltip(self) class QuestTooltip(Tooltip): def tooltip(self): self.append("name", self.obj.getName(), color=YELLOW) self.appendEmptyLine() self.append("objective", self.obj...
Implement getObjective and tooltip objective
game/quests: Implement getObjective and tooltip objective
Python
cc0-1.0
jleclanche/pywow,jleclanche/pywow,jleclanche/pywow,jleclanche/pywow,jleclanche/pywow,jleclanche/pywow
dd400066927e70e43001e3c3172241579a314b60
s3_sample.py
s3_sample.py
# Copyright 2013. Amazon Web Services, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by a...
# Copyright 2013. Amazon Web Services, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by a...
Update sample to also fetch the object, and delete the object and bucket.
Update sample to also fetch the object, and delete the object and bucket.
Python
apache-2.0
ceizner/codechallenge,awslabs/aws-python-sample,noahchense/aws-python-sample
938840b27fd218eeaf9c253e9162392e653dff0b
snippet_parser/it.py
snippet_parser/it.py
#-*- encoding: utf-8 -*- from __future__ import unicode_literals from core import * def handle_bandiera(template): return template.get(1) def handle_citazione(template): if template.params: return '« ' + sp(template.params[0]) + ' »' class SnippetParser(SnippetParserBase): def strip_template(sel...
#-*- encoding: utf-8 -*- from __future__ import unicode_literals from core import * class SnippetParser(SnippetParserBase): def strip_template(self, template, normalize, collapse): if template.name.matches('bandiera'): return self.handle_bandiera(template) elif template.name.matches('c...
Fix snippet parser for Italian.
Fix snippet parser for Italian. Former-commit-id: bb8d10f5f8301fbcd4f4232612bf722d380a3d10
Python
mit
guilherme-pg/citationhunt,eggpi/citationhunt,eggpi/citationhunt,guilherme-pg/citationhunt,guilherme-pg/citationhunt,eggpi/citationhunt,eggpi/citationhunt,guilherme-pg/citationhunt
d2e3fcedb5a228a234d5b564cca391214f95e617
us_ignite/apps/tests/fixtures.py
us_ignite/apps/tests/fixtures.py
from us_ignite.apps.models import Application, ApplicationMembership, Page from us_ignite.profiles.tests.fixtures import get_user def get_application(**kwargs): defaults = { 'name': 'Gigabit app', } if not 'owner' in kwargs: defaults['owner'] = get_user('us-ignite') defaults.update(kwa...
from us_ignite.apps.models import (Application, ApplicationMembership, Domain, Page) from us_ignite.profiles.tests.fixtures import get_user def get_application(**kwargs): data = { 'name': 'Gigabit app', } if not 'owner' in kwargs: data['owner'] = get_user...
Add ``get_domain`` test fixture factory.
Add ``get_domain`` test fixture factory. Helpful to test the ``Domain``.
Python
bsd-3-clause
us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite
f7ae0b3663f9fabd312f1f07c544ac9122241fc4
broadcaster.py
broadcaster.py
from threading import Thread from watchdog.events import FileSystemEventHandler from watchdog.observers import Observer import os import requests import time FRAMES_PATH = os.getenv("FRAMES_PATH", 'frames') PUBLISH_URL = os.getenv("PUBLISH_URL", 'http://localhost:9080/pub?id={channel}') class EventHandler(FileSystem...
from threading import Thread from watchdog.events import FileSystemEventHandler from watchdog.observers import Observer import os import requests import time FRAMES_PATH = os.getenv("FRAMES_PATH", 'frames') PUBLISH_URL = os.getenv("PUBLISH_URL", 'http://localhost:9080/pub?id={channel}') class EventHandler(FileSystem...
Fix bug when directory is created on watched path
Fix bug when directory is created on watched path
Python
mit
jbochi/live_thumb,jbochi/live_thumb,jbochi/live_thumb
c30ef8dba42dcc16eb7bf9e126d4551db30c06eb
exporters/filters/__init__.py
exporters/filters/__init__.py
from .key_value_filter import KeyValueFilter from .key_value_regex_filter import KeyValueRegexFilter from .no_filter import NoFilter from .pythonexp_filter import PythonexpFilter __all__ = ['KeyValueFilter', 'KeyValueRegexFilter', 'NoFilter', 'PythonexpFilter']
from .key_value_filters import KeyValueFilter, KeyValueRegexFilter from .no_filter import NoFilter from .pythonexp_filter import PythonexpFilter __all__ = ['KeyValueFilter', 'KeyValueRegexFilter', 'NoFilter', 'PythonexpFilter']
Use proper filters avoiding deprecated warnings.
Use proper filters avoiding deprecated warnings.
Python
bsd-3-clause
scrapinghub/exporters
c424744af801241fbdced0e3344c1f9b6f2c6416
citenet/cli.py
citenet/cli.py
"""Command-line interface for citenet.""" def main(): """Run the CLI.""" print('CiteNet CLI')
"""Command-line interface for citenet.""" import sys import json import citenet def main(): """Run the CLI.""" if len(sys.argv) != 2: print("Usage: {} <config_file>") with open(sys.argv[1]) as config_file: config = json.load(config_file) graph = citenet.read_csv_graph(**config['graph...
Add rudimentary JSON configuration to CLI
Add rudimentary JSON configuration to CLI
Python
mit
Pringley/citenet
7d714f0e19ceaa72e186674302549c176e98f442
streak-podium/render.py
streak-podium/render.py
import matplotlib.pyplot as plt import numpy as np def horizontal_bar(sorted_streaks, sort): """ Render a horizontal bar chart of streaks. Values have already been sorted by sort. """ # Only extract those users & streaks for streaks that are non-zero: users, streaks = zip(*[(user, streak.get(...
import matplotlib.pyplot as plt import numpy as np def horizontal_bar(sorted_streaks, sort): """ Render a horizontal bar chart of streaks. Values have already been sorted by sort. """ # Only extract those users & streaks for streaks that are non-zero: users, streaks = zip(*[(user, streak.get(...
Add argument to adjust figure size
Add argument to adjust figure size And minor styling tweaks.
Python
mit
supermitch/streak-podium,jollyra/hubot-commit-streak,jollyra/hubot-commit-streak,jollyra/hubot-streak-podium,jollyra/hubot-streak-podium,supermitch/streak-podium
94f5edd9b2f693b48181ddefa7af725be854c49e
src/config/common/ssl_adapter.py
src/config/common/ssl_adapter.py
""" HTTPS Transport Adapter for python-requests, that allows configuration of SSL version""" # -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # @author: Sanju Abraham, Juniper Networks, OpenContrail from requests.adapters import HTTPAdapter try: # This is required for RDO, which installs both...
""" HTTPS Transport Adapter for python-requests, that allows configuration of SSL version""" # -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # @author: Sanju Abraham, Juniper Networks, OpenContrail from requests.adapters import HTTPAdapter try: # This is required for RDO, which installs both...
Add ssl_version to the list of attributes, required when vnc_api gets called via multiprocessing module. This will ensure ssl_version gets included when pickle calls __getstate__ and __setstate__.
Add ssl_version to the list of attributes, required when vnc_api gets called via multiprocessing module. This will ensure ssl_version gets included when pickle calls __getstate__ and __setstate__. Courtesy: https://github.com/sigmavirus24/requests-toolbelt/commit/decadbd3512444889feb30cf1ff2f1448a3ecfca Closes-Bug:#1...
Python
apache-2.0
tcpcloud/contrail-controller,tcpcloud/contrail-controller,tcpcloud/contrail-controller,tcpcloud/contrail-controller,tcpcloud/contrail-controller,tcpcloud/contrail-controller
34513dd1716f7299b2244d488055e82da1aea080
armstrong/core/arm_layout/utils.py
armstrong/core/arm_layout/utils.py
from django.utils.safestring import mark_safe from django.template.loader import render_to_string def get_layout_template_name(model, name): ret = [] for a in model.__class__.mro(): if not hasattr(a, "_meta"): continue ret.append("layout/%s/%s/%s.html" % (a._meta.app_label, ...
from django.utils.safestring import mark_safe from django.template.loader import render_to_string from armstrong.utils.backends import GenericBackend template_finder = GenericBackend('ARMSTRONG_LAYOUT_TEMPLATE_FINDER', defaults='armstrong.core.arm_layout.utils.get_layout_template_name')\ .get_backend...
Use a GenericBackend for our template finding function.
Use a GenericBackend for our template finding function.
Python
apache-2.0
armstrong/armstrong.core.arm_layout,armstrong/armstrong.core.arm_layout
4dbeb34c0ca691ff4a9faf6d6a0fa9f67bacba5a
app/tests/conftest.py
app/tests/conftest.py
import os.path import pytest from alembic.command import upgrade from alembic.config import Config from app.database import sa, create_engine, create_db_session from app.models import Base HERE = os.path.dirname(os.path.abspath(__file__)) ALEMBIC_CONFIG = os.path.join(HERE, "..", "..", "alembic.ini") def apply_mi...
import os.path import pytest from alembic.command import upgrade from alembic.config import Config from app.database import db as _db from app.database import create_engine, create_db_session from app.models import Base HERE = os.path.dirname(os.path.abspath(__file__)) ALEMBIC_CONFIG = os.path.join(HERE, "..", ".."...
Change engine fixture to use db obj
Change engine fixture to use db obj
Python
mit
PsyBorgs/redditanalyser,PsyBorgs/redditanalyser
96b283adbb3156e77aee012a9fb8aba9d67343a9
src/bitmessageqt/widgets.py
src/bitmessageqt/widgets.py
from PyQt4 import uic import os.path import sys def resource_path(path): try: return os.path.join(sys._MEIPASS, path) except: return os.path.join(os.path.dirname(__file__), path) def load(path, widget): uic.loadUi(resource_path(path), widget)
from PyQt4 import uic import os.path import sys from shared import codePath def resource_path(resFile): baseDir = codePath() for subDir in ["ui", "bitmessageqt"]: if os.path.isdir(os.path.join(baseDir, subDir)) and os.path.isfile(os.path.join(baseDir, subDir, resFile)): return os.path.join(...
Change UI loading for frozen
Change UI loading for frozen
Python
mit
mailchuck/PyBitmessage,mailchuck/PyBitmessage,mailchuck/PyBitmessage,mailchuck/PyBitmessage
31b8ecda3d6b34428180b45e49489ebefc8a57e3
tests/test_util.py
tests/test_util.py
from unittest import TestCase from pytest import deprecated_call from w3lib.util import str_to_unicode, to_native_str, unicode_to_str class StrToUnicodeTestCase(TestCase): def test_deprecation(self): with deprecated_call(): str_to_unicode('') class ToNativeStrTestCase(TestCase): def ...
from unittest import TestCase from pytest import deprecated_call, raises from w3lib.util import ( str_to_unicode, to_bytes, to_native_str, to_unicode, unicode_to_str, ) class StrToUnicodeTestCase(TestCase): def test_deprecation(self): with deprecated_call(): str_to_unico...
Test the TypeError of to_bytes() and to_unicode()
Test the TypeError of to_bytes() and to_unicode()
Python
bsd-3-clause
scrapy/w3lib
7a33e2e94e46dc3465a088cf4755134a09f6627c
src/models/user.py
src/models/user.py
from flock import db class User(db.Model): id = db.Column(db.Integer, primary_key=True) def __init__(self): pass
from flock import db class User(db.Model): id = db.Column(db.Integer, primary_key=True) suggestions = db.relationship('Suggestion', secondary=suggestions, backref=db.backref('users', lazy='dynamic')) def __init__(self): pass
Add suggestions to User model
Add suggestions to User model
Python
agpl-3.0
DavidJFelix/hatchit,DavidJFelix/hatchit,DavidJFelix/hatchit
1666a48ccaef30d5d1dbceb3212160991beecbd5
wluopensource/osl_comments/models.py
wluopensource/osl_comments/models.py
from django.contrib.comments.models import Comment from django.contrib.comments.signals import comment_was_posted from django.contrib.contenttypes.models import ContentType from django.db import models import markdown class OslComment(Comment): parent_comment = models.ForeignKey(Comment, blank=True, null=True, re...
from django.contrib.comments.models import Comment from django.contrib.comments.signals import comment_was_posted from django.contrib.contenttypes.models import ContentType from django.db import models import markdown class OslComment(Comment): parent_comment = models.ForeignKey(Comment, blank=True, null=True, re...
Move applying auth user URLs to comments from signal to save method
Move applying auth user URLs to comments from signal to save method
Python
bsd-3-clause
jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website
3ef0c6adcfa74877245f586618c4592b308976cd
openapi_core/wrappers/flask.py
openapi_core/wrappers/flask.py
"""OpenAPI core wrappers module""" from openapi_core.wrappers.base import BaseOpenAPIRequest, BaseOpenAPIResponse class FlaskOpenAPIRequest(BaseOpenAPIRequest): def __init__(self, request): self.request = request @property def host_url(self): return self.request.host_url @property ...
"""OpenAPI core wrappers module""" import re from openapi_core.wrappers.base import BaseOpenAPIRequest, BaseOpenAPIResponse # http://flask.pocoo.org/docs/1.0/quickstart/#variable-rules PATH_PARAMETER_PATTERN = r'<(?:(?:string|int|float|path|uuid):)?(\w+)>' class FlaskOpenAPIRequest(BaseOpenAPIRequest): path_re...
Convert Flask path variables to OpenAPI path parameters
Convert Flask path variables to OpenAPI path parameters
Python
bsd-3-clause
p1c2u/openapi-core
481f580b30efe0cf6f46081c098e2a174444a10b
base/components/accounts/views.py
base/components/accounts/views.py
from django import http from django.conf import settings from django.views.generic import RedirectView, View from requests_oauthlib import OAuth2Session CLIENT_ID = settings.HELLO_BASE_CLIENT_ID CLIENT_SECRET = settings.HELLO_BASE_CLIENT_SECRET AUTHORIZATION_URL = 'https://localhost:8443/authorize' TOKEN_URL = 'http...
from django import http from django.conf import settings from django.views.generic import RedirectView, View from requests_oauthlib import OAuth2Session CLIENT_ID = settings.HELLO_BASE_CLIENT_ID CLIENT_SECRET = settings.HELLO_BASE_CLIENT_SECRET AUTHORIZATION_URL = 'https://localhost:8443/authorize/' TOKEN_URL = 'htt...
Add some slashes and other things.
Add some slashes and other things.
Python
apache-2.0
hello-base/web,hello-base/web,hello-base/web,hello-base/web
3853e133f420320c8fa475cafd62356179f6ef5c
zerver/migrations/0167_custom_profile_fields_sort_order.py
zerver/migrations/0167_custom_profile_fields_sort_order.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.11 on 2018-04-08 15:49 from __future__ import unicode_literals from django.db import migrations, models from django.db.models import F from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps def ...
# -*- coding: utf-8 -*- # Generated by Django 1.11.11 on 2018-04-08 15:49 from __future__ import unicode_literals from django.db import migrations, models from django.db.models import F from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps def ...
Add missing reverse_code for migration 0167.
migrations: Add missing reverse_code for migration 0167.
Python
apache-2.0
jackrzhang/zulip,zulip/zulip,synicalsyntax/zulip,kou/zulip,jackrzhang/zulip,showell/zulip,kou/zulip,dhcrzf/zulip,timabbott/zulip,tommyip/zulip,brainwane/zulip,dhcrzf/zulip,timabbott/zulip,andersk/zulip,brainwane/zulip,synicalsyntax/zulip,rishig/zulip,tommyip/zulip,rishig/zulip,punchagan/zulip,showell/zulip,jackrzhang/z...
8df7c4b2c008ce6c7735106c28bad1f7326f7012
tests/smoketests/test_twisted.py
tests/smoketests/test_twisted.py
from twisted.internet import reactor, task def test_deferred(): return task.deferLater(reactor, 0.05, lambda: None)
from twisted.internet import reactor, task from twisted.internet.defer import Deferred, succeed from twisted.python.failure import Failure def test_deferred(): return task.deferLater(reactor, 0.05, lambda: None) def test_failure(): """ Test that we can check for a failure in an asynchronously-called fun...
Add an example Twisted test that expects failure.
Add an example Twisted test that expects failure.
Python
mit
CheeseLord/warts,CheeseLord/warts
4fb6cd2b73deb500d664c1a0d2d6c57b11626a7e
tests/pyutils/test_path.py
tests/pyutils/test_path.py
from graphql.pyutils import Path def describe_path(): def add_path(): path = Path(None, 0, None) assert path.prev is None assert path.key == 0 prev, path = path, Path(path, 1, None) assert path.prev is prev assert path.key == 1 prev, path = path, Path(path, ...
from graphql.pyutils import Path def describe_path(): def can_create_a_path(): first = Path(None, 1, "First") assert first.prev is None assert first.key == 1 assert first.typename == "First" def can_add_a_new_key_to_an_existing_path(): first = Path(None, 1, "First") ...
Improve tests for Path methods
Improve tests for Path methods Replicates graphql/graphql-js@f42cee922d13576b1452bb5bf6c7b155bf0e2ecd
Python
mit
graphql-python/graphql-core
f232481f966580bfd54ddd0eeb781badda3a9394
swh/web/add_forge_now/apps.py
swh/web/add_forge_now/apps.py
# Copyright (C) 2022 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU Affero General Public License version 3, or any later version # See top-level LICENSE file for more information from django.apps import AppConfig class AddForgeNowConfig(AppCon...
# Copyright (C) 2022 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU Affero General Public License version 3, or any later version # See top-level LICENSE file for more information from django.apps import AppConfig class AddForgeNowConfig(AppCon...
Rename django app and add missing app_label
add_forge_now: Rename django app and add missing app_label This fixes errors when using django 3.2 and thus the packaging on debian unstable
Python
agpl-3.0
SoftwareHeritage/swh-web-ui,SoftwareHeritage/swh-web-ui,SoftwareHeritage/swh-web-ui
21dea82cd8fc2b7d8889013dfd827f59cc8ceb58
acmd/tools/assets.py
acmd/tools/assets.py
# coding: utf-8 import sys import os.path import optparse import json import requests from acmd import tool, log from acmd import OK, SERVER_ERROR, USER_ERROR from acmd.props import parse_properties parser = optparse.OptionParser("acmd assets <import|touch> [options] <file>") parser.add_option("-r", "--raw", ...
# coding: utf-8 import optparse import os import requests from acmd import OK, SERVER_ERROR from acmd import tool, error, log from acmd.tools.tool_utils import get_argument, get_command parser = optparse.OptionParser("acmd assets <import|touch> [options] <file>") parser.add_option("-r", "--raw", ac...
Support iterate of files in dir
Support iterate of files in dir
Python
mit
darashenka/aem-cmd,darashenka/aem-cmd,darashenka/aem-cmd
df8f5e0a6be5f3de31d61810b1624175b2d105ec
auth0/v2/device_credentials.py
auth0/v2/device_credentials.py
from .rest import RestClient class DeviceCredentials(object): def __init__(self, domain, jwt_token): url = 'https://%s/api/v2/device-credentials' % domain self.client = RestClient(endpoint=url, jwt=jwt_token) def get(self, user_id=None, client_id=None, type=None, fields=[], incl...
from .rest import RestClient class DeviceCredentials(object): def __init__(self, domain, jwt_token): url = 'https://%s/api/v2/device-credentials' % domain self.client = RestClient(endpoint=url, jwt=jwt_token) def get(self, user_id=None, client_id=None, type=None, fields=[], incl...
Implement create and delete methods for DeviceCredentials
Implement create and delete methods for DeviceCredentials
Python
mit
auth0/auth0-python,auth0/auth0-python
967795c9005b7ccdacdb17c461a86cda68409785
fileutil.py
fileutil.py
import os, shutil def atomic_write_file(path, data): temp = os.path.join(os.path.dirname(path), ".tmpsave." + os.path.basename(path)) try: with open(temp, "wb") as out: try: shutil.copystat(path, temp) except OSError: pass out.write(da...
import sys, os, shutil if sys.platform == "win32": # os.rename is broken on windows import win32file def rename(old, new): win32file.MoveFileEx(old, new, win32file.MOVEFILE_REPLACE_EXISTING) else: rename = os.rename def atomic_write_file(path, data): temp = os.path.join(os.path.dirname(pat...
Use MoveFileEx on Windows because os.rename does not replace existing files.
Use MoveFileEx on Windows because os.rename does not replace existing files.
Python
mit
shaurz/devo
a9f5603b9134a6daa757fd85c1600ac3aa67f5df
time_test.py
time_test.py
import timeit setup=""" from _ppeg import Pattern text = open('kjv10.txt').read() pat = Pattern() pat.setdummy() pat.dump() """ t = timeit.Timer(stmt='print pat.match(text)', setup=setup) N=5 print "Time taken: %.2f sec" % (t.timeit(N)/float(N))
import timeit setup=""" from _ppeg import Pattern text = open('kjv10.txt').read() pat = Pattern.Dummy() pat.dump() """ t = timeit.Timer(stmt='print pat(text)', setup=setup) N=5 print "Time taken: %.2f sec" % (t.timeit(N)/float(N))
Update timing test to new pattern API
Update timing test to new pattern API
Python
mit
moreati/ppeg,moreati/ppeg
ada71c4aa8e96e71b90c205fbfec9079ffa29142
test/features/steps/system.py
test/features/steps/system.py
from __future__ import print_function import sys import subprocess import os @given('a system executable {exe}') def step_impl(context, exe): binary = None if sys.platform.startswith('win'): try: binary = subprocess.check_output(["where", exe]).decode('utf8').strip() except: ...
from __future__ import print_function import sys import subprocess import os @given('a system executable {exe}') def step_impl(context, exe): binary = None if sys.platform.startswith('win'): try: binary = subprocess.check_output(["where", exe]).decode('utf8').strip() except: ...
Use the correct option when dumping dependent libraries.
test: Use the correct option when dumping dependent libraries.
Python
bsd-3-clause
hotgloupi/configure,hotgloupi/configure,hotgloupi/configure,hotgloupi/configure,hotgloupi/configure
acfa9a206e803ad41565f6f3a678d9e1130948d8
test/runmain.py
test/runmain.py
#!usr/bin/env python import ui_logic_mainwindow as uv from PyQt4 import QtGui import sys def main(): app = QtGui.QApplication(sys.argv) ex = uv.UiMainWindow() ex.show() sys.exit(app.exec_()) if __name__ == "__main__": main()
#!/usr/bin/env python from test import ui_logic_mainwindow as uv from PyQt4 import QtGui import sys def main(): app = QtGui.QApplication(sys.argv) ex = uv.UiMainWindow() ex.show() sys.exit(app.exec_()) if __name__ == "__main__": main()
Update run mainfile to reflect import paths
Update run mainfile to reflect import paths
Python
mit
bibsian/database-development
64f3e09eb74158233af37513d0cedf75b8d62aae
packagename/conftest.py
packagename/conftest.py
# this contains imports plugins that configure py.test for astropy tests. # by importing them here in conftest.py they are discoverable by py.test # no matter how it is invoked within the source tree. from astropy.tests.pytest_plugins import * ## Uncomment the following line to treat all DeprecationWarnings as ## exc...
# this contains imports plugins that configure py.test for astropy tests. # by importing them here in conftest.py they are discoverable by py.test # no matter how it is invoked within the source tree. from astropy.tests.pytest_plugins import * ## Uncomment the following line to treat all DeprecationWarnings as ## exc...
Add note about adding/removing packages to/from pytest header
Add note about adding/removing packages to/from pytest header
Python
bsd-3-clause
alexrudy/Zeeko,alexrudy/Zeeko
19e0b3f089c684fe4aaaed8a06b4baad31de2f41
currencies/models.py
currencies/models.py
from django.db import models from django.utils.translation import gettext_lazy as _ class Currency(models.Model): code = models.CharField(_('code'), max_length=3) name = models.CharField(_('name'), max_length=35) symbol = models.CharField(_('symbol'), max_length=4, blank=True) factor = models.DecimalF...
from django.db import models from django.utils.translation import gettext_lazy as _ class Currency(models.Model): code = models.CharField(_('code'), max_length=3) name = models.CharField(_('name'), max_length=35) symbol = models.CharField(_('symbol'), max_length=4, blank=True) factor = models.DecimalF...
Order currencies by name by default
Order currencies by name by default
Python
bsd-3-clause
marcosalcazar/django-currencies,jmp0xf/django-currencies,ydaniv/django-currencies,ydaniv/django-currencies,barseghyanartur/django-currencies,panosl/django-currencies,pathakamit88/django-currencies,bashu/django-simple-currencies,mysociety/django-currencies,pathakamit88/django-currencies,racitup/django-currencies,panosl/...
5fe3187ba546bea4d948914b2eb5cf9953a5bee6
tests/clip_test.py
tests/clip_test.py
import PyDSTool as dst from PyDSTool.Toolbox.phaseplane import Point2D from matplotlib import pyplot as plt from fovea.graphics import * # ISSUE: fix to use new argument format for function (no global) plotter.domain={'x': [-1,1], 'y': [-2,2]} plotter.coords=('x','y') a, b = force_line_to_extent(Point2D((0.25,0)), P...
import PyDSTool as dst from PyDSTool.Toolbox.phaseplane import Point2D from matplotlib import pyplot as plt import numpy as np from fovea.graphics import * plotter.domain={'x': [-1,1], 'y': [-2,2]} plotter.coords=('x','y') a, b = force_line_to_extent(Point2D((0.25,0)), Point2D((0.5,0.1)), ...
Fix new syntax and add example using numpy arrays
Fix new syntax and add example using numpy arrays
Python
bsd-3-clause
robclewley/fovea,akuefler/fovea
d68a7f9c42220d6497fe87cc8426ce8ff8098c30
wcontrol/src/results.py
wcontrol/src/results.py
from wcontrol.conf.config import BMI, BFP, MUSCLE class results(object): def __init__(self, control, gender): self.bmi = self.get_bmi(control.bmi) self.fat = self.get_fat(control.fat, gender) self.muscle = self.get_muscle(control.muscle, gender) def get_bmi(self, bmi): for lim...
from wcontrol.conf.config import BMI, BFP, MUSCLE, VISCERAL class results(object): def __init__(self, control, gender): self.bmi = self.get_bmi(control.bmi) self.fat = self.get_fat(control.fat, gender) self.muscle = self.get_muscle(control.muscle, gender) self.visceral = self.get_v...
Add function to get the visceral fat result
Add function to get the visceral fat result
Python
mit
pahumadad/weight-control,pahumadad/weight-control,pahumadad/weight-control,pahumadad/weight-control
bc576b0284ebf49e105af678b483173084068bfb
ufyr/utils/http.py
ufyr/utils/http.py
#! /usr/bin/python import json import requests class Callback(object): def __init__(self, url, method='GET', req_kwargs={}, **kwargs): assert isinstance(url, (str, unicode)) assert isinstance(method, (str, unicode)) assert isinstance(req_kwargs, dict) se...
#! /usr/bin/python import json import requests from ufyr.decorators import retry class Callback(object): def __init__(self, url, method='GET', req_kwargs={}, **kwargs): assert isinstance(url, (str, unicode)) assert isinstance(method, (str, unicode)) assert isinstance(req_kwargs,...
Add retry and failure detection to callback.execute
Add retry and failure detection to callback.execute
Python
unlicense
timeartist/ufyr
74adefcad1fe411b596981da7d124cda2f8e936d
mopidy/backends/local/__init__.py
mopidy/backends/local/__init__.py
from __future__ import unicode_literals import mopidy from mopidy import ext __doc__ = """A backend for playing music from a local music archive. This backend handles URIs starting with ``file:``. See :ref:`music-from-local-storage` for further instructions on using this backend. **Issues:** https://github.com/m...
from __future__ import unicode_literals import mopidy from mopidy import ext from mopidy.utils import config, formatting default_config = """ [ext.local] # If the local extension should be enabled or not enabled = true # Path to folder with local music music_path = $XDG_MUSIC_DIR # Path to playlist folder with m3...
Add default config and config schema
local: Add default config and config schema
Python
apache-2.0
jmarsik/mopidy,jmarsik/mopidy,jodal/mopidy,rawdlite/mopidy,ali/mopidy,SuperStarPL/mopidy,jcass77/mopidy,adamcik/mopidy,pacificIT/mopidy,diandiankan/mopidy,tkem/mopidy,swak/mopidy,diandiankan/mopidy,bacontext/mopidy,mokieyue/mopidy,pacificIT/mopidy,swak/mopidy,ZenithDK/mopidy,vrs01/mopidy,bencevans/mopidy,bacontext/mopi...
d6444cd75c8ce6babd373989abd3507dd14923bb
api.py
api.py
import json from tornado.httpserver import HTTPServer from tornado.web import URLSpec import tornado.ioloop import tornado.web from tornado.options import define, options from orders import Book, Buy, Sell define("port", default=3000, help="run on the given port", type=int) Book() class BookHandler(tornado.web.Req...
import json from tornado.httpserver import HTTPServer from tornado.httputil import HTTPHeaders from tornado.web import URLSpec import tornado.ioloop import tornado.web from tornado.options import define, options from orders import Book, Buy, Sell define("port", default=3000, help="run on the given port", type=int) B...
Add location and content-type headers to response.
Add location and content-type headers to response.
Python
mit
eigenholser/ddme,eigenholser/ddme
0cb295e80fbf8d08276166d8005722918012ca83
wafer/kv/models.py
wafer/kv/models.py
from django.contrib.auth.models import Group from django.db import models from jsonfield import JSONField class KeyValue(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) key = models.CharField(max_length=64, db_index=True) value = JSONField() def __unicode__(self): r...
from django.contrib.auth.models import Group from django.db import models from jsonfield import JSONField class KeyValue(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) key = models.CharField(max_length=64, db_index=True) value = JSONField() def __unicode__(self): r...
Add KeyValue.__str__ for python 3
Add KeyValue.__str__ for python 3
Python
isc
CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer
7f412fef594a514d13519a0f048c55b293fd84b3
abandoned/models.py
abandoned/models.py
from django.db import models class Author(models.Model): author_name = models.CharField(max_length=200, unique=True) author_link = models.URLField() def __str__(self): return str(self.name) class Reason(models.Model): reason = models.CharField(max_length=200) def __str__(self): ...
from django.db import models class Author(models.Model): author_name = models.CharField(max_length=200, unique=True) author_link = models.URLField() def __str__(self): return str(self.name) class Reason(models.Model): reason = models.CharField(max_length=200) def __str__(self): ...
Tag text is now converted to lowercase before being saved
Tag text is now converted to lowercase before being saved
Python
mit
Kunstmord/abandoned,Kunstmord/abandoned,Kunstmord/abandoned
61e792e1c4d41d2a0e3f3433b39f364a5c1df144
daybed/tests/test_id_generators.py
daybed/tests/test_id_generators.py
try: from unittest2 import TestCase except ImportError: from unittest import TestCase # flake8: noqa import six from mock import patch from daybed.backends.id_generators import KoremutakeGenerator class KoremutakeGeneratorTest(TestCase): def test_it_defaults_the_max_bytes_to_4(self): generator...
try: from unittest2 import TestCase except ImportError: from unittest import TestCase # flake8: noqa import six from mock import patch from daybed.backends.id_generators import KoremutakeGenerator class KoremutakeGeneratorTest(TestCase): def setUp(self): self.generator = KoremutakeGenerator() ...
Put the generator instanciation in the setUp
Put the generator instanciation in the setUp
Python
bsd-3-clause
spiral-project/daybed,spiral-project/daybed
aeb43ef66c0dc16d020b941e71fa19d357016e02
jsk_apc2016_common/scripts/install_trained_data.py
jsk_apc2016_common/scripts/install_trained_data.py
#!/usr/bin/env python from jsk_data import download_data def main(): PKG = 'jsk_apc2016_common' download_data( pkg_name=PKG, path='trained_data/vgg16_96000.chainermodel', url='https://drive.google.com/uc?id=0B9P1L--7Wd2vOTdzOGlJcGM1N00', md5='3c993d333cf554684b5162c9f69b20cf'...
#!/usr/bin/env python from jsk_data import download_data def main(): PKG = 'jsk_apc2016_common' download_data( pkg_name=PKG, path='trained_data/vgg16_96000.chainermodel', url='https://drive.google.com/uc?id=0B9P1L--7Wd2vOTdzOGlJcGM1N00', md5='3c993d333cf554684b5162c9f69b20cf'...
Fix 404 of trained data vgg16_rotation_translation_brightness_372000...
Fix 404 of trained data vgg16_rotation_translation_brightness_372000...
Python
bsd-3-clause
pazeshun/jsk_apc,pazeshun/jsk_apc,pazeshun/jsk_apc,pazeshun/jsk_apc,pazeshun/jsk_apc
27a24e265737c0d67ed5d93e705d250a9e6b855a
mistralclient/api/v2/tasks.py
mistralclient/api/v2/tasks.py
# Copyright 2014 - Mirantis, Inc. # # 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 ag...
# Copyright 2014 - Mirantis, Inc. # # 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 ag...
Support naive filtering in python API
Support naive filtering in python API Change-Id: I10caecf68c73e7c722a9ab93a718b80c588d4d0e
Python
apache-2.0
openstack/python-mistralclient,openstack/python-mistralclient,StackStorm/python-mistralclient,StackStorm/python-mistralclient
ed350a7387c376538f51a8a7a8cfde5469baba8a
tests/testutils.py
tests/testutils.py
import psycopg2 import os import getpass def get_pg_connection(): return psycopg2.connect( "dbname=bedquilt_test user={}".format(getpass.getuser()) )
import psycopg2 import os import getpass # CREATE DATABASE bedquilt_test # WITH OWNER = {{owner}} # ENCODING = 'UTF8' # TABLESPACE = pg_default # LC_COLLATE = 'en_GB.UTF-8' # LC_CTYPE = 'en_GB.UTF-8' # CONNECTION LIMIT = -1; def get_pg_connection(): return psycopg2.connect( ...
Add the sql to create the test database
Add the sql to create the test database
Python
mit
BedquiltDB/bedquilt-core
8c18b43880368bba654e715c2da197f7a6d9e41a
tests/test_carddb.py
tests/test_carddb.py
from hearthstone.enums import CardType, GameTag, Rarity import utils CARDS = utils.fireplace.cards.db def test_all_tags_known(): """ Iterate through the card database and check that all specified GameTags are known in hearthstone.enums.GameTag """ unknown_tags = set() known_tags = list(GameTag) known_rariti...
from hearthstone.enums import CardType, GameTag, Rarity import utils CARDS = utils.fireplace.cards.db def test_all_tags_known(): """ Iterate through the card database and check that all specified GameTags are known in hearthstone.enums.GameTag """ unknown_tags = set() known_tags = list(GameTag) known_rariti...
Simplify the CardDB test check for tags
Simplify the CardDB test check for tags
Python
agpl-3.0
smallnamespace/fireplace,NightKev/fireplace,smallnamespace/fireplace,beheh/fireplace,Ragowit/fireplace,Ragowit/fireplace,jleclanche/fireplace
d31bb7014a58eb90ffb3dd25d136595c24c47e68
app.py
app.py
import eventlet eventlet.monkey_patch() # NOLINT import importlib import sys from weaveserver.main import create_app from weaveserver.core.logger import configure_logging def handle_launch(): import signal from weaveserver.core.config_loader import get_config configure_logging() name = sys.argv[1]...
import eventlet eventlet.monkey_patch() # NOLINT import importlib import sys from weaveserver.main import create_app from weaveserver.core.logger import configure_logging def handle_launch(): import signal from weaveserver.core.config_loader import get_config configure_logging() token = sys.stdin....
Read for service token from stdin.
Read for service token from stdin.
Python
mit
supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer
6ecabe1e20ef7d82651bf91ccfc30bcb77bcb968
nbx/extensions/partial_run.py
nbx/extensions/partial_run.py
import six # only run for python 3, or else syntax errors if six.PY3: from ._partial_run import *
import six def load_ipython_extension(shell): # only run for python 3, or else syntax errors if not six.PY3: return from ._partial_run import safe_run_module shell.safe_run_module = safe_run_module.__get__(shell)
Update to use ipython kernel extension
Update to use ipython kernel extension
Python
mit
dalejung/nbx,dalejung/nbx,dalejung/nbx,dalejung/nbx
db8b85e2c5789b91a1d50a902f626fba95a4f4cc
txircd/modules/cmd_ping.py
txircd/modules/cmd_ping.py
from twisted.words.protocols import irc from txircd.modbase import Command class PingCommand(Command): def onUse(self, user, data): if data["params"]: user.sendMessage("PONG", ":{}".format(data["params"][0]), to=self.ircd.servconfig["server_name"], prefix=None) else: user.sendMessage(irc.ERR_NOORIGIN, ":No ...
from twisted.words.protocols import irc from txircd.modbase import Command class PingCommand(Command): def onUse(self, user, data): if data["params"]: user.sendMessage("PONG", ":{}".format(data["params"][0]), to=self.ircd.servconfig["server_name"]) else: user.sendMessage(irc.ERR_NOORIGIN, ":No origin specif...
Send the server prefix on the line when the client sends PING
Send the server prefix on the line when the client sends PING
Python
bsd-3-clause
Heufneutje/txircd,ElementalAlchemist/txircd,DesertBus/txircd
a7481dea799117199af4e48526a007194c8d3220
fabfile/docs.py
fabfile/docs.py
# Module: docs # Date: 03rd April 2013 # Author: James Mills, j dot mills at griffith dot edu dot au """Documentation Tasks""" from fabric.api import lcd, local, task from .utils import pip, requires PACKAGE = "src/ccav" @task() @requires("sphinx-apidoc") def api(): """Generate the API Documentation"...
# Module: docs # Date: 03rd April 2013 # Author: James Mills, j dot mills at griffith dot edu dot au """Documentation Tasks""" from fabric.api import lcd, local, task from .utils import pip, requires PACKAGE = "src/ccav" @task() @requires("sphinx-apidoc") def api(): """Generate the API Documentation"...
Use webbrowser.open_new_tab() instead of platform dependent open
Use webbrowser.open_new_tab() instead of platform dependent open
Python
mit
eriol/circuits,treemo/circuits,treemo/circuits,treemo/circuits,nizox/circuits,eriol/circuits,eriol/circuits
ae433a0ed222d3540581b2b49c9a49a8ad16819c
wagtailaltgenerator/translation_providers/google_translate.py
wagtailaltgenerator/translation_providers/google_translate.py
import logging from . import AbstractTranslationProvider from google.cloud import translate logger = logging.getLogger(__name__) class GoogleTranslate(AbstractTranslationProvider): def translate(self, strings, target_language, source_language="en"): client = translate.Client() response = client...
import logging from . import AbstractTranslationProvider logger = logging.getLogger(__name__) class GoogleTranslate(AbstractTranslationProvider): def translate(self, strings, target_language, source_language="en"): from google.cloud import translate client = translate.Client() response...
Enable test mocking for translate
Enable test mocking for translate
Python
mit
marteinn/wagtail-alt-generator,marteinn/wagtail-alt-generator,marteinn/wagtail-alt-generator
4237d5cb9d430c71089e3fe5965e5d83af9f97df
run.py
run.py
from __future__ import print_function import tornado from tornado import autoreload from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from tornado.log import enable_pretty_logging from app import app enable_pretty_logging() PORT = 8000 if __name__ == ...
from __future__ import print_function import tornado from tornado import autoreload from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from tornado.log import enable_pretty_logging from app import app, db from app.models import User enable_pretty_logging...
Add db creation and drop
Add db creation and drop
Python
mit
jochasinga/rpg-x,jochasinga/rpg-x,jochasinga/rpg-x,jochasinga/rpg-x
b51e0ff9407f8a609be580d8fcb9cad6cfd267d8
setup.py
setup.py
# Use setuptools if we can try: from setuptools.core import setup except ImportError: from distutils.core import setup PACKAGE = 'django-render-as' VERSION = '1.1' package_data = { 'render_as': [ 'templates/avoid_clash_with_real_app/*.html', 'templates/render_as/*.html', ], } setu...
# Use setuptools if we can try: from setuptools.core import setup except ImportError: from distutils.core import setup PACKAGE = 'django-render-as' VERSION = '1.2' package_data = { 'render_as': [ 'test_templates/avoid_clash_with_real_app/*.html', 'test_templates/render_as/*.html', ...
Include test templates in distributions.
Include test templates in distributions. This probably wasn't working before, although apparently I didn't notice. But then no one really runs tests for their 3PA, do they? This is v1.2.
Python
mit
jaylett/django-render-as,jaylett/django-render-as
003034caa0072d3e13b997df219b6612ae4b128e
setup.py
setup.py
#!/usr/bin/env python from distutils.core import setup version = "0.1.1" setup(name="riemann-sumd", version=version, description="Python agent for scheduling event generating processes and sending the results to Riemann", author="Brian Hatfield", author_email="bmhatfield@gmail.com", url=...
#!/usr/bin/env python from distutils.core import setup version = "0.2.0" setup(name="riemann-sumd", version=version, description="Python agent for scheduling event generating processes and sending the results to Riemann", author="Brian Hatfield", author_email="bmhatfield@gmail.com", url=...
Update Riemann-sumd version, add install_requires
Update Riemann-sumd version, add install_requires
Python
mit
crashlytics/riemann-sumd
5d7057bc34e10070a5b3f825618e87ad91fcbfea
stack.py
stack.py
#!/usr/bin/env python '''Implementation of a simple stack data structure. The stack has push, pop, and peek methods. ''' class Item(object): def __init__(self): pass class Stack(object): def __init__(self): pass
#!/usr/bin/env python '''Implementation of a simple stack data structure. The stack has push, pop, and peek methods. Items in the stack have a value, and next_item attribute. The stack has a top attribute. ''' class Item(object): def __init__(self, value, next_item=None): self.value = value self....
Add attributes to Stack and Item classes
Add attributes to Stack and Item classes
Python
mit
jwarren116/data-structures-deux
c6fc60ec33c98b0a4b6272f5304b76477f5955f8
src/dynmen/dmenu.py
src/dynmen/dmenu.py
# -*- coding: utf-8 -*- from os import path as _path from dynmen.common import TraitMenu as _TraitMenu from dynmen.generator import (AddOptions as _AddOptions, load_options as _load_options,) _dirname = _path.dirname(_path.abspath(__file__)) _path = _path.join(_dirname, 'data/dmenu_opts....
# -*- coding: utf-8 -*- from os import path as _path from dynmen.common import TraitMenu as _TraitMenu from dynmen.generator import (AddOptions as _AddOptions, load_options as _load_options,) _dirname = _path.dirname(_path.abspath(__file__)) _path = _path.join(_dirname, 'data/dmenu_opts....
Add a few aliases to DMenu
Add a few aliases to DMenu
Python
mit
frostidaho/dynmen
6c6a774ef2614ca82fbe61ec04e9b6a75415b015
setup.py
setup.py
from distutils.core import setup setup( name = 'openhomedevice', packages = ['openhomedevice'], version = '0.2.1', description = 'Provides an API for requesting information from an Openhome device', author = 'Barry John Williams', author_email = 'barry@bjw.me.uk', url = 'https://github.com/bazwilliams/ope...
from distutils.core import setup setup( name = 'openhomedevice', packages = ['openhomedevice'], version = '0.2.2', description = 'Provides an API for requesting information from an Openhome device', author = 'Barry John Williams', author_email = 'barry@bjw.me.uk', url = 'https://github.com/cak85/openhomed...
Change url to this fork
Change url to this fork
Python
mit
bazwilliams/openhomedevice
fc1bbf6972d8660f24aba0fa073991ca5847829a
setup.py
setup.py
from distutils.core import setup from jeni import __version__ CLASSIFIERS = [ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python'...
from distutils.core import setup from os import path from jeni import __version__ CLASSIFIERS = [ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming...
Read long description from README.
Read long description from README.
Python
bsd-2-clause
rduplain/jeni-python,groner/jeni-python
dab5d49b71700d93b466dc9f9d377a08f7fe68db
setup.py
setup.py
#!/usr/bin/env python # Copyright 2011 Andrew Ryrie (amr66) from distutils.core import setup setup(name='django-pyroven', description='A Django authentication backend for Ucam-WebAuth / Raven', long_description=open('README.md').read(), url='https://github.com/pyroven/django-pyroven', version...
#!/usr/bin/env python # Copyright 2011 Andrew Ryrie (amr66) from distutils.core import setup setup(name='django-pyroven', description='A Django authentication backend for Ucam-WebAuth / Raven', long_description=open('README.md').read(), url='https://github.com/pyroven/django-pyroven', version...
Fix flake8 indentation issues with classifiers
Fix flake8 indentation issues with classifiers
Python
mit
pyroven/django-pyroven
40a099f9f519f63695afb61a07a7c2d5b7f795af
setup.py
setup.py
#! /usr/bin/python from distutils.core import setup try: from distutils.command.build_py import build_py_2to3 as build_py except ImportError: # Python 2.x from distutils.command.build_py import build_py import photo import re DOCLINES = photo.__doc__.split("\n") DESCRIPTION = DOCLINES[0] LONG...
#! /usr/bin/python from distutils.core import setup try: from distutils.command.build_py import build_py_2to3 as build_py except ImportError: # Python 2.x from distutils.command.build_py import build_py import photo import re DOCLINES = photo.__doc__.split("\n") DESCRIPTION = DOCLINES[0] LONG...
Remove obsolete requirement of pyexiv2.
Remove obsolete requirement of pyexiv2.
Python
apache-2.0
RKrahl/photo-tools
96d2e3d47cf193046f68fef859244fd31be2ffa9
utils.py
utils.py
import vx def _expose(f=None, name=None): if name is None: name = f.__name__.lstrip('_') if getattr(vx, name, None) is not None: raise AttributeError("Cannot expose duplicate name: '{}'".format(name)) if f is None: def g(f): setattr(vx, name, f) return f ...
import vx from functools import partial def _expose(f=None, name=None): if f is None: return partial(_expose, name=name) if name is None: name = f.__name__.lstrip('_') if getattr(vx, name, None) is not None: raise AttributeError("Cannot expose duplicate name: '{}'".format(name)) ...
Fix vx.expose to not crash when None,None is passed
Fix vx.expose to not crash when None,None is passed Also reformat it using functools.partial
Python
mit
philipdexter/vx,philipdexter/vx
f40f951a52c6c19108224d306f0e173465d0054d
scripts/pycodestyle_on_repo.py
scripts/pycodestyle_on_repo.py
# Copyright 2016 Google Inc. # # 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 agreed to in writing, ...
# Copyright 2016 Google Inc. # # 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 agreed to in writing, ...
Use 'diff_base' for pycodestyle check, if set.
Use 'diff_base' for pycodestyle check, if set. Speeds it up, plus reduces spew when testing locally.
Python
apache-2.0
jonparrott/google-cloud-python,googleapis/google-cloud-python,tswast/google-cloud-python,Fkawala/gcloud-python,googleapis/google-cloud-python,tartavull/google-cloud-python,tseaver/google-cloud-python,Fkawala/gcloud-python,dhermes/google-cloud-python,calpeyser/google-cloud-python,calpeyser/google-cloud-python,quom/googl...
24eb92088115a4cd583a3dc759083ff295db3135
website/jdpages/signals.py
website/jdpages/signals.py
import logging logger = logging.getLogger(__name__) from django.contrib.contenttypes.models import ContentType from django.db.models.signals import post_save from django.dispatch import receiver from mezzanine.blog.models import BlogCategory from website.jdpages.models import ColumnElement @receiver(post_save) def...
import logging logger = logging.getLogger(__name__) from django.contrib.contenttypes.models import ContentType from django.db.models.signals import post_save, pre_delete from django.dispatch import receiver from mezzanine.blog.models import BlogCategory from website.jdpages.models import ColumnElement @receiver(po...
Delete the related ColumnElement when a BlogCategory is deleted.
Delete the related ColumnElement when a BlogCategory is deleted.
Python
mit
jonge-democraten/website,jonge-democraten/website,jonge-democraten/website,jonge-democraten/website
9afa5b8b2fe2a5236337346a6f677a04863b82c7
salt/output/__init__.py
salt/output/__init__.py
''' Used to manage the outputter system. This package is the modular system used for managing outputters. ''' # Import salt utils import salt.loader def display_output(data, out, opts=None): ''' Print the passed data using the desired output ''' if opts is None: opts = {} if not 'color' i...
''' Used to manage the outputter system. This package is the modular system used for managing outputters. ''' # Import salt utils import salt.loader def display_output(data, out, opts=None): ''' Print the passed data using the desired output ''' get_printout(out, opts)(data) def get_printout(out, o...
Fix issue where interfaces pass in _out
Fix issue where interfaces pass in _out
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
64bd4ea8a4b04ce1c65375ad3c7776a1583b7294
crypto-square/crypto_square.py
crypto-square/crypto_square.py
import math def encode(s): s = list(filter(str.isalnum, s.lower())) size = math.ceil(math.sqrt(len(s))) s += "." * (size**2 - len(s)) parts = [s[i*size:(i+1)*size] for i in range(size)] return " ".join(map("".join, zip(*parts))).replace(".", "")
import math def encode(s): s = "".join(filter(str.isalnum, s.lower())) size = math.ceil(math.sqrt(len(s))) return " ".join(s[i::size] for i in range(size))
Use string slices with a stride
Use string slices with a stride
Python
agpl-3.0
CubicComet/exercism-python-solutions
c4f0f13892f1a1af73a94e6cbea95d30e676203c
xorgauth/accounts/views.py
xorgauth/accounts/views.py
from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import render from django.views.generic import TemplateView from oidc_provider.models import UserConsent, Client @login_required def list_conse...
from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import render from django.views.generic import TemplateView from oidc_provider.models import UserConsent, Client @login_required def list_conse...
Fix access restriction to /accounts/profile/
Fix access restriction to /accounts/profile/ LoginRequiredMixin needs to come first for it to be applied. Otherwise, /accounts/profile/ is accessible even when the user is not authenticated.
Python
agpl-3.0
Polytechnique-org/xorgauth,Polytechnique-org/xorgauth
f0ceb7d9372766d9b1e55d619b8e05aee5950fb2
tests/matchers/test_boolean.py
tests/matchers/test_boolean.py
from robber import expect from robber.matchers.boolean import TrueMatcher, FalseMatcher class TestTrueMatcher: def test_matches(self): expect(TrueMatcher(True).matches()).to.eq(True) expect(TrueMatcher(False).matches()).to.eq(False) def test_failure_message(self): true = TrueMatcher(F...
from robber import expect from robber.matchers.boolean import TrueMatcher, FalseMatcher class TestTrueMatcher: def test_matches(self): expect(TrueMatcher(True).matches()).to.eq(True) expect(TrueMatcher(False).matches()).to.eq(False) def test_failure_message(self): true = TrueMatcher(F...
Add failure message test for not_to.be.true()
[f] Add failure message test for not_to.be.true()
Python
mit
vesln/robber.py
c65e2b3bb2d43a5d12d50cf79636e94a6a1f1dc5
Algo.py
Algo.py
# # Copyright (c) 2016, Gabriel Linder <linder.gabriel@gmail.com> # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS"...
# # Copyright (c) 2016, Gabriel Linder <linder.gabriel@gmail.com> # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS"...
Check that population_size is even, and set half_population_size.
Check that population_size is even, and set half_population_size. This will be used by genetic algorithms.
Python
isc
dargor/python-guess-random-color,dargor/python-guess-random-color
f80b9f42db599e0416bd4e28f69c81e0fda494d2
todoist/managers/generic.py
todoist/managers/generic.py
# -*- coding: utf-8 -*- class Manager(object): # should be re-defined in a subclass state_name = None object_type = None def __init__(self, api): self.api = api # shortcuts @property def state(self): return self.api.state @property def queue(self): return ...
# -*- coding: utf-8 -*- class Manager(object): # should be re-defined in a subclass state_name = None object_type = None def __init__(self, api): self.api = api # shortcuts @property def state(self): return self.api.state @property def queue(self): return ...
Fix the case of using `get_by_id` when there's not state
Fix the case of using `get_by_id` when there's not state Previous to this commit, if there's no state we would return raw data, which would break object chaining. Now we check the state one last time before giving up and returning the raw data because it may have been populated by methods like `get_by_id` (instead of ...
Python
mit
Doist/todoist-python
9c923b8a94ea534c5b18983e81add7301a1dfa66
waterbutler/core/streams/file.py
waterbutler/core/streams/file.py
import os from waterbutler.core.streams import BaseStream class FileStreamReader(BaseStream): def __init__(self, file_pointer): super().__init__() self.file_gen = None self.file_pointer = file_pointer self.read_size = None self.content_type = 'application/octet-stream' ...
import os # import asyncio from waterbutler.core.streams import BaseStream class FileStreamReader(BaseStream): def __init__(self, file_pointer): super().__init__() self.file_gen = None self.file_pointer = file_pointer self.read_size = None self.content_type = 'application...
Update FileStreamReader to use async generator
Update FileStreamReader to use async generator
Python
apache-2.0
RCOSDP/waterbutler,TomBaxter/waterbutler,rdhyee/waterbutler,CenterForOpenScience/waterbutler,felliott/waterbutler,Johnetordoff/waterbutler
75c53cc811ae7f374df211b220c220f01d8b37e9
flocker/node/functional/test_script.py
flocker/node/functional/test_script.py
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Functional tests for the ``flocker-changestate`` command line tool. """ from subprocess import check_output from unittest import skipUnless from twisted.python.procutils import which from twisted.trial.unittest import TestCase from ... import __version...
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Functional tests for the ``flocker-changestate`` command line tool. """ from subprocess import check_output from unittest import skipUnless from twisted.python.procutils import which from twisted.trial.unittest import TestCase from ... import __version...
Fix the functional testcase name
Fix the functional testcase name
Python
apache-2.0
jml/flocker,agonzalezro/flocker,Azulinho/flocker,AndyHuu/flocker,adamtheturtle/flocker,wallnerryan/flocker-profiles,Azulinho/flocker,1d4Nf6/flocker,LaynePeng/flocker,beni55/flocker,LaynePeng/flocker,hackday-profilers/flocker,beni55/flocker,w4ngyi/flocker,runcom/flocker,jml/flocker,jml/flocker,mbrukman/flocker,hackday-p...
c61b08475d82d57dae4349e1c4aa3e58fd7d8256
src/sentry/api/serializers/models/grouptagvalue.py
src/sentry/api/serializers/models/grouptagvalue.py
from __future__ import absolute_import from sentry.api.serializers import Serializer, register from sentry.models import GroupTagValue @register(GroupTagValue) class GroupTagValueSerializer(Serializer): def serialize(self, obj, attrs, user): d = { 'key': obj.key, 'value': obj.valu...
from __future__ import absolute_import from sentry.api.serializers import Serializer, register from sentry.models import GroupTagValue, TagValue @register(GroupTagValue) class GroupTagValueSerializer(Serializer): def get_attrs(self, item_list, user): assert len(set(i.key for i in item_list)) < 2 ...
Implement labels on group tag values
Implement labels on group tag values
Python
bsd-3-clause
ngonzalvez/sentry,mvaled/sentry,daevaorn/sentry,kevinlondon/sentry,imankulov/sentry,gencer/sentry,korealerts1/sentry,Natim/sentry,felixbuenemann/sentry,JamesMura/sentry,JackDanger/sentry,fotinakis/sentry,JackDanger/sentry,jean/sentry,looker/sentry,gencer/sentry,looker/sentry,gencer/sentry,looker/sentry,ngonzalvez/sentr...
c044c804633612608bbbf61621551d892483f179
yaspin/spinners.py
yaspin/spinners.py
# -*- coding: utf-8 -*- """ yaspin.spinners ~~~~~~~~~~~~~~~ A collection of cli spinners. """ import codecs import os from collections import namedtuple try: import simplejson as json except ImportError: import json THIS_DIR = os.path.dirname(os.path.realpath(__file__)) SPINNERS_PATH = os.path.join(THIS_D...
# -*- coding: utf-8 -*- """ yaspin.spinners ~~~~~~~~~~~~~~~ A collection of cli spinners. """ import codecs import pkgutil from collections import namedtuple try: import simplejson as json except ImportError: import json THIS_DIR = os.path.dirname(os.path.realpath(__file__)) SPINNERS_DATA = pkgutil.get_da...
Allow use inside zip bundled package
Allow use inside zip bundled package
Python
mit
pavdmyt/yaspin
01331f37c629f0738c5517527a6e78be55334e04
democracy/views/utils.py
democracy/views/utils.py
# -*- coding: utf-8 -*- from functools import lru_cache from rest_framework import serializers class AbstractFieldSerializer(serializers.RelatedField): parent_serializer_class = serializers.ModelSerializer def to_representation(self, image): return self.parent_serializer_class(image, context=self.co...
# -*- coding: utf-8 -*- from functools import lru_cache from rest_framework import serializers from rest_framework.relations import ManyRelatedField, MANY_RELATION_KWARGS class AbstractFieldSerializer(serializers.RelatedField): parent_serializer_class = serializers.ModelSerializer many_field_class = ManyRela...
Allow overriding the ManyRelatedField for image fields
Allow overriding the ManyRelatedField for image fields
Python
mit
City-of-Helsinki/kerrokantasi,stephawe/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,stephawe/kerrokantasi,vikoivun/kerrokantasi,vikoivun/kerrokantasi,vikoivun/kerrokantasi,stephawe/kerrokantasi,City-of-Helsinki/kerrokantasi
d240faeec0dea1b9dbefe080b479276ea19d2a0b
apps/explorer/tests/test_views.py
apps/explorer/tests/test_views.py
from django.core.urlresolvers import reverse from apps.core.factories import PIXELER_PASSWORD, PixelerFactory from apps.core.tests import CoreFixturesTestCase from apps.core.management.commands.make_development_fixtures import ( make_development_fixtures ) class PixelSetListViewTestCase(CoreFixturesTestCase): ...
from django.core.urlresolvers import reverse from apps.core.factories import PIXELER_PASSWORD, PixelerFactory from apps.core.tests import CoreFixturesTestCase from apps.core.management.commands.make_development_fixtures import ( make_development_fixtures ) class PixelSetListViewTestCase(CoreFixturesTestCase): ...
Fix empty pixel set list message
Fix empty pixel set list message
Python
bsd-3-clause
Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel
e475fdcf1054d5942addd28ca2c543542fc8abc5
geoalchemy2/shape.py
geoalchemy2/shape.py
""" This module provides utility functions for integrating with Shapely. """ import shapely.wkb import shapely.wkt from .elements import WKBElement, WKTElement from .compat import buffer, bytes def to_shape(element): """ Function to convert a :class:`geoalchemy2.types.SpatialElement` to a Shapely geomet...
""" This module provides utility functions for integrating with Shapely. .. note:: As GeoAlchemy 2 itself has no dependency on `Shapely`, applications using functions of this module have to ensure that `Shapely` is available. """ import shapely.wkb import shapely.wkt from .elements import WKBElement, WKTEle...
Add note in docu about Shapely
Add note in docu about Shapely
Python
mit
geoalchemy/geoalchemy2
c656ac5231d85e5f6a07688d3d7c2f4f07b3e154
backstage/settings/development.py
backstage/settings/development.py
import os import dj_database_url from .base import * DATABASE_URL = os.environ.get('DATABASE_URL') DATABASES = { 'default': dj_database_url.config() } STATIC_ROOT = 'static_sources' STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), )
import os import dj_database_url from .base import * DATABASE_URL = os.environ.get('DATABASE_URL') DATABASES = { 'default': dj_database_url.config() } # Media handling MEDIA_ROOT = BASE_DIR.child("media") # Static file handling STATIC_ROOT = 'static_sources' STATIC_URL = '/static/' STATICFILES_DIRS = ( ...
Add MEDIA_ROOT to dev settings
Add MEDIA_ROOT to dev settings
Python
mit
mhotwagner/backstage,mhotwagner/backstage,mhotwagner/backstage
76166f243b9f5f21582c95a843ddfa174ded8602
PyFVCOM/__init__.py
PyFVCOM/__init__.py
""" The FVCOM Python toolbox (PyFVCOM) """ __version__ = '1.6.2' __author__ = 'Pierre Cazenave' __credits__ = ['Pierre Cazenave'] __license__ = 'MIT' __maintainer__ = 'Pierre Cazenave' __email__ = 'pica@pml.ac.uk' import inspect from warnings import warn # Import everything! from PyFVCOM import buoy_tools from PyFV...
""" The FVCOM Python toolbox (PyFVCOM) """ __version__ = '1.6.2' __author__ = 'Pierre Cazenave' __credits__ = ['Pierre Cazenave'] __license__ = 'MIT' __maintainer__ = 'Pierre Cazenave' __email__ = 'pica@pml.ac.uk' import inspect from warnings import warn # Import everything! from PyFVCOM import buoy_tools from PyFV...
Put things in in alphabetical order.
Put things in in alphabetical order.
Python
mit
pwcazenave/PyFVCOM
3e6700e4bd7107c37cb706086ae93adec7164083
RealtimeInterval.py
RealtimeInterval.py
import time class RealtimeInterval: startTime = 0 interval = 0 def __init__(self, intervalInSeconds): self.startTime = time.time() self.interval = intervalInSeconds def start(self): self.startTime = time.time() def hasElapsed(self): timeNow =...
import time class RealtimeInterval: def __init__(self, intervalInSeconds, allowImmediate = True): self.interval = intervalInSeconds self.allowImmediate = allowImmediate self.reset() def reset(self): if self.allowImmediate: self.startTime = 0 else:...
Improve real time throttle so that it can start immediate the first time.
Improve real time throttle so that it can start immediate the first time.
Python
mit
AluminatiFRC/Vision2016,AluminatiFRC/Vision2016
4940a996a967608bb3c69659d1cc9f97fd2686c7
telepathy/server/properties.py
telepathy/server/properties.py
# telepathy-spec - Base classes defining the interfaces of the Telepathy framework # # Copyright (C) 2005,2006 Collabora Limited # Copyright (C) 2005,2006 Nokia Corporation # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as publish...
# telepathy-spec - Base classes defining the interfaces of the Telepathy framework # # Copyright (C) 2005,2006 Collabora Limited # Copyright (C) 2005,2006 Nokia Corporation # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as publish...
Fix import for renaming of Properties to Properties_INterface
Fix import for renaming of Properties to Properties_INterface 20070206124719-53eee-3edd233f30e8a6c5ae1cbaaa1a39a7bbdfb8373c.gz
Python
lgpl-2.1
freedesktop-unofficial-mirror/telepathy__telepathy-spec,TelepathyIM/telepathy-spec
377a0d4acd9a578146c0f02f518dbea502c8461f
arividam/siteconfig/apps.py
arividam/siteconfig/apps.py
from __future__ import unicode_literals from django.apps import AppConfig class SiteconfigConfig(AppConfig): name = 'siteconfig'
from __future__ import unicode_literals from django.apps import AppConfig from cms.cms_plugins import AliasPlugin from cms.plugin_pool import plugin_pool class SiteconfigConfig(AppConfig): name = 'siteconfig' verbose_name = "Site Configuration" def ready(self): def return_pass(self, r, p): ...
Disable AliasPlugin since it can accidentally
Disable AliasPlugin since it can accidentally cause problems if an alias is placed within itself
Python
mit
c4sc/arividam,c4sc/arividam,c4sc/arividam,c4sc/arividam
f291bb4b5bbf711fa12980fa3a9c8ceb831c6104
frigg/authentication/models.py
frigg/authentication/models.py
# -*- coding: utf8 -*- from django.contrib.auth.models import AbstractUser from django.utils.functional import cached_property from social.apps.django_app.default.models import UserSocialAuth from frigg.helpers import github class User(AbstractUser): @cached_property def github_token(self): try: ...
# -*- coding: utf8 -*- from django.contrib.auth.models import AbstractUser from django.utils.functional import cached_property from social.apps.django_app.default.models import UserSocialAuth from frigg.helpers import github class User(AbstractUser): @cached_property def github_token(self): try: ...
Fix is new check in User.save()
Fix is new check in User.save()
Python
mit
frigg/frigg-hq,frigg/frigg-hq,frigg/frigg-hq
08de7924f56606225e1772320831a02f2ae4aabd
core/AppResources.py
core/AppResources.py
""" AppResources :Authors: Berend Klein Haneveld """ import os from AppVars import AppVars class AppResources(object): """ AppResources is a static class that can be used to find common resources easily. Just provide a name to the imageNamed() method and it will return the correct path. """ @staticmethod d...
""" AppResources :Authors: Berend Klein Haneveld """ import os from AppVars import AppVars from core.elastix.Transformation import Transformation class AppResources(object): """ AppResources is a static class that can be used to find common resources easily. Just provide a name to the imageNamed() method and it...
Add method for getting the default transformations.
Add method for getting the default transformations.
Python
mit
berendkleinhaneveld/Registrationshop,berendkleinhaneveld/Registrationshop
9f39c7740d23b115680c36968407cf110029dbee
Python/item14.py
Python/item14.py
#!/usr/local/bin/python def divide1(x,y): try: return True,x/y except Exception , e: print e return False,None x1=5 y1=0 x2=2 y2=1 success1,result1= divide1(x1,y1) if not success1: print "Error" else: print result1 success2,result2= divide1(x2,y2) if not success2: print "Error" else: print res...
#!/usr/local/bin/python #def divide1(x,y): # try: # return True,x/y # except Exception , e: # print e # return False,None # #x1=5 #y1=0 #x2=2 #y2=1 #success1,result1= divide1(x1,y1) #if not success1: # print "Error" #else: # print result1 # #success2,result2= divide1(x2,y2) #if not success2: # print "Erro...
Add another way to solve the problem.
Add another way to solve the problem.
Python
mit
Vayne-Lover/Effective
cf25aeb751fc681907b1684c2675fc6d38b537ed
tests/test_webdriver_chrome.py
tests/test_webdriver_chrome.py
# -*- coding: utf-8 -*- try: import unittest2 as unittest except ImportError: import unittest from splinter import Browser from fake_webapp import EXAMPLE_APP from base import WebDriverTests class ChromeBrowserTest(WebDriverTests, unittest.TestCase): @classmethod def setUpClass(cls): cls.br...
# -*- coding: utf-8 -*- try: import unittest2 as unittest except ImportError: import unittest from splinter import Browser from fake_webapp import EXAMPLE_APP from base import WebDriverTests class ChromeBrowserTest(WebDriverTests, unittest.TestCase): @classmethod def setUpClass(cls): cls.br...
Test for the chrome attach_file disallowance removed
Test for the chrome attach_file disallowance removed
Python
bsd-3-clause
objarni/splinter,underdogio/splinter,bubenkoff/splinter,underdogio/splinter,bmcculley/splinter,lrowe/splinter,bubenkoff/splinter,objarni/splinter,lrowe/splinter,drptbl/splinter,nikolas/splinter,cobrateam/splinter,underdogio/splinter,objarni/splinter,myself659/splinter,bmcculley/splinter,gjvis/splinter,drptbl/splinter,m...
3c0d465dde4a93fe60b8b2ce897cb4c5745450ad
pysarus.py
pysarus.py
#!/usr/bin/python3 #Pysarus #A python wrapper for Big Huge Thesarus #Jacob Adams import urllib.request import json #where to save reteived defintions #if None than no files are saved savepath = "." #Your API key for Big Huge Thesarus APIkey = "" def thesarus(word): if(savepath): try: return json.load(savepath...
#!/usr/bin/python3 #Pysarus #A python wrapper for Big Huge Thesarus #Jacob Adams import urllib.request import json #where to save reteived defintions #if None than no files are saved savepath = "." #Your API key for Big Huge Thesarus APIkey = "" def thesarus(word): if(savepath): try: return json.load(savepath...
Use API key in URL
Use API key in URL
Python
mit
Tookmund/Pysarus
7e0024878352ba544a8b40d2c8b5741aedf05a70
Code/login_proxy.py
Code/login_proxy.py
# Sarah M. - 2017 import sys import datetime from colors import farben def request(flow): now = datetime.datetime.now() content = flow.request.get_text() host = flow.request.pretty_host method = flow.request.method if method == "POST" and ("pass" in content) or ("password" in content) : wi...
# Sarah M. - 2017 import re import sys import datetime from colors import farben def request(flow): now = datetime.datetime.now() content = flow.request.get_text() host = flow.request.pretty_host method = flow.request.method if method == "POST" and ("pass" in content) or ("password" in content): ...
Add regex for parsing password url parameter
Add regex for parsing password url parameter
Python
apache-2.0
sarah314/SpyPi
3c4eb325424fad2f68cfb9360d417bd531106711
exercises/palindrome-products/palindrome_products.py
exercises/palindrome-products/palindrome_products.py
def largest_palindrome(): pass def smallest_palindrome(): pass
def largest_palindrome(max_factor, min_factor): pass def smallest_palindrome(max_factor, min_factor): pass
Add parameter to exercise placeholder
palindrome-product: Add parameter to exercise placeholder
Python
mit
mweb/python,smalley/python,jmluy/xpython,behrtam/xpython,jmluy/xpython,smalley/python,pheanex/xpython,exercism/xpython,N-Parsons/exercism-python,mweb/python,N-Parsons/exercism-python,behrtam/xpython,exercism/python,exercism/python,pheanex/xpython,exercism/xpython
f15c623374f6ca955a37a90d3c90bd19fb781f00
dallinger/experiments/__init__.py
dallinger/experiments/__init__.py
"""A home for all Dallinger Experiments. Experiments should be registered with a ``setuptools`` ``entry_point`` for the ``dallinger.experiments`` group. """ import logging from pkg_resources import iter_entry_points from ..experiment import Experiment logger = logging.getLogger(__name__) logger.addHandler(logging.Null...
"""A home for all Dallinger Experiments. Experiments should be registered with a ``setuptools`` ``entry_point`` for the ``dallinger.experiments`` group. """ import logging from pkg_resources import iter_entry_points from ..config import get_config from ..experiment import Experiment config = get_config() config.load(...
Load config when loading dallinger.experiments
Load config when loading dallinger.experiments
Python
mit
Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger
424aa401806ddf536b9bc75efb1493561a5c2a5b
product/views.py
product/views.py
from django.views.generic import DetailView, ListView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from django.shortcuts import render from django.contrib.messages.views import SuccessMessageMixin from product.models import ProductCategory # Create your ...
from django.http import HttpResponseRedirect from django.views.generic import DetailView, ListView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from django.shortcuts import render from django.contrib import messages from django.contrib.messages.views impo...
Make messages show in delete view.
Make messages show in delete view.
Python
mit
borderitsolutions/amadaa,borderitsolutions/amadaa,borderitsolutions/amadaa