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
e00ad93c1a769a920c7f61eeccec582272766b26
badgify/templatetags/badgify_tags.py
badgify/templatetags/badgify_tags.py
# -*- coding: utf-8 -*- from django import template from ..models import Badge, Award from ..compat import get_user_model register = template.Library() @register.assignment_tag def badgify_badges(**kwargs): """ Returns all badges or only awarded badges for the given user. """ User = get_user_model()...
# -*- coding: utf-8 -*- from django import template from ..models import Badge, Award from ..compat import get_user_model register = template.Library() @register.assignment_tag def badgify_badges(**kwargs): """ Returns all badges or only awarded badges for the given user. """ User = get_user_model()...
Add missing select_related to badgify_badges
Add missing select_related to badgify_badges
Python
mit
ulule/django-badgify,ulule/django-badgify
c21eaccbee53f2b915fc35b85bf665e84b81dc8c
app/celery/__init__.py
app/celery/__init__.py
from celery import Celery class NewAcropolisCelery(Celery): def init_app(self, app): super(NewAcropolisCelery, self).__init__( app.import_name, broker=app.config['CELERY_BROKER_URL'], ) app.logger.info('Setting up celery: %s', app.config['CELERY_BROKER_URL']) ...
from celery import Celery class NewAcropolisCelery(Celery): def init_app(self, app): if not app.config['CELERY_BROKER_URL']: app.logger.info('Celery broker URL not set') return super(NewAcropolisCelery, self).__init__( app.import_name, broker=app.co...
Add logging for missing CELERY_BROKER_URL
Add logging for missing CELERY_BROKER_URL
Python
mit
NewAcropolis/api,NewAcropolis/api,NewAcropolis/api
df03a2d9543b392fb9ea9c027b93f4ed736e6788
pyked/_version.py
pyked/_version.py
__version_info__ = (0, 1, 1) __version__ = '.'.join(map(str, __version_info__))
__version_info__ = (0, 1, 1, 'a1') __version__ = '.'.join(map(str, __version_info__[:3])) if len(__version_info__) == 4: __version__ += __version_info__[-1]
Allow alpha versions in the versioning string
Allow alpha versions in the versioning string
Python
bsd-3-clause
bryanwweber/PyKED,pr-omethe-us/PyKED
27d8c3e0944056d23f1d25c651f7988f6cbf8353
froide/helper/tasks.py
froide/helper/tasks.py
from django.conf import settings from django.utils import translation from celery.task import task from haystack import site @task def delayed_update(instance_pk, model): """ Only index stuff that is known to be public """ translation.activate(settings.LANGUAGE_CODE) try: instance = model.publishe...
from django.conf import settings from django.utils import translation from celery.task import task from haystack import site @task def delayed_update(instance_pk, model): """ Only index stuff that is known to be public """ translation.activate(settings.LANGUAGE_CODE) try: instance = model.publishe...
Rewrite delayed_remove task: instance is gone, so cannot retrieve. Fake instance with proper pk and let haystack remove it from index.
Rewrite delayed_remove task: instance is gone, so cannot retrieve. Fake instance with proper pk and let haystack remove it from index.
Python
mit
CodeforHawaii/froide,CodeforHawaii/froide,LilithWittmann/froide,catcosmo/froide,ryankanno/froide,stefanw/froide,okfse/froide,catcosmo/froide,okfse/froide,ryankanno/froide,stefanw/froide,ryankanno/froide,CodeforHawaii/froide,CodeforHawaii/froide,LilithWittmann/froide,fin/froide,catcosmo/froide,catcosmo/froide,LilithWitt...
ca97a29dded7278b40785fe88b5e8c9ceb542d86
urllib3/util/wait.py
urllib3/util/wait.py
from .selectors import ( HAS_SELECT, DefaultSelector, EVENT_READ, EVENT_WRITE ) def _wait_for_io_events(socks, events, timeout=None): """ Waits for IO events to be available from a list of sockets or optionally a single socket if passed in. Returns a list of sockets that can be interacted ...
from .selectors import ( HAS_SELECT, DefaultSelector, EVENT_READ, EVENT_WRITE ) def _wait_for_io_events(socks, events, timeout=None): """ Waits for IO events to be available from a list of sockets or optionally a single socket if passed in. Returns a list of sockets that can be interacted ...
Use DefaultSelector as context manager.
Use DefaultSelector as context manager.
Python
mit
sigmavirus24/urllib3,Lukasa/urllib3,Disassem/urllib3,Lukasa/urllib3,Disassem/urllib3,urllib3/urllib3,urllib3/urllib3,sigmavirus24/urllib3
785717703baf0c8fd9234058a6c9845a6838a8bf
salt/modules/key.py
salt/modules/key.py
# -*- coding: utf-8 -*- ''' Functions to view the minion's public key information ''' from __future__ import absolute_import # Import python libs import os # Import Salt libs import salt.utils def finger(): ''' Return the minion's public key fingerprint CLI Example: .. code-block:: bash s...
# -*- coding: utf-8 -*- ''' Functions to view the minion's public key information ''' from __future__ import absolute_import # Import python libs import os # Import Salt libs import salt.utils def finger(): ''' Return the minion's public key fingerprint CLI Example: .. code-block:: bash s...
Use configurable hash_type for general Key fingerprinting
Use configurable hash_type for general Key fingerprinting
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
373b0210483839b7ac5b4fd8eb0bcfdfe8d63d83
begood_sites/fields.py
begood_sites/fields.py
from django.db import models from django.contrib.sites.models import Site class MultiSiteField(models.ManyToManyField): def __init__(self, **kwargs): defaults = { 'blank': False, } defaults.update(kwargs) super(MultiSiteField, self).__init__(Site, **defaults) class SingleSiteField(mod...
from django.db import models from django.contrib.sites.models import Site class MultiSiteField(models.ManyToManyField): def __init__(self, **kwargs): defaults = { 'blank': False, } defaults.update(kwargs) if 'to' in defaults: del defaults['to'] super(MultiSiteField, self).__in...
Fix problem with South migrations.
Fix problem with South migrations.
Python
mit
AGoodId/begood-sites
5dfd723b37e208c1b81e65cd2df1b7d9226493b3
numpy/_array_api/_sorting_functions.py
numpy/_array_api/_sorting_functions.py
def argsort(x, /, *, axis=-1, descending=False, stable=True): from .. import argsort from .. import flip # Note: this keyword argument is different, and the default is different. kind = 'stable' if stable else 'quicksort' res = argsort(x, axis=axis, kind=kind) if descending: res = flip(r...
def argsort(x, /, *, axis=-1, descending=False, stable=True): from .. import argsort from .. import flip # Note: this keyword argument is different, and the default is different. kind = 'stable' if stable else 'quicksort' res = argsort(x, axis=axis, kind=kind) if descending: res = flip(r...
Add missing returns to the array API sorting functions
Add missing returns to the array API sorting functions
Python
mit
cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy
b2470140f7fb33bee2af34cdc51695406a4073ec
utils/layers_test.py
utils/layers_test.py
# Lint as: python3 """Tests for spectral.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np import layers class LayersTest(tf.test.TestCase): def test_conv_transpose_shape(self): inputs = np.random.nor...
# Lint as: python3 """Tests for spectral.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np import os import layers class LayersTest(tf.test.TestCase): def test_conv_transpose_shape(self): inputs =...
Resolve Minor Issues with Test Ensure that the tensorflow tests run on the CPU
Resolve Minor Issues with Test Ensure that the tensorflow tests run on the CPU
Python
apache-2.0
googleinterns/audio_synthesis
5c4db9dc32eb4918866af5ae7037220b6f651a7d
fabfile.py
fabfile.py
from fabric.api import cd, sudo, env import os expected_vars = [ 'PROJECT', ] for var in expected_vars: if var not in os.environ: raise Exception('Please specify %s environment variable' % ( var,)) PROJECT = os.environ['PROJECT'] USER = os.environ.get('USER', 'jmbo') env.path = os.path.j...
from fabric.api import cd, sudo, env import os PROJECT = os.environ.get('PROJECT', 'go-rts-zambia') DEPLOY_USER = os.environ.get('DEPLOY_USER', 'jmbo') env.path = os.path.join('/', 'var', 'praekelt', PROJECT) def restart(): sudo('/etc/init.d/nginx restart') sudo('supervisorctl reload') def deploy(): w...
Fix USER in fabric file (the deploy user and ssh user aren't necessarily the same). Set default value for PROJECT (this is the go-rts-zambia repo after all).
Fix USER in fabric file (the deploy user and ssh user aren't necessarily the same). Set default value for PROJECT (this is the go-rts-zambia repo after all).
Python
bsd-3-clause
praekelt/go-rts-zambia
3b99493e606a04a6338d8ee2fc299595d19b2a44
fabfile.py
fabfile.py
from fabric.api import local, cd def docs(): local("./bin/docs") local("./bin/python setup.py upload_sphinx --upload-dir=docs/html") def release(): # update version id in setup.py, changelog and docs/source/conf.py local("python setup.py sdist --formats=gztar,zip upload")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from fabric.api import local, cd def docs(): local("./bin/docs") local("./bin/python setup.py upload_sphinx --upload-dir=docs/html") def release(): """Update version id in setup.py, changelog and docs/source/conf.py.""" local(("python setup.py bdist_e...
Add BzTar and EGG format to Fabric script
Add BzTar and EGG format to Fabric script
Python
bsd-3-clause
janusnic/importd,pombredanne/importd,arpitremarkable/importd,pombredanne/importd,akshar-raaj/importd,hitul007/importd,akshar-raaj/importd,hitul007/importd,janusnic/importd,arpitremarkable/importd
116d3837aa817dee6e15bdc24f20eac1e56066dd
buildtools/__init__.py
buildtools/__init__.py
__all__ = ['Config', 'Chdir', 'cmd', 'log','Properties','replace_vars','cmd'] from buildtools.config import Config, Properties, replace_vars from buildtools.os_utils import Chdir, cmd, ENV, BuildEnv from buildtools.bt_logging import log
__all__ = ['Config', 'Chdir', 'cmd', 'log','Properties','replace_vars','cmd','ENV','BuildEnv'] from buildtools.config import Config, Properties, replace_vars from buildtools.os_utils import Chdir, cmd, ENV, BuildEnv from buildtools.bt_logging import log
Add BuildEnv and ENV to __all__
Add BuildEnv and ENV to __all__
Python
mit
N3X15/python-build-tools,N3X15/python-build-tools,N3X15/python-build-tools
819380c964ca30f9d3e480a61371d502b7976abe
tests/basics/subclass_native_cmp.py
tests/basics/subclass_native_cmp.py
# Test calling non-special method inherited from native type class mytuple(tuple): pass t = mytuple((1, 2, 3)) print(t) print(t == (1, 2, 3)) print((1, 2, 3) == t)
# Test calling non-special method inherited from native type class mytuple(tuple): pass t = mytuple((1, 2, 3)) print(t) print(t == (1, 2, 3)) print((1, 2, 3) == t) print(t < (1, 2, 3), t < (1, 2, 4)) print((1, 2, 3) <= t, (1, 2, 4) < t)
Add test for tuple compare with class derived from tuple.
tests/basics: Add test for tuple compare with class derived from tuple. Only the "==" operator was tested by the test suite in for such arguments. Other comparison operators like "<" take a different path in the code so need to be tested separately.
Python
mit
adafruit/circuitpython,MrSurly/micropython,tobbad/micropython,tobbad/micropython,bvernoux/micropython,MrSurly/micropython,kerneltask/micropython,tobbad/micropython,pramasoul/micropython,bvernoux/micropython,selste/micropython,kerneltask/micropython,pozetroninc/micropython,henriknelson/micropython,henriknelson/micropyth...
bf84052d391774b13b8333acc06533e4ec9cde9e
MS2/visualize/dna-summary.py
MS2/visualize/dna-summary.py
#!/usr/bin/python """ Print log for given DNA program run """ import os import sys from readevtlog import * home = os.getenv('HOME') logdir = os.path.join(home,'_dna','logs',sys.argv[1]) for d in sorted(os.listdir(logdir)) : print "====",d,"================" [nm] = os.listdir(os.path.join(logdir,d)) nm ...
#!/usr/bin/python """ Print log for given DNA program run """ import os import sys from readevtlog import * class EntryFilter : """ Filter for log entries """ def __init__(self, strs) : self.neg = [s[1:] for s in strs if s[0] == '-'] self.pos = [s[1:] for s in strs if s[0] == '+'] ...
Allow some simplt matching on message tags
Allow some simplt matching on message tags
Python
apache-2.0
SKA-ScienceDataProcessor/RC,SKA-ScienceDataProcessor/RC,SKA-ScienceDataProcessor/RC,SKA-ScienceDataProcessor/RC,SKA-ScienceDataProcessor/RC
67f8acd6d0d9580dc346f4ddd6f765c24d687bcc
cached_counts/tests.py
cached_counts/tests.py
from django.test import TestCase from .models import CachedCount class CachedCountTechCase(TestCase): def setUp(self): initial_counts = ( { 'count_type': 'constituency', 'name': 'South Norfolk', 'count': 10, 'object_id': '65666' ...
import unittest from django.test import TestCase from candidates.tests.test_create_person import mock_create_person from .models import CachedCount class CachedCountTechCase(TestCase): def setUp(self): initial_counts = ( { 'count_type': 'constituency', 'name':...
Use mock_create_person to test increments work
Use mock_create_person to test increments work
Python
agpl-3.0
neavouli/yournextrepresentative,mysociety/yournextmp-popit,datamade/yournextmp-popit,mysociety/yournextrepresentative,datamade/yournextmp-popit,mysociety/yournextmp-popit,openstate/yournextrepresentative,YoQuieroSaber/yournextrepresentative,DemocracyClub/yournextrepresentative,openstate/yournextrepresentative,mysociety...
cbae962b77b7277f5904279a5418a53e38148f2c
karspexet/show/models.py
karspexet/show/models.py
from django.db import models import datetime class Production(models.Model): name = models.CharField(max_length=100) description = models.TextField(blank=True) def __str__(self): return self.name class Show(models.Model): production = models.ForeignKey(Production, on_delete=models.PROTECT) ...
from django.db import models import datetime class Production(models.Model): name = models.CharField(max_length=100) description = models.TextField(blank=True) def __str__(self): return self.name class Show(models.Model): production = models.ForeignKey(Production, on_delete=models.PROTECT) ...
Add Show.ticket_coverage() to get statistics on coverage
Add Show.ticket_coverage() to get statistics on coverage Very left join, much SQL, wow.
Python
mit
Karspexet/Karspexet,Karspexet/Karspexet,Karspexet/Karspexet,Karspexet/Karspexet,Karspexet/Karspexet
118eabf049db8804635001b2348fcb81c8a2a4f4
openstack_dashboard/dashboards/admin/routers/ports/tables.py
openstack_dashboard/dashboards/admin/routers/ports/tables.py
# Copyright 2012 NEC Corporation # # 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 2012 NEC Corporation # # 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...
Fix router details's name empty and change inheritance project table
Fix router details's name empty and change inheritance project table In admin router details page, the name column is empty, change to if no name show id. And change to inheritance from port table of project. Change-Id: I54d4ad95bd04db2432eb47f848917a452c5f54e9 Closes-bug:#1417948
Python
apache-2.0
j4/horizon,yeming233/horizon,henaras/horizon,yeming233/horizon,damien-dg/horizon,tqtran7/horizon,BiznetGIO/horizon,Hodorable/0602,tqtran7/horizon,RudoCris/horizon,dan1/horizon-x509,agileblaze/OpenStackTwoFactorAuthentication,kfox1111/horizon,maestro-hybrid-cloud/horizon,NeCTAR-RC/horizon,redhat-openstack/horizon,Tesora...
92e96d8b352f608a0d04521a140bdd3dcbe5ebbc
test/tools/service.py
test/tools/service.py
from os import environ as env from glanceclient import Client as glclient import keystoneclient.v2_0.client as ksclient import novaclient.v2.client as nvclient client_args = { } nova = nvclient.Client(auth_url=env['OS_AUTH_URL'], username=env['OS_USERNAME'], api_key=env['OS_PASSWORD'], ...
from os import environ as env from glanceclient import Client as glclient import keystoneclient.v2_0.client as ksclient import novaclient.client as nvclient client_args = { } nova = nvclient.Client('2', env['OS_USERNAME'], env['OS_PASSWORD'], env['OS_TENANT_NAME'], env['OS_AUTH_URL']) keystone = ksclient.C...
Fix nova client usage, it should not be initialized this way
Fix nova client usage, it should not be initialized this way
Python
apache-2.0
pellaeon/bsd-cloudinit-installer,pellaeon/bsd-cloudinit-installer
3d524f00269026bc66dcd2b085c60c0d43242ee5
changes/api/jobstep_deallocate.py
changes/api/jobstep_deallocate.py
from __future__ import absolute_import, division, unicode_literals from changes.api.base import APIView from changes.constants import Status from changes.config import db from changes.jobs.sync_job_step import sync_job_step from changes.models import JobStep class JobStepDeallocateAPIView(APIView): def post(sel...
from __future__ import absolute_import, division, unicode_literals from changes.api.base import APIView from changes.constants import Result, Status from changes.config import db from changes.jobs.sync_job_step import sync_job_step from changes.models import JobStep class JobStepDeallocateAPIView(APIView): def ...
Allow deallocation of running jobsteps
Allow deallocation of running jobsteps
Python
apache-2.0
bowlofstew/changes,bowlofstew/changes,dropbox/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,wfxiang08/changes,bowlofstew/changes,dropbox/changes
0409580aed43b6a0556fcc4b8e6e9252d9f082ea
froide/publicbody/management/commands/validate_publicbodies.py
froide/publicbody/management/commands/validate_publicbodies.py
from io import StringIO from contextlib import contextmanager from django.conf import settings from django.core.management.base import BaseCommand from django.utils import translation from django.utils.translation import ugettext_lazy as _ from froide.helper.email_sending import send_mail from ...validators import P...
from io import StringIO from contextlib import contextmanager from django.conf import settings from django.core.management.base import BaseCommand from django.utils import translation from django.utils.translation import ugettext_lazy as _ from froide.helper.email_sending import send_mail from ...validators import P...
Use queryset in validate publicbodies command
Use queryset in validate publicbodies command
Python
mit
stefanw/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide,fin/froide,fin/froide
62f3368eabc54c2cb2a78308fac639e65f55e989
hello.py
hello.py
#!/usr/bin/python -tt # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ """A tiny Python program to check that Python is working. Try running this program from t...
#!/usr/bin/python -tt # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ """A tiny Python program to check that Python is working. Try running this program from t...
Change indentation from 2 spaces (Google standard) to 4 spaces (PEP-8).
Change indentation from 2 spaces (Google standard) to 4 spaces (PEP-8). Add comments.
Python
apache-2.0
beepscore/google-python-exercises,beepscore/google-python-exercises
b211306824db0a10a79cdab4153c457813b44bca
linter.py
linter.py
# # linter.py # Markdown Linter for SublimeLinter, a code checking framework # for Sublime Text 3 # # Written by Jon LaBelle # Copyright (c) 2018 Jon LaBelle # # License: MIT # """This module exports the Markdownlint plugin class.""" from SublimeLinter.lint import NodeLinter, util class MarkdownLint(NodeLinter): ...
# # linter.py # Markdown Linter for SublimeLinter, a code checking framework # for Sublime Text 3 # # Written by Jon LaBelle # Copyright (c) 2018 Jon LaBelle # # License: MIT # """This module exports the Markdownlint plugin class.""" from SublimeLinter.lint import NodeLinter, util class MarkdownLint(NodeLinter): ...
Remove deprecated version requirement settings
Remove deprecated version requirement settings Linter plugins can no longer set version requirements. https://github.com/SublimeLinter/SublimeLinter/issues/1087
Python
mit
jonlabelle/SublimeLinter-contrib-markdownlint,jonlabelle/SublimeLinter-contrib-markdownlint
fa2d26f6c7652f1c4964ff5df076bf9dcdd3a493
webvtt/exceptions.py
webvtt/exceptions.py
class MalformedFileError(Exception): """Error raised when the file is not well formatted""" class MalformedCaptionError(Exception): """Error raised when a caption is not well formatted"""
class MalformedFileError(Exception): """Error raised when the file is not well formatted""" class MalformedCaptionError(Exception): """Error raised when a caption is not well formatted""" class InvalidCaptionsError(Exception): """Error raised when passing wrong captions to the segmenter"""
Add exception for invalid captions
Add exception for invalid captions
Python
mit
sampattuzzi/webvtt-py,glut23/webvtt-py
d5c296197c7f5b422f44e58f8e58ead5fdc5c2ad
reports/models.py
reports/models.py
from datetime import datetime from django.db import models from django.utils.translation import ugettext_lazy as _ class Report(models.Model): addressed_to = models.TextField() reported_from = models.ForeignKey('members.User') content = models.TextField() created_at = models.DateField(_("Date"), defa...
from datetime import datetime from django.db import models class Report(models.Model): addressed_to = models.TextField() reported_from = models.ForeignKey('members.User') content = models.TextField() created_at = models.DateField(default=datetime.now) copies = models.ManyToManyField('protocols.Top...
Add new initial migration for reports
Add new initial migration for reports
Python
mit
Hackfmi/Diaphanum,Hackfmi/Diaphanum
a542cfe1462869c2b64b2202d7316a0af1e3a613
core/modules/can_access.py
core/modules/can_access.py
import requests def can_access(url): try: current_page = (requests.get(url).text, 'lxml') answer = "SL" except requests.exceptions.ConnectionError: answer = "PL" return answer
import requests def can_access(url): try: current_page = (requests.get(url).text, 'lxml') answer = "SL" except requests.exceptions.ConnectionError: print("ERROR: Page is inaccessible, return U and move to next case.") answer = "U" return answer
Change handling for inaccessible pages
Change handling for inaccessible pages
Python
bsd-2-clause
mjkim610/phishing-detection,jaeyung1001/phishing_site_detection
bb14d53e8db76686a3a93a814b1258933083dc0b
resin/__init__.py
resin/__init__.py
""" Welcome to the Resin Python SDK documentation. This document aims to describe all the functions supported by the SDK, as well as showing examples of their expected usage. Install the Resin SDK: From Pip: ``` pip install resin-sdk ``` From Source (In case, you want to test a development branch): ``` https://githu...
""" Welcome to the Resin Python SDK documentation. This document aims to describe all the functions supported by the SDK, as well as showing examples of their expected usage. Install the Resin SDK: From Pip: ``` pip install resin-sdk ``` From Source (In case, you want to test a development branch): ``` https://githu...
Add getting started section to the docs.
Add getting started section to the docs.
Python
apache-2.0
resin-io/resin-sdk-python,resin-io/resin-sdk-python
5c116f4559520083d65848b3bde8bb95621a1633
moksha/hub/amqp/__init__.py
moksha/hub/amqp/__init__.py
""" Here is where we configure which AMQP hub implementation we are going to use. """ from qpid010 import QpidAMQPHub AMQPHub = QpidAMQPHub #from pyamqplib import AMQPLibHub #AMQPHub = AMQPLibHub
""" Here is where we configure which AMQP hub implementation we are going to use. """ try: from qpid010 import QpidAMQPHub AMQPHub = QpidAMQPHub except ImportError: print "Unable to import qpid module" class FakeHub(object): pass AMQPHub = FakeHub #from pyamqplib import AMQPLibHub #AMQPHub...
Handle working without the qpid module
Handle working without the qpid module
Python
apache-2.0
mokshaproject/moksha,mokshaproject/moksha,pombredanne/moksha,pombredanne/moksha,ralphbean/moksha,mokshaproject/moksha,lmacken/moksha,lmacken/moksha,ralphbean/moksha,ralphbean/moksha,lmacken/moksha,mokshaproject/moksha,pombredanne/moksha,pombredanne/moksha
eff9c3865f06eb0fe2100b48274c88db63c2cf4c
websocket_server/__init__.py
websocket_server/__init__.py
# websocket_server -- WebSocket server library # https://github.com/CylonicRaider/websocket-server """ websocket_server -- WebSocket server library This is a little stand-alone library for WebSocket servers. It integrates neatly with the standard library, providing easily set-up servers for both WebSockets and other ...
# websocket_server -- WebSocket server library # https://github.com/CylonicRaider/websocket-server """ websocket_server -- WebSocket server library This is a little stand-alone library for WebSocket servers. It integrates neatly with the standard library, providing easily set-up servers for both WebSockets and other ...
Embed constants into toplevel module
Embed constants into toplevel module
Python
mit
CylonicRaider/websocket-server,CylonicRaider/websocket-server
1bfc91af9d3ef59e39e6b4693457e00e2877f321
rtrss/database.py
rtrss/database.py
import logging from contextlib import contextmanager from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.exc import SQLAlchemyError from rtrss import OperationInterruptedException from rtrss import config _logger = logging.getLogger(__name__) engine = create_engine(config.SQLAL...
import logging from contextlib import contextmanager from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.exc import SQLAlchemyError from rtrss import OperationInterruptedException from rtrss import config _logger = logging.getLogger(__name__) engine = create_engine(config.SQLA...
Remove obsolete imports, add logging
Remove obsolete imports, add logging
Python
apache-2.0
notapresent/rtrss,notapresent/rtrss,notapresent/rtrss,notapresent/rtrss
83db8d5eb376304b1482b3f46f0b6a800571f50c
non_iterable_example/_5_context.py
non_iterable_example/_5_context.py
if random: numbers = 1 print_numbers(numbers) else: numbers = 1, 2, 3 print_numbers(numbers) def print_numbers(numbers): for n in numbers: print(n)
def print_numbers(numbers): for n in numbers: print(n) if random: numbers = 1 print_numbers(numbers) else: numbers = 1, 2, 3 print_numbers(numbers)
Make function exist when called.
Make function exist when called.
Python
unlicense
markshannon/buggy_code
17e80f746fd634f84f3050b8ef613537a62c1f73
reddit.py
reddit.py
#!/usr/bin/env python import sys,requests REDDIT=sys.argv[1] CHANNEL=sys.argv[2] FEED=sys.argv[3] STATEFILE="/home/ircbot/state/reddit-%s-%s-storyids"%(CHANNEL,REDDIT) seen = set(open(STATEFILE).read().split("\n")) data = requests.get("http://www.reddit.com/r/%s/%s.json" %(REDDIT,FEED)).json() new=[] writer=open("/...
#!/usr/bin/env python import sys,requests,json REDDIT=sys.argv[1] CHANNEL=sys.argv[2] FEED=sys.argv[3] # Test mode: if len(sys.argv) == 5: print "running in test mode" data = json.loads(open(sys.argv[4]).read()) writer=sys.stdout else: req = requests.get("http://www.reddit.com/r/%s/%s.json" %(REDDIT,FEED)) ...
Add a test mode, handle 429 errors, stop corrupting state file
Add a test mode, handle 429 errors, stop corrupting state file
Python
unlicense
iibot-irc/irc-reddit,iibot-irc/irc-reddit
189f62b93382a1db0f2780678bbd4ad9c7769623
util.py
util.py
import sys def format_cols(cols): widths = [0] * len(cols[0]) for i in cols: for idx, val in enumerate(i): widths[idx] = max(len(val), widths[idx]) f = "" t = [] for i in widths: t.append("%%-0%ds" % (i,)) return " ".join(t) def column_report(title, fields, c...
# As a hack, disable SSL warnings. import urllib3 urllib3.disable_warnings() import sys def format_cols(cols): widths = [0] * len(cols[0]) for i in cols: for idx, val in enumerate(i): widths[idx] = max(len(val), widths[idx]) f = "" t = [] for i in widths: t.append("%...
Disable SSL warnings by default.
Disable SSL warnings by default.
Python
mit
lightcrest/kahu-api-demo
8161ec1fc511ba948451ce121c863ca878ef482d
tests/test_pool.py
tests/test_pool.py
import random import unittest from aioes.pool import RandomSelector class TestRandomSelector(unittest.TestCase): def setUp(self): random.seed(123456) def tearDown(self): random.seed(None) def test_select(self): s = RandomSelector() r = s.select([1, 2, 3]) self.a...
import random import unittest from aioes.pool import RandomSelector, RoundRobinSelector class TestRandomSelector(unittest.TestCase): def setUp(self): random.seed(123456) def tearDown(self): random.seed(None) def test_select(self): s = RandomSelector() r = s.select([1, 2...
Add test for round-robin selector
Add test for round-robin selector
Python
apache-2.0
aio-libs/aioes
7fe3eae251f3b0b4d433cf2d14f619306159ae43
manage.py
manage.py
import os from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from app import create_app, db app = create_app(os.getenv("FLASK_CONFIG") or "default") migrate = Migrate(app, db) manager = Manager(app) manager.add_command("db", MigrateCommand) if __name__ == "__main__": manager.run...
import os from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from app import create_app, db app = create_app(os.getenv("MYDICTIONARY_CONFIG") or "default") migrate = Migrate(app, db) manager = Manager(app) manager.add_command("db", MigrateCommand) if __name__ == "__main__": mana...
Change environment variable for app configuration
Change environment variable for app configuration
Python
mit
Encrylize/MyDictionary,Encrylize/MyDictionary,Encrylize/MyDictionary
9f8a8321fbed1008f0eec608ba7bce9b08897e40
manage.py
manage.py
import os import unittest from flask.ext.script import Manager from server import app from server.models import db manager = Manager(app) @manager.command def init_db(): """ Initialize database: drop and create all columns """ db.drop_all() db.create_all() @manager.command def test(): tests_path ...
import os import unittest from flask.ext.script import Manager from server import app from server.models import db from server.models import Lecturer, Course, Lecture, Comment manager = Manager(app) @manager.command def init_db(): """ Initialize database: drop and create all columns """ db.drop_all() ...
Add command to mock some db data
Add command to mock some db data
Python
mit
MACSIFS/IFS,MACSIFS/IFS,MACSIFS/IFS,MACSIFS/IFS
abcd2bd21a9033353e04514edd78a2a0a06292de
manage.py
manage.py
from flask.ext.script import Manager, Shell from app import create_app, db from settings import DevConfig, ProdConfig import os if os.environ.get("ENV") == 'prod': app = create_app(ProdConfig) else: app = create_app(DevConfig) def _context(): """ Expose shell session access to the app and db modules....
from flask.ext.script import Manager, Shell, prompt, prompt_pass from app import create_app, models, db from settings import DevConfig, ProdConfig import os if os.environ.get("ENV") == 'prod': app = create_app(ProdConfig) else: app = create_app(DevConfig) manager = Manager(app) @manager.command def init_db(...
Add commands for database and user creation
Add commands for database and user creation
Python
mit
jawrainey/atc,jawrainey/atc
43002f30c23f0a5d739a096ec8e9c445a9502f97
manage.py
manage.py
#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager, Server from flask.ext.script.commands import ShowUrls, Clean from waitress import serve # default to dev config because no one should use this in # production anyway env = os.environ.get('APP_ENV', 'dev') app = create_ap...
#!/usr/bin/env python import os from app import app, assets from flask.ext.script import Manager, Server from flask.ext.assets import ManageAssets from flask.ext.script.commands import ShowUrls, Clean # default to dev config because no one should use this in # production anyway env = os.environ.get('APP_ENV', 'dev')...
Add assets command and misc clean-up
Add assets command and misc clean-up
Python
mit
doomspork/seancallan.com,doomspork/seancallan.com,doomspork/seancallan.com
084a923d928996022936e5c942e69876dc409b5e
edx_data_research/cli/commands.py
edx_data_research/cli/commands.py
""" In this module we define the interface between the cli input provided by the user and the analytics required by the user """ from edx_data_research import parsing from edx_data_research import reporting def cmd_report_basic(args): """ Run basic analytics """ edx_obj = reporting.Basic(args) geta...
""" In this module we define the interface between the cli input provided by the user and the analytics required by the user """ from edx_data_research import parsing from edx_data_research import reporting def cmd_report_basic(args): """ Run basic analytics """ edx_obj = reporting.Basic(args) geta...
Define proxy function for course specific tracking logs
Define proxy function for course specific tracking logs
Python
mit
McGillX/edx_data_research,McGillX/edx_data_research,McGillX/edx_data_research
db960486f223e04fe08a8f2b9619aa887dcafeda
yuno.py
yuno.py
#!/usr/bin/env python3 import os import re import sys from yuno.core import cli, config from yuno.core.util import working_dir def main(argv=None): # Figure out where Yuno lives so plugins can cd correctly if they need to. yuno_home = os.path.abspath(os.path.dirname(__file__)) config.update('YUNO_HOME',...
#!/usr/bin/env python3 import os import re import sys from yuno.core import cli, config from yuno.core.util import working_dir def main(argv=None): # Figure out where Yuno lives so plugins can cd correctly if they need to. yuno_home = os.path.abspath(os.path.dirname(os.path.realpath(__file__))) config.u...
Resolve symlinks when detecting YUNO_HOME.
Resolve symlinks when detecting YUNO_HOME.
Python
mit
bulatb/yuno,bulatb/yuno
395d35eafba14b52a301cb2cf0e7345ae7e0430c
src/argparser.py
src/argparser.py
"""ArgumentParser with Italian translation.""" import argparse import sys def _callable(obj): return hasattr(obj, '__call__') or hasattr(obj, '__bases__') class ArgParser(argparse.ArgumentParser): def __init__(self, **kwargs): if kwargs.get('parent', None) is None: kwargs['parents'] = [...
"""ArgumentParser with Italian translation.""" import argparse import sys def _callable(obj): return hasattr(obj, '__call__') or hasattr(obj, '__bases__') class ArgParser(argparse.ArgumentParser): def __init__(self, **kwargs): kwargs.setdefault('parents', []) super().__init__(**kwargs) ...
FIx wrong key name and simplify the assignment
FIx wrong key name and simplify the assignment
Python
mit
claudio-unipv/pvcheck,claudio-unipv/pvcheck
12096f2961f72e250e16b168c053e89277e442a5
test.py
test.py
import dis import time import pyte # Create a new consts value. consts = pyte.create_consts(None, "Hello, world!") # New varnames values varnames = pyte.create_varnames() # Create names (for globals) names = pyte.create_names("print") bc = [pyte.call.CALL_FUNCTION(names[0], consts[1]), pyte.tokens.RETURN_VALUE...
import dis import time import pyte # Create a new consts value. consts = pyte.create_consts(None, "Hello, world!") # New varnames values varnames = pyte.create_varnames() # Create names (for globals) names = pyte.create_names("print") bc = [pyte.ops.CALL_FUNCTION(names[0], consts[1]), pyte.ops.END_FUNCTION(con...
Add instruction for returning a value
Add instruction for returning a value
Python
mit
SunDwarf/Pyte
0bd1865730106d2573acb04d95b23290e935f4c4
util.py
util.py
from math import sin, cos, asin, sqrt def hav(lona, lonb, lata, latb): # ported from latlontools # assume latitude and longitudes are in radians diff_lat = lata - latb diff_lon = lona - lonb a = sin(diff_lat/2)**2 + cos(lona) * cos(latb) * sin(diff_lon/2)**2 c = 2 * asin(sqrt(a)) r = 6371 # radius of earth in...
from math import sin, cos, asin, sqrt def hav(lonlata, lonlatb): # ported from latlontools # assume latitude and longitudes are in radians lona = lonlata[0] lata = lonlata[1] lonb = lonlatb[0] latb = lonlatb[1] diff_lat = lata - latb diff_lon = lona - lonb a = sin(diff_lat/2)**2 + cos(lona) * cos(latb) * ...
Change call signature of hav to 2 pairs
Change call signature of hav to 2 pairs
Python
bsd-3-clause
LemonPi/Pathtreker,LemonPi/Pathtreker,LemonPi/Pathtreker
de7219dd9d40f316dc0dd6f6c2cad68e66898762
tests/test_live.py
tests/test_live.py
""" Tests run against live mail providers. These aren't generally run as part of the test suite. """ import os import pytest from aiosmtplib import SMTP, SMTPAuthenticationError, SMTPStatus pytestmark = [ pytest.mark.skipif( os.environ.get("CI") == "true", reason="No tests against real servers ...
""" Tests run against live mail providers. These aren't generally run as part of the test suite. """ import os import pytest from aiosmtplib import SMTP, SMTPAuthenticationError, SMTPStatus pytestmark = [ pytest.mark.skipif( os.environ.get("AIOSMTPLIB_LIVE_TESTS") != "true", reason="No tests ag...
Disable live tests by default
Disable live tests by default
Python
mit
cole/aiosmtplib
94475ea2ed73e57870e8947a5b3ed474a70447e4
src/sentry/signals.py
src/sentry/signals.py
from __future__ import absolute_import from functools import wraps from django.dispatch import Signal class BetterSignal(Signal): def connect(self, receiver=None, **kwargs): """ Support decorator syntax: >>> @signal.connect(sender=type) >>> def my_receiver(**kwargs): >>>...
from __future__ import absolute_import from functools import wraps from django.dispatch import Signal class BetterSignal(Signal): def connect(self, receiver=None, **kwargs): """ Support decorator syntax: >>> @signal.connect(sender=type) >>> def my_receiver(**kwargs): >>>...
Add missing args to event_received
Add missing args to event_received
Python
bsd-3-clause
jean/sentry,mitsuhiko/sentry,ifduyue/sentry,zenefits/sentry,JamesMura/sentry,mvaled/sentry,beeftornado/sentry,fotinakis/sentry,JamesMura/sentry,jean/sentry,mitsuhiko/sentry,gencer/sentry,jean/sentry,zenefits/sentry,BuildingLink/sentry,JackDanger/sentry,looker/sentry,looker/sentry,zenefits/sentry,beeftornado/sentry,mval...
36d98f499316d4695c20544701dd1d4300aca600
corehq/ex-submodules/dimagi/utils/couch/cache/cache_core/lib.py
corehq/ex-submodules/dimagi/utils/couch/cache/cache_core/lib.py
from __future__ import absolute_import from __future__ import unicode_literals import simplejson from django_redis.cache import RedisCache from . import CACHE_DOCS, key_doc_id, rcache from corehq.util.soft_assert import soft_assert def invalidate_doc_generation(doc): from .gen import GenerationCache doc_type ...
from __future__ import absolute_import from __future__ import unicode_literals import simplejson from . import CACHE_DOCS, key_doc_id, rcache def invalidate_doc_generation(doc): from .gen import GenerationCache doc_type = doc.get('doc_type', None) generation_mgr = GenerationCache.doc_type_generation_map()...
Revert "track multi key ops in Redis"
Revert "track multi key ops in Redis"
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
786de8ec482ed67b78696357c66dfa9292eea62f
tk/templatetags.py
tk/templatetags.py
from django.core.urlresolvers import reverse, resolve from django.template import Library from django.utils import translation from django.templatetags.i18n import register @register.simple_tag(takes_context=True) def translate_url(context, language): view = resolve(context['request'].path) args = [a for a in...
from django.core.urlresolvers import reverse, resolve from django.template import Library from django.utils import translation from django.templatetags.i18n import register @register.simple_tag(takes_context=True) def translate_url(context, language): if hasattr(context.get('object', None), 'get_absolute_url'): ...
Fix getting the translated urls for material detail views
Fix getting the translated urls for material detail views
Python
agpl-3.0
GISAElkartea/tresna-kutxa,GISAElkartea/tresna-kutxa,GISAElkartea/tresna-kutxa,GISAElkartea/tresna-kutxa
91165642fb40165987ab0ff734959f88712e514c
humblemedia/resources/migrations/0001_initial.py
humblemedia/resources/migrations/0001_initial.py
# encoding: utf8 from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( ...
# encoding: utf8 from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('auth', '__first__'), ('contenttypes', '_...
Add dependencies to contenttypes to the migration
Add dependencies to contenttypes to the migration
Python
mit
vladimiroff/humble-media,vladimiroff/humble-media
430fd5393668249f01a2b941eef62569d758c6cf
tools/skp/page_sets/skia_intelwiki_desktop.py
tools/skp/page_sets/skia_intelwiki_desktop.py
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=W0401,W0614 from telemetry import story from telemetry.page import page as page_module from telemetry.page import shared_page_state clas...
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=W0401,W0614 from telemetry import story from telemetry.page import page as page_module from telemetry.page import shared_page_state clas...
Add scrolling to go to the more interesting parts of desk_intelwiki.skp
Add scrolling to go to the more interesting parts of desk_intelwiki.skp Bug: skia:11804 Change-Id: I96ce34311b5e5420ee343a0dbc68ef20f399be4f Reviewed-on: https://skia-review.googlesource.com/c/skia/+/390336 Commit-Queue: Ravi Mistry <9fa2e7438b8cb730f96b74865492597170561628@google.com> Reviewed-by: Robert Phillips <95...
Python
bsd-3-clause
google/skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,google/skia,google/skia,google/skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,google/skia,aosp-mirror/platform_external_skia,google/skia,aosp-mirror/platform_external_skia,google/skia,google/skia,aosp-mirror/pl...
902e4500b57d54a80a586b0843ff3a68706a5c58
setup.py
setup.py
""" Distutils script for building cython .c and .so files. Call it with: python setup.py build_ext --inplace """ from distutils.core import setup from Cython.Build import cythonize #from Cython.Compiler.Options import directive_defaults #directive_defaults['profile'] = True setup( name = "Pentacular", ...
""" Distutils script for building cython .c and .so files. Call it with: python setup.py build_ext --inplace """ from distutils.core import setup from Cython.Build import cythonize #from Cython.Compiler.Options import directive_defaults #directive_defaults['profile'] = True cy_modules = [ 'board_strip.py...
Remove py modules causing GUI lag
Remove py modules causing GUI lag
Python
mit
cropleyb/pentai,cropleyb/pentai,cropleyb/pentai
c8360831ab2fa4d5af2929a85beca4a1f33ef9d1
travis_settings.py
travis_settings.py
# Settings used for running tests in Travis # # Load default settings # noinspection PyUnresolvedReferences from settings import * # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'alexia_test', ...
# Settings used for running tests in Travis # # Load default settings # noinspection PyUnresolvedReferences from settings import * # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'alexia_test', ...
Use MySQL database backend in Travis CI.
Use MySQL database backend in Travis CI.
Python
bsd-3-clause
Inter-Actief/alexia,Inter-Actief/alexia,Inter-Actief/alexia,Inter-Actief/alexia
95ebac75381580fe3767d7c9e287226a75bc43bf
elections/kenya/lib.py
elections/kenya/lib.py
from __future__ import unicode_literals import re def shorten_post_label(post_label): return re.sub(r'^Member of Parliament for ', '', post_label)
from __future__ import unicode_literals import re def shorten_post_label(post_label): return re.sub(r'^(County Assembly Member for|Member of the National Assembly for|County Governor for|Women Representative for|Senator for|President of)\s+', '', post_label)
Implement post label abbreviation for current posts
KE: Implement post label abbreviation for current posts
Python
agpl-3.0
mysociety/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextmp-popit,mysociety/yournextmp-popit,mysociety/yournextrepresentative
3830ef5200f3d1763be5d162f5123cd59ca1da0b
virtualenv/__init__.py
virtualenv/__init__.py
from __future__ import absolute_import, division, print_function from virtualenv.__about__ import ( __author__, __copyright__, __email__, __license__, __summary__, __title__, __uri__, __version__ ) from virtualenv.core import create def create_environment( home_dir, site_packages=False, clear=False, ...
from __future__ import absolute_import, division, print_function from virtualenv.__about__ import ( __author__, __copyright__, __email__, __license__, __summary__, __title__, __uri__, __version__ ) # some support for old api in legacy virtualenv from virtualenv.core import create from virtualenv.__main__ impo...
Add a main function (more support for the api in the legacy virtualenv).
Add a main function (more support for the api in the legacy virtualenv).
Python
mit
ionelmc/virtualenv,ionelmc/virtualenv,ionelmc/virtualenv
33f1cd2950bf1544f4bb481aa0c31326a5c061ab
examples/rpc_pubsub.py
examples/rpc_pubsub.py
import asyncio import aiozmq.rpc class Handler(aiozmq.rpc.AttrHandler): @aiozmq.rpc.method def remote_func(self, a: int, b: int): pass @asyncio.coroutine def go(): subscriber = yield from aiozmq.rpc.serve_pubsub( Handler(), subscribe='topic', bind='tcp://*:*') subscriber_addr = next...
import asyncio import aiozmq.rpc from itertools import count class Handler(aiozmq.rpc.AttrHandler): def __init__(self): self.connected = False @aiozmq.rpc.method def remote_func(self, step, a: int, b: int): self.connected = True print("HANDLER", step, a, b) @asyncio.coroutine d...
Make rpc pubsub example stable
Make rpc pubsub example stable
Python
bsd-2-clause
aio-libs/aiozmq,asteven/aiozmq,claws/aiozmq,MetaMemoryT/aiozmq
891ce02157c0862f707cab7a140389e0b059acd4
registration/__init__.py
registration/__init__.py
VERSION = (0, 9, 0, 'beta', 1) def get_version(): from django.utils.version import get_version as django_get_version return django_get_version(VERSION) # pragma: no cover
VERSION = (1, 0, 0, 'final', 0) def get_version(): "Returns a PEP 386-compliant version number from VERSION." assert len(VERSION) == 5 assert VERSION[3] in ('alpha', 'beta', 'rc', 'final') # Now build the two parts of the version number: # main = X.Y[.Z] # sub = .devN - for pre-alpha releases...
Fix version number reporting so we can be installed before Django.
Fix version number reporting so we can be installed before Django.
Python
bsd-3-clause
christang/django-registration-1.5,fedenko/django-registration,fedenko/django-registration,christang/django-registration-1.5
7b2db239b0862db256722f57241c74d4cc9b42ff
diss/__init__.py
diss/__init__.py
import os import hashlib import magic from base64 import b64encode, b64decode from datetime import datetime from .settings import inventory from .encryption import random_key, copy_and_encrypt, decrypt_blob hashing = hashlib.sha256 def add_file(filepath, *, key=None): "Import a file into Dis." if not os.p...
import os import hashlib import magic from base64 import b64encode, b64decode from datetime import datetime from .settings import inventory from .encryption import random_key, copy_and_encrypt, decrypt_blob hashing = hashlib.sha256 def add_file(filepath, *, key=None): "Import a file into Dis." # Resolve s...
Fix mimetype detection on symlink
Fix mimetype detection on symlink
Python
agpl-3.0
hoh/Billabong,hoh/Billabong
421e811242b737a7b1bf27814d70f719f345131b
watchlist/utils.py
watchlist/utils.py
from .models import ShiftSlot, weekday_loc from website.settings import WORKSHOP_OPEN_DAYS def get_shift_weekview_rows(): '''Returns a dictionary of shifts for each timeslot, for each weekday''' slots = ShiftSlot.objects.all() if not slots: return None # Could be troublesome wrt. sorting of di...
from .models import ShiftSlot, weekday_loc from website.settings import WORKSHOP_OPEN_DAYS def get_shift_weekview_rows(): '''Returns a dictionary of shifts for each timeslot, for each weekday''' slots = ShiftSlot.objects.all() if not slots: return None # Could be troublesome wrt. sorting of di...
Order weekday columns in watchlist
Order weekday columns in watchlist
Python
mit
hackerspace-ntnu/website,hackerspace-ntnu/website,hackerspace-ntnu/website
8db252d2980451a3c2107df64c4438de44781eea
frigg/projects/urls.py
frigg/projects/urls.py
from django.conf.urls import url from . import views urlpatterns = [ url(r'^projects/approve/$', views.approve_projects, name='approve_projects_overview'), url(r'^projects/approve/(?P<project_id>\d+)/$', views.approve_projects, name='approve_project'), url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+).svg$', views....
from django.conf.urls import url from . import views urlpatterns = [ url(r'^projects/approve/$', views.approve_projects, name='approve_projects_overview'), url(r'^projects/approve/(?P<project_id>\d+)/$', views.approve_projects, name='approve_project'), url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+).svg$', views....
Add support for specifying branch name to svg badges
Add support for specifying branch name to svg badges
Python
mit
frigg/frigg-hq,frigg/frigg-hq,frigg/frigg-hq
9261db252969c69ede633d4a4c02bb87c7bc1434
quilt/__init__.py
quilt/__init__.py
# vim: fileencoding=utf-8 et sw=4 ts=4 tw=80: # python-quilt - A Python implementation of the quilt patch system # # Copyright (C) 2012 Björn Ricks <bjoern.ricks@googlemail.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as ...
# vim: fileencoding=utf-8 et sw=4 ts=4 tw=80: # python-quilt - A Python implementation of the quilt patch system # # Copyright (C) 2012 Björn Ricks <bjoern.ricks@googlemail.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as ...
Add docstring for main module
Add docstring for main module
Python
mit
bjoernricks/python-quilt,vadmium/python-quilt
17b3ea3fb2af48aa7680b339bb83cba15f842a83
classes/wechatMessageType.py
classes/wechatMessageType.py
from enum import Enum class WechatMessageType(Enum): TEXT = 1 SYSTEM_MESSAGE = 10000 VOICE = 34 EMOTION = 47 VIDEO = 62 CALL = 50 PICTURE = 3 POSITION = 48 CARD = 42 LINK = 49 UNHANDLED = -999
from enum import Enum class WechatMessageType(Enum): TEXT = 1 SYSTEM_MESSAGE = 10000 VOICE = 34 VIDEO1 = 43 EMOTION = 47 VIDEO2 = 62 CALL = 50 PICTURE = 3 POSITION = 48 CARD = 42 LINK = 49 UNHANDLED = -999
Support wechat message type 43
Support wechat message type 43
Python
apache-2.0
jambus/wechat-analysis
3c4a9c08858378624600a3f64616f03e29d21f31
actually-do-refunds.py
actually-do-refunds.py
#!/usr/bin/env python -u from __future__ import absolute_import, division, print_function, unicode_literals import csv, os, requests url = 'https://api.balancedpayments.com/debits/{}/refunds' balanced_api_secret = os.environ['BALANCED_API_SECRET'] inp = csv.reader(open('refunds.csv')) out = csv.writer(open('refunds....
#!/usr/bin/env python -u from __future__ import absolute_import, division, print_function, unicode_literals from gratipay.billing.payday import threaded_map import csv, os, requests import threading url = 'https://api.balancedpayments.com/debits/{}/refunds' balanced_api_secret = os.environ['BALANCED_API_SECRET'] inp...
Use threaded_map to speed up refunds
Use threaded_map to speed up refunds
Python
mit
gratipay/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com
0cb87e52f91c85ec99b58f2795c7762354531e7c
python/assemble_BFs.py
python/assemble_BFs.py
import doseresponse as dr import numpy as np import itertools as it import os import argparse import sys parser = argparse.ArgumentParser() requiredNamed = parser.add_argument_group('required arguments') requiredNamed.add_argument("--data-file", type=str, help="csv file from which to read in data, in same format as p...
import doseresponse as dr import numpy as np import itertools as it import os import argparse import sys parser = argparse.ArgumentParser() requiredNamed = parser.add_argument_group('required arguments') requiredNamed.add_argument("--data-file", type=str, help="csv file from which to read in data, in same format as p...
Unravel index for argmin of array
Unravel index for argmin of array
Python
bsd-3-clause
mirams/PyHillFit,mirams/PyHillFit,mirams/PyHillFit
70808dfd53c5a5760a13252a72caf229793e8225
crawl.py
crawl.py
import urllib2; from bs4 import BeautifulSoup;
import urllib.parse; import urllib.request; from bs4 import BeautifulSoup; def searchLink(search): BASE_URL = "http://www.990.ro/" key = urllib.parse.urlencode({'kw': search}).encode('ascii'); re = urllib.request.Request(BASE_URL + 'functions/search3/live_search_using_jquery_ajax/search.php', key); re_link = ur...
Add search method to find the movies/series home url
Add search method to find the movies/series home url
Python
mit
raztechs/py-video-crawler
e03bc2013adb21154a1fc2b4737d92f649325154
utils.py
utils.py
import re import textwrap import html2text text_maker = html2text.HTML2Text() text_maker.body_width = 0 def strip_html_tags(text): text = re.sub(r'<a.*?</a>', '', text) return re.sub('<[^<]+?>', '', text) def html_to_md(string, strip_html=True, markdown=False): if not string: return 'No Descri...
import re import textwrap import html2text text_maker = html2text.HTML2Text() text_maker.body_width = 0 def strip_html_tags(text): text = re.sub(r'<a.*?</a>', '', text) return re.sub('<[^<]+?>', '', text) def html_to_md(string, strip_html=True, markdown=False): if not string: return 'No Descri...
Create a new string, instead of modifying the `template`
Create a new string, instead of modifying the `template`
Python
mit
avinassh/Laozi,avinassh/Laozi
eea8b5622ced613cde54e6d09cd98f6483543dfd
tests/test_parser2.py
tests/test_parser2.py
import support from html5lib import html5parser from html5lib.treebuilders import dom import unittest # tests that aren't autogenerated from text files class MoreParserTests(unittest.TestCase): def test_assertDoctypeCloneable(self): parser = html5parser.HTMLParser(tree=dom.TreeBuilder) doc = parser.parse('...
import support from html5lib import html5parser from html5lib.treebuilders import dom import unittest # tests that aren't autogenerated from text files class MoreParserTests(unittest.TestCase): def test_assertDoctypeCloneable(self): parser = html5parser.HTMLParser(tree=dom.TreeBuilder) doc = parser.parse('...
Add a test case to ensure that this continues to work
Add a test case to ensure that this continues to work --HG-- extra : convert_revision : svn%3Aacbfec75-9323-0410-a652-858a13e371e0/trunk%40952
Python
mit
alex/html5lib-python,html5lib/html5lib-python,mgilson/html5lib-python,mindw/html5lib-python,ordbogen/html5lib-python,mgilson/html5lib-python,mindw/html5lib-python,html5lib/html5lib-python,dstufft/html5lib-python,alex/html5lib-python,ordbogen/html5lib-python,mindw/html5lib-python,dstufft/html5lib-python,html5lib/html5li...
7d362cfc37398a22440173fa7209224a2542778e
eng100l/ambulances/urls.py
eng100l/ambulances/urls.py
from django.conf.urls import url from . import views urlpatterns = [ url(r'^update/(?P<pk>[0-9]+)$', views.AmbulanceUpdateView.as_view(), name="ambulance_update"), url(r'^info/(?P<pk>[0-9]+)$', views.AmbulanceInfoView.as_view(), name="ambulance_info"), url(r'...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^update/(?P<pk>[0-9]+)$', views.AmbulanceUpdateView.as_view(), name="ambulance_update"), url(r'^info/(?P<pk>[0-9]+)$', views.AmbulanceInfoView.as_view(), name="ambulance_info"), url(r'...
Simplify URL for ambulance creation
Simplify URL for ambulance creation
Python
bsd-3-clause
EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient
9fba993ea52df48de8d812c1ad0128d48c8ab4cf
classes/room.py
classes/room.py
class Room(object): def __init__(self, room_name, room_type, max_persons): self.room_name = room_name self.room_type = room_type self.max_persons = max_persons self.persons = [] def add_occupant(self, person): if len(self.persons) < self.max_persons: self.pe...
class Room(object): def __init__(self, room_name, room_type, max_persons): self.room_name = room_name self.room_type = room_type self.max_persons = max_persons self.persons = [] def add_occupant(self, person): if len(self.persons) < self.max_persons: self.per...
Add Error statement to add_occupant method for when max capacity is reached
Add Error statement to add_occupant method for when max capacity is reached
Python
mit
peterpaints/room-allocator
d9fc2cfdcfaf13f2e8491ace60680f3c94ad5c83
tests/test_async.py
tests/test_async.py
try: import asyncio loop = asyncio.get_event_loop() except ImportError: asyncio = None import pexpect import unittest @unittest.skipIf(asyncio is None, "Requires asyncio") class AsyncTests(unittest.TestCase): def test_simple_expect(self): p = pexpect.spawn('cat') p.sendline('Hello asyn...
try: import asyncio except ImportError: asyncio = None import pexpect import unittest def run(coro): return asyncio.get_event_loop().run_until_complete(coro) @unittest.skipIf(asyncio is None, "Requires asyncio") class AsyncTests(unittest.TestCase): def test_simple_expect(self): p = pexpect.sp...
Expand tests for async expect
Expand tests for async expect
Python
isc
dongguangming/pexpect,quatanium/pexpect,crdoconnor/pexpect,Depado/pexpect,crdoconnor/pexpect,dongguangming/pexpect,crdoconnor/pexpect,Wakeupbuddy/pexpect,nodish/pexpect,Wakeupbuddy/pexpect,blink1073/pexpect,nodish/pexpect,quatanium/pexpect,bangi123/pexpect,dongguangming/pexpect,bangi123/pexpect,quatanium/pexpect,Depado...
aaac1ae0667dabe6fd038c9f5a42c157b9457ef1
tests/test_parse.py
tests/test_parse.py
from hypothesis_auto import auto_pytest_magic from isort import parse from isort.settings import default TEST_CONTENTS = """ import xyz import abc def function(): pass """ def test_file_contents(): ( in_lines, out_lines, import_index, place_imports, import_placement...
from hypothesis_auto import auto_pytest_magic from isort import parse from isort.settings import Config TEST_CONTENTS = """ import xyz import abc def function(): pass """ def test_file_contents(): ( in_lines, out_lines, import_index, place_imports, import_placements...
Fix use of default config to match new refactor
Fix use of default config to match new refactor
Python
mit
PyCQA/isort,PyCQA/isort
39309bb0b8fe088b6576cfbf4d744f58ca6b1b0b
tests/test_quiz1.py
tests/test_quiz1.py
from playwright.sync_api import sync_playwright def run(playwright): browser = playwright.chromium.launch(headless=False, slow_mo=100) context = browser.new_context() # Open new page page = context.new_page() page.goto("http://pyar.github.io/PyZombis/master/quiz/Quiz1.html") page....
def test_quiz1_2(page): page.goto("/quiz/Quiz1.html") page.click("text=def metros_a_milimetros(n):") page.press("text=def metros_a_milimetros(n):", "ArrowDown") page.press("text=def metros_a_milimetros(n):", "Tab") page.type("text=def metros_a_milimetros(n):", "return n * 1000") pa...
Convert sample test to pytest
Convert sample test to pytest
Python
agpl-3.0
PyAr/PyZombis,PyAr/PyZombis,PyAr/PyZombis
254ecc95cdd0c2809328634e50882ea42fb32105
tests/test_utils.py
tests/test_utils.py
import pytest from bonsai.utils import escape_filter_exp from bonsai.utils import escape_attribute_value def test_escape_attribute_value(): """ Test escaping special characters in attribute values. """ assert ( escape_attribute_value(" dummy=test,something+somethingelse") == r"\ dummy\=test\,...
import pytest from bonsai.utils import escape_filter_exp from bonsai.utils import escape_attribute_value from bonsai.utils import set_connect_async def test_escape_attribute_value(): """ Test escaping special characters in attribute values. """ assert ( escape_attribute_value(" dummy=test,something+s...
Add simple call test for set_connect_async
Add simple call test for set_connect_async
Python
mit
Noirello/PyLDAP,Noirello/bonsai,Noirello/PyLDAP,Noirello/PyLDAP,Noirello/bonsai,Noirello/bonsai
5503a615db51a6ae0461cc0417c61ba508a43eae
ufyr/storage/utils.py
ufyr/storage/utils.py
from os import chmod, unlink, stat, makedirs from os.path import isfile, split, exists from shutil import copyfile def move_verify_delete(in_file, out_file): ''' Moves in_file to out_file, verifies that the filesizes are the same and then does a chmod 666 ''' if not exists(split(out_file)[0]): ...
from os import chmod, unlink, stat, makedirs from os.path import isfile, split, exists from shutil import copyfile def move_verify_delete(in_file, out_file, overwrite=False): ''' Moves in_file to out_file, verifies that the filesizes are the same and then does a chmod 666 ''' if not exists(split(ou...
Add in overwrite output file
Add in overwrite output file
Python
unlicense
timeartist/ufyr
4d55b1bde81c9f426da97f474d759ba8b0a94650
cpt/test/unit/config_test.py
cpt/test/unit/config_test.py
import unittest from conans.errors import ConanException from cpt.config import ConfigManager from cpt.printer import Printer from cpt.test.integration.base import BaseTest from cpt.test.unit.packager_test import MockConanAPI class RemotesTest(unittest.TestCase): def setUp(self): self.conan_api = MockC...
import unittest from conans.errors import ConanException from cpt.config import ConfigManager from cpt.printer import Printer from cpt.test.integration.base import BaseTest from cpt.test.unit.packager_test import MockConanAPI class RemotesTest(unittest.TestCase): def setUp(self): self.conan_api = MockC...
Update Bincrafters config url for tests
Update Bincrafters config url for tests Signed-off-by: Uilian Ries <d4bad57018205bdda203549c36d3feb0bfe416a7@gmail.com>
Python
mit
conan-io/conan-package-tools
f55f965c4102e2d7230ace39a0eecdaf585538ea
blaze/expr/scalar/boolean.py
blaze/expr/scalar/boolean.py
import operator from datashape import dshape from .core import Scalar, BinOp, UnaryOp class BooleanInterface(Scalar): def __not__(self): return Not(self) def __and__(self, other): return And(self, other) def __or__(self, other): return Or(self, other) class Boolean(BooleanInter...
import operator from datashape import dshape from .core import Scalar, BinOp, UnaryOp class BooleanInterface(Scalar): def __invert__(self): return Invert(self) def __and__(self, other): return And(self, other) def __or__(self, other): return Or(self, other) class Boolean(Boolea...
Use __invert__ instead of __not__
Use __invert__ instead of __not__
Python
bsd-3-clause
LiaoPan/blaze,caseyclements/blaze,cpcloud/blaze,cowlicks/blaze,caseyclements/blaze,jdmcbr/blaze,dwillmer/blaze,nkhuyu/blaze,scls19fr/blaze,mrocklin/blaze,cowlicks/blaze,dwillmer/blaze,cpcloud/blaze,xlhtc007/blaze,jcrist/blaze,maxalbert/blaze,jdmcbr/blaze,ChinaQuants/blaze,ContinuumIO/blaze,maxalbert/blaze,mrocklin/blaz...
367d5d6196c3c21e2d1353b258801e6d5e14e602
xos/core/models/node.py
xos/core/models/node.py
import os from django.db import models from core.models import PlCoreBase from core.models.plcorebase import StrippedCharField from core.models import Site, SiteDeployment, SitePrivilege from core.models import Tag from django.contrib.contenttypes import generic # Create your models here. class Node(PlCoreBase): ...
import os from django.db import models from core.models import PlCoreBase from core.models.plcorebase import StrippedCharField from core.models import Site, SiteDeployment, SitePrivilege from core.models import Tag from django.contrib.contenttypes import generic # Create your models here. class Node(PlCoreBase): ...
Make Node syncs a noop
Make Node syncs a noop
Python
apache-2.0
jermowery/xos,cboling/xos,cboling/xos,cboling/xos,jermowery/xos,cboling/xos,xmaruto/mcord,jermowery/xos,xmaruto/mcord,xmaruto/mcord,cboling/xos,jermowery/xos,xmaruto/mcord
b706c31fe24e4e940108882f420c0509cce94970
django_databrowse/plugins/objects.py
django_databrowse/plugins/objects.py
from django import http from django.core.exceptions import ObjectDoesNotExist from django_databrowse.datastructures import EasyModel from django_databrowse.sites import DatabrowsePlugin from django.shortcuts import render_to_response import urlparse class ObjectDetailPlugin(DatabrowsePlugin): def model_view(self, ...
from django import http from django.core.exceptions import ObjectDoesNotExist from django_databrowse.datastructures import EasyModel from django_databrowse.sites import DatabrowsePlugin from django.shortcuts import render_to_response from django.template import RequestContext import urlparse class ObjectDetailPlugin(D...
Add RequestContext for object detail
Add RequestContext for object detail
Python
bsd-3-clause
Alir3z4/django-databrowse,Alir3z4/django-databrowse
f8ff675f8c9a4ef2b370e5254d33b97261a9d8ca
byceps/util/sentry.py
byceps/util/sentry.py
""" byceps.util.sentry ~~~~~~~~~~~~~~~~~~ Sentry_ integration .. _Sentry: https://sentry.io/ :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from flask import Flask def configure_sentry_for_webapp(dsn: str, environment: str, app: Flask) -> None: """Initialize an...
""" byceps.util.sentry ~~~~~~~~~~~~~~~~~~ Sentry_ integration .. _Sentry: https://sentry.io/ :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from flask import Flask def configure_sentry_for_webapp(dsn: str, environment: str, app: Flask) -> None: """Initialize an...
Set Sentry `site_id` tag only in site app mode
Set Sentry `site_id` tag only in site app mode
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps
1b7d84526ac7650f18851610ebef47bdfef828ea
scripts/galaxy/gedlab.py
scripts/galaxy/gedlab.py
""" k-mer count and presence """ from galaxy.datatypes.binary import Binary import os import logging log = logging.getLogger(__name__) class Count(Binary): def __init__(self, **kwd): Binary.__init__(self, **kwd) class Presence(Binary): def __init__(self, **kwd): Binary.__init__(self, **...
""" k-mer count and presence """ from galaxy.datatypes.binary import Binary import logging log = logging.getLogger(__name__) class Count(Binary): def __init__(self, **kwd): Binary.__init__(self, **kwd) class Presence(Binary): def __init__(self, **kwd): Binary.__init__(self, **kwd) Bina...
Fix pylint warning: Unused import os
Fix pylint warning: Unused import os
Python
bsd-3-clause
Winterflower/khmer,kdmurray91/khmer,souravsingh/khmer,jas14/khmer,kdmurray91/khmer,Winterflower/khmer,F1000Research/khmer,jas14/khmer,ged-lab/khmer,kdmurray91/khmer,ged-lab/khmer,F1000Research/khmer,ged-lab/khmer,F1000Research/khmer,jas14/khmer,Winterflower/khmer,souravsingh/khmer,souravsingh/khmer
cbd9c312b857565bfebc2d9f8452453ca333ba92
giles.py
giles.py
#!/usr/bin/env python2 # Giles: giles.py, the main loop. # Copyright 2012 Phil Bordelon # # 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 op...
#!/usr/bin/env python2 # Giles: giles.py, the main loop. # Copyright 2012 Phil Bordelon # # 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 op...
Support choosing a port on the command line.
Support choosing a port on the command line. Just put a number as the only CLI for now. Useful for me testing changes now that I'm actually keeping the server running.
Python
agpl-3.0
sunfall/giles
5d2f585779bef5e8bd82e7f4e7b46818153af711
build.py
build.py
from conan.packager import ConanMultiPackager if __name__ == "__main__": builder = ConanMultiPackager() builder.add_common_builds(pure_c=False) builder.run()
from conan.packager import ConanMultiPackager if __name__ == "__main__": builder = ConanMultiPackager() builder.add_common_builds(pure_c=False) builds = [] for settings, options, env_vars, build_requires, reference in builder.items: settings["cppstd"] = 14 builds.append([settings, optio...
Use std 14 in CI
CI: Use std 14 in CI
Python
mit
zhuhaow/libnekit,zhuhaow/libnekit,zhuhaow/libnekit,zhuhaow/libnekit
6b4f4f07c442705f76294b9ec9a37d3d02ca1551
run_tests.py
run_tests.py
#!/usr/bin/env python import os, sys, re, shutil os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' import django from django.core.management import call_command names = next((a for a in sys.argv[1:] if not a.startswith('-')), None) if names and re.search(r'^\d+$', names): names = 'tests.tests.IssueTests.tes...
#!/usr/bin/env python import os, sys, re, shutil os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' import django from django.core.management import call_command names = next((a for a in sys.argv[1:] if not a.startswith('-')), None) if not names: names = 'tests' elif re.search(r'^\d+$', names): names = '...
Allow running separate test files
Allow running separate test files With e.g.: ./runtests.py tests.tests_transactions
Python
bsd-3-clause
rutube/django-cacheops,Suor/django-cacheops,LPgenerator/django-cacheops,ErwinJunge/django-cacheops,bourivouh/django-cacheops
a5ce33cf60deb5a1045a0bf693b58eb20dbad8d2
sshkeys_update.py
sshkeys_update.py
#!/usr/bin/python import config, store, os standalone_py = os.path.join(os.path.dirname(__file__), 'standalone.py') c = config.Config("config.ini") s = store.Store(c) cursor = s.get_cursor() cursor.execute("lock table sshkeys in exclusive mode") # to prevent simultaneous updates cursor.execute("select u.name,s.key from...
#!/usr/bin/python import config, store, os standalone_py = os.path.join(os.path.dirname(__file__), 'standalone.py') c = config.Config("config.ini") s = store.Store(c) cursor = s.get_cursor() cursor.execute("lock table sshkeys in exclusive mode") # to prevent simultaneous updates cursor.execute("select u.name,s.key from...
Make sure to write in ~submit's authorized_keys.
Make sure to write in ~submit's authorized_keys.
Python
bsd-3-clause
pydotorg/pypi,pydotorg/pypi,pydotorg/pypi,pydotorg/pypi
2f1d32ba80816e3880a464a63d8f3f549a2be9e2
tests/__init__.py
tests/__init__.py
import os try: # 2.7 # pylint: disable = E0611,F0401 from unittest.case import SkipTest # pylint: enable = E0611,F0401 except ImportError: try: # Nose from nose.plugins.skip import SkipTest except ImportError: # Failsafe class SkipTest(Exception): pass from mopidy impor...
import os try: # 2.7 # pylint: disable = E0611,F0401 from unittest.case import SkipTest # pylint: enable = E0611,F0401 except ImportError: try: # Nose from nose.plugins.skip import SkipTest except ImportError: # Failsafe class SkipTest(Exception): pass from mopidy impor...
Add IsA helper to tests to provde any_int, any_str and any_unicode
Add IsA helper to tests to provde any_int, any_str and any_unicode
Python
apache-2.0
bencevans/mopidy,diandiankan/mopidy,ZenithDK/mopidy,vrs01/mopidy,liamw9534/mopidy,dbrgn/mopidy,swak/mopidy,jodal/mopidy,SuperStarPL/mopidy,jmarsik/mopidy,bacontext/mopidy,woutervanwijk/mopidy,ali/mopidy,pacificIT/mopidy,woutervanwijk/mopidy,quartz55/mopidy,jmarsik/mopidy,dbrgn/mopidy,mokieyue/mopidy,bencevans/mopidy,mo...
cf9012ff2f6bf745d46f35923f95b6ce0b9d91e1
homeful/views.py
homeful/views.py
from django.shortcuts import render import logging from homeful.hud_helper import getSeattleFairMarketRents, getSeattleMultiFamilyProperties logger = logging.getLogger(__name__) def index(request): context = {} return render(request, 'homeful/index.html', context) def list(request): zipcode = request.GET...
from django.shortcuts import render import logging from homeful.hud_helper import getSeattleFairMarketRents, getSeattleMultiFamilyProperties logger = logging.getLogger(__name__) def index(request): context = {} return render(request, 'homeful/index.html', context) def list(request): zipcode = request.GET...
Add zipcode filter for MFPs.
Add zipcode filter for MFPs.
Python
mit
happyhousing/happyhousing
fdd75e81f6d71a8f82abdd79cff6ecd20cbfdb6d
tests/runtests.py
tests/runtests.py
#!/usr/bin/env python ''' Discover all instances of unittest.TestCase in this directory. ''' # Import python libs import os # Import salt libs import saltunittest from integration import TestDaemon TEST_DIR = os.path.dirname(os.path.normpath(os.path.abspath(__file__))) def run_integration_tests(): with TestDaemon...
#!/usr/bin/env python ''' Discover all instances of unittest.TestCase in this directory. ''' # Import python libs import os # Import salt libs import saltunittest from integration import TestDaemon TEST_DIR = os.path.dirname(os.path.normpath(os.path.abspath(__file__))) PNUM = 50 def run_integration_tests(): prin...
Add some pretty to the unit tests
Add some pretty to the unit tests
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
dd877d22080d8417709fe4b5afacec8f0b32a226
sendsms.py
sendsms.py
#! /usr/bin/env python3 """sendsms.py: program for sending SMS.""" from sys import argv from googlevoice import Voice from googlevoice.util import LoginError # E-mail SMTP settings with open('/home/nick/dev/prv/serupbot/email_password.txt') as email_password: password = email_password.read().strip() def send(...
#! /usr/bin/env python3 """sendsms.py: program for sending SMS.""" from sys import argv from googlevoice import Voice from googlevoice.util import LoginError # E-mail SMTP settings with open('/home/nick/dev/prv/serupbot/email_password.txt') as email_password: password = email_password.read().strip() # Google v...
Include exception when trying send_sms function.
Include exception when trying send_sms function.
Python
mpl-2.0
nicorellius/server-upbot
621c69b22c6364020cf1ed66e4563bd7b43263fc
src/pytest_django_casperjs/fixtures.py
src/pytest_django_casperjs/fixtures.py
import os import pytest from pytest_django.lazy_django import skip_if_no_django @pytest.fixture(scope='session') def casper_js(request): skip_if_no_django() from pytest_django_casperjs.helper import CasperJSLiveServer addr = request.config.getvalue('liveserver') if not addr: addr = os.gete...
import os import pytest from pytest_django.lazy_django import skip_if_no_django @pytest.fixture(scope='session') def casper_js(request): skip_if_no_django() from pytest_django_casperjs.helper import CasperJSLiveServer addr = request.config.getvalue('liveserver') if not addr: addr = os.gete...
Remove the helper-fixture, we make transactions explicit. Will write documentation about that
Remove the helper-fixture, we make transactions explicit. Will write documentation about that
Python
bsd-3-clause
EnTeQuAk/pytest-django-casperjs
a3c768ab90d1354441d90699049f7dd946e683c2
cleverhans/future/torch/attacks/__init__.py
cleverhans/future/torch/attacks/__init__.py
# pylint: disable=missing-docstring from cleverhans.future.torch.attacks.fast_gradient_method import fast_gradient_method from cleverhans.future.torch.attacks.projected_gradient_descent import projected_gradient_descent from cleverhans.future.torch.attacks.noise import noise from cleverhans.future.torch.attacks.semanti...
# pylint: disable=missing-docstring from cleverhans.future.torch.attacks.fast_gradient_method import fast_gradient_method from cleverhans.future.torch.attacks.projected_gradient_descent import projected_gradient_descent from cleverhans.future.torch.attacks.noise import noise from cleverhans.future.torch.attacks.semanti...
Allow spsa to be imported from cleverhans.future.torch.attacks
Allow spsa to be imported from cleverhans.future.torch.attacks
Python
mit
cleverhans-lab/cleverhans,cleverhans-lab/cleverhans,cleverhans-lab/cleverhans
e572dcb08e9c89d11c4702927561ef9c2ebc3cb1
custos/notify/http.py
custos/notify/http.py
import logging import requests from .base import Notifier log = logging.getLogger(__name__) class HTTPNotifier(Notifier): ''' A Notifier that sends http post request to a given url ''' def __init__(self, auth=None, **kwargs): ''' Create a new HTTPNotifier :param auth: If given, auth...
import logging import requests from .base import Notifier log = logging.getLogger(__name__) class HTTPNotifier(Notifier): ''' A Notifier that sends http post request to a given url ''' def __init__(self, auth=None, json=True, **kwargs): ''' Create a new HTTPNotifier :param auth: If ...
Add option to send message as json payload in HTTPNotifier
Add option to send message as json payload in HTTPNotifier
Python
mit
fact-project/pycustos
70ee0532f68a08fa12ba7bbfb217273ca8ef7a48
bluesky/tests/test_simulators.py
bluesky/tests/test_simulators.py
from bluesky.plans import scan from bluesky.simulators import print_summary, print_summary_wrapper def test_print_summary(motor_det): motor, det = motor_det print_summary(scan([det], motor, -1, 1, 10)) list(print_summary_wrapper(scan([det], motor, -1, 1, 10)))
from bluesky.plans import scan from bluesky.simulators import print_summary, print_summary_wrapper import pytest def test_print_summary(motor_det): motor, det = motor_det print_summary(scan([det], motor, -1, 1, 10)) list(print_summary_wrapper(scan([det], motor, -1, 1, 10))) def test_old_module_name(motor...
Test that plan_tools import works but warns.
TST: Test that plan_tools import works but warns.
Python
bsd-3-clause
ericdill/bluesky,ericdill/bluesky
b748de5c965219688562819b3cabad1b7ee357d1
ibis/__init__.py
ibis/__init__.py
# Copyright 2014 Cloudera 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, so...
# Copyright 2014 Cloudera 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, so...
Add desc to ibis namespace
Add desc to ibis namespace
Python
apache-2.0
mariusvniekerk/ibis,koverholt/ibis,shaunstanislaus/ibis,deepfield/ibis,Supermem/ibis,o0neup/ibis,ibis-project/ibis,ashhher3/ibis,fivejjs/ibis,Supermem/ibis,koverholt/ibis,cloudera/ibis,laserson/ibis,mahantheshhv/ibis,cloudera/ibis,korotkyn/ibis,Winterflower/ibis,ibis-project/ibis,fivejjs/ibis,adamobeng/ibis,dboyliao/ib...
e43c03fbb04de6ef067a22b62ce5c8049020831a
cw_find_the_unique_number.py
cw_find_the_unique_number.py
"""Codewars: Find the unique number 6 kyu URL: https://www.codewars.com/kata/find-the-unique-number-1/ There is an array with some numbers. All numbers are equal except for one. Try to find it! find_uniq([ 1, 1, 1, 2, 1, 1 ]) == 2 find_uniq([ 0, 0, 0.55, 0, 0 ]) == 0.55 It’s guaranteed that array contains more than...
"""Codewars: Find the unique number 6 kyu URL: https://www.codewars.com/kata/find-the-unique-number-1/ There is an array with some numbers. All numbers are equal except for one. Try to find it! find_uniq([ 1, 1, 1, 2, 1, 1 ]) == 2 find_uniq([ 0, 0, 0.55, 0, 0 ]) == 0.55 It's guaranteed that array contains more than...
Complete dict sol w/ time/space complexity
Complete dict sol w/ time/space complexity
Python
bsd-2-clause
bowen0701/algorithms_data_structures
9ca11ae97ac21d6525da853c9ec3e8007939d187
Lib/xml/__init__.py
Lib/xml/__init__.py
"""Core XML support for Python. This package contains three sub-packages: dom -- The W3C Document Object Model. This supports DOM Level 1 + Namespaces. parsers -- Python wrappers for XML parsers (currently only supports Expat). sax -- The Simple API for XML, developed by XML-Dev, led by David Meggins...
"""Core XML support for Python. This package contains three sub-packages: dom -- The W3C Document Object Model. This supports DOM Level 1 + Namespaces. parsers -- Python wrappers for XML parsers (currently only supports Expat). sax -- The Simple API for XML, developed by XML-Dev, led by David Meggins...
Use Guido's trick for always extracting the version number from a CVS Revision string correctly, even under -kv.
Use Guido's trick for always extracting the version number from a CVS Revision string correctly, even under -kv.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
2b1cc5b2426994953e8f8b937364d91f4e7aadf2
MyHub/MyHub/urls.py
MyHub/MyHub/urls.py
from django.conf.urls import patterns, include, url from MyHub.home.views import home_page from MyHub.resume.views import resume_page from MyHub.projects.views import projects_page from MyHub.contact.views import contact_page from MyHub.views import loader_page from django.contrib import admin from django.conf import s...
from django.conf.urls import patterns, include, url from MyHub.home.views import home_page from MyHub.resume.views import resume_page from MyHub.projects.views import projects_page from MyHub.contact.views import contact_page from MyHub.views import loader_page from django.contrib import admin from django.conf import s...
Change default URL to display home content. Temporary fix.
Change default URL to display home content. Temporary fix.
Python
mit
sebastienbarbier/sebastienbarbier.com,sebastienbarbier/sebastienbarbier.com,sebastienbarbier/sebastienbarbier.com,sebastienbarbier/sebastienbarbier.com
d0651d590f558f69f2c09230daf59336ac3f6406
molo/core/api/constants.py
molo/core/api/constants.py
from collections import namedtuple CONTENT_TYPES = [ ("core.ArticlePage", "Article"), ("core.SectionPage", "Section"), ] ENDPOINTS = [ ("page", "api/v1/pages") ] SESSION_VARS = namedtuple( "SESSION_VARS", ["first", "second", ] ) ARTICLE_SESSION_VARS = SESSION_VARS( first=("url", "content_typ...
from collections import namedtuple CONTENT_TYPES = [ ("core.ArticlePage", "Article"), ("core.SectionPage", "Section"), ] ENDPOINTS = [ ("page", "api/v1/pages") ] SESSION_VARS = namedtuple( "SESSION_VARS", ["first", "second", ] ) ARTICLE_SESSION_VARS = SESSION_VARS( first=("url", "article_con...
Change article session variable names
Change article session variable names
Python
bsd-2-clause
praekelt/molo,praekelt/molo,praekelt/molo,praekelt/molo
46f3067650001454ed99351cc5569813a378dcec
mopidy_jukebox/frontend.py
mopidy_jukebox/frontend.py
import pykka from mopidy import core class JukeboxFrontend(pykka.ThreadingActor, core.CoreListener): def __init__(self, config, core): super(JukeboxFrontend, self).__init__() self.core = core def track_playback_ended(self, tl_track, time_position): # Remove old votes pass ...
import pykka from mopidy import core from models import Vote class JukeboxFrontend(pykka.ThreadingActor, core.CoreListener): def __init__(self, config, core): super(JukeboxFrontend, self).__init__() self.core = core core.tracklist.set_consume(True) def track_playback_ended(self, tl_...
Delete votes when track is over.
Delete votes when track is over.
Python
mit
qurben/mopidy-jukebox,qurben/mopidy-jukebox,qurben/mopidy-jukebox
a56b69ef48acb0badf04625650dfdc25d1517a81
resdk/tests/functional/resolwe/e2e_resolwe.py
resdk/tests/functional/resolwe/e2e_resolwe.py
# pylint: disable=missing-docstring from resdk.tests.functional.base import BaseResdkFunctionalTest class TestDataUsage(BaseResdkFunctionalTest): expected_fields = { 'user_id', 'username', 'full_name', 'data_size', 'data_size_normalized', 'data_count', 'dat...
# pylint: disable=missing-docstring from resdk.tests.functional.base import BaseResdkFunctionalTest class TestDataUsage(BaseResdkFunctionalTest): expected_fields = { 'user_id', 'username', 'full_name', 'data_size', 'data_size_normalized', 'data_count', 'dat...
Support collection statistics in data usage tests
Support collection statistics in data usage tests
Python
apache-2.0
genialis/resolwe-bio-py
3956293089e500ef1f7d665bc3fcf45706fc5d6b
kombu_fernet/serializers/__init__.py
kombu_fernet/serializers/__init__.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import import os from cryptography.fernet import Fernet, InvalidToken fernet = Fernet(os.environ['KOMBU_FERNET_KEY']) def fernet_encode(func): def inner(message): return fernet.encrypt(func(message)) return inner def fernet_de...
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import import os from cryptography.fernet import Fernet, InvalidToken fernet = Fernet(os.environ['KOMBU_FERNET_KEY']) fallback_fernet = None try: fallback_fernet = Fernet(os.environ['OLD_KOMBU_FERNET_KEY']) except KeyError: pass def f...
Add ability to in-place rotate fernet key.
Add ability to in-place rotate fernet key.
Python
mit
heroku/kombu-fernet-serializers
212b5a126e464ff46e60e00846bbb87a2de3fbb2
seleniumbase/config/proxy_list.py
seleniumbase/config/proxy_list.py
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:po...
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:po...
Update the sample proxy list
Update the sample proxy list
Python
mit
mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase
b0ef175fbf5e71c0dbfa8761b5b01b1bc4ff171d
seleniumbase/config/proxy_list.py
seleniumbase/config/proxy_list.py
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:po...
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:po...
Update the example proxy list
Update the example proxy list
Python
mit
mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase
d88c1221e2d07b300f29ef2605acea18c9e7fbf2
test/tiny.py
test/tiny.py
from mpipe import OrderedStage, Pipeline def increment(value): return value + 1 def double(value): return value * 2 stage1 = OrderedStage(increment, 3) stage2 = OrderedStage(double, 3) stage1.link(stage2) pipe = Pipeline(stage1) for number in range(10): pipe.put(number) pipe.put(None) for result in pip...
from mpipe import OrderedStage, Pipeline def increment(value): return value + 1 def double(value): return value * 2 stage1 = OrderedStage(increment, 3) stage2 = OrderedStage(double, 3) pipe = Pipeline(stage1.link(stage2)) for number in range(10): pipe.put(number) pipe.put(None) for result in pipe.resu...
Use multi-link pipeline construction syntax.
Use multi-link pipeline construction syntax.
Python
mit
vmlaker/mpipe