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 |
|---|---|---|---|---|---|---|---|---|---|
a43d461bf2d5c40b8d828873f9fa0b5e2048a0df | SnsManager/google/GoogleBase.py | SnsManager/google/GoogleBase.py | import httplib2
from apiclient.discovery import build
from oauth2client.client import AccessTokenCredentials, AccessTokenCredentialsError
from SnsManager.SnsBase import SnsBase
from SnsManager import ErrorCode
class GoogleBase(SnsBase):
def __init__(self, *args, **kwargs):
super(self.__class__, self).__ini... | import httplib2
from apiclient.discovery import build
from oauth2client.client import AccessTokenCredentials, AccessTokenCredentialsError
from SnsManager.SnsBase import SnsBase
from SnsManager import ErrorCode
class GoogleBase(SnsBase):
def __init__(self, *args, **kwargs):
super(GoogleBase, self).__init__(... | Move http object as based object | Move http object as based object
| Python | bsd-3-clause | waveface/SnsManager |
a99d07e02f69961be5096ce8575007cec7ec213d | photoshell/__main__.py | photoshell/__main__.py | import os
from gi.repository import GObject
from photoshell.config import Config
from photoshell.library import Library
from photoshell.views.slideshow import Slideshow
from photoshell.views.window import Window
c = Config({
'library': os.path.join(os.environ['HOME'], 'Pictures/Photoshell'),
'dark_theme': Tr... | import os
import signal
from photoshell.config import Config
from photoshell.library import Library
from photoshell.views.slideshow import Slideshow
from photoshell.views.window import Window
c = Config({
'library': os.path.join(os.environ['HOME'], 'Pictures/Photoshell'),
'dark_theme': True,
'import_path'... | Add a signal handler to handle SIGINTs | Add a signal handler to handle SIGINTs
Fixes #135
| Python | mit | photoshell/photoshell,SamWhited/photoshell,campaul/photoshell |
691bee381bda822a059c5d9fa790feabc7e00a8d | dnsimple2/tests/services/base.py | dnsimple2/tests/services/base.py | import os
from unittest import TestCase
from dnsimple2.client import DNSimple
from dnsimple2.resources import (
AccountResource,
DomainResource
)
from dnsimple2.tests.utils import get_test_domain_name
class BaseServiceTestCase(TestCase):
@classmethod
def setUpClass(cls):
access_token = os.get... | import os
from unittest import TestCase
from dnsimple2.client import DNSimple
from dnsimple2.resources import (
AccountResource,
DomainResource
)
from dnsimple2.tests.utils import get_test_domain_name
class BaseServiceTestCase(TestCase):
@classmethod
def setUpClass(cls):
access_token = os.get... | Use env variable for account id in tests. | Use env variable for account id in tests.
| Python | mit | indradhanush/dnsimple2-python |
1bda8188458b81866c5938529ba85b3913caedc0 | project/api/indexes.py | project/api/indexes.py | from algoliasearch_django import AlgoliaIndex
class ChartIndex(AlgoliaIndex):
fields = [
'title',
'arrangers'
]
settings = {
'searchableAttributes': [
'title',
'arrangers',
]
}
class GroupIndex(AlgoliaIndex):
should_index = 'is_active'
... | from algoliasearch_django import AlgoliaIndex
class ChartIndex(AlgoliaIndex):
fields = [
'title',
'arrangers'
]
settings = {
'searchableAttributes': [
'title',
'arrangers',
]
}
class GroupIndex(AlgoliaIndex):
should_index = 'is_active'
... | Add faceting test to Group index | Add faceting test to Group index
| Python | bsd-2-clause | barberscore/barberscore-api,dbinetti/barberscore-django,dbinetti/barberscore-django,dbinetti/barberscore,barberscore/barberscore-api,dbinetti/barberscore,barberscore/barberscore-api,barberscore/barberscore-api |
59c698e5db5c7fb2d537398cdad93215714b21f0 | SimpleLoop.py | SimpleLoop.py | # Copyright 2011 Seppo Yli-Olli
#
# 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 writ... | # Copyright 2011 Seppo Yli-Olli
#
# 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 writ... | Add a way to have the loop quit after current invocation has been processed. | Add a way to have the loop quit after current invocation has been processed.
| Python | apache-2.0 | nanonyme/SimpleLoop,nanonyme/SimpleLoop |
6b5461955e196ee4a12b708fb6f9bef750d468ad | testcontainers/oracle.py | testcontainers/oracle.py | from testcontainers.core.generic import DbContainer
class OracleDbContainer(DbContainer):
"""
Oracle database container.
Example
-------
::
with OracleDbContainer():
e = sqlalchemy.create_engine(oracle.get_connection_url())
result = e.execute("select 1 from dual")... | from testcontainers.core.generic import DbContainer
class OracleDbContainer(DbContainer):
"""
Oracle database container.
Example
-------
::
with OracleDbContainer() as oracle:
e = sqlalchemy.create_engine(oracle.get_connection_url())
result = e.execute("select 1 f... | Add missing _configure to OracleDbContainer | Add missing _configure to OracleDbContainer
Additionally, fix Oracle example.
| Python | apache-2.0 | SergeyPirogov/testcontainers-python |
9b83a9dbfe1cc3dc4e8da3df71b6c414e304f53f | testing/runtests.py | testing/runtests.py | # -*- coding: utf-8 -*-
import os, sys
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
from django.core.management import call_command
if __name__ == "__main__":
args = sys.argv[1:]
call_command("test", *args, verbosity=2)
| # -*- coding: utf-8 -*-
import os, sys
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
if __name__ == "__main__":
from django.core.management import execute_from_command_line
args = sys.argv
args.insert(1, "test")
args.insert(2, "pg_uuid_fields")
execute_from_command_line(args)
| Fix tests to run with django 1.7 | Fix tests to run with django 1.7
| Python | bsd-3-clause | niwinz/djorm-ext-pguuid |
f68139ce9114f260487048716d7430fcb1b3173b | 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... | import logging
from django.conf import settings
from django.utils import translation
from celery.task import task
from celery.signals import task_failure
from haystack import site
from sentry.client.handlers import SentryHandler
# Hook up sentry to celery's logging
# Based on http://www.colinhowe.co.uk/2011/02/08/c... | Add celery task failure sentry tracking | Add celery task failure sentry tracking | Python | mit | catcosmo/froide,okfse/froide,ryankanno/froide,LilithWittmann/froide,CodeforHawaii/froide,ryankanno/froide,LilithWittmann/froide,LilithWittmann/froide,catcosmo/froide,ryankanno/froide,CodeforHawaii/froide,catcosmo/froide,stefanw/froide,LilithWittmann/froide,CodeforHawaii/froide,CodeforHawaii/froide,ryankanno/froide,okfs... |
b9a16863a1baca989ccec66a88b4218aad676160 | utils.py | utils.py | commands = {}
def add_cmd(name, alias=None, owner=False, admin=False):
def real_command(func):
commands[name] = func
if alias:
commands[alias] = func
return real_command
def call_command(bot, event, irc):
command = ' '.join(event.arguments).split(' ')
args = command[1]
... | commands = {}
def add_cmd(name, alias=None, owner=False, admin=False):
def real_command(func):
commands[name] = func
if alias:
commands[alias] = func
return real_command
def call_command(bot, event, irc):
command = ' '.join(event.arguments).split(' ')
args = command[1:] i... | Fix a bug and log to the console | Fix a bug and log to the console
Fix a bug where a command is called without any arguments, so no indices will be out-of-range
Log to the console whenever someone calls a command
| Python | mit | wolfy1339/Python-IRC-Bot |
c65ed9ec976c440b46dedc514daf883bba940282 | myElsClient.py | myElsClient.py | import requests
class myElsClient:
"""A class that implements a Python interface to api.elsevier.com"""
# local variables
__base_url = "http://api.elsevier.com/"
def __init__(self, apiKey):
"""Instantiates a client with a given API Key."""
self.apiKey = apiKey
def getBaseURL... | import requests
class myElsClient:
"""A class that implements a Python interface to api.elsevier.com"""
# local variables
__base_url = "http://api.elsevier.com/"
# constructors
def __init__(self, apiKey):
"""Instantiates a client with a given API Key."""
self.apiKey = apiKey
... | Add ability to set insttoken | Add ability to set insttoken
| Python | bsd-3-clause | ElsevierDev/elsapy |
2565724364eac8a548be2f59173e2f0630fa2f5d | music/api.py | music/api.py | from django.conf.urls.defaults import url
from tastypie.resources import ModelResource
from tastypie.constants import ALL
from jmbo.api import ModelBaseResource
from music.models import Track
class TrackResource(ModelBaseResource):
class Meta:
queryset = Track.permitted.all()
resource_name = 't... | from django.conf.urls.defaults import url
from tastypie.resources import ModelResource
from tastypie.constants import ALL
from tastypie import fields
from jmbo.api import ModelBaseResource
from music.models import Track, TrackContributor
class TrackContributorResource(ModelBaseResource):
class Meta:
qu... | Include contributor in track feed | Include contributor in track feed
| Python | bsd-3-clause | praekelt/jmbo-music,praekelt/jmbo-music |
c45c3fa8670ed7030010a255aee0233c8a3c434f | test/assets/test_task_types_for_asset.py | test/assets/test_task_types_for_asset.py | from test.base import ApiDBTestCase
class AssetTaskTypesTestCase(ApiDBTestCase):
def setUp(self):
super(AssetTaskTypesTestCase, self).setUp()
self.generate_fixture_project_status()
self.generate_fixture_project()
self.generate_fixture_entity_type()
self.generate_fixture_se... | from test.base import ApiDBTestCase
class AssetTaskTypesTestCase(ApiDBTestCase):
def setUp(self):
super(AssetTaskTypesTestCase, self).setUp()
self.generate_fixture_project_status()
self.generate_fixture_project()
self.generate_fixture_entity_type()
self.generate_fixture_se... | Add tests for task types for assets routes | Add tests for task types for assets routes
Add a test to ensure that a 404 is returned when the give id is wrong.
| Python | agpl-3.0 | cgwire/zou |
dd3cc71bb09ab2fb265b3f4bdda69cb1880842c6 | tests/utils_test.py | tests/utils_test.py | import unittest
from zttf.utils import fixed_version, binary_search_parameters
class TestUtils(unittest.TestCase):
def test_fixed_version(self):
cases = [
(0x00005000, 0.5),
(0x00010000, 1.0),
(0x00035000, 3.5),
(0x00105000, 10.5)
]
for case... | import unittest
import struct
from zttf.utils import fixed_version, binary_search_parameters, ttf_checksum
class TestUtils(unittest.TestCase):
def test_fixed_version(self):
cases = [
(0x00005000, 0.5),
(0x00010000, 1.0),
(0x00035000, 3.5),
(0x00105000, 10.5... | Add a simple test for the checksum routine. | Add a simple test for the checksum routine.
| Python | apache-2.0 | zathras777/zttf |
473aee0eda226acc6ae959a3ef39656dce6031b5 | akanda/horizon/routers/views.py | akanda/horizon/routers/views.py | from django.utils.translation import ugettext_lazy as _ # noqa
from horizon import exceptions
from openstack_dashboard import api
def get_interfaces_data(self):
try:
router_id = self.kwargs['router_id']
ports = api.neutron.port_list(self.request,
router_id=r... | from django.utils.translation import ugettext_lazy as _ # noqa
from horizon import exceptions
from openstack_dashboard import api
def get_interfaces_data(self):
try:
router_id = self.kwargs['router_id']
router = api.quantum.router_get(self.request, router_id)
ports = [api.quantum.Port(p)... | Fix router's interface listing view | Fix router's interface listing view
To get all the ports for a router Horizon uses port_list
filtering by the device_id value which in vanilla openstack
is the quantum router_id, but we use the akanda_id as value for
that field so the listing doesn't work for us. Lets replace the
port_list call with router_get.
Chan... | Python | apache-2.0 | dreamhost/akanda-horizon,dreamhost/akanda-horizon |
22aaf754eb04e9f345c55f73ffb0f549d83c68df | apps/explorer/tests/test_templatetags.py | apps/explorer/tests/test_templatetags.py | from django.test import TestCase
from ..templatetags import explorer
class HighlightTestCase(TestCase):
def test_highlight_returns_text_when_empty_word(self):
expected = 'foo bar baz'
assert explorer.highlight('foo bar baz', '') == expected
def test_highlight(self):
expected = '<s... | from django.test import TestCase
from ..templatetags import explorer
class HighlightTestCase(TestCase):
def test_highlight_returns_text_when_empty_word(self):
expected = 'foo bar baz'
assert explorer.highlight('foo bar baz', '') == expected
def test_highlight(self):
expected = '<s... | Add test for concat template tag | Add test for concat template tag
| Python | bsd-3-clause | Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel |
f52c8cc3938567a24ac6ea0a807654aa73caa871 | pages/views.py | pages/views.py | from pages.models import Page, Language, Content
from pages.utils import auto_render
from django.contrib.admin.views.decorators import staff_member_required
from django import forms
from django.http import Http404
import settings
@auto_render
def details(request, page_id=None):
template = None
lang = Language.... | from pages.models import Page, Language, Content
from pages.utils import auto_render
from django.contrib.admin.views.decorators import staff_member_required
from django import forms
from django.http import Http404
import settings
@auto_render
def details(request, page_id=None):
template = None
lang = Language.... | Fix a bug with an empty database | Fix a bug with an empty database
git-svn-id: 54fea250f97f2a4e12c6f7a610b8f07cb4c107b4@138 439a9e5f-3f3e-0410-bc46-71226ad0111b
| Python | bsd-3-clause | pombredanne/django-page-cms-1,oliciv/django-page-cms,akaihola/django-page-cms,pombredanne/django-page-cms-1,akaihola/django-page-cms,remik/django-page-cms,pombredanne/django-page-cms-1,batiste/django-page-cms,oliciv/django-page-cms,remik/django-page-cms,batiste/django-page-cms,oliciv/django-page-cms,batiste/django-page... |
265ed91b7e7f204926e7c5f9d2fbe76f447f7955 | gitfs/views/read_only.py | gitfs/views/read_only.py | import os
from errno import EROFS
from fuse import FuseOSError
from gitfs import FuseMethodNotImplemented
from .view import View
class ReadOnlyView(View):
def getxattr(self, path, fh):
raise FuseMethodNotImplemented
def open(self, path, flags):
return 0
def create(self, path, fh):
... | import os
from errno import EROFS
from fuse import FuseOSError
from gitfs import FuseMethodNotImplemented
from .view import View
class ReadOnlyView(View):
def getxattr(self, path, fh):
raise FuseMethodNotImplemented
def open(self, path, flags):
return 0
def create(self, path, fh):
... | Raise read-only filesystem when the user wants to chmod in /history. | Raise read-only filesystem when the user wants to chmod in /history.
| Python | apache-2.0 | PressLabs/gitfs,bussiere/gitfs,rowhit/gitfs,ksmaheshkumar/gitfs,PressLabs/gitfs |
bbc6ce8225cf54e56331ec75fa2de007d02162af | src/_thread/__init__.py | src/_thread/__init__.py | from __future__ import absolute_import
import sys
__future_module__ = True
if sys.version_info[0] < 3:
from dummy_thread import *
else:
raise ImportError('This package should not be accessible on Python 3. '
'Either you are trying to run from the python-future src folder '
... | from __future__ import absolute_import
import sys
__future_module__ = True
if sys.version_info[0] < 3:
try:
from thread import *
except ImportError:
from dummy_thread import *
else:
raise ImportError('This package should not be accessible on Python 3. '
'Either you are... | Fix bug where dummy_thread was always imported | Fix bug where dummy_thread was always imported
The code always import the dummy_thread module even on platforms where the real thread module is available. This caused bugs in other packages that use this import style:
try:
from _thread import interrupt_main # Py 3
except ImportError:
from thread import ... | Python | mit | QuLogic/python-future,QuLogic/python-future,PythonCharmers/python-future,michaelpacer/python-future,michaelpacer/python-future,PythonCharmers/python-future |
4f7382303d56871b2b174e291b47b238777f5d32 | yubico/yubico_exceptions.py | yubico/yubico_exceptions.py | __all___ = [
'YubicoError',
'StatusCodeError',
'InvalidClientIdError',
'InvalidValidationResponse',
'SignatureVerificationError'
]
class YubicoError(Exception):
""" Base class for Yubico related exceptions. """
pass
class StatusCodeError(YubicoError):
def __init__(self, status_code):... | __all___ = [
'YubicoError',
'StatusCodeError',
'InvalidClientIdError',
'InvalidValidationResponse',
'SignatureVerificationError'
]
class YubicoError(Exception):
""" Base class for Yubico related exceptions. """
pass
class StatusCodeError(YubicoError):
def __init__(self, status_code):... | Set message attribute on InvalidValidationResponse error class. | Set message attribute on InvalidValidationResponse error class.
| Python | bsd-3-clause | Kami/python-yubico-client |
cbbfa328f3f5998c2d3bc78315f9ecfc3fee9aad | pirx/checks.py | pirx/checks.py | #!/usr/bin/env python
import socket
import sys
def host(name):
"""Check if host name is equal to the given name"""
return socket.gethostname() == name
def arg(name, expected_value=None):
"""
Check if command-line argument with a given name was passed and if it has
the expected value.
"""
... | #!/usr/bin/env python
import socket
import sys
def host(name):
"""Check if host name is equal to the given name"""
return socket.gethostname() == name
def arg(name, expected_value=None):
"""
Check if command-line argument with a given name was passed and if it has
the expected value.
"""
... | Fix for-if in "arg" function | Fix for-if in "arg" function
| Python | mit | piotrekw/pirx |
9e17cda40ddefaa5c2b905b3ffdfadf485461eaa | plugin/main.py | plugin/main.py | #!/usr/bin/env python
"""
Deploy builds to a Rancher orchestrated stack using rancher-compose
"""
import os
import drone
import subprocess
def main():
"""The main entrypoint for the plugin."""
payload = drone.plugin.get_input()
vargs = payload["vargs"]
# Change directory to deploy path
deploy_pa... | #!/usr/bin/env python
"""
Deploy builds to a Rancher orchestrated stack using rancher-compose
"""
import os
import drone
import subprocess
def main():
"""The main entrypoint for the plugin."""
payload = drone.plugin.get_input()
vargs = payload["vargs"]
# Change directory to deploy path
deploy_pa... | Append services string only if not blank | Append services string only if not blank
| Python | apache-2.0 | dangerfarms/drone-rancher |
5055e3b911afe52f70f60915254d27bfc0c2b645 | application/navigation/views.py | application/navigation/views.py | from flask import Markup
from flask import render_template
from application.page.models import Page
def find_subpages(pages, parent):
subpages = []
for page in pages:
prefix = '/'.join(page.path.split('/')[:-1])
if prefix == parent.path:
subpages.append(page)
return subpages
def view_bar(current_page='')... | from flask import Markup
from flask import render_template
from application.page.models import Page
def find_subpages(pages, parent):
subpages = []
for page in pages:
prefix = '/'.join(page.path.split('/')[:-1])
if prefix == parent.path:
subpages.append(page)
return subpages
def view_bar(current_page='')... | Remove print statement so Stephan won't be annoyed anymore | Remove print statement so Stephan won't be annoyed anymore
| Python | mit | viaict/viaduct,viaict/viaduct,viaict/viaduct,viaict/viaduct,viaict/viaduct |
2fb3a72885d279f7a79e10f00d71991144748f1c | haas/plugins/base_plugin.py | haas/plugins/base_plugin.py | from haas.utils import uncamelcase
from .i_plugin import IPlugin
class BasePlugin(IPlugin):
name = None
enabled = False
enabling_option = None
def __init__(self, name=None):
if name is None:
name = uncamelcase(type(self).__name__, sep='-')
self.name = name
self.en... | from haas.utils import uncamelcase
from .i_plugin import IPlugin
class BasePlugin(IPlugin):
name = None
enabled = False
enabling_option = None
def __init__(self, name=None):
if name is None:
name = uncamelcase(type(self).__name__, sep='-')
self.name = name
self.en... | Add help text for plugin enable option | Add help text for plugin enable option
| Python | bsd-3-clause | sjagoe/haas,scalative/haas,sjagoe/haas,itziakos/haas,scalative/haas,itziakos/haas |
9fc92a176fbc9425229d02a032d3494566139e6a | tests/Physics/TestNTC.py | tests/Physics/TestNTC.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from numpy.testing import assert_approx_equal, assert_allclose, assert_array_less
from nose.tools import raises, assert_true, assert_equal
from UliEngineering.Physics.NTC import *
from UliEngineering.Exceptions import *
import functools
import numpy as np
class TestNTC(ob... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from numpy.testing import assert_approx_equal, assert_allclose, assert_array_less
from nose.tools import raises, assert_true, assert_equal
from UliEngineering.Physics.NTC import *
from UliEngineering.Exceptions import *
import functools
import numpy as np
class TestNTC(ob... | Add more NTC unit tests | Add more NTC unit tests
| Python | apache-2.0 | ulikoehler/UliEngineering |
4b9789350a01fee5c341ac8a5612c7dae123fddd | tests/test_boto_store.py | tests/test_boto_store.py | #!/usr/bin/env python
import pytest
boto = pytest.importorskip('boto')
from simplekv.net.botostore import BotoStore
from basic_store import BasicStore
from url_store import UrlStore
from bucket_manager import boto_credentials, boto_bucket
@pytest.fixture(params=boto_credentials,
ids=[c['access_key'... | #!/usr/bin/env python
import os
from tempdir import TempDir
import pytest
boto = pytest.importorskip('boto')
from simplekv.net.botostore import BotoStore
from basic_store import BasicStore
from url_store import UrlStore
from bucket_manager import boto_credentials, boto_bucket
@pytest.fixture(params=boto_credentia... | Fix botos rudeness when handling nonexisting files. | Fix botos rudeness when handling nonexisting files.
| Python | mit | fmarczin/simplekv,karteek/simplekv,fmarczin/simplekv,mbr/simplekv,mbr/simplekv,karteek/simplekv |
acf9e2d1f879758412154fe8008371b387f4d2bc | namegen/name.py | namegen/name.py |
import random
__metaclass__ = type
class Generator:
def __init__(self, data):
if isinstance(data, str):
data = data.split('\n')
self.clusters = []
for item in data:
if item.find(' ') < 0:
item += ' '
name, info = item.split(' ', 2)
... |
import random
__metaclass__ = type
class Generator:
def __init__(self, data):
if isinstance(data, str):
data = data.split('\n')
self.clusters = []
for item in data:
if item.find(' ') < 0:
item += ' '
name, info = item.split(' ', 2)
... | Use cluster length of 3 | Use cluster length of 3
| Python | mit | lethosor/py-namegen |
ff35b4353fbb47c602d3561c5e6e84201355df14 | Cryptor.py | Cryptor.py | from Crypto.Cipher import AES
class Cryptor(object):
def __init__(self, key, iv):
#self.aes = AES.new(key, mode=AES.MODE_CBC, IV=iv) # This resembles stuff from shairtunes
self.aes = AES.new(key, mode=AES.MODE_ECB, IV=iv) # I found this in airtunesd
self.inbuf = ""
self.outbuf = ""
self.lastLen = 0
def d... | from Crypto.Cipher import AES
import Crypto.Util.Counter
class Cryptor(AES.AESCipher):
def __init__(self, key, iv):
self.counter = Crypto.Util.Counter.new(128, initial_value=long(iv.encode("hex"), 16))
AES.AESCipher.__init__(self, key, mode=AES.MODE_CTR, counter=self.counter)
class EchoCryptor(object):
def de... | Use CTR as encrypton mode. Works with iOS6. | Use CTR as encrypton mode. Works with iOS6.
| Python | bsd-2-clause | tzwenn/PyOpenAirMirror,tzwenn/PyOpenAirMirror |
f9903bc92bf02eeaa18e1a2843d288e909b71c33 | social_core/tests/backends/test_asana.py | social_core/tests/backends/test_asana.py | import json
from .oauth import OAuth2Test
class AsanaOAuth2Test(OAuth2Test):
backend_path = 'social_core.backends.asana.AsanaOAuth2'
user_data_url = 'https://app.asana.com/api/1.0/users/me'
expected_username = 'erlich@bachmanity.com'
access_token_body = json.dumps({
'access_token': 'aviato',
... | import json
from .oauth import OAuth2Test
class AsanaOAuth2Test(OAuth2Test):
backend_path = 'social_core.backends.asana.AsanaOAuth2'
user_data_url = 'https://app.asana.com/api/1.0/users/me'
expected_username = 'erlich@bachmanity.com'
access_token_body = json.dumps({
'access_token': 'aviato',
... | Correct mocked response from Asana API | Correct mocked response from Asana API
| Python | bsd-3-clause | tobias47n9e/social-core,python-social-auth/social-core,python-social-auth/social-core |
05e86efadfd0a05bac660e2ce47a5502b5bbdddb | tempest/tests/fake_auth_provider.py | tempest/tests/fake_auth_provider.py | # Copyright 2014 Hewlett-Packard Development Company, L.P.
# 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... | # Copyright 2014 Hewlett-Packard Development Company, L.P.
# 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... | Remove auth_request as no used | Remove auth_request as no used
Function auth_request() isn't be used, it can be removed for the
code clean.
Change-Id: I979b67e934c72f50dd62c75ac614f99f136cfeae
| Python | apache-2.0 | vedujoshi/tempest,Tesora/tesora-tempest,openstack/tempest,openstack/tempest,vedujoshi/tempest,masayukig/tempest,masayukig/tempest,Juniper/tempest,cisco-openstack/tempest,sebrandon1/tempest,sebrandon1/tempest,cisco-openstack/tempest,Tesora/tesora-tempest,Juniper/tempest |
51ab41fc42bf3cc79461733fbfac50667da63eed | sanitytest.py | sanitytest.py | #!/usr/bin/python
import libvirt
globals = dir(libvirt)
# Sanity test that the generator hasn't gone wrong
# Look for core classes
assert("virConnect" in globals)
assert("virDomain" in globals)
assert("virDomainSnapshot" in globals)
assert("virInterface" in globals)
assert("virNWFilter" in globals)
assert("virNodeD... | #!/usr/bin/python
import libvirt
globals = dir(libvirt)
# Sanity test that the generator hasn't gone wrong
# Look for core classes
for clsname in ["virConnect",
"virDomain",
"virDomainSnapshot",
"virInterface",
"virNWFilter",
"virNodeDe... | Check if classes are derived from object | Check if classes are derived from object
This makes sure we don't regress to old style classes
| Python | lgpl-2.1 | cardoe/libvirt-python,cardoe/libvirt-python,libvirt/libvirt-python,libvirt/libvirt-python,libvirt/libvirt-python,cardoe/libvirt-python |
c8decb4f11059b58dd96442a4114f10cb95c7b35 | tv-script-generation/helper.py | tv-script-generation/helper.py | import os
import pickle
def load_data(path):
"""
Load Dataset from File
"""
input_file = os.path.join(path)
with open(input_file, "r") as f:
data = f.read()
return data
def preprocess_and_save_data(dataset_path, token_lookup, create_lookup_tables):
"""
Preprocess Text Data
... | import os
import pickle
def load_data(path):
"""
Load Dataset from File
"""
input_file = os.path.join(path)
with open(input_file, "r") as f:
data = f.read()
return data
def preprocess_and_save_data(dataset_path, token_lookup, create_lookup_tables):
"""
Preprocess Text Data
... | Remove copyright notice during preprocessing | Remove copyright notice during preprocessing
| Python | mit | danresende/deep-learning,snegirigens/DLND,0x4a50/udacity-0x4a50-deep-learning-nanodegree,kitu2007/dl_class,seinberg/deep-learning,samirma/deep-learning,schaber/deep-learning,dataewan/deep-learning,michaelgat/Udacity_DL,Bismarrck/deep-learning,greg-ashby/deep-learning-nanodegree,cranium/deep-learning,thiagoqd/queirozdia... |
4a95e49570a26f1295a2dad9d6d71ad9a887f1b1 | setup_data.py | setup_data.py | INFO = {
'name': 'Mayavi',
'version': '3.4.1',
'install_requires': [
'AppTools >= 3.4.1.dev',
'Traits >= 3.6.0.dev',
],
}
| INFO = {
'extras_require': {
'app' : [
'EnvisageCore >= 3.2.0.dev',
'EnvisagePlugins >= 3.2.0.dev',
'TraitsBackendWX >= 3.6.0.dev',
],
},
'name': 'Mayavi',
'version': '3.4.1',
'install_requires': [
'AppTools >= 3.4.1.dev',
'... | Add back the extra requires for the | MISC: Add back the extra requires for the [app]
| Python | bsd-3-clause | liulion/mayavi,dmsurti/mayavi,alexandreleroux/mayavi,alexandreleroux/mayavi,dmsurti/mayavi,liulion/mayavi |
ac923a58ffa7c437985e68d98e7dd0e4e67df39c | shiva/http.py | shiva/http.py | from flask import current_app as app, Response
from flask.ext import restful
from shiva.decorators import allow_origins
class Resource(restful.Resource):
def __new__(cls, *args, **kwargs):
if app.config.get('CORS_ENABLED') is True:
# Applies to all inherited resources
cls.method_d... | from flask import current_app as app, Response
from flask.ext import restful
from shiva.decorators import allow_origins
class Resource(restful.Resource):
def __new__(cls, *args, **kwargs):
if app.config.get('CORS_ENABLED') is True:
# Applies to all inherited resources
cls.method_d... | Fix for OPTIONS method to an instance | Fix for OPTIONS method to an instance
OPTIONS /track/1
TypeError: options() got an unexpected keyword argument 'track_id'
| Python | mit | tooxie/shiva-server,maurodelazeri/shiva-server,maurodelazeri/shiva-server,tooxie/shiva-server |
41e0ea623baaff22ed5f436ad563edf52b762bcc | Main.py | Main.py | """Main Module of PDF Splitter"""
import argparse
import os
from PyPDF2 import PdfFileWriter
from Util import all_pdf_files_in_directory, split_on_condition, concat_pdf_pages
parser = \
argparse.ArgumentParser(
description='Split all the pages of multiple PDF files in a directory by document number'
... | """Main Module of PDF Splitter"""
import argparse
import os
from PyPDF2 import PdfFileWriter
from Util import all_pdf_files_in_directory, split_on_condition, concat_pdf_pages
parser = \
argparse.ArgumentParser(
description='Split all the pages of multiple PDF files in a directory by document number'
... | Fix bug where only PDF files in current directory can be found | Fix bug where only PDF files in current directory can be found
| Python | mit | shunghsiyu/pdf-processor |
84741b8f6c7aec220b8644d92535e1a805c65b08 | run_example.py | run_example.py | import keras
from DatasetHandler.CreateDataset import *
from ModelHandler.CreateModel.functions_for_vgg16 import *
import time
#d = load_8376_resized_150x150(desired_number=10)
#d.statistics()
start = time.time()
print time.ctime()
main_vgg16(TMP_size_of_dataset=100, TMP_num_of_epochs=150, name_of_the_experiment = '... | import keras
from DatasetHandler.CreateDataset import *
from ModelHandler.CreateModel.functions_for_vgg16 import *
import time
import sys
# DEFAULT VALUES:
TMP_size_of_dataset=100
TMP_num_of_epochs=150
name_of_the_experiment = '-newWawe-1stRoundShouldCountBoth'
# python python_script.py var1 var2 var3
if len(sys.argv... | Add the support for custom setting given by bash script (run as "python_script.py sizeOfDataset numOfEpochs nameOfExp") | Add the support for custom setting given by bash script (run as "python_script.py sizeOfDataset numOfEpochs nameOfExp")
| Python | mit | previtus/MGR-Project-Code,previtus/MGR-Project-Code,previtus/MGR-Project-Code |
d4580c01fc6adc078b382281a23022537c87940a | imager/imagerprofile/handlers.py | imager/imagerprofile/handlers.py | from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from imagerprofile.models import ImagerProfile
@receiver(post_save, sender=User)
def add_profile(sender, instance, **kwargs):
if kwargs['created']:
# try:
new_profile = I... | from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from imagerprofile.models import ImagerProfile
@receiver(post_save, sender=User)
def add_profile(sender, instance, **kwargs):
if kwargs['created']:
new_profile = ImagerProfile(us... | Remove commented out code that isn't needed | Remove commented out code that isn't needed
| Python | mit | nbeck90/django-imager,nbeck90/django-imager |
52d8ace9c944dda105dc95ab0baff4a41b4b48c3 | scripts/art.py | scripts/art.py | #!/usr/bin/env python
import sys
from pyfiglet import Figlet
from optparse import OptionParser
def draw_text(f, font, text):
f.setFont(font=font)
print f.renderText(text)
def main(args):
parser = OptionParser()
parser.add_option("-f", "--font", help="specify the font",
action="store... | #!/usr/bin/env python
import sys
from pyfiglet import Figlet
from optparse import OptionParser
def draw_text(figlet, font, textlist):
figlet.setFont(font=font)
for t in textlist:
print figlet.renderText(t)
def list_fonts(figlet, count=10):
fonts = figlet.getFonts()
nrows = len(fonts)/count
... | Support for text input via args. | Support for text input via args.
1. better help message
2. support for input arguments
3. better defaults
4. columnar display of fonts
| Python | mit | shiva/asciiart |
a7d8d2f95acbf801c0cc8b0f2a8cc008f6cb34c0 | rouver/types.py | rouver/types.py | from __future__ import annotations
from collections.abc import Iterable, Mapping
from typing import Any, Callable, Dict, Tuple
from typing_extensions import TypeAlias
from werkzeug.wrappers import Request
# (name, value)
Header: TypeAlias = Tuple[str, str]
WSGIEnvironment: TypeAlias = Dict[str, Any]
# (body) -> No... | from __future__ import annotations
from typing import Any, Callable, Dict, Iterable, Mapping, Tuple
from typing_extensions import TypeAlias
from werkzeug.wrappers import Request
# (name, value)
Header: TypeAlias = Tuple[str, str]
WSGIEnvironment: TypeAlias = Dict[str, Any]
# (body) -> None
StartResponseReturnType:... | Fix imports on Python <= 3.8 | Fix imports on Python <= 3.8
| Python | mit | srittau/rouver |
5b87029e229fa3dcf0e81231899c36bd52a7616c | numpy/core/__init__.py | numpy/core/__init__.py |
from info import __doc__
from numpy.version import version as __version__
import multiarray
import umath
import numerictypes as nt
multiarray.set_typeDict(nt.sctypeDict)
import _sort
from numeric import *
from fromnumeric import *
from defmatrix import *
import ma
import defchararray as char
import records as rec
fro... |
from info import __doc__
from numpy.version import version as __version__
import multiarray
import umath
import _internal # for freeze programs
import numerictypes as nt
multiarray.set_typeDict(nt.sctypeDict)
import _sort
from numeric import *
from fromnumeric import *
from defmatrix import *
import ma
import defchar... | Add an dummy import statement so that freeze programs pick up _internal.p | Add an dummy import statement so that freeze programs pick up _internal.p
| Python | bsd-3-clause | dato-code/numpy,jorisvandenbossche/numpy,mathdd/numpy,stefanv/numpy,sinhrks/numpy,stuarteberg/numpy,rajathkumarmp/numpy,madphysicist/numpy,skwbc/numpy,rudimeier/numpy,abalkin/numpy,brandon-rhodes/numpy,Linkid/numpy,shoyer/numpy,pizzathief/numpy,rherault-insa/numpy,pbrod/numpy,mingwpy/numpy,MaPePeR/numpy,argriffing/nump... |
389fd283c0e05a7c3ccdc871b2423a1d0f3b2280 | stack/cluster.py | stack/cluster.py | from troposphere import (
Parameter,
Ref,
)
from troposphere.ecs import (
Cluster,
)
from .template import template
container_instance_type = Ref(template.add_parameter(Parameter(
"ContainerInstanceType",
Description="The container instance type",
Type="String",
Default="t2.micro",
A... | from troposphere import (
Parameter,
Ref,
)
from troposphere.ecs import (
Cluster,
)
from .template import template
container_instance_type = Ref(template.add_parameter(Parameter(
"ContainerInstanceType",
Description="The container instance type",
Type="String",
Default="t2.micro",
A... | Add a `ECS` ami ids as a region mapping | Add a `ECS` ami ids as a region mapping
| Python | mit | tobiasmcnulty/aws-container-basics,caktus/aws-web-stacks |
56300ddbac1a47f9b2c9f7946c8810e55e19bb07 | Code/Native/update_module_builder.py | Code/Native/update_module_builder.py | """
This script downloads and updates the module builder.
"""
# Dont checkout all files
IGNORE_FILES = [
"__init__.py",
".gitignore",
"LICENSE",
"README.md",
"config.ini",
"Source/config_module.cpp",
"Source/config_module.h",
"Source/ExampleClass.cpp",
"Source/ExampleClass.h",
... | """
This script downloads and updates the module builder.
"""
# Dont checkout all files
IGNORE_FILES = [
"__init__.py",
".gitignore",
"LICENSE",
"README.md",
"config.ini",
"Source/config_module.cpp",
"Source/config_module.h",
"Source/ExampleClass.cpp",
"Source/ExampleClass.h",
... | Fix missing __init__ in native directory | Fix missing __init__ in native directory
| Python | mit | eswartz/RenderPipeline,eswartz/RenderPipeline,eswartz/RenderPipeline |
716f6d2f8ed4e2845746bcb803092806dd8f50b7 | tx_salaries/utils/transformers/mixins.py | tx_salaries/utils/transformers/mixins.py | class OrganizationMixin(object):
"""
Adds a generic ``organization`` property to the class
This requires that the class mixing it in adds an
``ORGANIZATION_NAME`` property of the main level agency or
department.
"""
@property
def organization(self):
return {
'name': ... | class OrganizationMixin(object):
"""
Adds a generic ``organization`` property to the class
This requires that the class mixing it in adds an
``ORGANIZATION_NAME`` property of the main level agency or
department and needs a ``department`` property.
"""
@property
def organization(self):
... | Tweak the wording just a bit | Tweak the wording just a bit
| Python | apache-2.0 | texastribune/tx_salaries,texastribune/tx_salaries |
7b4b5bc95f0a498ab83422192410f9213bfdb251 | praw/models/listing/mixins/submission.py | praw/models/listing/mixins/submission.py | """Provide the SubmissionListingMixin class."""
from ....const import API_PATH
from ..generator import ListingGenerator
from .base import BaseListingMixin
from .gilded import GildedListingMixin
class SubmissionListingMixin(BaseListingMixin, GildedListingMixin):
"""Adds additional methods pertaining to Submission ... | """Provide the SubmissionListingMixin class."""
from ....const import API_PATH
from ..generator import ListingGenerator
from .gilded import GildedListingMixin
class SubmissionListingMixin(GildedListingMixin):
"""Adds additional methods pertaining to Submission instances."""
def duplicates(self, **generator_k... | Remove BaseListingMixin as superclass for SubmissionListingMixin | Remove BaseListingMixin as superclass for SubmissionListingMixin
| Python | bsd-2-clause | darthkedrik/praw,leviroth/praw,praw-dev/praw,gschizas/praw,13steinj/praw,nmtake/praw,13steinj/praw,gschizas/praw,nmtake/praw,praw-dev/praw,darthkedrik/praw,leviroth/praw |
af0f80d2385001b52560cb0ec9d31e85c4a891bf | mopidy/frontends/mpd/__init__.py | mopidy/frontends/mpd/__init__.py | import logging
from mopidy.frontends.base import BaseFrontend
from mopidy.frontends.mpd.dispatcher import MpdDispatcher
from mopidy.frontends.mpd.thread import MpdThread
from mopidy.utils.process import unpickle_connection
logger = logging.getLogger('mopidy.frontends.mpd')
class MpdFrontend(BaseFrontend):
"""
... | import logging
from mopidy.frontends.base import BaseFrontend
from mopidy.frontends.mpd.dispatcher import MpdDispatcher
from mopidy.frontends.mpd.thread import MpdThread
from mopidy.utils.process import unpickle_connection
logger = logging.getLogger('mopidy.frontends.mpd')
class MpdFrontend(BaseFrontend):
"""
... | Add MPD_SERVER_PASSWORD to list of relevant frontend settings | Add MPD_SERVER_PASSWORD to list of relevant frontend settings
| Python | apache-2.0 | ali/mopidy,quartz55/mopidy,priestd09/mopidy,rawdlite/mopidy,quartz55/mopidy,vrs01/mopidy,mokieyue/mopidy,mopidy/mopidy,jcass77/mopidy,pacificIT/mopidy,bencevans/mopidy,ali/mopidy,hkariti/mopidy,bencevans/mopidy,pacificIT/mopidy,kingosticks/mopidy,jcass77/mopidy,quartz55/mopidy,jodal/mopidy,glogiotatidis/mopidy,diandian... |
a7bea68d4e904a27c53d08d37093ac5ed2c033f0 | utilities/StartPages.py | utilities/StartPages.py | #--coding:utf-8--
#StartPage.py
#Create/Edit file:'../cfg/StartPage.json'
import os
import re
import sys
import json
from __common__code__ import CreateFile
from __tmpl__ import Prompt
class PromptClass(Prompt.ErrPrompt):
def InitInput(self):
print ("Please input URL(s), use EOF to finish. \n(CTRL+D. if no... | #--coding:utf-8--
#StartPage.py
#Create/Edit file:'../cfg/StartPage.json'
import re
import sys
import json
from __common__code__ import CreateFile
from __tmpl__ import Prompt
class PromptClass(Prompt.ErrPrompt):
def InitInput(self):
print ("Please input URL(s), use EOF to finish. \n(CTRL+D. if not work for... | Fix bug: continue running when fail to open file | Fix bug: continue running when fail to open file
| Python | mit | nday-dev/Spider-Framework |
c136ee96237a05cb717c777dd33b9a3dff9b0015 | test/test_py3.py | test/test_py3.py | import pytest
from in_place import InPlace
from test_in_place_util import UNICODE, pylistdir
def test_py3_textstr(tmpdir):
""" Assert that `InPlace` works with text strings in Python 3 """
assert pylistdir(tmpdir) == []
p = tmpdir.join("file.txt")
p.write_text(UNICODE, 'utf-8')
with I... | import locale
import pytest
from in_place import InPlace
from test_in_place_util import UNICODE, pylistdir
def test_py3_textstr(tmpdir):
""" Assert that `InPlace` works with text strings in Python 3 """
assert pylistdir(tmpdir) == []
p = tmpdir.join("file.txt")
p.write_text(UNICODE, local... | Handle different default encoding on Windows in tests | Handle different default encoding on Windows in tests
| Python | mit | jwodder/inplace |
f5ace7ea8badb2401190e4845fb0216c7a80891e | tests/testall.py | tests/testall.py | #!/usr/bin/env python
import unittest, os, sys
try:
import coverage
coverage.erase()
coverage.start()
except ImportError:
coverage = None
my_dir = os.path.dirname(sys.argv[0])
if not my_dir:
my_dir = os.getcwd()
sys.argv.append('-v')
suite_names = [f[:-3] for f in os.listdir(my_dir)
if f.startswith('test') an... | #!/usr/bin/env python
import unittest, os, sys
try:
import coverage
coverage.erase()
coverage.start()
except ImportError:
coverage = None
my_dir = os.path.dirname(sys.argv[0])
if not my_dir:
my_dir = os.getcwd()
testLoader = unittest.TestLoader()
if len(sys.argv) > 1:
alltests = testLoader.loadTestsFromNames(s... | Allow specifying which unit-tests to run | Allow specifying which unit-tests to run
e.g. 0test ../0release.xml -- testrelease.TestRelease.testBinaryRelease
| Python | lgpl-2.1 | timbertson/0release,0install/0release,0install/0release,gfxmonk/0release |
d190e4466a28714bf0e04869dc11a940526031b1 | fullcalendar/templatetags/fullcalendar.py | fullcalendar/templatetags/fullcalendar.py | from django import template
from fullcalendar.models import Occurrence
register = template.Library()
@register.inclusion_tag('events/agenda_tag.html')
def show_agenda(*args, **kwargs):
qs = Occurrence.objects.upcoming()
if 'limit' in kwargs:
qs.limit(int(kwargs['limit']))
return {
'occu... | from django import template
from fullcalendar.models import Occurrence
register = template.Library()
@register.inclusion_tag('events/agenda_tag.html')
def show_agenda(*args, **kwargs):
qs = Occurrence.objects.upcoming()
if 'limit' in kwargs:
qs = qs[:int(kwargs['limit'])]
return {
'occu... | Use the right way to limit queries | Use the right way to limit queries
| Python | mit | jonge-democraten/mezzanine-fullcalendar |
3a70e339637285355e594f9bec15481eae631a63 | ibmcnx/config/j2ee/RoleBackup.py | ibmcnx/config/j2ee/RoleBackup.py | ######
# Create a backup of J2EE Security Roles
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
#
import sys
import os
import ibmcnx.functions
... | ######
# Create a backup of J2EE Security Roles
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
#
import sys
import os
import ibmcnx.functions
... | Test all scripts on Windows | 10: Test all scripts on Windows
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/10 | Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 |
8dcda9a9dd5c7f106d5544bb185fa348157495fb | blimp_boards/accounts/serializers.py | blimp_boards/accounts/serializers.py | from rest_framework import serializers
from ..utils.fields import DomainNameField
from .fields import SignupDomainsField
from .models import Account
class ValidateSignupDomainsSerializer(serializers.Serializer):
"""
Serializer that handles signup domains validation endpoint.
"""
signup_domains = Sign... | from rest_framework import serializers
from ..utils.fields import DomainNameField
from .fields import SignupDomainsField
from .models import Account
class ValidateSignupDomainsSerializer(serializers.Serializer):
"""
Serializer that handles signup domains validation endpoint.
"""
signup_domains = Sign... | Set Account logo_color to be read only | Set Account logo_color to be read only | Python | agpl-3.0 | jessamynsmith/boards-backend,jessamynsmith/boards-backend,GetBlimp/boards-backend |
243feb2fe194ad00f59c6ff22ac41989fe0978d1 | bots.sample/number-jokes/__init__.py | bots.sample/number-jokes/__init__.py | import random
from botfriend.bot import TextGeneratorBot
class ExampleBot(TextGeneratorBot):
def generate_text(self):
"""Tell a joke about numbers."""
num = random.randint(1,10)
arguments = dict(
num=num,
plus_1=num+1,
plus_3=num+3
)
setu... | import random
from botfriend.bot import TextGeneratorBot
class NumberJokes(TextGeneratorBot):
def generate_text(self):
"""Tell a joke about numbers."""
num = random.randint(1,10)
arguments = dict(
num=num,
plus_1=num+1,
plus_3=num+3
)
set... | Change number-jokes to match the tutorial. | Change number-jokes to match the tutorial.
| Python | mit | leonardr/botfriend |
d01adfce91927c57258f1e13ed34e4e600e40048 | pipenv/pew/__main__.py | pipenv/pew/__main__.py | from pipenv.patched import pew
if __name__ == '__main__':
pew.pew.pew()
| from pipenv.patched import pew
import os
import sys
pipenv_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
pipenv_vendor = os.sep.join([pipenv_root, 'vendor'])
pipenv_patched = os.sep.join([pipenv_root, 'patched'])
if __name__ == '__main__':
sys.path.insert(0, pipenv_vendor)
sys.path.inser... | Add vendor and patch directories to pew path | Add vendor and patch directories to pew path
- Fixes #1661
| Python | mit | kennethreitz/pipenv |
8a61bd499e9a3cc538d7d83719c6d4231753925b | megalista_dataflow/uploaders/uploaders.py | megalista_dataflow/uploaders/uploaders.py | # Copyright 2022 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2022 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Change the notifier to be sent on finish_bundle instead of teardown | Change the notifier to be sent on finish_bundle instead of teardown
Change-Id: I6b80b1d0431b0fe285a5b59e9a33199bf8bd3510
| Python | apache-2.0 | google/megalista,google/megalista |
0c9582598d172585466f89434035cf3e3cafcf61 | frontends/etiquette_flask/etiquette_flask_launch.py | frontends/etiquette_flask/etiquette_flask_launch.py | import gevent.monkey
gevent.monkey.patch_all()
import logging
handler = logging.StreamHandler()
log_format = '{levelname}:etiquette.{module}.{funcName}: {message}'
handler.setFormatter(logging.Formatter(log_format, style='{'))
logging.getLogger().addHandler(handler)
import etiquette_flask
import gevent.pywsgi
import ... | import gevent.monkey
gevent.monkey.patch_all()
import logging
handler = logging.StreamHandler()
log_format = '{levelname}:etiquette.{module}.{funcName}: {message}'
handler.setFormatter(logging.Formatter(log_format, style='{'))
logging.getLogger().addHandler(handler)
import etiquette_flask
import gevent.pywsgi
import ... | Add arg --https even for non-443. | Add arg --https even for non-443.
| Python | bsd-3-clause | voussoir/etiquette,voussoir/etiquette,voussoir/etiquette |
d75d26bc51ed35eec362660e29bda58a91cd418b | pebble_tool/util/npm.py | pebble_tool/util/npm.py | # encoding: utf-8
from __future__ import absolute_import, print_function, division
import os
import subprocess
from pebble_tool.exceptions import ToolError
from pebble_tool.util.versions import version_to_key
def check_npm():
try:
npm_version = subprocess.check_output(["npm", "--version"]).strip()
... | # encoding: utf-8
from __future__ import absolute_import, print_function, division
import os
import subprocess
from pebble_tool.exceptions import ToolError
from pebble_tool.util.versions import version_to_key
def check_npm():
try:
npm_version = subprocess.check_output(["npm", "--version"]).strip()
... | Add check for isdir to handle non-directories | Add check for isdir to handle non-directories
| Python | mit | pebble/pebble-tool,pebble/pebble-tool,gregoiresage/pebble-tool,pebble/pebble-tool,gregoiresage/pebble-tool,gregoiresage/pebble-tool,gregoiresage/pebble-tool,pebble/pebble-tool |
003d3921bb6c801c5a2efdede20ed70ee07edf3d | src/nodeconductor_openstack/openstack/migrations/0031_tenant_backup_storage.py | src/nodeconductor_openstack/openstack/migrations/0031_tenant_backup_storage.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.contenttypes.models import ContentType
from django.db import migrations
from nodeconductor.quotas import models as quotas_models
from .. import models
def delete_backup_storage_quota_from_tenant(apps, schema_editor):
tenant_con... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.contenttypes.models import ContentType
from django.db import migrations
from nodeconductor.quotas import models as quotas_models
from .. import models
def cleanup_tenant_quotas(apps, schema_editor):
for obj in models.Tenant.obj... | Replace quota deletion with cleanup | Replace quota deletion with cleanup [WAL-433]
| Python | mit | opennode/nodeconductor-openstack |
878975b1b82d22bba0ac23cf162eb68b46e76f0a | wagtail/wagtailembeds/finders/__init__.py | wagtail/wagtailembeds/finders/__init__.py | from django.utils.module_loading import import_string
from django.conf import settings
from wagtail.wagtailembeds.finders.oembed import oembed
from wagtail.wagtailembeds.finders.embedly import embedly
MOVED_FINDERS = {
'wagtail.wagtailembeds.embeds.embedly': 'wagtail.wagtailembeds.finders.embedly.embedly',
'... | from django.utils.module_loading import import_string
from django.conf import settings
MOVED_FINDERS = {
'wagtail.wagtailembeds.embeds.embedly': 'wagtail.wagtailembeds.finders.embedly.embedly',
'wagtail.wagtailembeds.embeds.oembed': 'wagtail.wagtailembeds.finders.oembed.oembed',
}
def get_default_finder():
... | Refactor get_default_finder to work without importing finders | Refactor get_default_finder to work without importing finders
| Python | bsd-3-clause | takeflight/wagtail,mikedingjan/wagtail,JoshBarr/wagtail,gasman/wagtail,chrxr/wagtail,FlipperPA/wagtail,JoshBarr/wagtail,inonit/wagtail,wagtail/wagtail,nilnvoid/wagtail,mikedingjan/wagtail,gasman/wagtail,timorieber/wagtail,torchbox/wagtail,jnns/wagtail,hamsterbacke23/wagtail,nealtodd/wagtail,iansprice/wagtail,timorieber... |
a8244c25c5cc7e2279723538daa9889a1d327cae | extensions/ExtGameController.py | extensions/ExtGameController.py | from python_cowbull_game.GameController import GameController
from python_cowbull_game.GameMode import GameMode
class ExtGameController(GameController):
additional_modes = [
GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0),
GameMode(mode="hexTough", priority=5, digits=3, guesses_al... | from python_cowbull_game.GameController import GameController
from python_cowbull_game.GameMode import GameMode
class ExtGameController(GameController):
additional_modes = [
# GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0),
# GameMode(mode="hexTough", priority=5, digits=3, guesses_... | Remove new modes for testing. | Remove new modes for testing.
| Python | apache-2.0 | dsandersAzure/python_cowbull_server,dsandersAzure/python_cowbull_server |
b678d2da0845ae7f567eb6c4cd55471974d5b5e1 | apps/storybase_user/models.py | apps/storybase_user/models.py | from django.contrib.auth.models import User
from django.db import models
from uuidfield.fields import UUIDField
from storybase.fields import ShortTextField
class Organization(models.Model):
""" An organization or a community group that users and stories can be associated with. """
organization_id = UUIDField(a... | from django.contrib.auth.models import User
from django.db import models
from uuidfield.fields import UUIDField
from storybase.fields import ShortTextField
class Organization(models.Model):
""" An organization or a community group that users and stories can be associated with. """
organization_id = UUIDField(a... | Use correct named view for organization detail view | Use correct named view for organization detail view
| Python | mit | denverfoundation/storybase,denverfoundation/storybase,denverfoundation/storybase,denverfoundation/storybase |
c09f346f7a2be5bdfd5dca8821ab260494a652af | routines/migrate-all.py | routines/migrate-all.py | from pmxbot import logging
from pmxbot import util
from pmxbot import rss
from pmxbot import storage
storage.migrate_all('sqlite:pmxbot.sqlite', 'mongodb://localhost')
| import importlib
import pmxbot.storage
def run():
# load the storage classes so the migration routine will find them.
for mod in ('pmxbot.logging', 'pmxbot.karma', 'pmxbot.quotes',
'pmxbot.rss'):
importlib.import_module(mod)
pmxbot.storage.migrate_all('sqlite:pmxbot.sqlite', 'mongodb://localhost')
if __name_... | Update migration script so it only runs if executed as a script. Also updated module references. | Update migration script so it only runs if executed as a script. Also updated module references.
| Python | bsd-3-clause | jamwt/diesel-pmxbot,jamwt/diesel-pmxbot |
793baa838b7bc7bfed3eb74a69c297645b4c5da6 | app/passthrough/views.py | app/passthrough/views.py | import boto3
import botocore
from flask import (
abort,
current_app,
flash,
make_response,
redirect,
request,
Response,
url_for,
)
from flask_login import current_user
from . import passthrough_bp
@passthrough_bp.route('/<path:path>')
def passthrough(path):
if not current_user.is_a... | import boto3
import botocore
from flask import (
abort,
current_app,
flash,
make_response,
redirect,
request,
Response,
url_for,
)
from flask_login import current_user
from . import passthrough_bp
@passthrough_bp.route('/<path:path>')
def passthrough(path):
if not current_user.is_a... | Handle the case of an empty path | Handle the case of an empty path
This will deal with the root domain request going to default page. | Python | mit | iandees/bucket-protection,iandees/bucket-protection |
3daa15b0ccb3fc4891daf55724cbeaa705f923e5 | scripts/clio_daemon.py | scripts/clio_daemon.py |
import logging
import simpledaemon
class clio_daemon(simpledaemon.Daemon):
default_conf = 'clio_daemon.conf'
section = 'clio'
def run(self):
import eventlet
from clio.store import app
logger = logging.getLogger()
if logger.handlers:
[app.logger.addHandler(h) f... |
import simpledaemon
class clio_daemon(simpledaemon.Daemon):
default_conf = 'clio_daemon.conf'
section = 'clio'
def run(self):
import eventlet
from clio.store import app
eventlet.serve(eventlet.listen((app.config['HOST'], app.config['PORT']), backlog=2048), app)
if __name__ == '__... | Revert "output flask logging into simpledaemon's log file." | Revert "output flask logging into simpledaemon's log file."
This is completely superfluous - logging does this already
automatically.
This reverts commit 18091efef351ecddb1d29ee7d01d0a7fb567a7b7.
| Python | apache-2.0 | geodelic/clio,geodelic/clio |
d19f054cdc68d0060731d6c742886f94ac41f3ab | diceclient.py | diceclient.py | #!/usr/bin/env python
import sys
from twisted.internet import reactor, defer
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp
from twisted.python import usage
from diceserver import RollDice, port
class Options(usage.Options):
optParameters = [
["host", "h",... | #!/usr/bin/env python
import sys
from twisted.internet import reactor, defer
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp
from twisted.python import usage
from diceserver import RollDice, port
class Options(usage.Options):
optParameters = [
["host", "h",... | Make done a top-level function rather than a nested one. | Make done a top-level function rather than a nested one.
| Python | mit | dripton/ampchat |
cdb546a9db593d79c2b9935b746e9862a2b1221c | winthrop/people/urls.py | winthrop/people/urls.py | from django.conf.urls import url
from django.contrib.admin.views.decorators import staff_member_required
from winthrop.people.views import ViafAutoSuggest
urlpatterns = [
url(r'^autocomplete/viaf/suggest/$', staff_member_required(ViafAutoSuggest.as_view()),
name='autocomplete-suggest'),
]
| from django.conf.urls import url
from django.contrib.admin.views.decorators import staff_member_required
from winthrop.people.views import ViafAutoSuggest
urlpatterns = [
url(r'^autocomplete/viaf/suggest/$', staff_member_required(ViafAutoSuggest.as_view()),
name='viaf-autosuggest'),
]
| Make the url name for autosuggest clearer | Make the url name for autosuggest clearer
| Python | apache-2.0 | Princeton-CDH/winthrop-django,Princeton-CDH/winthrop-django,Princeton-CDH/winthrop-django |
8589af4b858acace99cc856ce118f73568fb96b1 | main.py | main.py | #!/usr/bin/env python3.6
import argparse
import asyncio
import logging
import sys
from pathlib import Path
from MoMMI.logsetup import setup_logs
# Do this BEFORE we import master, because it does a lot of event loop stuff.
if sys.platform == "win32":
loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(lo... | #!/usr/bin/env python3.6
import argparse
import asyncio
import logging
import sys
from pathlib import Path
from MoMMI.logsetup import setup_logs
# Do this BEFORE we import master, because it does a lot of event loop stuff.
if sys.platform == "win32":
loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(lo... | Make uvloop except be explicit ImportError | Make uvloop except be explicit ImportError
| Python | mit | PJB3005/MoMMI,PJB3005/MoMMI,PJB3005/MoMMI |
306dc0d7e96d91b417a702230a9d34fa1dbcc289 | util.py | util.py | import collections
def flatten(l, ltypes=collections.Sequence):
l = list(l)
while l:
if isinstance(l[0], str):
yield l.pop(0)
continue
while l and isinstance(l[0], ltypes):
l[0:1] = l[0]
if l:
yield l.pop(0)
noop = lambda self, *a, **kw:... | import collections
def flatten(l, ltypes=collections.Sequence):
l = list(l)
while l:
if isinstance(l[0], str):
yield l.pop(0)
continue
while l and isinstance(l[0], ltypes):
l[0:1] = l[0]
if l:
yield l.pop(0)
def getattrpath(obj, path):
... | Add helpers for nested attributes | Add helpers for nested attributes
getattrpath is for nested retrieval (getting obj.a.b.c with
getattrpath(obj, 'a.b.c))
prefix_keys generates key, value pairs with the prefix prepended to each
key.
| Python | mit | numberoverzero/origami |
6c7c69fccd924ab65219c7f28dbdef66bec7181a | 4/src.py | 4/src.py | import sys
from itertools import imap
from collections import Counter
class Room:
pass
def parse_room(s):
last_dash = s.rfind("-")
after_name = s[last_dash+1:]
bracket = after_name.find("[")
room = Room()
room.name = s[:last_dash]
room.sector = int(after_name[:bracket])
room.checksum ... | import sys
from itertools import imap
from collections import Counter
class Room:
pass
def parse_room(s):
last_dash = s.rfind("-")
after_name = s[last_dash+1:]
bracket = after_name.find("[")
room = Room()
room.name = s[:last_dash]
room.sector = int(after_name[:bracket])
room.checksum ... | Replace lambda with higher-order function | Replace lambda with higher-order function
| Python | mit | amalloy/advent-of-code-2016 |
3f160ac663ff37b5b8b16ebe630536521969d079 | text.py | text.py | import ibmcnx.filehandle
emp1 = ibmcnx.filehandle.Ibmcnxfile()
emp1.writeToFile( execfile('ibmcnx/doc/JVMSettings.py' ) )
#emp1.writeToFile("Test2")
#emp1.writeToFile("Test3")
emp1.closeFile()
| import ibmcnx.filehandle
import sys
sys.stdout = open("/tmp/documentation.txt", "w")
print "test"
execfile('ibmcnx/doc/JVMSettings.py' )
| Create script to save documentation to a file | 4: Create script to save documentation to a file
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/4 | Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 |
b725eac62c72dd3674f35898ff6704c613e7272d | bears/julia/JuliaLintBear.py | bears/julia/JuliaLintBear.py | from coalib.bearlib.abstractions.Lint import Lint
from coalib.bears.LocalBear import LocalBear
from coalib.results.RESULT_SEVERITY import RESULT_SEVERITY
class JuliaLintBear(LocalBear, Lint):
executable = 'julia'
arguments = '-e \'import Lint.lintfile; lintfile({filename})\''
output_regex = r'(^.*\.jl):(?... | from coalib.bearlib.abstractions.Lint import Lint
from coalib.bears.LocalBear import LocalBear
from coalib.results.RESULT_SEVERITY import RESULT_SEVERITY
class JuliaLintBear(LocalBear, Lint):
executable = 'julia'
arguments = '-e \'import Lint.lintfile; lintfile({filename})\''
prerequisite_command = ['juli... | Add Skip Condition for JuliaBear | bears/julia: Add Skip Condition for JuliaBear
Add prerequisite_command and prerequisite_fail_msg
to JuliaBear.
Fixes https://github.com/coala-analyzer/coala-bears/issues/222
| Python | agpl-3.0 | yash-nisar/coala-bears,naveentata/coala-bears,kaustubhhiware/coala-bears,mr-karan/coala-bears,shreyans800755/coala-bears,sims1253/coala-bears,coala-analyzer/coala-bears,coala/coala-bears,coala-analyzer/coala-bears,chriscoyfish/coala-bears,seblat/coala-bears,Vamshi99/coala-bears,seblat/coala-bears,sounak98/coala-bears,L... |
e38f81fff1edf83bc6739804447e4a64a0a76de8 | apps/persona/urls.py | apps/persona/urls.py | from django.conf.urls.defaults import *
from mozorg.util import page
import views
urlpatterns = patterns('',
page('', 'persona/persona.html'),
page('about', 'persona/about.html'),
page('privacy-policy', 'persona/privacy-policy.html'),
page('terms-of-service', 'persona/terms-of-service.html'),
page(... | from django.conf.urls.defaults import *
from mozorg.util import page
urlpatterns = patterns('',
page('', 'persona/persona.html'),
page('about', 'persona/about.html'),
page('privacy-policy', 'persona/privacy-policy.html'),
page('terms-of-service', 'persona/terms-of-service.html'),
page('developer-fa... | Remove unnecessary 'import views' line | Remove unnecessary 'import views' line
| Python | mpl-2.0 | mmmavis/bedrock,pmclanahan/bedrock,malena/bedrock,craigcook/bedrock,dudepare/bedrock,davehunt/bedrock,flodolo/bedrock,dudepare/bedrock,schalkneethling/bedrock,mahinthjoe/bedrock,analytics-pros/mozilla-bedrock,flodolo/bedrock,mkmelin/bedrock,mermi/bedrock,pmclanahan/bedrock,SujaySKumar/bedrock,mmmavis/bedrock,mahinthjoe... |
cd5c50c94f2240c3d4996e38cc1712e5f397120f | datalogger/__init__.py | datalogger/__init__.py | from datalogger import api
from datalogger import analysis
from datalogger import acquisition
from datalogger import analysis_window, acquisition_window
#from datalogger.api import workspace as workspace
from datalogger.api import workspace as workspace
import os.path as _path
_PKG_ROOT = _path.abspath(_path.dirname(... | from datalogger import api
from datalogger import analysis
from datalogger import acquisition
from datalogger import analysis_window, acquisition_window
#from datalogger.api import workspace as workspace
from datalogger.api import workspace as workspace
import os.path as _path
_PKG_ROOT = _path.abspath(_path.dirname(... | Add __version__=None if no VERSION found | Add __version__=None if no VERSION found
| Python | bsd-3-clause | torebutlin/cued_datalogger |
493df570353fbeff288d6ee61fb0842622443967 | sleekxmpp/thirdparty/__init__.py | sleekxmpp/thirdparty/__init__.py | try:
from ordereddict import OrderedDict
except:
from sleekxmpp.thirdparty.ordereddict import OrderedDict
| try:
from collections import OrderedDict
except:
from sleekxmpp.thirdparty.ordereddict import OrderedDict
| Fix thirdparty imports for Python3 | Fix thirdparty imports for Python3
| Python | mit | destroy/SleekXMPP-gevent |
53dc5e1029ea905f6e5da86592b33911309d1acd | bdateutil/__init__.py | bdateutil/__init__.py | # bdateutil
# -----------
# Adds business day logic and improved data type flexibility to
# python-dateutil.
#
# Author: ryanss <ryanssdev@icloud.com>
# Website: https://github.com/ryanss/bdateutil
# License: MIT (see LICENSE file)
__version__ = '0.1-dev'
from dateutil.relativedelta import MO, TU, WE, TH, FR... | # bdateutil
# -----------
# Adds business day logic and improved data type flexibility to
# python-dateutil.
#
# Author: ryanss <ryanssdev@icloud.com>
# Website: https://github.com/ryanss/bdateutil
# License: MIT (see LICENSE file)
__version__ = '0.1-dev'
from dateutil.relativedelta import MO, TU, WE, TH, FR... | Fix import statement in Python 3 | Fix import statement in Python 3
| Python | mit | pganssle/bdateutil |
4d7c1fec37943558ccc8bf6a17860b2a86fe1941 | gee_asset_manager/batch_copy.py | gee_asset_manager/batch_copy.py | import ee
import os
import csv
import logging
def copy(source, destination):
with open(source, 'r') as f:
reader = csv.reader(f)
for line in reader:
name = line[0]
gme_id = line[1]
gme_path = 'GME/images/' + gme_id
ee_path = os.path.join(destination, ... | import ee
import os
import csv
import logging
def copy(source, destination):
with open(source, 'r') as f:
reader = csv.reader(f)
for line in reader:
name = line[0]
gme_id = line[1]
gme_path = 'GME/images/' + gme_id
ee_path = os.path.join(destination, ... | Add exception handling to batch copy | Add exception handling to batch copy
| Python | apache-2.0 | tracek/gee_asset_manager |
cf4b58ff5afa6c7c8649e89b430b5386fabdc02c | djmoney/serializers.py | djmoney/serializers.py | # coding=utf-8
import json
from decimal import Decimal
from django.core.serializers.python import Deserializer as PythonDeserializer
from django.core.serializers.json import Serializer as JSONSerializer
from django.core.serializers.python import _get_model
from django.utils import six
from djmoney.models.fields impo... | # coding=utf-8
import json
from decimal import Decimal
from django.core.serializers.python import Deserializer as PythonDeserializer
from django.core.serializers.json import Serializer as JSONSerializer
from django.core.serializers.python import _get_model
from django.utils import six
from djmoney.models.fields impo... | Fix for de-serialization. Using vanilla django-money, when one did the following: | Fix for de-serialization.
Using vanilla django-money, when one did the following:
./manage.py dumpdata
the values were saved properly, i.e:
{
'amount': '12',
'amount_currency': 'USD',
}
however, after the de-serialization:
./manage.py loaddata [fixtures]
the currencies were omitted.
i have no idea (yet) how ... | Python | bsd-3-clause | rescale/django-money,tsouvarev/django-money,iXioN/django-money,iXioN/django-money,recklessromeo/django-money,recklessromeo/django-money,tsouvarev/django-money,AlexRiina/django-money |
9719a31459e033cc84a5a522e4fc618aa11b45fe | charlesbot/util/http.py | charlesbot/util/http.py | import asyncio
import aiohttp
import logging
log = logging.getLogger(__name__)
@asyncio.coroutine
def http_get_auth_request(auth_string,
url,
content_type="application/json",
auth_method="Token",
payload={}):
h... | import asyncio
import aiohttp
import logging
log = logging.getLogger(__name__)
@asyncio.coroutine
def http_get_auth_request(auth_string,
url,
content_type="application/json",
auth_method="Token",
payload={}):
h... | Print the URL that erred out, along with the other info | Print the URL that erred out, along with the other info
| Python | mit | marvinpinto/charlesbot,marvinpinto/charlesbot |
d9ab4683a8c5859b8d5e2579dbfe1f718f3ff423 | skylines/tests/test_i18n.py | skylines/tests/test_i18n.py | import os
import sys
import glob
from babel.messages.pofile import read_po
import nose
def get_language_code(filename):
filename = os.path.split(filename)[0]
filename = os.path.split(filename)[0]
filename = os.path.split(filename)[1]
return filename
def test_pofiles():
for filename in glob.glob(... | import os
import sys
import glob
from babel.messages.pofile import read_po
import nose
def get_language_code(filename):
filename = os.path.split(filename)[0]
filename = os.path.split(filename)[0]
filename = os.path.split(filename)[1]
return filename
def test_pofiles():
for filename in glob.glob(... | Raise AssertionError to mark tests as failed instead of errored | tests: Raise AssertionError to mark tests as failed instead of errored
| Python | agpl-3.0 | snip/skylines,Turbo87/skylines,kerel-fs/skylines,Harry-R/skylines,kerel-fs/skylines,TobiasLohner/SkyLines,Turbo87/skylines,skylines-project/skylines,snip/skylines,RBE-Avionik/skylines,RBE-Avionik/skylines,shadowoneau/skylines,Turbo87/skylines,Harry-R/skylines,TobiasLohner/SkyLines,RBE-Avionik/skylines,Turbo87/skylines,... |
9e745b0e5ac673d04d978887654627b686813d93 | cms/apps/pages/tests/urls.py | cms/apps/pages/tests/urls.py | from django.conf.urls import patterns, url
def view():
pass
urlpatterns = patterns(
"",
url("^$", view, name="index"),
url("^(?P<url_title>[^/]+)/$", view, name="detail"),
)
| from django.conf.urls import patterns, url
urlpatterns = patterns(
"",
url("^$", lambda: None, name="index"),
url("^(?P<url_title>[^/]+)/$", lambda: None, name="detail"),
)
| Replace page test url views with lambdas. | Replace page test url views with lambdas.
| Python | bsd-3-clause | danielsamuels/cms,jamesfoley/cms,dan-gamble/cms,lewiscollard/cms,jamesfoley/cms,jamesfoley/cms,lewiscollard/cms,danielsamuels/cms,lewiscollard/cms,jamesfoley/cms,dan-gamble/cms,danielsamuels/cms,dan-gamble/cms |
621a97a0904e085c33ef78d68cd733af0d816aee | app/aflafrettir/routes.py | app/aflafrettir/routes.py | from flask import render_template
from . import aflafrettir
@aflafrettir.route('/')
def index():
return render_template('aflafrettir/index.html')
@talks.route('/user/<username>')
def user(username):
return render_template('aflafrettir/index.html', username = username)
| from flask import render_template
from . import aflafrettir
@aflafrettir.route('/')
def index():
return render_template('aflafrettir/index.html')
@aflafrettir.route('/user/<username>')
def user(username):
return render_template('aflafrettir/user.html', username = username)
| Use the correct template, and call the aflafrettir route decorator | Use the correct template, and call the aflafrettir route decorator
| Python | mit | finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is |
517668eeb493bcd72838716258d40abd4a73e039 | alexandria/views/user.py | alexandria/views/user.py | from pyramid.view import (
view_config,
view_defaults,
)
from pyramid.security import (
remember,
forget,
)
@view_defaults(accept='application/json', renderer='json', context='..traversal.User')
class User(object):
def __init__(self, context, request):
self.... | from pyramid.view import (
view_config,
view_defaults,
)
from pyramid.httpexceptions import HTTPSeeOther
from pyramid.security import (
remember,
forget,
)
@view_defaults(accept='application/json', renderer='json', context='..traversal.User')
class User(object):
de... | Implement the login/logout functionality on the REST endpoints | Implement the login/logout functionality on the REST endpoints
| Python | isc | cdunklau/alexandria,bertjwregeer/alexandria,cdunklau/alexandria,cdunklau/alexandria,bertjwregeer/alexandria |
36edb0e161fd3c65d2957b7b319b67975e846e7e | src/sentry/templatetags/sentry_assets.py | src/sentry/templatetags/sentry_assets.py | from __future__ import absolute_import
from django.template import Library
from sentry.utils.assets import get_asset_url
register = Library()
@register.simple_tag
def asset_url(module, path):
"""
Returns a versioned asset URL (located within Sentry's static files).
Example:
{% asset_url 'sentry'... | from __future__ import absolute_import
from django.template import Library
from sentry.utils.assets import get_asset_url
from sentry.utils.http import absolute_uri
register = Library()
@register.simple_tag
def asset_url(module, path):
"""
Returns a versioned asset URL (located within Sentry's static files)... | Make all asset URLs absolute | Make all asset URLs absolute
| Python | bsd-3-clause | mvaled/sentry,looker/sentry,JamesMura/sentry,zenefits/sentry,BuildingLink/sentry,gencer/sentry,ifduyue/sentry,BuildingLink/sentry,fotinakis/sentry,mitsuhiko/sentry,zenefits/sentry,fotinakis/sentry,gencer/sentry,looker/sentry,beeftornado/sentry,gencer/sentry,mitsuhiko/sentry,BayanGroup/sentry,fotinakis/sentry,daevaorn/s... |
75eacb13930ef03c1ebc1ff619f47b54cde85532 | examples/hello.py | examples/hello.py | from cell import Actor, Agent
from cell.actors import Server
from kombu import Connection
from kombu.log import setup_logging
connection = Connection()
class GreetingActor(Server):
default_routing_key = 'GreetingActor'
class state:
def greet(self, who='world'):
return 'Hello %s' % who... | from cell import Actor, Agent
from cell.actors import Server
from kombu import Connection
from kombu.log import setup_logging
connection = Connection()
class GreetingActor(Server):
default_routing_key = 'GreetingActor'
class state:
def greet(self, who='world'):
return 'Hello %s' % who
... | Use the Server class (an Actor derived class) | Use the Server class (an Actor derived class)
| Python | bsd-3-clause | celery/cell,celery/cell |
ddec6067054cc4408ac174e3ea4ffeca2a962201 | regulations/views/notice_home.py | regulations/views/notice_home.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from operator import itemgetter
import logging
from django.http import Http404
from django.template.response import TemplateResponse
from django.views.generic.base import View
from regulations.generator.api_reader import ApiReader
from regulations.vie... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from operator import itemgetter
import logging
from django.http import Http404
from django.template.response import TemplateResponse
from django.views.generic.base import View
from regulations.generator.api_reader import ApiReader
from regulations.vie... | Remove unnecessary assert from view for Notice home. | Remove unnecessary assert from view for Notice home.
| Python | cc0-1.0 | 18F/regulations-site,18F/regulations-site,eregs/regulations-site,tadhg-ohiggins/regulations-site,tadhg-ohiggins/regulations-site,tadhg-ohiggins/regulations-site,eregs/regulations-site,eregs/regulations-site,eregs/regulations-site,tadhg-ohiggins/regulations-site,18F/regulations-site,18F/regulations-site |
a0af5dc1478fe8b639cc5a37898ad180f1f20a89 | src/twelve_tone/cli.py | src/twelve_tone/cli.py | """
Module that contains the command line app.
Why does this file exist, and why not put this in __main__?
You might be tempted to import things from __main__ later, but that will cause
problems: the code will get executed twice:
- When you run `python -mtwelve_tone` python will execute
``__main__.py`` as ... | """
Module that contains the command line app.
Why does this file exist, and why not put this in __main__?
You might be tempted to import things from __main__ later, but that will cause
problems: the code will get executed twice:
- When you run `python -mtwelve_tone` python will execute
``__main__.py`` as ... | Add --midi option to CLI | Add --midi option to CLI
| Python | bsd-2-clause | accraze/python-twelve-tone |
3868a4ef30835ed1904a37318013e20f2295a8a9 | ckanext/cob/plugin.py | ckanext/cob/plugin.py | import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
def groups():
# Return a list of groups
return toolkit.get_action('group_list')(data_dict={'all_fields': True})
def dataset_count():
# Return a count of all datasets
result = toolkit.get_action('package_search')(data_dict={'rows': 1... | import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
def groups():
# Return a list of groups
return toolkit.get_action('group_list')(data_dict={'all_fields': True})
def dataset_count():
# Return a count of all datasets
result = toolkit.get_action('package_search')(data_dict={'rows': 1... | Remove fantastic from COB theme | Remove fantastic from COB theme
Updates #10
| Python | agpl-3.0 | City-of-Bloomington/ckanext-cob,City-of-Bloomington/ckanext-cob |
7cac8f8ba591315d68e223503c4e93f976c8d89d | characters/views.py | characters/views.py | from django.shortcuts import get_object_or_404, redirect, render
from characters.forms import CharacterForm
from characters.models import Character, Class, Race
def index(request):
all_characters = Character.objects.all()
context = {'all_characters': all_characters}
return render(request, 'characters/ind... | from django.shortcuts import get_object_or_404, redirect, render
from characters.forms import CharacterForm
from characters.models import Character, Class, Race
def index(request):
all_characters = Character.objects.all()
context = {'all_characters': all_characters}
return render(request, 'characters/ind... | Set default race and class without extra database queries | Set default race and class without extra database queries
| Python | mit | mpirnat/django-tutorial-v2 |
dc50a4ec058f9893e87a069bc64e4715ecfa0bea | haas_rest_test/plugins/assertions.py | haas_rest_test/plugins/assertions.py | # -*- coding: utf-8 -*-
# Copyright (c) 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.
from __future__ import absolute_import, unicode_literals
class StatusCodeAssertion(object):
_sche... | # -*- coding: utf-8 -*-
# Copyright (c) 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.
from __future__ import absolute_import, unicode_literals
from jsonschema.exceptions import ValidationEr... | Add initial status code assertion | Add initial status code assertion
| Python | bsd-3-clause | sjagoe/usagi |
dbec204b242ab643de162046ba73dca32043c6c2 | space-age/space_age.py | space-age/space_age.py | class SpaceAge(object):
def __init__(self, seconds):
self.seconds = seconds
@property
def years(self):
return self.seconds/31557600
def on_earth(self):
return round(self.years, 2)
def on_mercury(self):
return round(self.years/0.2408467, 2)
def on_venus(self):
... | class SpaceAge(object):
YEARS = {"on_earth": 1,
"on_mercury": 0.2408467,
"on_venus": 0.61519726,
"on_mars": 1.8808158,
"on_jupiter": 11.862615,
"on_saturn": 29.447498,
"on_uranus": 84.016846,
"on_neptune": 164.79132}
def... | Implement __getattr__ to reduce code | Implement __getattr__ to reduce code
| Python | agpl-3.0 | CubicComet/exercism-python-solutions |
ea8cbcaf41f01a46390882fbc99e6e14d70a49d1 | src/mmw/apps/user/models.py | src/mmw/apps/user/models.py | # -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from django.db import models
class ItsiUserManager(models.Manager):
def create_itsi_user(self, user, itsi_id):
itsi_user = self.create(user=user, itsi_id=itsi_id)
return itsi_user
class ItsiUser(models.Model):
user = models.... | # -*- coding: utf-8 -*-
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
@receiver(post_save, sender=settings.AUTH_USER_MODEL... | Create an API auth token for every newly created user | Create an API auth token for every newly created user
* Add a post_save signal to add a new authtoken for every new user. For use with
the Geoprocessing API
| Python | apache-2.0 | WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed |
137271045313a12bbe9388ab1ac6c8cb786b32b7 | guardian/testapp/tests/test_management.py | guardian/testapp/tests/test_management.py | from __future__ import absolute_import
from __future__ import unicode_literals
from guardian.compat import get_user_model
from guardian.compat import mock
from guardian.compat import unittest
from guardian.management import create_anonymous_user
import django
mocked_get_init_anon = mock.Mock()
class TestGetAnonymo... | from __future__ import absolute_import
from __future__ import unicode_literals
from guardian.compat import get_user_model
from guardian.compat import mock
from guardian.compat import unittest
from guardian.management import create_anonymous_user
import django
mocked_get_init_anon = mock.Mock()
class TestGetAnonymo... | Reset mock befor running test. | Reset mock befor running test.
Not strictly required however ensures test doesn't fail if run multiple
times in succession.
| Python | bsd-2-clause | benkonrath/django-guardian,benkonrath/django-guardian,rmgorman/django-guardian,lukaszb/django-guardian,lukaszb/django-guardian,rmgorman/django-guardian,lukaszb/django-guardian,rmgorman/django-guardian,benkonrath/django-guardian |
30020d3826a2460288b6a57963753787020a945a | temporenc/temporenc.py | temporenc/temporenc.py |
def packb(type=None, year=None, month=None, day=None):
raise NotImplementedError()
|
import struct
SUPPORTED_TYPES = set([
'D',
'T',
'DT',
'DTZ',
'DTS',
'DTSZ',
])
STRUCT_32 = struct.Struct('>L')
def packb(type=None, year=None, month=None, day=None):
"""
Pack date and time information into a byte string.
:return: encoded temporenc value
:rtype: bytes
""... | Implement support for the 'D' type in packb() | Implement support for the 'D' type in packb()
| Python | bsd-3-clause | wbolster/temporenc-python |
7b746d2d4ae732ee1eae326254f3a6df676a7973 | components/table.py | components/table.py | """A class to store tables."""
class SgTable:
"""A class to store tables."""
def __init__(self):
self._fields = []
self._table = []
def __len__(self):
return len(self._table)
def __iter__(self):
for row in self._table:
yield row
def __getitem__(self,... | """A class to store tables."""
class SgTable:
"""A class to store tables."""
def __init__(self):
self._fields = []
self._table = []
def __len__(self):
return len(self._table)
def __iter__(self):
for row in self._table:
yield row
def __getitem__(self,... | Add __str__ function for SgTable | Add __str__ function for SgTable
| Python | mit | lnishan/SQLGitHub |
0c160c8e787a9019571f358b70633efa13cad466 | inbox/util/__init__.py | inbox/util/__init__.py | """ Non-server-specific utility modules. These shouldn't depend on any code
from the inbox module tree!
Don't add new code here! Find the relevant submodule, or use misc.py if
there's really no other place.
"""
| """ Non-server-specific utility modules. These shouldn't depend on any code
from the inbox module tree!
Don't add new code here! Find the relevant submodule, or use misc.py if
there's really no other place.
"""
# Allow out-of-tree submodules.
from pkgutil import extend_path
__path__ = extend_path(__path__,... | Support for inbox.util.eas in the /inbox-eas repo; this is where EAS-specific util code would live. | Support for inbox.util.eas in the /inbox-eas repo; this is where EAS-specific util code would live.
Summary: As above.
Test Plan: Sync runs as before.
Reviewers: spang
Differential Revision: https://review.inboxapp.com/D226
| Python | agpl-3.0 | gale320/sync-engine,Eagles2F/sync-engine,jobscore/sync-engine,wakermahmud/sync-engine,EthanBlackburn/sync-engine,jobscore/sync-engine,Eagles2F/sync-engine,PriviPK/privipk-sync-engine,wakermahmud/sync-engine,Eagles2F/sync-engine,closeio/nylas,Eagles2F/sync-engine,wakermahmud/sync-engine,ErinCall/sync-engine,rmasters/inb... |
933a082a76c6c9b72aaf275f45f0d155f66eeacf | asv/__init__.py | asv/__init__.py | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
| # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import sys
if sys.version_info >= (3, 3):
# OS X framework builds of Python 3.3 can not call other 3.3
# virtual... | Fix Python 3.3 calling another virtualenv as a subprocess. | Fix Python 3.3 calling another virtualenv as a subprocess.
| Python | bsd-3-clause | waylonflinn/asv,airspeed-velocity/asv,edisongustavo/asv,giltis/asv,giltis/asv,qwhelan/asv,edisongustavo/asv,pv/asv,edisongustavo/asv,waylonflinn/asv,mdboom/asv,qwhelan/asv,cpcloud/asv,spacetelescope/asv,qwhelan/asv,pv/asv,giltis/asv,ericdill/asv,cpcloud/asv,mdboom/asv,mdboom/asv,ericdill/asv,cpcloud/asv,pv/asv,airspeed... |
20e8ef6bd68100a70b9d50013630ff71d8b7ec94 | changes/artifacts/__init__.py | changes/artifacts/__init__.py | from __future__ import absolute_import, print_function
from .manager import Manager
from .coverage import CoverageHandler
from .xunit import XunitHandler
manager = Manager()
manager.register(CoverageHandler, ['coverage.xml'])
manager.register(XunitHandler, ['xunit.xml', 'junit.xml'])
| from __future__ import absolute_import, print_function
from .manager import Manager
from .coverage import CoverageHandler
from .xunit import XunitHandler
manager = Manager()
manager.register(CoverageHandler, ['coverage.xml', '*.coverage.xml'])
manager.register(XunitHandler, ['xunit.xml', 'junit.xml', '*.xunit.xml', ... | Support wildcard matches on coverage/junit results | Support wildcard matches on coverage/junit results
| Python | apache-2.0 | dropbox/changes,bowlofstew/changes,wfxiang08/changes,dropbox/changes,wfxiang08/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes |
ae8f9c39cd75d837a4cb5a4cea4d3d11fd1cabed | tests/test_comments.py | tests/test_comments.py | from hypothesis_auto import auto_pytest_magic
from isort import comments
auto_pytest_magic(comments.parse)
auto_pytest_magic(comments.add_to_line)
| from hypothesis_auto import auto_pytest_magic
from isort import comments
auto_pytest_magic(comments.parse)
auto_pytest_magic(comments.add_to_line)
def test_add_to_line():
assert comments.add_to_line([], "import os # comment", removed=True).strip() == "import os"
| Add additional test case for comments | Add additional test case for comments
| Python | mit | PyCQA/isort,PyCQA/isort |
270c8ca68357f92999474fbf110fed7b01cdfdf2 | cqlengine/__init__.py | cqlengine/__init__.py | import os
from cqlengine.columns import *
from cqlengine.functions import *
from cqlengine.models import Model
from cqlengine.query import BatchQuery
__cqlengine_version_path__ = os.path.realpath(__file__ + '/../VERSION')
__version__ = open(__cqlengine_version_path__, 'r').readline().strip()
# compaction
SizeTieredC... | import os
import pkg_resources
from cqlengine.columns import *
from cqlengine.functions import *
from cqlengine.models import Model
from cqlengine.query import BatchQuery
__cqlengine_version_path__ = pkg_resources.resource_filename('cqlengine',
'VERSION')
... | Use proper way to access package resources. | Use proper way to access package resources.
| Python | apache-2.0 | bbirand/python-driver,mike-tr-adamson/python-driver,HackerEarth/cassandra-python-driver,vipjml/python-driver,coldeasy/python-driver,jregovic/python-driver,jregovic/python-driver,datastax/python-driver,thobbs/python-driver,stef1927/python-driver,markflorisson/python-driver,coldeasy/python-driver,bbirand/python-driver,jf... |
374c386a6b2dd1ad1ba75ba70009de6c7ee3c3fc | restalchemy/api/applications.py | restalchemy/api/applications.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2014 Eugene Frolov <eugene@frolov.net.ru>
#
# 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
#
# ... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2014 Eugene Frolov <eugene@frolov.net.ru>
#
# 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
#
# ... | Add process_request method to Application | Add process_request method to Application
This allows to override a process_request method without having to
add webob to child project.
Change-Id: Ic5369076704f1ba459b2872ed0f4632a15b75c25
| Python | apache-2.0 | phantomii/restalchemy |
a84dde598297495fe6f0f8b233b3a3761b0df7d4 | tests/functional/test_warning.py | tests/functional/test_warning.py |
def test_environ(script, tmpdir):
"""$PYTHONWARNINGS was added in python2.7"""
demo = tmpdir.join('warnings_demo.py')
demo.write('''
from pip._internal.utils import deprecation
deprecation.install_warning_logger()
from logging import basicConfig
basicConfig()
from warnings import warn
warn("deprecated!",... | import textwrap
def test_environ(script, tmpdir):
"""$PYTHONWARNINGS was added in python2.7"""
demo = tmpdir.join('warnings_demo.py')
demo.write(textwrap.dedent('''
from logging import basicConfig
from pip._internal.utils import deprecation
deprecation.install_warning_logger()
... | Update test to check newer logic | Update test to check newer logic
| Python | mit | pypa/pip,pfmoore/pip,pypa/pip,pradyunsg/pip,rouge8/pip,xavfernandez/pip,pradyunsg/pip,rouge8/pip,xavfernandez/pip,xavfernandez/pip,rouge8/pip,sbidoul/pip,sbidoul/pip,techtonik/pip,techtonik/pip,techtonik/pip,pfmoore/pip |
d13204abb2cf5d341eff78416dd442c303042697 | 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.per... | 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 person not in self.persons:
if len(self.person... | Modify add_occupant method to raise exception in case of a duplicate | Modify add_occupant method to raise exception in case of a duplicate
| Python | mit | peterpaints/room-allocator |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.