commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13
values | lang stringclasses 23
values |
|---|---|---|---|---|---|---|---|---|
f84ff2febb7dc027ffa0c34e91e2e733380eb903 | Rename --build to --preprocess for consistency and obviousness. | grow/pygrow,grow/grow,grow/grow,codedcolors/pygrow,codedcolors/pygrow,codedcolors/pygrow,grow/pygrow,denmojo/pygrow,denmojo/pygrow,grow/grow,denmojo/pygrow,grow/grow,grow/pygrow,denmojo/pygrow | grow/commands/deploy.py | grow/commands/deploy.py | from grow.common import utils
from grow.deployments.destinations import base
from grow.deployments.stats import stats
from grow.pods import pods
from grow.pods import storage
import click
import os
@click.command()
@click.argument('deployment_name', required=False, default='default')
@click.argument('pod_path', defau... | from grow.common import utils
from grow.deployments.destinations import base
from grow.deployments.stats import stats
from grow.pods import pods
from grow.pods import storage
import click
import os
@click.command()
@click.argument('deployment_name')
@click.argument('pod_path', default='.')
@click.option('--build/--no... | mit | Python |
5c53b58d31e81bebfc3cf094a83da5c6fa2a257a | Remove useless import | alkadis/vcv,liqd/adhocracy,DanielNeugebauer/adhocracy,phihag/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,liqd/adhocracy,DanielNeugebauer/adhocracy,alkadis/vcv,liqd/adhocracy,phihag/adhocracy,DanielNeugebauer/adhocracy,liqd/adhocracy,alkadis/vcv,phihag/adhocracy,phihag/adhocra... | src/adhocracy/migration/versions/069_optional_attributes_text.py | src/adhocracy/migration/versions/069_optional_attributes_text.py | from sqlalchemy import MetaData, Table
from sqlalchemy.types import TEXT
def upgrade(migrate_engine):
meta = MetaData(bind=migrate_engine)
table = Table('user', meta, autoload=True)
col = table.c.optional_attributes
if col.type != TEXT:
col.alter(type=TEXT)
| from sqlalchemy import MetaData, Table, Column
from sqlalchemy.types import TEXT
def upgrade(migrate_engine):
meta = MetaData(bind=migrate_engine)
table = Table('user', meta, autoload=True)
col = table.c.optional_attributes
if col.type != TEXT:
col.alter(type=TEXT)
| agpl-3.0 | Python |
fbcfe69270498eb64050245253b477cc5d88c0d4 | Bump minor version | prkumar/uplink | uplink/__about__.py | uplink/__about__.py | """
This module is the single source of truth for any package metadata
that is used both in distribution (i.e., setup.py) and within the
codebase.
"""
__version__ = "0.7.0"
| """
This module is the single source of truth for any package metadata
that is used both in distribution (i.e., setup.py) and within the
codebase.
"""
__version__ = "0.6.1"
| mit | Python |
aa937bd3414481998e522832336ab618a8cf756d | fix authorized sha csrf (#6434) | hail-is/hail,danking/hail,cseed/hail,danking/hail,danking/hail,hail-is/hail,danking/hail,danking/hail,hail-is/hail,cseed/hail,hail-is/hail,cseed/hail,hail-is/hail,danking/hail,danking/hail,cseed/hail,hail-is/hail,cseed/hail,hail-is/hail,danking/hail,cseed/hail,cseed/hail,hail-is/hail,cseed/hail | hailjwt/hailjwt/csrf.py | hailjwt/hailjwt/csrf.py | import secrets
import logging
from functools import wraps
from aiohttp import web
log = logging.getLogger('hailjwt')
def new_csrf_token():
return secrets.token_urlsafe(64)
def check_csrf_token(fun):
@wraps(fun)
async def wrapped(request, *args, **kwargs):
token1 = request.cookies.get('_csrf')
... | import secrets
import logging
from functools import wraps
from aiohttp import web
log = logging.getLogger('hailjwt')
def new_csrf_token():
return secrets.token_urlsafe(64)
def check_csrf_token(fun):
@wraps(fun)
async def wrapped(request, *args, **kwargs):
token1 = request.cookies.get('_csrf')
... | mit | Python |
3e9297e692a7fb7e5b283eb5208765036afcb1d2 | fix csrf session deleted bug | limodou/uliweb,wwfifi/uliweb,limodou/uliweb,wwfifi/uliweb,wwfifi/uliweb,wwfifi/uliweb,limodou/uliweb,limodou/uliweb | uliweb/contrib/csrf/__init__.py | uliweb/contrib/csrf/__init__.py | import time
import uuid
from werkzeug.exceptions import Forbidden
def csrf_token():
"""
Get csrf token or create new one
"""
from uliweb import request, settings
from uliweb.utils.common import safe_str
v = {}
token_name = settings.CSRF.cookie_token_name
if not request.session.dele... | import time
import uuid
from werkzeug.exceptions import Forbidden
def csrf_token():
"""
Get csrf token or create new one
"""
from uliweb import request, settings
from uliweb.utils.common import safe_str
v = {}
token_name = settings.CSRF.cookie_token_name
if request.session.get(toke... | bsd-2-clause | Python |
9b475f092e23870ae5573ea2b914c990013d7ea4 | Fix broken test due to change in function name | YunoHost/moulinette | test/test_actionsmap.py | test/test_actionsmap.py | import pytest
from moulinette.actionsmap import (
CommentParameter,
AskParameter,
PatternParameter,
RequiredParameter,
ActionsMap
)
from moulinette.interfaces import BaseActionsMapParser
from moulinette.core import MoulinetteError
@pytest.fixture
def iface():
return 'iface'
def test_comment... | import pytest
from moulinette.actionsmap import (
CommentParameter,
AskParameter,
PatternParameter,
RequiredParameter,
ActionsMap
)
from moulinette.interfaces import BaseActionsMapParser
from moulinette.core import MoulinetteError
@pytest.fixture
def iface():
return 'iface'
def test_comment... | agpl-3.0 | Python |
d62b271b65be3a2348289aba9730f77ec32cda55 | remove stuff | noisyboiler/wampy | test/test_app_runner.py | test/test_app_runner.py | import datetime
import pytest
from wampy.cli.run import run
from wampy.peers.clients import Client
from wampy.roles.callee import callee
from wampy.roles.subscriber import subscribe
class DateService(Client):
@callee
def get_todays_date(self):
return datetime.date.today().isoformat()
class Subscr... | import datetime
import pytest
from wampy.cli.run import run
from wampy.peers.clients import Client
from wampy.roles.callee import callee
from wampy.roles.subscriber import subscribe
class DateService(Client):
@callee
def get_todays_date(self):
return datetime.date.today().isoformat()
class Subscr... | mpl-2.0 | Python |
21b9863674a6bd5ab06b6343037ae0a3a807ebf1 | Fix if statement UserPaginator.page_range | proevo/pythondotorg,Mariatta/pythondotorg,proevo/pythondotorg,manhhomienbienthuy/pythondotorg,python/pythondotorg,python/pythondotorg,Mariatta/pythondotorg,proevo/pythondotorg,proevo/pythondotorg,python/pythondotorg,manhhomienbienthuy/pythondotorg,Mariatta/pythondotorg,manhhomienbienthuy/pythondotorg,Mariatta/pythondot... | users/paginators.py | users/paginators.py | from django.core.paginator import Paginator
class UserPaginator(Paginator):
def __init__(self, object_list, per_page, orphans=0, allow_empty_first_page=True):
super().__init__(object_list, per_page, orphans, allow_empty_first_page)
self._current_page = 1
self._page_range_size = 10
de... | from django.core.paginator import Paginator
class UserPaginator(Paginator):
def __init__(self, object_list, per_page, orphans=0, allow_empty_first_page=True):
super().__init__(object_list, per_page, orphans, allow_empty_first_page)
self._current_page = 1
self._page_range_size = 10
de... | apache-2.0 | Python |
2a42b84f027be2b68d2f5e9928bc9b9ceea524c8 | Bump development version | nephila/djangocms-blog,skirsdeda/djangocms-blog,skirsdeda/djangocms-blog,skirsdeda/djangocms-blog,nephila/djangocms-blog,nephila/djangocms-blog | djangocms_blog/__init__.py | djangocms_blog/__init__.py | # -*- coding: utf-8 -*-
__author__ = 'Iacopo Spalletti'
__email__ = 'i.spalletti@nephila.it'
__version__ = '0.6.1.post1'
default_app_config = 'djangocms_blog.apps.BlogAppConfig'
| # -*- coding: utf-8 -*-
__author__ = 'Iacopo Spalletti'
__email__ = 'i.spalletti@nephila.it'
__version__ = '0.6.1'
default_app_config = 'djangocms_blog.apps.BlogAppConfig'
| bsd-3-clause | Python |
9afaf43ff0972dad18caae3717963ba738c366e0 | Use a regular expression to try to detect unresolved links. | stweil/documentation-generator,nickanderson/documentation-generator,nickanderson/documentation-generator,cfengine/documentation-generator,stweil/documentation-generator,stweil/documentation-generator,cfengine/documentation-generator,michaelclelland/documentation-generator,stweil/documentation-generator,cfengine/documen... | _scripts/cfdoc_sourcelinks.py | _scripts/cfdoc_sourcelinks.py | # The MIT License (MIT)
#
# Copyright (c) 2013 CFEngine AS
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modif... | # The MIT License (MIT)
#
# Copyright (c) 2013 CFEngine AS
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modif... | mit | Python |
36c539a9c53b888b799b2a406211d84bb963ea5b | fix credential check | ThreatResponse/aws_ir-api | api/app.py | api/app.py |
import os
import requests
import json
from chalice import Chalice
from chalicelib import credential
#The aws_ir modules we need to drive the API
#key compromise plugins
from chalicelib.aws_ir.aws_ir.plugins import gather_host
#from aws_ir.plugins import revokests_key
#host compromise plugins
from chalicelib.aws_ir.... |
import os
import requests
import json
from chalice import Chalice
from chalicelib import credential
#The aws_ir modules we need to drive the API
#key compromise plugins
from chalicelib.aws_ir.aws_ir.plugins import gather_host
#from aws_ir.plugins import revokests_key
#host compromise plugins
from chalicelib.aws_ir.... | mit | Python |
4a0cf8e608dae8220020d17daf6a24d5602eec15 | Disable builtin 'autolink' feature | xuanhan863/zulip,umkay/zulip,mahim97/zulip,jeffcao/zulip,bssrdf/zulip,Frouk/zulip,sup95/zulip,synicalsyntax/zulip,kou/zulip,qq1012803704/zulip,zhaoweigg/zulip,KingxBanana/zulip,easyfmxu/zulip,LAndreas/zulip,adnanh/zulip,brockwhittaker/zulip,ashwinirudrappa/zulip,KingxBanana/zulip,saitodisse/zulip,MariaFaBella85/zulip,P... | zephyr/lib/bugdown/__init__.py | zephyr/lib/bugdown/__init__.py | import re
import markdown
from zephyr.lib.avatar import gravatar_hash
from zephyr.lib.bugdown import codehilite
class Gravatar(markdown.inlinepatterns.Pattern):
def handleMatch(self, match):
img = markdown.util.etree.Element('img')
img.set('class', 'message_body_gravatar img-rounded')
img... | import re
import markdown
from zephyr.lib.avatar import gravatar_hash
from zephyr.lib.bugdown import codehilite
class Gravatar(markdown.inlinepatterns.Pattern):
def handleMatch(self, match):
img = markdown.util.etree.Element('img')
img.set('class', 'message_body_gravatar img-rounded')
img... | apache-2.0 | Python |
38e65570aec40bfe5dd7fb6ffedb25abe8b85b88 | Use Python 3 syntax for typing in heroku/view.py. | shubhamdhama/zulip,timabbott/zulip,dhcrzf/zulip,kou/zulip,tommyip/zulip,eeshangarg/zulip,mahim97/zulip,punchagan/zulip,kou/zulip,jackrzhang/zulip,rht/zulip,kou/zulip,rishig/zulip,hackerkid/zulip,shubhamdhama/zulip,zulip/zulip,shubhamdhama/zulip,hackerkid/zulip,synicalsyntax/zulip,rishig/zulip,rishig/zulip,punchagan/zul... | zerver/webhooks/heroku/view.py | zerver/webhooks/heroku/view.py | # Webhooks for external integrations.
from typing import Text
from django.http import HttpRequest, HttpResponse
from zerver.decorator import api_key_only_webhook_view
from zerver.lib.actions import check_send_stream_message
from zerver.lib.request import REQ, has_request_variables
from zerver.lib.response import json... | # Webhooks for external integrations.
from typing import Text
from django.http import HttpRequest, HttpResponse
from zerver.decorator import api_key_only_webhook_view
from zerver.lib.actions import check_send_stream_message
from zerver.lib.request import REQ, has_request_variables
from zerver.lib.response import json... | apache-2.0 | Python |
cf510db518e1d1cf8759648f2440486f958bda20 | debug == True | InfoAgeTech/django-activities,InfoAgeTech/django-activities,InfoAgeTech/django-activities | tests/settings.py | tests/settings.py | from __future__ import unicode_literals
import os
import sys
NOTIFICATION_MODEL_MIXIN = 'test_models.AbstractNotificationMixin'
NOTIFICATION_MANAGER = 'test_models.managers.NotificationManager'
NOTIFICATIONS_BASE_TEMPLATE = 'base_notifications.html'
DEBUG = True
# Local time zone for this installation. Choices can... | # -*- coding: utf-8 -*-
import os
import sys
NOTIFICATION_MODEL_MIXIN = 'test_models.AbstractNotificationMixin'
NOTIFICATION_MANAGER = 'test_models.managers.NotificationManager'
NOTIFICATIONS_BASE_TEMPLATE = 'base_notifications.html'
# Do not run in DEBUG in production!!!
DEBUG = False
# Local time zone for this ins... | mit | Python |
806a82f2190449ba7b31dc063881d2ddb68c961c | Fix test_naive_bayes_sql test. | marinkaz/orange3,qPCR4vir/orange3,kwikadi/orange3,qPCR4vir/orange3,marinkaz/orange3,kwikadi/orange3,cheral/orange3,marinkaz/orange3,kwikadi/orange3,cheral/orange3,kwikadi/orange3,cheral/orange3,cheral/orange3,marinkaz/orange3,qPCR4vir/orange3,kwikadi/orange3,kwikadi/orange3,cheral/orange3,cheral/orange3,qPCR4vir/orange... | Orange/tests/sql/test_naive_bayes_sql.py | Orange/tests/sql/test_naive_bayes_sql.py | import unittest
from numpy import array
import Orange.classification.naive_bayes as nb
from Orange import preprocess
from Orange.data.sql.table import SqlTable
from Orange.data import Domain
from Orange.data.variable import DiscreteVariable
from Orange.tests.sql.base import sql_test, connection_params
@sql_test
cla... | import unittest
from numpy import array
import Orange.classification.naive_bayes as nb
from Orange import preprocess
from Orange.data.sql.table import SqlTable
from Orange.data import Domain
from Orange.data.variable import DiscreteVariable
from Orange.tests.sql.base import sql_test
@sql_test
class NaiveBayesTest(u... | bsd-2-clause | Python |
25160e42fa223b175bdeb3343bc3b5871039bc98 | Set `DEFAULT_PAGINATION_CLASS` in `tests.settings` to silence `rest_framework.W001` warning | AltSchool/dynamic-rest,AltSchool/dynamic-rest | tests/settings.py | tests/settings.py | import os
BASE_DIR = os.path.dirname(__file__)
SECRET_KEY = "test"
INSTALL_DIR = "/usr/local/altschool/dynamic-rest/"
STATIC_URL = "/static/"
STATIC_ROOT = os.environ.get("STATIC_ROOT", INSTALL_DIR + "www/static")
ENABLE_INTEGRATION_TESTS = os.environ.get("ENABLE_INTEGRATION_TESTS", False)
DEBUG = True
DATABASES ... | import os
BASE_DIR = os.path.dirname(__file__)
SECRET_KEY = 'test'
INSTALL_DIR = '/usr/local/altschool/dynamic-rest/'
STATIC_URL = '/static/'
STATIC_ROOT = os.environ.get('STATIC_ROOT', INSTALL_DIR + 'www/static')
ENABLE_INTEGRATION_TESTS = os.environ.get('ENABLE_INTEGRATION_TESTS', False)
DEBUG = True
DATABASES ... | mit | Python |
f3c1e5bdf25b46e96a77221ace7438eb3b55cb05 | Make loop a little more readable | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle | bluebottle/common/management/commands/makemessages.py | bluebottle/common/management/commands/makemessages.py | import json
import codecs
import tempfile
from django.core.management.commands.makemessages import Command as BaseCommand
class Command(BaseCommand):
""" Extend the makemessages to include some of the fixtures """
fixtures = [
('bb_projects', 'project_data.json'),
('bb_tasks', 'skills.json'),... | import json
import codecs
import tempfile
from django.core.management.commands.makemessages import Command as BaseCommand
class Command(BaseCommand):
""" Extend the makemessages to include some of the fixtures """
fixtures = [
('bb_projects', 'project_data.json'),
('bb_tasks', 'skills.json'),... | bsd-3-clause | Python |
2531d68c7747d1ae5aeac56609842888fe815263 | Add test case for applying change | PyCQA/isort,PyCQA/isort | tests/test_api.py | tests/test_api.py | """Tests the isort API module"""
from unittest.mock import MagicMock, patch
import pytest
from isort import api, exceptions
def test_sort_file(tmpdir) -> None:
tmp_file = tmpdir.join(f"test_bad_syntax.py")
tmp_file.write_text("""print('mismathing quotes")""", "utf8")
with pytest.warns(UserWarning):
... | """Tests the isort API module"""
import pytest
from isort import api, exceptions
def test_sort_file(tmpdir) -> None:
tmp_file = tmpdir.join(f"test_bad_syntax.py")
tmp_file.write_text("""print('mismathing quotes")""", "utf8")
with pytest.warns(UserWarning):
api.sort_file(tmp_file, atomic=True)
... | mit | Python |
ecc56eec0ebee4a93d5052280ae5d8c649e1e6da | Refactor api test to setup test client in setup +review PLAT-127 DCORE-1109 | bradsokol/PyLCP,Points/PyLCP,bradsokol/PyLCP,Points/PyLCP | tests/test_api.py | tests/test_api.py | from nose.tools import eq_
import mock
from lcp import api
class TestApiClient(object):
def setup(self):
self.client = api.Client('BASE_URL')
def test_request_does_not_alter_absolute_urls(self):
for absolute_url in [
'http://www.points.com',
'https://www.point... | from nose.tools import eq_
import mock
from lcp import api
@mock.patch('lcp.api.requests.request')
def _assert_calls_requests_with_url(original_url, expected_url, request_mock):
api.Client('BASE_URL').request('METHOD', original_url)
expected_headers = {'Content-Type': 'application/json'}
eq_(request_mock... | bsd-3-clause | Python |
7bdfb1ef77d23bc868434e8d74d6184dd68c0a6e | Improve API test by only comparing args and varargs. | ahri/pycurlbrowser | tests/test_api.py | tests/test_api.py | # coding: utf-8
"""
Test the backend API
Written so that after creating a new backend, you can immediately see which
parts are missing!
"""
from unittest import TestCase
import inspect
from pycurlbrowser.backend import *
from pycurlbrowser import Browser
def is_http_backend_derived(t):
if t is HttpBackend:
... | # coding: utf-8
"""
Test the backend API
Written so that after creating a new backend, you can immediately see which
parts are missing!
"""
from unittest import TestCase
import inspect
from pycurlbrowser.backend import *
from pycurlbrowser import Browser
def is_http_backend_derived(t):
if t is HttpBackend:
... | agpl-3.0 | Python |
85fde7413ed1377a3a9b65e80830edc48a48964f | fix trying to del dir with unlink | obestwalter/i3configger | tests/test_cli.py | tests/test_cli.py | import subprocess
from contextlib import suppress
import pytest
from i3configger import exc, watch, config
class Runner:
COMMAND_NAME = "i3configger"
def __init__(self, cwd):
self.cwd = cwd
def __call__(self, args=None, otherCwd=None):
cmd = [self.COMMAND_NAME]
if args:
... | import subprocess
from contextlib import suppress
import pytest
from i3configger import exc, watch, config
class Runner:
COMMAND_NAME = "i3configger"
def __init__(self, cwd):
self.cwd = cwd
def __call__(self, args=None, otherCwd=None):
cmd = [self.COMMAND_NAME]
if args:
... | mit | Python |
916900aaa29c5a59bcdd78ca05069ea431629de4 | Fix error message for initdb test | SCUEvals/scuevals-api,SCUEvals/scuevals-api | tests/test_cmd.py | tests/test_cmd.py | import unittest
from click.testing import CliRunner
from scuevals_api.cmd import cli
class CmdsTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.runner = CliRunner()
def cli_run(self, *cmds):
return self.runner.invoke(cli, cmds)
cls.cli_run = cli_run
... | import unittest
from click.testing import CliRunner
from scuevals_api.cmd import cli
class CmdsTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.runner = CliRunner()
def cli_run(self, *cmds):
return self.runner.invoke(cli, cmds)
cls.cli_run = cli_run
... | agpl-3.0 | Python |
cfaaf421bb9627f1741a9ef4074517fd5daaec86 | Use meinheld worker (same as other Python Frameworks) | torhve/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,denkab/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,grob/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,jetty-project/FrameworkBenchmark... | wsgi/setup.py | wsgi/setup.py |
import subprocess
import sys
import setup_util
import os
def start(args):
subprocess.Popen('gunicorn hello:app --worker-class="egg:meinheld#gunicorn_worker" -b 0.0.0.0:8080 -w '
+ str((args.max_threads * 2)) + " --log-level=critical", shell=True, cwd="wsgi")
return 0
def stop():
p = subproces... |
import subprocess
import sys
import setup_util
import os
def start(args):
subprocess.Popen("gunicorn hello:app -b 0.0.0.0:8080 -w " + str((args.max_threads * 2)) + " --log-level=critical", shell=True, cwd="wsgi")
return 0
def stop():
p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
out, err = p.com... | bsd-3-clause | Python |
e7c62838aabdda98b8f6aca38f45571d8ed05377 | Add new tests | sorgerlab/bioagents,bgyori/bioagents | tests/tra_test.py | tests/tra_test.py | from bioagents.trips.kqml_list import KQMLList
from bioagents.tra import tra_module
def test_get_time_interval_full():
ts = '(:lower-bound 2 :upper-bound 4 :unit "hour")'
lst = KQMLList.from_string(ts)
ti = tra_module.get_time_interval(lst)
def test_get_time_interval_ub():
ts = '(:upper-bound 4 :unit ... | from bioagents.trips.kqml_list import KQMLList
from bioagents.tra import tra_module
def test_get_time_interval_full():
ts = '(:lower-bound 2 :upper-bound 4 :unit "hour")'
lst = KQMLList.from_string(ts)
ti = tra_module.get_time_interval(lst)
def test_get_time_interval_ub():
ts = '(:upper-bound 4 :unit ... | bsd-2-clause | Python |
a07237029325c1336a38aac00ab8085272ba69cd | Remove logging module. | lmjohns3/cube-experiment,lmjohns3/cube-experiment,lmjohns3/cube-experiment | vizard/configure.py | vizard/configure.py | #!/usr/bin/env python
import sys
import viz
import vizshape
import viztask
import suit
import targets
import vrlab
M = [13, 12, 11, 10]
TRACKER = None
def workflow():
vrlab.sounds.cowbell.play()
yield viztask.waitTime(5)
for target in targets.NUMBERED:
if True:# target.center == (0, 0, 0):
... | #!/usr/bin/env python
import logging
import sys
import viz
import vizshape
import viztask
import suit
import targets
import vrlab
M = [13, 12, 11, 10]
TRACKER = None
def workflow():
vrlab.sounds.cowbell.play()
yield viztask.waitTime(5)
for target in targets.NUMBERED:
if True:# target.center == ... | mit | Python |
6f2f4f84a4182b16bc40d16e4a0b159b835028fc | hide "branches" in try_efficiency | ahal/active-data-recipes,ahal/active-data-recipes | adr/recipes/try_efficiency.py | adr/recipes/try_efficiency.py | """
Prints information on try effifiency. This is a measure of how effective try is
at preventing backouts. It is roughly:
1000000 / (total_compute_hours_on_try * backout_rate)
.. code-block:: bash
adr try_efficiency
`View Results <https://mozilla.github.io/active-data-recipes/#try-efficiency>`_
"""
from __... | """
Prints information on try effifiency. This is a measure of how effective try is
at preventing backouts. It is roughly:
1000000 / (total_compute_hours_on_try * backout_rate)
.. code-block:: bash
adr try_efficiency
`View Results <https://mozilla.github.io/active-data-recipes/#try-efficiency>`_
"""
from __... | mpl-2.0 | Python |
d4ed1cff368e135dc9f55298391649eb30128452 | rewrite in a more pythonic way using map | henry808/euler | 006/eul006.py | 006/eul006.py | #! /usr/bin/python
from __future__ import print_function
def sqr(x):
return x ** 2
def sum_squares(n):
return (sum(map(sqr, range(1, n + 1))))
# sum1 = 0
# for i in range(1, n + 1):
# sum1 += i**2
# return sum1
if __name__ == '__main__':
print(sum_squares(10))
| #! /usr/bin/python
from __future__ import print_function
def sum_squares(n):
sum1 = 0
for i in range(1, n + 1):
sum1 += i**2
return sum1
if __name__ == '__main__':
print(sum_squares(10))
| mit | Python |
9f56693ad4b7d517fc0db20cfc291116e91d646f | Add documentation for CloudXNS | jsha/letsencrypt,lmcro/letsencrypt,letsencrypt/letsencrypt,letsencrypt/letsencrypt,stweil/letsencrypt,stweil/letsencrypt,jsha/letsencrypt,lmcro/letsencrypt | certbot-dns-cloudxns/certbot_dns_cloudxns/__init__.py | certbot-dns-cloudxns/certbot_dns_cloudxns/__init__.py | """
The `~certbot_dns_cloudxns.dns_cloudxns` plugin automates the process of
completing a ``dns-01`` challenge (`~acme.challenges.DNS01`) by creating, and
subsequently removing, TXT records using the CloudXNS API.
Named Arguments
---------------
======================================== =============================... | """CloudXNS DNS Authenticator"""
| apache-2.0 | Python |
1d4777f810388ee87cceb01c2b53367723fb3a71 | Add a function to retrieve roles from reactions | linsalrob/PyFBA | PyFBA/cmd/__init__.py | PyFBA/cmd/__init__.py | from .citation import cite_me_please
from .fluxes import measure_fluxes
from .gapfill_from_roles import gapfill_from_roles
from .assigned_functions_to_reactions import to_reactions
from .fba_from_reactions import run_the_fba
from .gapfill_from_reactions_multiple_conditions import gapfill_multiple_media
from .media impo... | from .citation import cite_me_please
from .fluxes import measure_fluxes
from .gapfill_from_roles import gapfill_from_roles
from .assigned_functions_to_reactions import to_reactions
from .fba_from_reactions import run_the_fba
from .gapfill_from_reactions_multiple_conditions import gapfill_multiple_media
from .media impo... | mit | Python |
c315c19825d6a798bb58b2d8af8289b036cf121b | Fix session | yshalenyk/databridge | databridge/contrib/storage.py | databridge/contrib/storage.py | import couchdbreq
import requests
from requests.adapters import HTTPAdapter
from databridge.helpers import create_db_url
class Storage(object):
def __init__(self, config, session=None, adapter=None):
if not isinstance(config, dict):
raise TypeError(
"Expected a dict as config,... | import couchdbreq
import requests
from requests.adapters import HTTPAdapter
from databridge.helpers import create_db_url
class Storage(object):
def __init__(self, config, session=None, adapter=None):
if not isinstance(config, dict):
raise TypeError(
"Expected a dict as config,... | apache-2.0 | Python |
6cb7d654c391e41060fdda3319ad6870cafad5df | Add docstring to uncompress() | ronrest/convenience_py,ronrest/convenience_py | convenience/file_convenience/uncompress.py | convenience/file_convenience/uncompress.py |
# ==============================================================================
# UNCOMPRESS
# ==============================================================================
def uncompress(file, method="tar"):
"""
Uncompress packaged files s... |
def uncompress(file, method="tar"):
#TODO: Add an output dir option.
if method == "tar":
import tarfile
with tarfile.open(filename) as fileObj:
#sys.stdout.flush()
fileObj.extractall()
| apache-2.0 | Python |
05ced3dbc01e6f99c6033f3414810ec48a03824a | update description with example of using projectmap config section | wakatime/wakatime,prashanthr/wakatime,Djabbz/wakatime,wakatime/wakatime,gandarez/wakatime,wakatime/wakatime,Djabbz/wakatime,queenp/wakatime,wakatime/wakatime,wakatime/wakatime,wakatime/wakatime,wangjun/wakatime,wakatime/wakatime,wakatime/wakatime,wakatime/wakatime,wakatime/wakatime,wakatime/wakatime,Djabbz/wakatime,gan... | wakatime/projects/projectmap.py | wakatime/projects/projectmap.py | # -*- coding: utf-8 -*-
"""
wakatime.projects.projectmap
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Use the ~/.wakatime.cfg file to set custom project names by
recursively matching folder paths.
Project maps go under the [projectmap] config section.
For example:
[projectmap]
/home/user/proj... | # -*- coding: utf-8 -*-
"""
wakatime.projects.projectmap
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Use the ~/.wakatime.cfg file to define custom projects for folders.
:copyright: (c) 2013 Alan Hamlett.
:license: BSD, see LICENSE for more details.
"""
import logging
import os
from .base import BaseProject
l... | bsd-3-clause | Python |
6fd7f3cb01f621d2ea79e15188f8000c7b6fa361 | Remove code specific to my system | Mause/autobit | tools/add_feed.py | tools/add_feed.py | import os
from autobit import Client
def main():
client = Client('http://localhost:8081/gui/', auth=('admin', '20133'))
client.get_torrents()
name = input('name> ')
directory = input('directory> ')
os.makedirs(directory, exist_ok=True)
client.add_feed(
name,
input('url> '),... | import os
from urllib.parse import urlencode, quote
from autobit import Client
def add_rarbg_feed(client, name, directory, filter_kwargs):
url = 'http://localhost:5555/{}?{}'.format(
quote(name),
urlencode(filter_kwargs)
)
return client.add_feed(name, url, directory)
def main():
cl... | mit | Python |
894203d67e88e8bac8ec4f8948d940789387b648 | Add all blank parameters to sample question | sherlocke/pywatson | tests/data/questions.py | tests/data/questions.py | QUESTIONS = [
{
'questionText': 'What is the Labour Code?'
},
{
'questionText': 'When can a union start a strike?',
'items': 0,
'evidenceRequest': {
'items': 0,
'profile': ''
},
'answerAssertion': '',
'category': '',
'co... | QUESTIONS = [
{
'questionText': 'What is the Labour Code?'
},
{
'questionText': 'When can a union start a strike?'
}
]
| mit | Python |
660c275acaef9e5eadd0dbac7eaf8bd5f503c0cf | Fix bad path import on urls.py | diegojromerolopez/django-async-include,diegojromerolopez/django-async-include | async_include/urls.py | async_include/urls.py | # -*- coding: utf-8 -*-
from django.conf.urls import url, include
from async_include import views
urlpatterns = [
# Load
url(r'^get/?$', views.get_template, name="get_template"),
] | # -*- coding: utf-8 -*-
from django.conf.urls import url, include
from djangotrellostats.apps.async_include import views
urlpatterns = [
# Load
url(r'^get/?$', views.get_template, name="get_template"),
] | mit | Python |
2be37b18cde36e96314a51cbce0cdef1e67f0915 | add common interface to wblogin module | ResolveWang/WeiboSpider,ResolveWang/WeiboSpider | wblogin/__init__.py | wblogin/__init__.py | from .login import get_session
from .cookies_gen import get_sub_and_subp
| from .login import get_session
| mit | Python |
6d41ae34126b0f5c76e75bd3c27e94fd9fede010 | Add get_latest_build helper | jleclanche/pywow,jleclanche/pywow,jleclanche/pywow,jleclanche/pywow,jleclanche/pywow,jleclanche/pywow | wdbc/environment.py | wdbc/environment.py | # -*- coding: utf-8 -*-
import os
from .utils import getfilename, fopen
DEFAULT_CACHE_DIR = "/var/www/sigrie/caches/"
class BaseLookup(list):
"""
List class that will standardize the name
and return a list of matches on getitem.
"""
def __contains__(self, item):
return getfilename(item) in [getfilename(k) f... | # -*- coding: utf-8 -*-
import os
from .utils import getfilename, fopen
DEFAULT_CACHE_DIR = "/var/www/sigrie/caches/"
class BaseLookup(list):
"""
List class that will standardize the name
and return a list of matches on getitem.
"""
def __contains__(self, item):
return getfilename(item) in [getfilename(k) f... | cc0-1.0 | Python |
0bbffbd5de2fd7f053ac38e920954c68bd500646 | add get_user_process_list | kisom/py-rouletted | roulette.py | roulette.py | import random
import subprocess
import sys
def die(errstr):
if errstr:
sys.stderr.write("%s\n" % errstr)
sys.exit(1)
# uses who and uniq to grab a unique user list. optionally, pass in a list of sysadmins
# to not kill. note this only kills users logged in interactively, which is the point
# of this ... | import random
import subprocess
import sys
# uses who and uniq to grab a unique user list. optionally, pass in a list of sysadmins
# to not kill. note this only kills users logged in interactively, which is the point
# of this little game.
def get_random_user(exclude_list = None):
command = "who | awk '{ print $1... | isc | Python |
eda64ca6218b29a8f576b628e81d3ebe607b069a | Update VMwareGuestToolsURLProvider.py | autopkg/rtrouton-recipes,autopkg/rtrouton-recipes | VMware-Tools/VMwareGuestToolsURLProvider.py | VMware-Tools/VMwareGuestToolsURLProvider.py | #!/usr/bin/env python
import re
from xml.dom.minidom import parse, parseString
import urllib2
from autopkglib import Processor, ProcessorError
__all__ = ["VMwareGuestToolsURLProvider"]
FUSION_URL_BASE = 'http://softwareupdate.vmware.com/cds/vmw-desktop/'
DARWIN_TOOLS_URL_APPEND = 'packages/com.vmware.fusion.tools.d... | #!/usr/bin/env python
import re
from xml.dom.minidom import parse, parseString
import urllib2
from autopkglib import Processor, ProcessorError
__all__ = ["VMwareGuestToolsURLProvider"]
FUSION_URL_BASE = 'http://softwareupdate.vmware.com/cds/vmw-desktop/'
DARWIN_TOOLS_URL_APPEND = 'packages/com.vmware.fusion.tools.d... | mit | Python |
eb4aa3107446d8f932dc4deac2562306ebf3d257 | Repair nuke.workio | getavalon/core,mindbender-studio/core,mindbender-studio/core,getavalon/core | avalon/nuke/workio.py | avalon/nuke/workio.py | """Host API required by Work Files tool"""
import os
import nuke
def file_extensions():
return [".nk"]
def has_unsaved_changes():
return nuke.Root().modified()
def save(filepath):
nuke.scriptSaveAs(filepath)
def open(filepath):
nuke.scriptClear()
nuke.scriptOpen(filepath)
return True
d... | """Host API required by Work Files tool"""
import os
import nuke
def file_extensions():
return [".nk"]
def has_unsaved_changes():
return nuke.Root().modified()
def save(filepath):
nuke.scriptSaveAs(filepath)
def open(filepath):
nuke.scriptClear()
nuke.scriptOpen(filepath)
return True
d... | mit | Python |
57183893d57f04cad3ac90f4fb38dd885a5dbfe4 | Refactor send_queued_mail lockfile parameters | JostCrow/django-post_office,RafRaf/django-post_office,yprez/django-post_office,ui/django-post_office,fapelhanz/django-post_office,CasherWest/django-post_office,CasherWest/django-post_office,carrerasrodrigo/django-post_office,LeGast00n/django-post_office,ui/django-post_office,ekohl/django-post_office,jrief/django-post_o... | post_office/management/commands/send_queued_mail.py | post_office/management/commands/send_queued_mail.py | import tempfile
import sys
from optparse import make_option
from django.core.management.base import BaseCommand
from ...lockfile import FileLock
from ...mail import send_queued
from ...logutils import setup_loghandlers
logger = setup_loghandlers()
default_lockfile = tempfile.gettempdir() + "/post_office"
class Co... | import os
import tempfile
import sys
from optparse import make_option
from django.core.management.base import BaseCommand
from ...lockfile import FileLock
from ...mail import send_queued
from ...logutils import setup_loghandlers
logger = setup_loghandlers()
class Command(BaseCommand):
option_list = BaseComma... | mit | Python |
a540a998f96dd8a5ed0900c96279882b87f7aef9 | Add a test for adding a timedelta to a DistantDate. | jwg4/qual,jwg4/calexicon | calexicon/dates/tests/test_distant.py | calexicon/dates/tests/test_distant.py | import unittest
from datetime import date as vanilla_date, timedelta
from calexicon.calendars import ProlepticJulianCalendar
from calexicon.dates import DateWithCalendar, DistantDate
class TestDistantDate(unittest.TestCase):
def test_subtraction(self):
dd = DistantDate(10000, 1, 1)
self.assertIs... | import unittest
from datetime import date as vanilla_date, timedelta
from calexicon.calendars import ProlepticJulianCalendar
from calexicon.dates import DateWithCalendar, DistantDate
class TestDistantDate(unittest.TestCase):
def test_subtraction(self):
dd = DistantDate(10000, 1, 1)
self.assertIs... | apache-2.0 | Python |
d5fbf27335a9df265b8151425e88e311333f176c | Fix test | recognai/spaCy,explosion/spaCy,spacy-io/spaCy,recognai/spaCy,honnibal/spaCy,honnibal/spaCy,honnibal/spaCy,explosion/spaCy,recognai/spaCy,spacy-io/spaCy,spacy-io/spaCy,aikramer2/spaCy,explosion/spaCy,aikramer2/spaCy,recognai/spaCy,explosion/spaCy,aikramer2/spaCy,aikramer2/spaCy,spacy-io/spaCy,spacy-io/spaCy,aikramer2/sp... | spacy/tests/lang/en/test_tagger.py | spacy/tests/lang/en/test_tagger.py | # coding: utf-8
from __future__ import unicode_literals
from ....parts_of_speech import SPACE
from ...util import get_doc
import six
import pytest
def test_en_tagger_load_morph_exc(en_tokenizer):
text = "I like his style."
tags = ['PRP', 'VBP', 'PRP$', 'NN', '.']
morph_exc = {'VBP': {'like': {'L': 'luck... | # coding: utf-8
from __future__ import unicode_literals
from ....parts_of_speech import SPACE
from ...util import get_doc
import six
import pytest
def test_en_tagger_load_morph_exc(en_tokenizer):
text = "I like his style."
tags = ['PRP', 'VBP', 'PRP$', 'NN', '.']
morph_exc = {'VBP': {'like': {'L': 'luck... | mit | Python |
24a13a002c2a06b7c958cd325141ed0b3c150f7a | fix error message formatting. closes #515 (credits duelafn) | JohnHowland/kivy,ernstp/kivy,mSenyor/kivy,akshayaurora/kivy,angryrancor/kivy,hansent/kivy,eHealthAfrica/kivy,angryrancor/kivy,edubrunaldi/kivy,rafalo1333/kivy,el-ethan/kivy,arcticshores/kivy,youprofit/kivy,bliz937/kivy,vitorio/kivy,matham/kivy,inclement/kivy,KeyWeeUsr/kivy,autosportlabs/kivy,matham/kivy,andnovar/kivy,b... | kivy/core/image/img_pygame.py | kivy/core/image/img_pygame.py | '''
Pygame: Pygame image loader
'''
__all__ = ('ImageLoaderPygame', )
from kivy.logger import Logger
from kivy.core.image import ImageLoaderBase, ImageData, ImageLoader
try:
import pygame
except:
raise
class ImageLoaderPygame(ImageLoaderBase):
'''Image loader based on PIL library'''
@staticmethod
... | '''
Pygame: Pygame image loader
'''
__all__ = ('ImageLoaderPygame', )
from kivy.logger import Logger
from kivy.core.image import ImageLoaderBase, ImageData, ImageLoader
try:
import pygame
except:
raise
class ImageLoaderPygame(ImageLoaderBase):
'''Image loader based on PIL library'''
@staticmethod
... | mit | Python |
210d9929c42ea5c1fdd4f0bee25d14f4bd61c1c1 | Refactor and document datacite XML functions | arpitar/osf.io,asanfilippo7/osf.io,GaryKriebel/osf.io,crcresearch/osf.io,brianjgeiger/osf.io,mluo613/osf.io,jeffreyliu3230/osf.io,jinluyuan/osf.io,chrisseto/osf.io,TomHeatwole/osf.io,samchrisinger/osf.io,HalcyonChimera/osf.io,dplorimer/osf,mluke93/osf.io,hmoco/osf.io,kwierman/osf.io,aaxelb/osf.io,acshi/osf.io,binocular... | website/identifiers/metadata.py | website/identifiers/metadata.py | # -*- coding: utf-8 -*-
import lxml.etree
import lxml.builder
NAMESPACE = 'http://datacite.org/schema/kernel-3'
XSI = 'http://www.w3.org/2001/XMLSchema-instance'
SCHEMA_LOCATION = 'http://datacite.org/schema/kernel-3 http://schema.datacite.org/meta/kernel-3/metadata.xsd'
E = lxml.builder.ElementMaker(nsmap={
None:... | # -*- coding: utf-8 -*-
import lxml.etree
import lxml.builder
NAMESPACE = 'http://datacite.org/schema/kernel-3'
XSI = 'http://www.w3.org/2001/XMLSchema-instance'
SCHEMA_LOCATION = 'http://datacite.org/schema/kernel-3 http://schema.datacite.org/meta/kernel-3/metadata.xsd'
E = lxml.builder.ElementMaker(nsmap={
None:... | apache-2.0 | Python |
111d0bd356c18d0c028c73cd8c84c9d3e3ae591c | Fix ASDF tag test helper to load schemas correctly | pllim/astropy,astropy/astropy,lpsinger/astropy,larrybradley/astropy,StuartLittlefair/astropy,mhvk/astropy,pllim/astropy,MSeifert04/astropy,saimn/astropy,dhomeier/astropy,lpsinger/astropy,pllim/astropy,stargaser/astropy,larrybradley/astropy,larrybradley/astropy,bsipocz/astropy,StuartLittlefair/astropy,astropy/astropy,dh... | astropy/io/misc/asdf/tags/tests/helpers.py | astropy/io/misc/asdf/tags/tests/helpers.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-
import os
import urllib.parse
import urllib.request
import yaml
import numpy as np
def run_schema_example_test(organization, standard, name, version, check_func=None):
import asdf
from asdf.tests import helpers
from... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-
import os
import urllib.parse
import yaml
import numpy as np
def run_schema_example_test(organization, standard, name, version, check_func=None):
import asdf
from asdf.tests import helpers
from asdf.types import for... | bsd-3-clause | Python |
026fc35ce6986337a7b451c3fceedecaf1871e1b | Add url edit | openego/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform | tutorials/urls.py | tutorials/urls.py | from django.conf.urls import include, url
from tutorials import views
urlpatterns = [
url(r'^$', views.ListTutorials.as_view()),
url(r'add/', views.NewTutorial.as_view(), name='add_tutorial'),
url(r'(?P<tutorial_id>[\w\-]+)/edit/', views.EditTutorials.as_view(), name='edit_tutorial'),
# This must be ... | from django.conf.urls import include, url
from tutorials import views
urlpatterns = [
url(r'^$', views.ListTutorials.as_view()),
url(r'add/', views.NewTutorial.as_view(), name='add_tutorial'),
# This must be last, otherwise it will match anything
url(r'^(?P<tutorial_id>[\w\-]+)/$', views.TutorialDeta... | agpl-3.0 | Python |
79c7cc00e626c2dd98297814b068bb1d6c738a69 | make sure min_level is valid | alessandrod/twiggy,alessandrod/twiggy | twiggy/Emitter.py | twiggy/Emitter.py | import Levels
import re
__re_type = type(re.compile('foo')) # XXX is there a canonical place for this?
def msgFilter(x):
"""return a function suitable for use as a filter with emitters.
You may pass:
:None, True: the filter will always return True
:False: the filter will always return False
:st... | import re
__re_type = type(re.compile('foo')) # XXX is there a canonical place for this?
def msgFilter(x):
"""return a function suitable for use as a filter with emitters.
You may pass:
:None, True: the filter will always return True
:False: the filter will always return False
:string: compiled ... | bsd-3-clause | Python |
e2f1787601e7c05c9c5ab2efe26b6d1cb90b2ccb | Fix plugin permission data migration | mociepka/saleor,mociepka/saleor,mociepka/saleor | saleor/account/migrations/0040_auto_20200415_0443.py | saleor/account/migrations/0040_auto_20200415_0443.py | # Generated by Django 3.0.5 on 2020-04-15 09:43
from django.db import migrations
def change_extension_permission_to_plugin_permission(apps, schema_editor):
permission = apps.get_model("auth", "Permission")
users = apps.get_model("account", "User")
service_account = apps.get_model("account", "ServiceAccou... | # Generated by Django 3.0.5 on 2020-04-15 09:43
from django.db import migrations
def change_extension_permission_to_plugin_permission(apps, schema_editor):
permission = apps.get_model("auth", "Permission")
users = apps.get_model("account", "User")
plugin_permission = permission.objects.filter(
c... | bsd-3-clause | Python |
e2d171b6b0d6eaba04169b626d9f6ac9269d3bc5 | Move the recv call to the bottom of the iterator loop so that it really has no lag. | hugovk/twitter,adonoho/twitter,miragshin/twitter,Adai0808/twitter,jessamynsmith/twitter,sixohsix/twitter,tytek2012/twitter | twitter/stream.py | twitter/stream.py | try:
import urllib.request as urllib_request
import urllib.error as urllib_error
import io
except ImportError:
import urllib2 as urllib_request
import urllib2 as urllib_error
import json
from .api import TwitterCall, wrap_response
class TwitterJSONIter(object):
def __init__(self, handle, uri,... | try:
import urllib.request as urllib_request
import urllib.error as urllib_error
import io
except ImportError:
import urllib2 as urllib_request
import urllib2 as urllib_error
import json
from .api import TwitterCall, wrap_response
class TwitterJSONIter(object):
def __init__(self, handle, uri,... | mit | Python |
03e0e11491c64ae546134eb6c963a31958fe6d6d | Add `add_group` method to `AddressBook` class - to make it possible to add groups to the address book | dizpers/python-address-book-assignment | address_book/address_book.py | address_book/address_book.py | from person import Person
__all__ = ['AddressBook']
class AddressBook(object):
def __init__(self):
self.persons = []
self.groups = []
def add_person(self, person):
self.persons.append(person)
def add_group(self, group):
self.groups.append(group)
def __contains__(se... | from person import Person
__all__ = ['AddressBook']
class AddressBook(object):
def __init__(self):
self.persons = []
def add_person(self, person):
self.persons.append(person)
def __contains__(self, item):
if isinstance(item, Person):
return item in self.persons
... | mit | Python |
7e76e22705ed491cbc11b174f5d6c2cf265e029b | Make test_pep8 ignore template files (and make it conform PEP8 ;) ) | SysTheron/adhocracy,alkadis/vcv,liqd/adhocracy,alkadis/vcv,phihag/adhocracy,liqd/adhocracy,DanielNeugebauer/adhocracy,liqd/adhocracy,DanielNeugebauer/adhocracy,DanielNeugebauer/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,DanielNeugebauer/adhocracy,phihag/adhocracy,alkadis/vcv,phihag/adhocracy,phihag/adhocracy,SysT... | adhocracy/tests/test_pep8.py | adhocracy/tests/test_pep8.py | #!/usr/bin/env python
import os.path
import unittest
import pep8
SRC_PATH = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
EXCLUDE = ['.svn', 'CVS', '.bzr', '.hg', '.git',
'Paste-1.7.5.1-py2.6.egg', 'PasteDeploy-1.5.0-py2.6.egg', 'data']
class AdhocracyStyleGuide(pep8.StyleGuide):
def i... | #!/usr/bin/env python
import os.path
import unittest
import pep8
SRC_PATH = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
class AdhocracyStyleGuide(pep8.StyleGuide):
def ignore_code(self, code):
IGNORED = [
'E111', # indentation is not a multiple of four
'E121', # c... | agpl-3.0 | Python |
c281493ab6d7caab1feaa30369a5cd3508502ccd | remove superfluous test | ethereum/pyrlp,ethereum/pyrlp | tests/test_bytearray.py | tests/test_bytearray.py | # -*- coding: utf8 -*-
from rlp import (
encode,
decode,
decode_lazy,
)
from rlp.utils import str_to_bytes
def test_bytearray():
e = encode('abc')
expected = decode(e)
actual = decode(bytearray(e))
assert actual == expected
def test_bytearray_lazy():
e = encode('abc')
expected = ... | # -*- coding: utf8 -*-
from eth_utils import (
encode_hex,
decode_hex,
)
from rlp import (
encode,
decode,
decode_lazy,
)
from rlp.utils import str_to_bytes
def test_bytearray():
e = encode('abc')
expected = decode(e)
actual = decode(bytearray(e))
assert actual == expected
def t... | mit | Python |
72466cb328fb56bfe28f5c3a1f8fca082db24319 | Clean exports from typer, remove unneeded Click components, add needed ones | tiangolo/typer,tiangolo/typer | typer/__init__.py | typer/__init__.py | """Typer, build great CLIs. Easy to code. Based on Python type hints."""
__version__ = "0.0.4"
from click.exceptions import Abort, Exit # noqa
from click.termui import ( # noqa
clear,
confirm,
echo_via_pager,
edit,
get_terminal_size,
getchar,
launch,
pause,
progressbar,
promp... | """Typer, build great CLIs. Easy to code. Based on Python type hints."""
__version__ = "0.0.4"
from click.exceptions import ( # noqa
Abort,
BadArgumentUsage,
BadOptionUsage,
BadParameter,
ClickException,
FileError,
MissingParameter,
NoSuchOption,
UsageError,
)
from click.termui im... | mit | Python |
fb9aaf3cb0c182463b23692007b2676a028b134d | Prepare version number for next development cycle. | sosy-lab/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,dbeyer/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,dbeyer/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,dbeyer/benchexec,sosy-lab/benchexec | benchexec/__init__.py | benchexec/__init__.py | # This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
"""Main package of BenchExec.
The following modules are the public entry points:
- benche... | # This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
"""Main package of BenchExec.
The following modules are the public entry points:
- benche... | apache-2.0 | Python |
4b2b388aca80e22ec8b1036d4638b6dda3539793 | Update P05_textMyself fixed depreciated class | JoseALermaIII/python-tutorials,JoseALermaIII/python-tutorials | books/AutomateTheBoringStuffWithPython/Chapter16/P05_textMyself.py | books/AutomateTheBoringStuffWithPython/Chapter16/P05_textMyself.py | #! python3
# P05_textMyself.py - Defines the textmyself() function that texts a message
# passed to it as a string.
from twilio.rest import Client
# Preset values:
with open('twilio_info') as config:
accountSID, authToken, twilioNumber, myNumber = config.read().splitlines()
def textmyself(message):
twilioCl... | #! python3
# P05_textMyself.py - Defines the textmyself() function that texts a message
# passed to it as a string.
from twilio.rest import TwilioRestClient
# Preset values:
with open('twilio_info') as config:
accountSID, authToken, twilioNumber, myNumber = config.read().splitlines()
def textmyself(message):
... | mit | Python |
ed5107f15a7ef159c1e4429d28f4dd505b3fef1e | Remove useless signal 'login_done'. | knipknap/exscript,maximumG/exscript,knipknap/exscript,maximumG/exscript | src/Exscript/TerminalActions/Authenticate.py | src/Exscript/TerminalActions/Authenticate.py | # Copyright (C) 2007 Samuel Abels, http://debain.org
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOU... | # Copyright (C) 2007 Samuel Abels, http://debain.org
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOU... | mit | Python |
70320094cf2eb424b60e1a5da360a58582a5cd73 | Remove comment | ava-project/AVA | ava/ava.py | ava/ava.py | from os import path
from .components import ComponentManager
from .input import Input
from .dispatcher import Dispatcher
from .builtin_runner import BuiltinRunner
from .plugins import PluginInvoker, PluginManager
from .speech_to_text import SpeechToText
from .text_to_speech import TextToSpeech
from .input import Input
... | from os import path
from .components import ComponentManager
from .input import Input
from .dispatcher import Dispatcher
from .builtin_runner import BuiltinRunner
from .plugins import PluginInvoker, PluginManager
from .speech_to_text import SpeechToText
from .text_to_speech import TextToSpeech
from .input import Input
... | mit | Python |
a9f4a1d8a3fa1bf4ffae0260f93d41fd09409579 | fix website url in manifest | OCA/account-invoicing,OCA/account-invoicing | account_invoice_check_total/__manifest__.py | account_invoice_check_total/__manifest__.py | # -*- coding: utf-8 -*-
# Copyright 2016 Acsone SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': 'Account Invoice Check Total',
'summary': """
Check if the verification total is equal to the bill's total""",
'version': '10.0.1.0.0',
'license': 'AGPL-3',
'autho... | # -*- coding: utf-8 -*-
# Copyright 2016 Acsone SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': 'Account Invoice Check Total',
'summary': """
Check if the verification total is equal to the bill's total""",
'version': '10.0.1.0.0',
'license': 'AGPL-3',
'autho... | agpl-3.0 | Python |
b8afd9f7f5832d39b737d15a75789e7d1271d21c | include assert true | geoscixyz/em_examples | tests/test_notebooks.py | tests/test_notebooks.py | import unittest
import sys
import os
import subprocess
# Testing for the notebooks - use nbconvert to execute all cells of the
# notebook
TestDir = os.path.abspath('../') # where are the notebooks?
def setUp():
nbpaths = [] # list of notebooks, with file paths
nbnames = [] # list of notebook names (for ma... | import unittest
import sys
import os
import subprocess
# Testing for the notebooks - use nbconvert to execute all cells of the
# notebook
TestDir = os.path.abspath('../') # where are the notebooks?
def setUp():
nbpaths = [] # list of notebooks, with file paths
nbnames = [] # list of notebook names (for ma... | mit | Python |
832471701409d19b3786982a9d439a71a5ea3fa2 | add more functionality to the the post admin | texastribune/wjordpress | wjordpress/admin.py | wjordpress/admin.py | from django.contrib import admin
from . import models
class WPSiteAdmin(admin.ModelAdmin):
list_display = ('name', 'url', 'hook')
readonly_fields = ('name', 'description')
def save_model(self, request, obj, form, change):
# TODO do this sync async (give celery another shot?)
obj.save()
... | from django.contrib import admin
from . import models
class WPSiteAdmin(admin.ModelAdmin):
list_display = ('name', 'url', 'hook')
readonly_fields = ('name', 'description')
def save_model(self, request, obj, form, change):
# TODO do this sync async (give celery another shot?)
obj.save()
... | apache-2.0 | Python |
35378da87a60ecfdadad94e2fea74e81c0d28adc | IMPROVE sheet detection | ograndedjogo/tab-translator,ograndedjogo/tab-translator | tests/test_transform.py | tests/test_transform.py | import numpy as np
import cv2
from tabtranslator.transform import order_points, distance, get_target_rectangle_size, resize, detect_englobing_polygon
import pkg_resources as pkg
def test_order_points():
test_case = [(1, 1), (0, 1), (0, 0), (1, 0)]
order = (2, 3, 0, 1)
__assert_points_order(test_case, order... | import numpy as np
import cv2
from tabtranslator.transform import order_points, distance, get_target_rectangle_size, resize, detect_englobing_polygon
import pkg_resources as pkg
def test_order_points():
test_case = [(1, 1), (0, 1), (0, 0), (1, 0)]
order = (2, 3, 0, 1)
__assert_points_order(test_case, order... | mit | Python |
88fcd254e7e005dc7a713c380caae8e416516389 | remove works | AveryPratt/data-structures | src/trie.py | src/trie.py | """Implementation of a trie data structure."""
class Trie(object):
"""A tree data structure...
...that groups related words in branches, which split where they
differ from each other.
insert(self, val):
creates a new branch containing nodes that spell the value
which diverges where the spell... | """Implementation of a trie data structure."""
class Trie(object):
"""A tree data structure that groups related words in branches,
which split where they differ from each other.
insert(self, val):
creates a new branch containing nodes that spell the value
which diverges where the spelling differs... | mit | Python |
a7a7b778eadd1c79148e15f197ab9fe9fe46bc36 | clean up the code in Reader | alphatwirl/alphatwirl,alphatwirl/alphatwirl,alphatwirl/alphatwirl,alphatwirl/alphatwirl | alphatwirl/summary/Reader.py | alphatwirl/summary/Reader.py | # Tai Sakuma <tai.sakuma@gmail.com>
import logging
from .WeightCalculatorOne import WeightCalculatorOne
##__________________________________________________________________||
class Reader(object):
def __init__(self, keyValComposer, summarizer, nextKeyComposer=None,
weightCalculator=WeightCalculat... | # Tai Sakuma <tai.sakuma@gmail.com>
import logging
from .WeightCalculatorOne import WeightCalculatorOne
##__________________________________________________________________||
class Reader(object):
def __init__(self, keyValComposer, summarizer, nextKeyComposer=None,
weightCalculator=WeightCalculat... | bsd-3-clause | Python |
81679d7401031a3d4bfc24e2e2799b24cecbc444 | add tests for UpdateItem | scylladb/scylla,scylladb/scylla,avikivity/scylla,avikivity/scylla,avikivity/scylla,scylladb/scylla,scylladb/scylla | alternator-test/test_item.py | alternator-test/test_item.py | # Tests for the CRUD item operations: PutItem, GetItem, UpdateItem, DeleteItem
import random
import string
import pytest
from botocore.exceptions import ClientError
def random_string(len=10, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for x in range(len))
# Basic test for ... | # Tests for the CRUD item operations: PutItem, GetItem, UpdateItem, DeleteItem
import random
import string
import pytest
from botocore.exceptions import ClientError
def random_string(len=10, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for x in range(len))
# Basic test for ... | agpl-3.0 | Python |
6a9c85010bfe82292f1b6c4a52f83a7a26b63eb2 | Modify viewsets to add some documentation | Desenho-2-2017/Ecom_merci,Desenho-2-2017/Ecom_merci,Desenho-2-2017/Ecom_merci,Desenho-2-2017/Ecom_merci | users/viewsets.py | users/viewsets.py | from rest_framework.viewsets import ModelViewSet
from .models import (
CustomerUser,
PhoneNumber,
CreditCard,
ShippingAddress
)
from .serializers import (
# CustomerUserSerializer,
PhoneNumberSerializer,
CreditCardSerializer,
ShippingAddressSerializer,
CustomerUserSerializerDefau... | from rest_framework.viewsets import ModelViewSet
from .models import (
CustomerUser,
PhoneNumber,
CreditCard,
ShippingAddress
)
from .serializers import (
CustomerUserSerializer,
PhoneNumberSerializer,
CreditCardSerializer,
ShippingAddressSerializer
)
class CustomerUserViewSet(... | mit | Python |
6709944d7e856fbce0434da0dc731fc83b55feb1 | Extend integration test to check correctness of dumped json data | hackebrot/cibopath | tests/test_cli_update.py | tests/test_cli_update.py | # -*- coding: utf-8 -*-
import pathlib
import json
def test_store_template_data_to_json(cli_runner, tmp_rc, tmp_templates_file):
result = cli_runner([
'-c', tmp_rc, 'update'
])
assert result.exit_code == 0
templates = pathlib.Path(tmp_templates_file)
assert templates.exists()
with ... | # -*- coding: utf-8 -*-
import pathlib
def test_should_write_json(cli_runner, tmp_rc, tmp_templates_file):
result = cli_runner([
'-c', tmp_rc, 'update'
])
assert result.exit_code == 0
templates = pathlib.Path(tmp_templates_file)
assert templates.exists()
| bsd-3-clause | Python |
497da856fc1caf0c44ca639126391d295b0fc39d | Update LogPrinterTest.py | CruiseDevice/coala,Tanmay28/coala,shreyans800755/coala,NiklasMM/coala,refeed/coala,vinc456/coala,incorrectusername/coala,impmihai/coala,svsn2117/coala,arafsheikh/coala,AbdealiJK/coala,Tanmay28/coala,tltuan/coala,MariosPanag/coala,dagdaggo/coala,refeed/coala,coala-analyzer/coala,jayvdb/coala,AbdealiJK/coala,SanketDG/coa... | coalib/tests/output/LogPrinterTest.py | coalib/tests/output/LogPrinterTest.py | """
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT... | """
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT... | agpl-3.0 | Python |
9ee1db76af2a1afdf59bf9099008715d9bca2f4d | Make sure getting buckets and checking for their presence work. | kgaughan/bukkit | tests/test_collection.py | tests/test_collection.py | from bukkit import Collection
def test_creation():
buckets = Collection(rate=5, limit=23, timeout=31, clock=lambda: 0)
assert buckets.rate == 5
assert buckets.limit == 23
assert buckets.timeout == 31
assert buckets.head_node.prev_node is buckets.tail_node
assert buckets.tail_node.next_node is ... | from bukkit import Collection
def test_creation():
buckets = Collection(rate=5, limit=23, timeout=31, clock=lambda: 0)
assert buckets.rate == 5
assert buckets.limit == 23
assert buckets.timeout == 31
assert buckets.head_node.prev_node is buckets.tail_node
assert buckets.tail_node.next_node is ... | mit | Python |
7e4ff6e6b5b12083a3d2b0637ee9f038308b4d5a | Add an applyOperation method to Selection | onitake/Uranium,onitake/Uranium | UM/Scene/Selection.py | UM/Scene/Selection.py | from UM.Signal import Signal
from UM.Math.Vector import Vector
class Selection:
@classmethod
def add(cls, object):
if not object in cls.__selection:
cls.__selection.append(object)
cls.selectionChanged.emit()
@classmethod
def remove(cls, object):
if object in cls... | from UM.Signal import Signal
from UM.Math.Vector import Vector
class Selection:
@classmethod
def add(cls, object):
if not object in cls.__selection:
cls.__selection.append(object)
cls.selectionChanged.emit()
@classmethod
def remove(cls, object):
if object in cls... | agpl-3.0 | Python |
e33ce1d121bd9283209df0197af7fb1eb1458a49 | add test for bug issue #16 | codeforamerica/straymapper,codeforamerica/straymapper,codeforamerica/straymapper | animals/tests.py | animals/tests.py | from datetime import datetime
from django.core.urlresolvers import reverse
from django.test import TestCase
from animals.models import Animal
class AnimalsViewsTestCase(TestCase):
def test_index(self):
resp = self.client.get(reverse('animals_index'))
self.assertEqual(resp.status_code, 200)
... | from django.core.urlresolvers import reverse
from django.test import TestCase
class AnimalsViewsTestCase(TestCase):
def test_index(self):
resp = self.client.get(reverse('animals_index'))
self.assertEqual(resp.status_code, 200)
self.assertTrue('form' in resp.context)
self.assertTrue... | bsd-3-clause | Python |
929bc230ecaa3214698955cca5f8b06b216cb8e2 | Fix load vectors | spacy-io/thinc,spacy-io/thinc,spacy-io/thinc,explosion/thinc,explosion/thinc,explosion/thinc,explosion/thinc | thinc/extra/load_nlp.py | thinc/extra/load_nlp.py | import numpy
SPACY_MODELS = {}
VECTORS = {}
def get_spacy(lang, **kwargs):
global SPACY_MODELS
import spacy
if lang not in SPACY_MODELS:
SPACY_MODELS[lang] = spacy.load(lang, **kwargs)
return SPACY_MODELS[lang]
def get_vectors(ops, lang):
global VECTORS
key = (ops.device, lang)
... | import numpy
SPACY_MODELS = {}
VECTORS = {}
def get_spacy(lang, **kwargs):
global SPACY_MODELS
import spacy
if lang not in SPACY_MODELS:
SPACY_MODELS[lang] = spacy.load(lang, **kwargs)
return SPACY_MODELS[lang]
def get_vectors(ops, lang):
global VECTORS
key = (ops.device, lang)
... | mit | Python |
bbe6a682ae9c05e7821e52e47373406565034b1d | Update applications/apps.py | hackupc/backend,hackupc/backend,hackupc/backend,hackupc/backend | applications/apps.py | applications/apps.py | from __future__ import unicode_literals
from django.apps import AppConfig
class ApplicationsConfig(AppConfig):
name = 'applications'
def ready(self):
super(ApplicationsConfig, self).ready()
from .signals import clean_draft_application
clean_draft_application
| from __future__ import unicode_literals
from django.apps import AppConfig
class ApplicationsConfig(AppConfig):
name = 'applications'
def ready(self):
super(ApplicationsConfig, self).ready()
from .signals import clean_draftapplication
clean_draft_application
| mit | Python |
b8002f5ec0650e29ecbda920e16a9868c8e819eb | Revert "conf/setup-environment.d: Enable meta-rust-bin" | UpdateHub/meta-updatehub,UpdateHub/meta-updatehub,UpdateHub/meta-updatehub | conf/setup-environment.d/updatehub.py | conf/setup-environment.d/updatehub.py | def __after_init_updatehub():
PLATFORM_ROOT_DIR = os.environ['PLATFORM_ROOT_DIR']
append_layers([ os.path.join(PLATFORM_ROOT_DIR, 'sources', p) for p in
[
'meta-openembedded/meta-networking',
'meta-openembedded/meta-oe',
... | def __after_init_updatehub():
PLATFORM_ROOT_DIR = os.environ['PLATFORM_ROOT_DIR']
append_layers([ os.path.join(PLATFORM_ROOT_DIR, 'sources', p) for p in
[
'meta-openembedded/meta-networking',
'meta-openembedded/meta-oe',
... | mit | Python |
80c4b0fe0a654ef4ec56faac73af993408b846f1 | Add first test for a good response | nbeck90/network_tools | test_client.py | test_client.py | from client import client
import pytest
def test_response_ok():
msg = "GET /path/to/myindex.html HTTP/1.1\r\nHost: localhost:50000\r\n"
result = "HTTP/1.1 200 OK\r\n"
con_type = "Content-Type: text/plain\r\n"
body = "Content length: {}".format(21)
# Length of message from file name to end of line
... | from client import client
import pytest
def test_string_input():
assert client("String") == "You sent: String"
def test_int_input():
assert client(42) == "You sent: 42"
def test_empty_input():
with pytest.raises(TypeError):
client()
def test_over32_input():
assert client("A long message ... | mit | Python |
b32e59b51f9ed14ebee1230b44b6f90a975b699f | Update test_get_config | Springerle/cookiecutter,takeflight/cookiecutter,michaeljoseph/cookiecutter,benthomasson/cookiecutter,audreyr/cookiecutter,moi65/cookiecutter,cguardia/cookiecutter,stevepiercy/cookiecutter,christabor/cookiecutter,agconti/cookiecutter,benthomasson/cookiecutter,hackebrot/cookiecutter,hackebrot/cookiecutter,moi65/cookiecut... | tests/test_get_config.py | tests/test_get_config.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_get_config
---------------
Tests formerly known from a unittest residing in test_config.py named
TestGetConfig.test_get_config
TestGetConfig.test_get_config_does_not_exist
TestGetConfig.test_invalid_config
TestGetConfigWithDefaults.test_get_config_with_defaults
"... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_get_config
---------------
Tests formerly known from a unittest residing in test_config.py named
TestGetConfig.test_get_config
TestGetConfig.test_get_config_does_not_exist
TestGetConfig.test_invalid_config
TestGetConfigWithDefaults.test_get_config_with_defaults
"... | bsd-3-clause | Python |
8549b814029ed1770da6a49caf19212407644966 | Test HttpPutMiddleware | jgorset/django-respite,jgorset/django-respite,jgorset/django-respite | tests/test_middleware.py | tests/test_middleware.py | """Tests for respite.middleware."""
from nose.tools import *
from urllib import urlencode
from django.utils import simplejson as json
from django.test.client import Client, RequestFactory
from respite.middleware import *
client = Client()
def test_json_middleware():
response = client.post(
path = '/',... | """Tests for respite.middleware."""
from nose.tools import *
from django.utils import simplejson as json
from django.test.client import Client, RequestFactory
from respite.middleware import JsonMiddleware, HttpMethodOverrideMiddleware
client = Client()
def test_json_middleware():
response = client.post(
... | mit | Python |
61e0e86de4b63201e186085d0d7281677d94b1dd | Simplify resampling test | blackjax-devs/blackjax | tests/test_resampling.py | tests/test_resampling.py | """Test the resampling functions for SMC."""
import chex
import jax
import numpy as np
from absl.testing import absltest, parameterized
import blackjax.smc.resampling as resampling
resampling_methods = {
"systematic": resampling.systematic,
"stratified": resampling.stratified,
"multinomial": resampling.mu... | """Test the resampling functions for SMC."""
import itertools
import chex
import jax
import numpy as np
from absl.testing import absltest, parameterized
import blackjax.smc.resampling as resampling
resampling_methods = {
"systematic": resampling.systematic,
"stratified": resampling.stratified,
"multinomi... | apache-2.0 | Python |
8b4f5eb6b3c491e0561739026e9049995df7a04e | Use HTTPS URL | xtaran/debian-devel-changes-bot,xtaran/debian-devel-changes-bot,sebastinas/debian-devel-changes-bot | DebianDevelChangesBot/datasources/testing_rc_bugs.py | DebianDevelChangesBot/datasources/testing_rc_bugs.py | # -*- coding: utf-8 -*-
#
# Debian Changes Bot
# Copyright (C) 2008 Chris Lamb <chris@chris-lamb.co.uk>
# Copyright (C) 2015 Sebastian Ramacher <sramacher@debian.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# p... | # -*- coding: utf-8 -*-
#
# Debian Changes Bot
# Copyright (C) 2008 Chris Lamb <chris@chris-lamb.co.uk>
# Copyright (C) 2015 Sebastian Ramacher <sramacher@debian.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# p... | agpl-3.0 | Python |
050be98bc0e0b440e0f4899e18624c80b03458cc | Fix for when there is no blog. | codefisher/djangopress,codefisher/djangopress,codefisher/djangopress,codefisher/djangopress | djangopress/blog/templatetags/blog_tags.py | djangopress/blog/templatetags/blog_tags.py | from django import template
from djangopress.blog.models import Entry, Blog, Category
from django.utils import timezone
register = template.Library()
@register.inclusion_tag('blog/show_latest.html')
def show_blog_latest(number=5, words=20, blog=None):
blog = Blog.objects.get(slug=blog)
try:
number = i... | from django import template
from djangopress.blog.models import Entry, Blog, Category
from django.utils import timezone
register = template.Library()
@register.inclusion_tag('blog/show_latest.html')
def show_blog_latest(number=5, words=20, blog=None):
blog = Blog.objects.get(slug=blog)
try:
number = i... | mit | Python |
edf16b8e2cee47de1039b816b230225a78c897ae | Edit the output of the script to match the code (#25855) | ray-project/ray,ray-project/ray,ray-project/ray,ray-project/ray,ray-project/ray,ray-project/ray,ray-project/ray,ray-project/ray | doc/source/ray-core/doc_code/actor-sync.py | doc/source/ray-core/doc_code/actor-sync.py | import asyncio
import ray
# We set num_cpus to zero because this actor will mostly just block on I/O.
@ray.remote(num_cpus=0)
class SignalActor:
def __init__(self):
self.ready_event = asyncio.Event()
def send(self, clear=False):
self.ready_event.set()
if clear:
self.ready... | import asyncio
import ray
# We set num_cpus to zero because this actor will mostly just block on I/O.
@ray.remote(num_cpus=0)
class SignalActor:
def __init__(self):
self.ready_event = asyncio.Event()
def send(self, clear=False):
self.ready_event.set()
if clear:
self.ready... | apache-2.0 | Python |
41082ad96a9ecd1e01ed55d3a51b2d4c81ef8ed5 | clean code | ljean/coop_cms,ljean/coop_cms,ljean/coop_cms | coop_cms/ci/semaphore_project/urls.py | coop_cms/ci/semaphore_project/urls.py | # -*- coding: utf-8 -*-
"""urls"""
from __future__ import unicode_literals
import sys
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.staticfiles.views import serve as serve_static
from django.views.static import serve as serve_media
fr... | # -*- coding: utf-8 -*-
"""urls"""
from __future__ import unicode_literals
import sys
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.staticfiles.views import serve as serve_static
from django.views.static import serve as serve_media
fr... | bsd-3-clause | Python |
a26effb7a26439a2dfc8df0ec59d1d0e952152b7 | Fix typo in function restart of class NginxLB | openstack/akanda-appliance,stackforge/akanda-appliance,openstack/akanda-appliance,stackforge/akanda-appliance | astara_router/drivers/loadbalancer/nginx.py | astara_router/drivers/loadbalancer/nginx.py | # Copyright (c) 2015 Akanda, 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 applicable la... | # Copyright (c) 2015 Akanda, 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 applicable la... | apache-2.0 | Python |
e821343322464d6434cf18a7b39b52b9eab448cf | Improve documentation. | Beskhue/enactive-agents,Beskhue/enactive-agents,Beskhue/enactive-agents | enactiveagents/appstate.py | enactiveagents/appstate.py | """
Module implementing a global application state.
"""
class AppState:
"""
Class to hold the application state.
"""
state = None
running = True
save_simulation_renders = False
t = 0
@staticmethod
def get_state():
"""
Static method to get an application state obje... | """
Module implementing a global application state.
"""
class AppState:
"""
Class to hold the application state.
"""
state = None
running = True
save_simulation_renders = False
t = 0
@staticmethod
def get_state():
"""
Static method to get an application state obje... | mit | Python |
49b5cea13f4df7364d2acebbfbe788d0efa485ab | update vm_deploy_info.py | Interoute/python-rules-the-cloud | vm_deploy_info.py | vm_deploy_info.py | #! /usr/bin/env python
# Python script for the Interoute Virtual Data Centre API:
# Name: vm_deploy_info.py
# Purpose: List information required for deployment of a VM
# Requires: class VDCApiCall in the file vdc_api_call.py
# For download and information:
# http://cloudstore.interoute.com/main/knowledge-centr... | #! /usr/bin/env python
# Python script for the Interoute Virtual Data Centre API:
# Name: vm_deploy_info.py
# Purpose: List information required for deployment of a VM
# Requires: class VDCApiCall in the file vdc_api_call.py
# For download and information:
# http://cloudstore.interoute.com/main/knowledge-centr... | apache-2.0 | Python |
6d6528182eb5dc21f41eb4ea5e4cfd08163edc96 | Simplify state and save server URL | WalkingMachine/sara_behaviors,WalkingMachine/sara_behaviors | sara_flexbe_states/src/sara_flexbe_states/Wonderland_Request.py | sara_flexbe_states/src/sara_flexbe_states/Wonderland_Request.py | #!/usr/bin/env python
# encoding=utf8
import requests
from flexbe_core import EventState, Logger
class Wonderland_Request(EventState):
'''
Send requests to Wonderland server
># url string url to call
<= response string Finish job.
'''
def __init__(self):
# See example_state.py for basic explan... | #!/usr/bin/env python
# encoding=utf8
import requests
from flexbe_core import EventState, Logger
class Wonderland_Request(EventState):
'''
MoveArm receive a ROS pose as input and launch a ROS service with the same pose
># url string url to call
<= response string Finish job.
'''
def __init__(sel... | bsd-3-clause | Python |
01e10343b3db535bfc212363258ef20ef1f69794 | Fix clean_user TelekomLabs-DCO-1.1-Signed-off-by: Łukasz Biernot <lukasz.biernot@gmail.com> (github: ElmoVanKielmo) | litedesk/litedesk-webserver-provision,litedesk/litedesk-webserver-provision | src/tenants/management/commands/clean_user.py | src/tenants/management/commands/clean_user.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2014, Deutsche Telekom AG - Laboratories (T-Labs)
#
# 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/lice... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2014, Deutsche Telekom AG - Laboratories (T-Labs)
#
# 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/lice... | apache-2.0 | Python |
e4750e96fb0884eda1a6cc8904bcd882b5a63ace | add the task full exception | xsank/Pyeventbus,xsank/Pyeventbus | eventbus/exception.py | eventbus/exception.py | __author__ = 'Xsank'
class EventbusException():
'''This is the base exception of the Eventbus.'''
def __str__(self):
return self.__doc__
class EventTypeError(EventbusException):
'''Event type is invalid!'''
class ListenerTypeError(EventbusException):
'''Listener type is invalid!'''
class... | __author__ = 'Xsank'
class EventbusException():
'''This is the base exception of the Eventbus.'''
def __str__(self):
return self.__doc__
class EventTypeError(EventbusException):
'''Event type is invalid!'''
class ListenerTypeError(EventbusException):
'''Listener type is invalid!'''
class... | mit | Python |
be97cb8f258b49633d7250f14fc0beeada058ddc | Use copyright header in version.py | beetbox/audioread | audioread/version.py | audioread/version.py | # This file is part of audioread.
# Copyright 2017, Adrian Sampson.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, co... | #!/usr/bin/env python
'''Version information'''
version = '2.1.5pre'
short_version = '2.1'
| mit | Python |
e524dcac6d15831e87b347f89c796ecbf60ef27f | Fix problem when loading the txt files on windows | foobarmus/autocorrect,phatpiglet/autocorrect | autocorrect/utils.py | autocorrect/utils.py | # Python 3 Spelling Corrector
#
# Copyright 2014 Jonas McCallum.
# Updated for Python 3, based on Peter Norvig's
# 2007 version: http://norvig.com/spell-correct.html
#
# Open source, MIT license
# http://www.opensource.org/licenses/mit-license.php
"""
File reader, concat function and dict wrapper
Author: Jonas McCallu... | # Python 3 Spelling Corrector
#
# Copyright 2014 Jonas McCallum.
# Updated for Python 3, based on Peter Norvig's
# 2007 version: http://norvig.com/spell-correct.html
#
# Open source, MIT license
# http://www.opensource.org/licenses/mit-license.php
"""
File reader, concat function and dict wrapper
Author: Jonas McCallu... | mit | Python |
b9ec0ac6a981bc25baf6eaa4882f7ff115176789 | add multigrad_dict to autograd/__init__.py | HIPS/autograd,hips/autograd,hips/autograd,barak/autograd,kcarnold/autograd,HIPS/autograd | autograd/__init__.py | autograd/__init__.py | from __future__ import absolute_import
from .core import grad, primitive, jacobian
from . import container_types
from .convenience_wrappers import (multigrad, multigrad_dict, elementwise_grad,
value_and_grad, grad_and_aux, hessian_vector_product,
hes... | from __future__ import absolute_import
from .core import grad, primitive, jacobian
from . import container_types
from .convenience_wrappers import (multigrad, elementwise_grad, value_and_grad,
grad_and_aux, hessian_vector_product, hessian)
| mit | Python |
042fddf30345529e2e0db91d17d1a10ad3503169 | update frequency to run remove old blob objects task to every 1 hour | OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft | packages/grid/backend/grid/periodic_tasks.py | packages/grid/backend/grid/periodic_tasks.py | # stdlib
import datetime
# third party
import pytz
# syft absolute
from syft.core.node.common.util import get_s3_client
# grid absolute
from grid.core.celery_app import celery_app
from grid.core.node import node
@celery_app.task
def cleanup_incomplete_uploads_from_blob_store() -> bool:
"""Cleans up incomplete ... | # stdlib
import datetime
# third party
import pytz
# syft absolute
from syft.core.node.common.util import get_s3_client
# grid absolute
from grid.core.celery_app import celery_app
from grid.core.node import node
@celery_app.task
def cleanup_incomplete_uploads_from_blob_store() -> bool:
"""Cleans up incomplete ... | apache-2.0 | Python |
ae30548707a18e9f199af84081f03cf792dce1a4 | Remove project. | Mc01/wgit-py,Mc01/wgit-py | wizards/remove.py | wizards/remove.py | from instruments.arguments import Arguments
from instruments.file import File
from wizards.__wizard import Wizard
class Remove(Wizard):
def call(self, args):
config = self.assert_config()
assume = Arguments.assume(args, 1)
if config and assume:
alias = args[0]
data ... | from wizards.__wizard import Wizard
class Remove(Wizard):
def call(self, args):
pass
| mit | Python |
43748548beba41caa68d4bc92b3638cdeadfec75 | fix the wrong exception type found on testing. | douban/brownant | brownant/dinergate.py | brownant/dinergate.py | from six import with_metaclass
from werkzeug.utils import cached_property
from requests import Session
class DinergateType(type):
"""The metaclass of :class:`~Dinergate` and its subclasses.
This metaclass will give all members are instance of
:class:`~werkzeug.utils.cached_property` default names. It is ... | from six import with_metaclass
from werkzeug.utils import cached_property
from requests import Session
class DinergateType(type):
"""The metaclass of :class:`~Dinergate` and its subclasses.
This metaclass will give all members are instance of
:class:`~werkzeug.utils.cached_property` default names. It is ... | bsd-3-clause | Python |
f9d5b05f1a0fdccb161f2f444f4b9f2d68bc3fa8 | Make it faster | Schevo/kiwi,Schevo/kiwi,Schevo/kiwi | examples/tasklet/simple.py | examples/tasklet/simple.py | import gobject
from kiwi.tasklet import Tasklet, WaitForTimeout, WaitForMessages, Message, \
WaitForTasklet, get_event
## ----------------------------
## And here's an example...
## ----------------------------
class _CountSomeNumbers2(Tasklet):
'''Counts numbers with at random time spacings'''
def __in... | import gobject
from kiwi.tasklet import Tasklet, WaitForTimeout, WaitForMessages, Message, \
WaitForTasklet, get_event
## ----------------------------
## And here's an example...
## ----------------------------
class _CountSomeNumbers2(Tasklet):
'''Counts numbers with at random time spacings'''
def __in... | lgpl-2.1 | Python |
bde6b9dfa8ef7dff87ca92dbc596eb940dbc0e45 | Update coindesk.py | joequant/bitcoin-price-api,dursk/bitcoin-price-api | exchanges/coindesk.py | exchanges/coindesk.py | from decimal import Decimal
from exchanges.helpers import get_datetime, get_response
class CoinDesk(object):
@classmethod
def get_current_price(cls, currency='USD'):
url = 'https://api.coindesk.com/v1/bpi/currentprice/{}.json'.format(
currency
)
data = get_response(url)
... | from decimal import Decimal
from exchanges.helpers import get_datetime, get_response
class CoinDesk(object):
@classmethod
def get_current_price(cls, currency='USD'):
url = 'https://api.coindesk.com/v1/bpi/currentprice/{}.json'.format(
currency
)
data = get_response(url)
... | mit | Python |
17a4a8756f8464a3827872065e18075f8b808bc1 | Add `init_version` to validators schema (#2349) | petrjasek/superdesk-core,petrjasek/superdesk-core,superdesk/superdesk-core,petrjasek/superdesk-core,petrjasek/superdesk-core,superdesk/superdesk-core,superdesk/superdesk-core,superdesk/superdesk-core | apps/validators/validators.py | apps/validators/validators.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import super... | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import super... | agpl-3.0 | Python |
f275c8cc020119b52ed01bc6b56946279853d854 | Stop ulmo caching for suds-jurko compliance | WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed | src/mmw/apps/bigcz/clients/cuahsi/details.py | src/mmw/apps/bigcz/clients/cuahsi/details.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from datetime import date, timedelta
from rest_framework.exceptions import ValidationError
DATE_FORMAT = '%m/%d/%Y'
def details(wsdl, site):
if not wsdl:
raise Validatio... | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from datetime import date, timedelta
from rest_framework.exceptions import ValidationError
DATE_FORMAT = '%m/%d/%Y'
def details(wsdl, site):
if not wsdl:
raise Validatio... | apache-2.0 | Python |
4c448a7d7fc18f802880eee0962e8b98feeec1a7 | Initialize null logger | scalative/haas,scalative/haas,sjagoe/haas,itziakos/haas,itziakos/haas,sjagoe/haas | haas/__init__.py | haas/__init__.py | # -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
try:
from haas.version import version as __version__
except ImportError: # pragma: no cover
... | # -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
try:
from haas.version import version as __version__
except ImportError: # pragma: no cover
... | bsd-3-clause | Python |
1b63ce89b16e08891f7538a2d42394dd23ac7e1a | Improve type hint formatting for id command | Harmon758/Harmonbot,Harmon758/Harmonbot | Discord/cogs/user.py | Discord/cogs/user.py |
import discord
from discord.ext import commands
import inspect
from typing import Optional
from modules import utilities
from utilities import checks
def setup(bot):
bot.add_cog(User(bot))
class User(commands.Cog):
def __init__(self, bot):
self.bot = bot
for name, command in inspect.getmembers(self):
if... |
import discord
from discord.ext import commands
import inspect
from typing import Optional
from modules import utilities
from utilities import checks
def setup(bot):
bot.add_cog(User(bot))
class User(commands.Cog):
def __init__(self, bot):
self.bot = bot
for name, command in inspect.getmembers(self):
if... | mit | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.