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 |
|---|---|---|---|---|---|---|---|---|---|
bb6599477ffe696a5d37a781b33f02f5623dc1a2 | eve_swagger/swagger.py | eve_swagger/swagger.py | # -*- coding: utf-8 -*-
"""
eve-swagger.swagger
~~~~~~~~~~~~~~~~~~~
swagger.io extension for Eve-powered REST APIs.
:copyright: (c) 2015 by Nicola Iarocci.
:license: BSD, see LICENSE for more details.
"""
from collections import OrderedDict
from flask import Blueprint, jsonify
from objects import ... | # -*- coding: utf-8 -*-
"""
eve-swagger.swagger
~~~~~~~~~~~~~~~~~~~
swagger.io extension for Eve-powered REST APIs.
:copyright: (c) 2015 by Nicola Iarocci.
:license: BSD, see LICENSE for more details.
"""
from collections import OrderedDict
from flask import Blueprint, jsonify
from objects import ... | Refactor node() into a closure | Refactor node() into a closure
| Python | bsd-3-clause | nicolaiarocci/eve-swagger |
d37f9646b13df624f04050a63d34b3d33e9e6e9e | python/matasano/set1/c8.py | python/matasano/set1/c8.py | from matasano.util.converters import hex_to_bytestr
from Crypto.Cipher import AES
if __name__ == "__main__":
chal_file = open("matasano/data/c8.txt", 'r');
for line in chal_file:
ct = hex_to_bytestr(line[:-1])
for i in range(0, len(ct), 16):
for j in range(i+16, len(ct), 16):
... | from matasano.util.converters import hex_to_bytestr
if __name__ == "__main__":
chal_file = open("matasano/data/c8.txt", 'r');
coll_count = {}
for idx, line in enumerate(chal_file):
count = 0
ct = line[:-1]
for i in range(0, len(ct), 32):
for j in range(i+32, len(ct), 3... | Improve the code, return most collisions. Work on hex strings. | Improve the code, return most collisions. Work on hex strings.
| Python | mit | TheLunchtimeAttack/matasano-challenges,TheLunchtimeAttack/matasano-challenges |
02d1b76067a8c3b2de9abc09cd841fe8b8bd7605 | example/app/integrations/fps_integration.py | example/app/integrations/fps_integration.py | from billing.integrations.amazon_fps_integration import AmazonFpsIntegration as Integration
from django.core.urlresolvers import reverse
import urlparse
class FpsIntegration(Integration):
def transaction(self, request):
"""Ideally at this method, you will check the
caller reference against a user ... | from billing.integrations.amazon_fps_integration import AmazonFpsIntegration as Integration
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
import urlparse
class FpsIntegration(Integration):
def transaction(self, request):
"""Ideally at this method, you will check ... | Use the HttpResponseRedirect for redirection. | Use the HttpResponseRedirect for redirection.
| Python | bsd-3-clause | biddyweb/merchant,spookylukey/merchant,spookylukey/merchant,digideskio/merchant,mjrulesamrat/merchant,agiliq/merchant,SimpleTax/merchant,mjrulesamrat/merchant,biddyweb/merchant,SimpleTax/merchant,agiliq/merchant,digideskio/merchant |
886fac0476d05806c5d396f0740bc24f3fa343ed | rslinac/pkcli/beam_solver.py | rslinac/pkcli/beam_solver.py | import rslinac
def run(ini_filename, input_filename, output_filename):
rslinac.run_beam_solver(ini_filename, input_filename, output_filename)
| import rslinac
from argh import arg
@arg('ini', help='path configuration file in INI format')
@arg('input', help='path to file with input data')
@arg('output', help='path to file to write output data')
def run(ini, input, output):
"""runs the beam solver"""
rslinac.run_beam_solver(ini, input, output)
| Add documentation to cli command arguments | Add documentation to cli command arguments
| Python | apache-2.0 | elventear/rslinac,radiasoft/rslinac,radiasoft/rslinac,elventear/rslinac,elventear/rslinac,radiasoft/rslinac,radiasoft/rslinac,radiasoft/rslinac,elventear/rslinac,elventear/rslinac,elventear/rslinac |
077016fbe6ee17c8eb3528b957b05eb4682b8d26 | scrapi/processing/elastic_search.py | scrapi/processing/elastic_search.py | import json
import logging
from elasticsearch import Elasticsearch
from scrapi import settings
from scrapi.processing.base import BaseProcessor
es = Elasticsearch(
settings.ELASTIC_URI,
request_timeout=settings.ELASTIC_TIMEOUT
)
logging.getLogger('elasticsearch').setLevel(logging.WARN)
logging.getLogger('el... | import json
import logging
from elasticsearch import Elasticsearch
from scrapi import settings
from scrapi.processing.base import BaseProcessor
es = Elasticsearch(
settings.ELASTIC_URI,
request_timeout=settings.ELASTIC_TIMEOUT
)
logging.getLogger('elasticsearch').setLevel(logging.WARN)
logging.getLogger('el... | Handle 404s due to index not existing when doing versioning | Handle 404s due to index not existing when doing versioning
| Python | apache-2.0 | jeffreyliu3230/scrapi,ostwald/scrapi,felliott/scrapi,felliott/scrapi,fabianvf/scrapi,erinspace/scrapi,fabianvf/scrapi,erinspace/scrapi,mehanig/scrapi,CenterForOpenScience/scrapi,mehanig/scrapi,icereval/scrapi,alexgarciac/scrapi,CenterForOpenScience/scrapi |
36288cf5357d58b0989b090965fd231bb01137ed | imager/profiles/tests.py | imager/profiles/tests.py | from django.test import TestCase
import factory
from django.contrib.auth.models import User
from profiles.models import ImagerProfile
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = User
django_get_or_create = ('username',)
username = 'john'
class Test_ImagerProfile... | from django.test import TestCase
import factory
from django.contrib.auth.models import User
from profiles.models import ImagerProfile
class UserFactory(factory.django.DjangoModelFactory):
"""Creates a test user not: non permante to db"""
class Meta:
model = User
django_get_or_create = ('userna... | Update docstrings for test file | Update docstrings for test file
| Python | mit | edpark13/django-imager |
d142bed6916d8b34509c12623b4802eca9206695 | tests/test_ab_testing.py | tests/test_ab_testing.py | from . import TheInternetTestCase
from helium.api import go_to, S, get_driver
class AbTestingTest(TheInternetTestCase):
def get_page(self):
return "http://the-internet.herokuapp.com/abtest"
def test_ab_variates(self):
variation = S("h3")
first_variation = variation.web_element.text
self.assertIn(
first_va... | from . import TheInternetTestCase
from helium.api import go_to, S, get_driver
class AbTestingTest(TheInternetTestCase):
def get_page(self):
return "http://the-internet.herokuapp.com/abtest"
def test_ab_variates(self):
header = S("h3")
first_variation = header.web_element.text
self.assertIn(
first_variatio... | Make the AB test case more stable. | Make the AB test case more stable.
| Python | mit | bugfree-software/the-internet-solution-python |
8a73d31a9bbff831be3e92b73ddb0841e61b3457 | reviewboard/admin/tests.py | reviewboard/admin/tests.py | from django.conf import settings
from django.test import TestCase
from reviewboard.admin import checks
class UpdateTests(TestCase):
"""Tests for update required pages"""
def tearDown(self):
# Make sure we don't break further tests by resetting this fully.
checks.reset_check_cache()
def ... | from django.conf import settings
from django.test import TestCase
from reviewboard.admin import checks
class UpdateTests(TestCase):
"""Tests for update required pages"""
def tearDown(self):
# Make sure we don't break further tests by resetting this fully.
checks.reset_check_cache()
def ... | Fix the media manual updates unit test to account for the new ext dir page. | Fix the media manual updates unit test to account for the new ext dir page.
My previous change for the extension directory manual updates page broke
the unit tests. The existing test for the upload directory didn't take
into account that the extension directory would also now be needed. The
test was fixed and renamed ... | Python | mit | brennie/reviewboard,beol/reviewboard,sgallagher/reviewboard,custode/reviewboard,1tush/reviewboard,atagar/ReviewBoard,beol/reviewboard,1tush/reviewboard,davidt/reviewboard,brennie/reviewboard,1tush/reviewboard,Khan/reviewboard,davidt/reviewboard,1tush/reviewboard,Khan/reviewboard,atagar/ReviewBoard,custode/reviewboard,a... |
4753a6d19d00f9669e864f92730d56aaf31575da | 1-multiples-of-3-and-5.py | 1-multiples-of-3-and-5.py | from itertools import chain
def threes_and_fives_gen(num=1000):
for i in range(num):
if i % 3 == 0 or i % 5 == 0:
yield i
def threes_and_fives_fun(n):
return set(chain(range(3, n+1, 3), range(5, n+1, 5)))
if __name__ == '__main__':
print(sum(threes_and_fives_gen(10000000)))
| from itertools import chain
def threes_and_fives_gen(num=1000):
for i in range(num):
if i % 3 == 0 or i % 5 == 0:
yield i
def threes_and_fives_fun(n):
return set(chain(range(3, n+1, 3), range(5, n+1, 5)))
def solve(n):
return sum(
filter(lambda x: x%3==0 or x%5==0,
... | Add functional solution to 1 | Add functional solution to 1
| Python | mit | dawran6/project-euler |
80503c24854e976fa4bc86319f6c11dc3a5186b2 | test/test_property.py | test/test_property.py | import unittest
from odml import Property, Section, Document
class TestProperty(unittest.TestCase):
def setUp(self):
pass
def test_value(self):
p = Property("property", 100)
assert(p.value[0] == 100)
def test_name(self):
pass
def test_parent(self):
pass
... | import unittest
from odml import Property, Section, Document, DType
class TestProperty(unittest.TestCase):
def setUp(self):
pass
def test_value(self):
p = Property("property", 100)
assert(p.value[0] == 100)
def test_bool_conversion(self):
p = Property(name='received', v... | Add tests for boolean conversion | Add tests for boolean conversion
| Python | bsd-3-clause | lzehl/python-odml |
f2005fadb9fb2e2bcad32286a9d993c291c1992e | lazyblacksmith/models/api/industry_index.py | lazyblacksmith/models/api/industry_index.py | # -*- encoding: utf-8 -*-
from . import db
from lazyblacksmith.models import Activity
class IndustryIndex(db.Model):
solarsystem_id = db.Column(
db.Integer, db.ForeignKey('solar_system.id'), primary_key=True
)
solarsystem = db.relationship('SolarSystem', backref=db.backref('indexes'))
activi... | # -*- encoding: utf-8 -*-
from . import db
from lazyblacksmith.models import Activity
class IndustryIndex(db.Model):
solarsystem_id = db.Column(
db.Integer, db.ForeignKey('solar_system.id'), primary_key=True
)
solarsystem = db.relationship('SolarSystem', backref=db.backref('indexes'))
activi... | Fix celery task for industry indexes by adding missing field | Fix celery task for industry indexes by adding missing field
| Python | bsd-3-clause | Kyria/LazyBlacksmith,Kyria/LazyBlacksmith,Kyria/LazyBlacksmith,Kyria/LazyBlacksmith |
874a6eff186d1c1ca6f90d69fd24fad11180c5a9 | thread_output_ctrl.py | thread_output_ctrl.py | import threading
import wx
from styled_text_ctrl import StyledTextCtrl
class ThreadOutputCtrl(StyledTextCtrl):
def __init__(self, parent, env, auto_scroll=False):
StyledTextCtrl.__init__(self, parent, env)
self.auto_scroll = auto_scroll
self.__lock = threading.Lock()
self.__queue ... | import threading
import wx
from styled_text_ctrl import StyledTextCtrl
class ThreadOutputCtrl(StyledTextCtrl):
def __init__(self, parent, env, auto_scroll=False):
StyledTextCtrl.__init__(self, parent, env)
self.auto_scroll = auto_scroll
self.__lock = threading.Lock()
self.__queue ... | Clear undo buffer when terminal cleared. | Clear undo buffer when terminal cleared.
| Python | mit | shaurz/devo |
53080f89af51340b0b2c1854e0a4bf38346c14a8 | kill.py | kill.py | #!/usr/bin/env python2
return 1
| #!/usr/bin/env python2
from datetime import datetime, timedelta
from json import loads
import sys
if len(sys.argv) < 2:
raise Exception("Need an amount of keep-days of which to save your comments.")
days = int(sys.argv[1])
before_time = datetime.now() - timedelta(days=days)
f = open('data.json', 'r')
data = lo... | Work out now() - 7 days | Work out now() - 7 days
| Python | bsd-2-clause | bparafina/Shreddit,bparafina/Shreddit,ijkilchenko/Shreddit,ijkilchenko/Shreddit |
9d3889a67ff6de69cd539b688cf3c2b9db17f0cb | jarn/mkrelease/python.py | jarn/mkrelease/python.py | from process import Process
from exit import err_exit
class Python(object):
"""A Python interpreter path that can test itself."""
def __init__(self, defaults, process=None):
self.process = process or Process()
self.python = defaults.python
def __str__(self):
return self.python
... | import sys
from process import Process
from exit import err_exit
class Python(object):
"""A Python interpreter path that can test itself."""
def __init__(self, defaults, process=None):
self.process = process or Process()
self.python = defaults.python
def __str__(self):
return se... | Optimize the common case to reduce startup time. | Optimize the common case to reduce startup time.
| Python | bsd-2-clause | Jarn/jarn.mkrelease |
72f8249cb26ad38e77ac74a7d149839fb3a1cf95 | utils/swift_build_support/swift_build_support/diagnostics.py | utils/swift_build_support/swift_build_support/diagnostics.py | # swift_build_support/diagnostics.py - Diagnostic Utilities -*- python -*-
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.tx... | # swift_build_support/diagnostics.py - Diagnostic Utilities -*- python -*-
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.tx... | Print build-script notes to stderr | Print build-script notes to stderr
This makes it easier to ignore them programmatically.
| Python | apache-2.0 | xwu/swift,aschwaighofer/swift,karwa/swift,sschiau/swift,shajrawi/swift,airspeedswift/swift,hooman/swift,devincoughlin/swift,stephentyrone/swift,jmgc/swift,rudkx/swift,rudkx/swift,xwu/swift,allevato/swift,xedin/swift,allevato/swift,apple/swift,benlangmuir/swift,atrick/swift,parkera/swift,tkremenek/swift,hooman/swift,nat... |
029bd1c15a489ab8833ffaff5130995bf4d31c5a | tests/test_auth.py | tests/test_auth.py | # -*- coding: utf-8 *-*
import logging
import unittest
from mongolog import MongoHandler
try:
from pymongo import MongoClient as Connection
except ImportError:
from pymongo import Connection
class TestAuth(unittest.TestCase):
def setUp(self):
""" Create an empty database that could be used for ... | # -*- coding: utf-8 *-*
import logging
import unittest
from mongolog import MongoHandler
try:
from pymongo import MongoClient as Connection
except ImportError:
from pymongo import Connection
class TestAuth(unittest.TestCase):
def setUp(self):
""" Create an empty database that could be used for ... | Add roles argument for createUser command. | Add roles argument for createUser command.
| Python | bsd-2-clause | puentesarrin/mongodb-log,puentesarrin/mongodb-log |
ff12421cc6c3067bac11ece75cf4a16d11859ed0 | tests/test_envs.py | tests/test_envs.py | import gym
import pytest
# Import for side-effect of registering environment
import imitation.examples.airl_envs # noqa: F401
import imitation.examples.model_envs # noqa: F401
ENV_NAMES = [env_spec.id for env_spec in gym.envs.registration.registry.all()
if env_spec.id.startswith('imitation/')]
@pytes... | import gym
import pytest
# Import for side-effect of registering environment
import imitation.examples.airl_envs # noqa: F401
import imitation.examples.model_envs # noqa: F401
ENV_NAMES = [env_spec.id for env_spec in gym.envs.registration.registry.all()
if env_spec.id.startswith('imitation/')]
@pytes... | Move the pragma: nocover to except block | Move the pragma: nocover to except block
| Python | mit | HumanCompatibleAI/imitation,humancompatibleai/imitation,humancompatibleai/imitation,HumanCompatibleAI/imitation |
011ad6090e183ce359c0a74bbd2f2530e1d5178c | tests/test_repr.py | tests/test_repr.py | """ Test __str__ methods. """
import pexpect
from . import PexpectTestCase
class TestCaseMisc(PexpectTestCase.PexpectTestCase):
def test_str_spawnu(self):
""" Exercise spawnu.__str__() """
# given,
p = pexpect.spawnu('cat')
# exercise,
value = str(p)
# verify
... | """ Test __str__ methods. """
import pexpect
from . import PexpectTestCase
class TestCaseMisc(PexpectTestCase.PexpectTestCase):
def test_str_spawnu(self):
""" Exercise spawnu.__str__() """
# given,
p = pexpect.spawnu('cat')
# exercise,
value = str(p)
# verify
... | Check error repr can be str-ed | Check error repr can be str-ed
| Python | isc | nodish/pexpect,nodish/pexpect,nodish/pexpect |
2234cbdc78e81329c4110f4eb4e69f429d9b6fb5 | csvkit/convert/dbase.py | csvkit/convert/dbase.py | #!/usr/bin/env python
from cStringIO import StringIO
import dbf
from csvkit import table
def dbf2csv(f, **kwargs):
"""
Convert a dBASE .dbf file to csv.
"""
db = dbf.Table(f.name)
headers = db.field_names
column_ids = range(len(headers))
data_columns = [[] for c in headers]
for ... | #!/usr/bin/env python
from cStringIO import StringIO
import dbf
from csvkit import table
def dbf2csv(f, **kwargs):
"""
Convert a dBASE .dbf file to csv.
"""
with dbf.Table(f.name) as db:
headers = db.field_names
column_ids = range(len(headers))
data_columns = [[] for c in h... | Fix for bug in latest dbf module. Pypy passes now. | Fix for bug in latest dbf module. Pypy passes now.
| Python | mit | bradparks/csvkit__query_join_filter_CSV_cli,matterker/csvkit,unpingco/csvkit,kyeoh/csvkit,Jobava/csvkit,snuggles08/csvkit,dannguyen/csvkit,cypreess/csvkit,jpalvarezf/csvkit,archaeogeek/csvkit,gepuro/csvkit,haginara/csvkit,barentsen/csvkit,bmispelon/csvkit,wjr1985/csvkit,KarrieK/csvkit,onyxfish/csvkit,wireservice/csvkit... |
61072f0054abcb50caa813fc35eff194be64727b | src/icecast_parser.py | src/icecast_parser.py | from bs4 import BeautifulSoup
from requests.auth import HTTPBasicAuth
import requests
import json
def parse_content():
rs = requests.get('http://soundspectra.com/admin/', auth=HTTPBasicAuth('admin', 'h@ckm3'))
html_data = rs.text
soup = BeautifulSoup(html_data)
details = {'stream_details' : []}
... | from bs4 import BeautifulSoup
from requests.auth import HTTPBasicAuth
import requests
import json
def parse_content():
rs = requests.get('http://soundspectra.com/admin/', auth=HTTPBasicAuth('admin', 'h@ckm3'))
html_data = rs.text
soup = BeautifulSoup(html_data)
details = {'stream_details' : []}
... | Return the json from the parser method | Return the json from the parser method
| Python | apache-2.0 | ekholabs/icecast_scraper |
b3e892f476c743a6ed2e2518fd1c9c2bec4d56ae | invocations/testing.py | invocations/testing.py | from invoke import ctask as task
@task(help={
'module': "Just runs tests/STRING.py.",
'runner': "Use STRING to run tests instead of 'spec'.",
'opts': "Extra flags for the test runner",
'pty': "Whether to run tests under a pseudo-tty",
})
def test(c, module=None, runner=None, opts=None, pty=True):
... | from invoke import ctask as task
@task(help={
'module': "Just runs tests/STRING.py.",
'runner': "Use STRING to run tests instead of 'spec'.",
'opts': "Extra flags for the test runner",
'pty': "Whether to run tests under a pseudo-tty",
})
def test(c, module=None, runner=None, opts=None, pty=True):
... | Use spec 1.1 --with-timing option | Use spec 1.1 --with-timing option
| Python | bsd-2-clause | mrjmad/invocations,singingwolfboy/invocations,pyinvoke/invocations |
f495ecb5f9131c2c13c41e78cc3fc2e182bdc8fc | hotline/db/db_redis.py | hotline/db/db_redis.py | import os
import redis
from urllib.parse import urlparse
redis_url = os.environ.get('REDISCLOUD_URL', 'redis://localhost:6379')
redis_url_parse = urlparse(redis_url)
redis_client = redis.StrictRedis(host=redis_url_parse.hostname, port=redis_url_parse.port)
| from db.db_abstract import AbstractClient
from redis import StrictRedis
from urllib.parse import urlparse
class RedisClient(AbstractClient):
def __init__(self, url):
self.url = url
self.client = None
def connect(self):
redis_url = urlparse(self.url)
self.client = StrictRedis(h... | Update to inherit from abstract class | Update to inherit from abstract class
| Python | mit | wearhacks/hackathon_hotline |
71b72c3f09af86da83a027502d28c9649db1cf86 | kai/controllers/tracs.py | kai/controllers/tracs.py | import logging
from pylons import config, tmpl_context as c
from pylons.controllers.util import abort
# Conditionally import the trac components in case things trac isn't installed
try:
import os
os.environ['TRAC_ENV_PARENT_DIR'] = '/usr/local/www'
os.environ['PYTHON_EGG_CACHE'] = os.path.join(config['pyl... | import logging
from pylons import config, tmpl_context as c
from pylons.controllers.util import abort
# Monkey patch the lazywriter, since mercurial needs that on the stdout
import paste.script.serve as serve
serve.LazyWriter.closed = False
# Conditionally import the trac components in case things trac isn't install... | Add monkey patch for mercurial trac | Add monkey patch for mercurial trac
| Python | bsd-3-clause | Pylons/kai,Pylons/kai |
48213f561c802e5279770cc833a9a5a68575bf72 | inventory.py | inventory.py | from flask import Flask, render_template, url_for, redirect
from flask import session, escape, request
from peewee import *
#from datetime import date
app = Flask(__name__)
# http://docs.peewee-orm.com/en/latest/peewee/quickstart.html
database = SqliteDatabase('developmentData.db')
#class Device(Model):
# idNumber = ... | from flask import Flask, render_template, url_for, redirect
from flask import session, escape, request
from peewee import *
#from datetime import date
app = Flask(__name__)
# http://docs.peewee-orm.com/en/latest/peewee/quickstart.html
database = SqliteDatabase('developmentData.db')
#class Device(Model):
# idNumber = ... | Add debug code to test login post | Add debug code to test login post
| Python | mit | lcdi/Inventory,lcdi/Inventory,lcdi/Inventory,lcdi/Inventory |
82d5276b6c9164e4b8bffe74dc3068ed3e6a967e | main.py | main.py | from jsonrpc import JSONRPCResponseManager
from funcs import d
def app(environ, start_response):
if 'POST'!=environ.get('REQUEST_METHOD'):
if 'OPTIONS'==environ.get('REQUEST_METHOD'):
start_response('200 OK',[('Access-Control-Allow-Origin','*'), ('Access-Control-Allow-Methods', 'POST')])
... | from jsonrpc import JSONRPCResponseManager
from funcs import d
def app(environ, start_response):
if 'POST'!=environ.get('REQUEST_METHOD'):
if 'OPTIONS'==environ.get('REQUEST_METHOD'):
start_response('200 OK',[
('Access-Control-Allow-Origin','*'),
('Access-Control... | Add allowed headers to preflight response. | Add allowed headers to preflight response. | Python | mit | 1stop-st/jsonrpc-calculator |
dcdfd994f1ab79a5fd8e50e7bf478100211a77aa | oscar_vat_moss/checkout/session.py | oscar_vat_moss/checkout/session.py | from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from oscar.apps.checkout import session, exceptions
from oscar_vat_moss import vat
class CheckoutSessionMixin(session.CheckoutSessionMixin):
def build_submission(self, **kwargs):
submission = super(Checko... | from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from oscar.apps.checkout import session, exceptions
from oscar_vat_moss import vat
class CheckoutSessionMixin(session.CheckoutSessionMixin):
def build_submission(self, **kwargs):
submission = super(Checko... | Add a "valid shipping address check" to account for VAT discrepancies | Add a "valid shipping address check" to account for VAT discrepancies
If we get a phone number and a city/country combination that yield
incompatible VAT results, we need to flag this to the user. The best
place to do this is, ironically, the shipping address check.
| Python | bsd-3-clause | hastexo/django-oscar-vat_moss,fghaas/django-oscar-vat_moss,arbrandes/django-oscar-vat_moss,fghaas/django-oscar-vat_moss,hastexo/django-oscar-vat_moss,arbrandes/django-oscar-vat_moss |
6fafe0e2d10229ac68fd5bc7857b938d7cd5b212 | wafer/talks/models.py | wafer/talks/models.py | from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
# constants to make things clearer elsewhere
ACCEPTED = 'A'
PENDING = 'P'
REJECTED = 'R'
class Talk(models.Model):
TALK_STATUS = (
... | from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from wafer.snippets.markdown_field import MarkdownTextField
# constants to make things clearer elsewhere
ACCEPTED = 'A'
PENDING = 'P'
REJECTED ... | Make the abstract a Markdown field | Make the abstract a Markdown field
| Python | isc | CarlFK/wafer,CTPUG/wafer,CarlFK/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CarlFK/wafer,CarlFK/wafer |
42d667c0478b5b500d765e3d70cc03ec7e7d84d3 | main.py | main.py | #!/usr/bin/env python3
from time import sleep
from utils.mqtt import publish
from weather import Weather
w = Weather()
while True:
publish(w.basics(),"stormfly")
sleep(600)
| #!/usr/bin/env python3
from time import sleep
from utils.mqtt import publish
from weather import Weather
w = Weather()
while True:
publish(w.basics(),"stormfly")
sleep(600)
w.refresh()
| FIX refresh data when running in loop | FIX refresh data when running in loop
| Python | mit | paulfantom/AGH-weather-mqtt |
693f4f52bfed6d25fc32504fcfc8a57e466533a0 | list/list.py | list/list.py | #!/usr/local/bin/python
#a=[1,2,3,4,5,6,7,8,9,10]
#print a[:3]
#print a[-3:]
#print a[:]
#print a[::2]
#print a[8:3:-1]
#print [1,2,3]+[4,5,6]
#print ["Hi"]*3
#print 1 in a
#print max(a)
#print min(a)
#print len(a)
#print list("Hello")
#b=[1,3,5,7,9,8]
#b[1]=4
#print b
#del b[1]
#print b
c=list("Perl")
c[1:1]=list('yth... | #!/usr/local/bin/python
#a=[1,2,3,4,5,6,7,8,9,10]
#print a[:3]
#print a[-3:]
#print a[:]
#print a[::2]
#print a[8:3:-1]
#print [1,2,3]+[4,5,6]
#print ["Hi"]*3
#print 1 in a
#print max(a)
#print min(a)
#print len(a)
#print list("Hello")
#b=[1,3,5,7,9,8]
#b[1]=4
#print b
#del b[1]
#print b
#c=list("Perl")
#c[1:1]=list('y... | Use sort,pop,remove and so on. | Use sort,pop,remove and so on.
| Python | apache-2.0 | Vayne-Lover/Python |
2f6e13a868f18a516f0eb79efa70f3ae527c4aad | tinman/handlers/__init__.py | tinman/handlers/__init__.py | """Custom Tinman Handlers add wrappers to based functionality to speed
application development.
"""
from tinman.handlers.session import SessionRequestHandler
| """Custom Tinman Handlers add wrappers to based functionality to speed
application development.
"""
from tinman.handlers.base import RequestHandler
from tinman.handlers.session import SessionRequestHandler
| Make the base request handler available by default | Make the base request handler available by default
| Python | bsd-3-clause | lucius-feng/tinman,gmr/tinman,lucius-feng/tinman,gmr/tinman,lucius-feng/tinman |
d937e254ce3c806300ac7763e30bd4303661cba6 | whaler/analysis.py | whaler/analysis.py | """
"""
import os
from whaler.dataprep import IO
class Analysis():
"""
"""
def __init__(self):
self.loc = os.getcwd()
self.structs = next(os.walk('.'))[1]
print(self.loc)
print(self.structs)
def groundstates_all(self):
"""Compares the energies of each... | """
"""
import os
import numpy as np
from whaler.dataprep import IO
class Analysis():
"""
"""
def __init__(self):
self.loc = os.getcwd()
self.structs = next(os.walk('.'))[1]
print(self.loc)
print(self.structs)
def groundstates_all(self, outname="groundstates.... | Set up data tabulation for gs | Set up data tabulation for gs
| Python | mit | tristanbrown/whaler |
7d81a2f27c0bf9ab57d046152981c3882016e013 | wordcloud/views.py | wordcloud/views.py | import os
from django.conf import settings
from django.http import HttpResponse
from django.utils import simplejson
from django.views.decorators.cache import cache_page
from .wordcloud import popular_words
@cache_page(60*60*4)
def wordcloud(request, max_entries=30):
""" Return tag cloud JSON results"""
cach... | import os
from django.conf import settings
from django.http import HttpResponse
from django.utils import simplejson
from django.views.decorators.cache import cache_page
from .wordcloud import popular_words
@cache_page(60*60*4)
def wordcloud(request, max_entries=30):
""" Return tag cloud JSON results"""
cach... | Use x-sendfile to serve pre-generated wordcloud JSON. | Use x-sendfile to serve pre-generated wordcloud JSON.
If we've pre-generated the wordcloud JSON file, use x-sendfile to
serve it rather than reading the file in Django.
| Python | agpl-3.0 | geoffkilpin/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola,geoffkilpin/pombola,mysociety/pombola,mysociety/pombola |
cca7e512061948abe05fd25111974f41fa6fb6ec | romanesco/plugins/swift/tests/swift_test.py | romanesco/plugins/swift/tests/swift_test.py | import romanesco
import unittest
class TestSwiftMode(unittest.TestCase):
def testSwiftMode(self):
task = {
'mode': 'swift',
'script': """
type file;
app (file out) echo_app (string s)
{
echo s stdout=filename(out);
}
string a = arg("a", "10");
file out <"out.csv">;
out = echo... | import romanesco
import unittest
class TestSwiftMode(unittest.TestCase):
def testSwiftMode(self):
task = {
'mode': 'swift',
'script': """
type file;
app (file out) echo_app (string s)
{
echo s stdout=filename(out);
}
string a = arg("a", "10");
file out <"out.csv">;
out = echo... | Remove comments that don't make sense | Remove comments that don't make sense
| Python | apache-2.0 | girder/girder_worker,girder/girder_worker,Kitware/romanesco,Kitware/romanesco,Kitware/romanesco,Kitware/romanesco,girder/girder_worker |
9bf6aec99ac490fce1af2ea92bea57b7d1e9acd9 | heat/common/environment_format.py | heat/common/environment_format.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | Make the template and env yaml parsing more consistent | Make the template and env yaml parsing more consistent
in the environment_format.py use the same yaml_loader
Partial-bug: #1242155
Change-Id: I66b08415d450bd4758af648eaff0f20dd934a9cc
| Python | apache-2.0 | noironetworks/heat,ntt-sic/heat,openstack/heat,srznew/heat,dragorosson/heat,steveb/heat,gonzolino/heat,pratikmallya/heat,srznew/heat,redhat-openstack/heat,cryptickp/heat,pratikmallya/heat,cwolferh/heat-scratch,pshchelo/heat,NeCTAR-RC/heat,miguelgrinberg/heat,pshchelo/heat,dragorosson/heat,maestro-hybrid-cloud/heat,take... |
6500d388fa894bb0ea8cb0ca1328a73cc54ba4e8 | Challenges/chall_02.py | Challenges/chall_02.py | #!/usr/local/bin/python3
# Python Challenge - 2
# http://www.pythonchallenge.com/pc/def/ocr.html
# Keyword: equality
def main():
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
letters = []
with open('garbage.txt', 'r') as garbage:
for line in garbage.readlines():
for... | #!/usr/local/bin/python3
# Python Challenge - 2
# http://www.pythonchallenge.com/pc/def/ocr.html
# Keyword: equality
import string
def main():
'''
Hint: recognize the characters. maybe they are in the book,
but MAYBE they are in the page source.
Page source text saved in garbage.txt
'''
alph... | Refactor code, add page hints | Refactor code, add page hints
| Python | mit | HKuz/PythonChallenge |
5631276591cf2c4e3c83920da32857e47286d9c9 | wanikani/django.py | wanikani/django.py | from __future__ import absolute_import
import os
import logging
from django.http import HttpResponse
from django.views.generic.base import View
from icalendar import Calendar, Event
from wanikani.core import WaniKani, Radical, Kanji
CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.wanikani')
with open(CONFI... |
from __future__ import absolute_import
from django.http import HttpResponse
from django.views.generic.base import View
from icalendar import Calendar, Event
from wanikani.core import WaniKani, Radical, Kanji
class WaniKaniView(View):
def get(self, request, **kwargs):
client = WaniKani(kwargs['api_key... | Switch to getting the API key from the URL instead of a config file. | Switch to getting the API key from the URL instead of a config file.
Allows other people to get their anki calendar if they want. | Python | mit | kfdm/wanikani,kfdm/wanikani |
1d9b7d855d633da6388daf663398449cfc0e6ab6 | StandaloneViewer/etc/redirectingSimpleServer.py | StandaloneViewer/etc/redirectingSimpleServer.py | import SimpleHTTPServer, SocketServer
import urlparse, os
PORT = 3000
class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
# Parse query data to find out what was requested
parsedParams = urlparse.urlparse(self.path)
# See if the file requested exists
if os.ac... | import SimpleHTTPServer, SocketServer
import urlparse, os
PORT = 3000
## Note: If you set this parameter, you can try to serve files
# at a subdirectory. You should use
# -u http://localhost:3000/subdirectory
# when building the application, which will set this as your
# ROOT_URL.
#URL_PATH="/subdirectory"
URL_PATH="... | Update Python simple server script to allow subdomains | Update Python simple server script to allow subdomains
| Python | mit | OHIF/Viewers,OHIF/Viewers,OHIF/Viewers |
7a4aeffc89120d0d5de53837a71f62ee21ba9bd6 | app/backend/wells/apps.py | app/backend/wells/apps.py | """
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distri... | """
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distri... | Remove redundant post migrate step for increasing well_tag_number count (no longer needed, data is no longer being replicated) | Remove redundant post migrate step for increasing well_tag_number count (no longer needed, data is no longer being replicated)
| Python | apache-2.0 | bcgov/gwells,bcgov/gwells,bcgov/gwells,bcgov/gwells |
d113fd75456c14f651cb9769d922d9394b369d63 | tools/add_previews.py | tools/add_previews.py | import os
import sys
import django
sys.path.append("/var/projects/museum/")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "museum.settings")
django.setup()
from museum_site.models import *
from museum_site.common import *
from museum_site.constants import *
def main():
articles = Article.objects.filter(previ... | import os
import sys
import django
sys.path.append("/var/projects/museum/")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "museum.settings")
django.setup()
from museum_site.models import * # noqa: E402
from museum_site.common import * # noqa: E402
from museum_site.constants import * # noqa: E402
HELP = """This... | Add script explanation and message when script is complete. | Add script explanation and message when script is complete.
| Python | mit | DrDos0016/z2,DrDos0016/z2,DrDos0016/z2 |
582964f9da6029cd089117496babf9267c41ecd5 | evewspace/core/utils.py | evewspace/core/utils.py | # Eve W-Space
# Copyright (C) 2013 Andrew Austin and other contributors
#
# 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... | # Eve W-Space
# Copyright (C) 2013 Andrew Austin and other contributors
#
# 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... | Reduce queries used to lookup config | Reduce queries used to lookup config
| Python | apache-2.0 | evewspace/eve-wspace,nyrocron/eve-wspace,hybrid1969/eve-wspace,hybrid1969/eve-wspace,acdervis/eve-wspace,marbindrakon/eve-wspace,Unsettled/eve-wspace,proycon/eve-wspace,mmalyska/eve-wspace,evewspace/eve-wspace,gpapaz/eve-wspace,acdervis/eve-wspace,proycon/eve-wspace,marbindrakon/eve-wspace,Zumochi/eve-wspace,marbindrak... |
dcc2821cac0619fc2ca5f486ad30416f3c3cfda9 | ce/expr/parser.py | ce/expr/parser.py | #!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
from ..semantics import mpq
from .common import OPERATORS, ADD_OP, MULTIPLY_OP
def try_to_number(s):
try:
return mpq(s)
except (ValueError, TypeError):
return s
def _parse_r(s):
s = s.strip()
bracket_level = 0
operator_pos =... | #!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
import ast
from ..semantics import mpq
from .common import OPERATORS, ADD_OP, MULTIPLY_OP
def try_to_number(s):
try:
return mpq(s)
except (ValueError, TypeError):
return s
OPERATOR_MAP = {
ast.Add: ADD_OP,
ast.Mult: MULTIPLY_OP... | Replace parsing with Python's ast | Replace parsing with Python's ast
Allows greater flexibility and syntax checks
| Python | mit | admk/soap |
15090b84e1c7359c49cb45aec4d9b4d492f855ac | tests/scoring_engine/engine/checks/test_smb.py | tests/scoring_engine/engine/checks/test_smb.py | from scoring_engine.engine.basic_check import CHECKS_BIN_PATH
from tests.scoring_engine.engine.checks.check_test import CheckTest
class TestSMBCheck(CheckTest):
check_name = 'SMBCheck'
required_properties = ['share', 'file', 'hash']
properties = {
'share': 'ScoringShare',
'file': 'flag.tx... | from scoring_engine.engine.basic_check import CHECKS_BIN_PATH
from tests.scoring_engine.engine.checks.check_test import CheckTest
class TestSMBCheck(CheckTest):
check_name = 'SMBCheck'
required_properties = ['share', 'file', 'hash']
properties = {
'share': 'ScoringShare',
'file': 'flag.tx... | Update smb test to include port parameter | Update smb test to include port parameter
| Python | mit | pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine |
b3889bbdab80fb502c74b99b61cf36bae112ce2c | node/node.py | node/node.py | from configparser import ConfigParser
from driver import BTRFSDriver
class Node:
"""
# Dummy config example
[bk1-z3.presslabs.net]
ssd = True
"""
def __init__(self, context):
self._conf_path = context['node']['conf_path']
self._driver = BTRFSDriver(context['volume_path'])
... | from configparser import ConfigParser
from driver import BTRFSDriver
class Node:
"""
# Dummy config example
[bk1-z3.presslabs.net]
ssd = True
"""
def __init__(self, context):
self._conf_path = context['node']['conf_path']
self._driver = BTRFSDriver(context['volume_path'])
... | Add property decorator to getters | Add property decorator to getters
| Python | apache-2.0 | PressLabs/cobalt,PressLabs/cobalt |
493637ace6881defedee22971f3bc39fe9a5bd0a | freesas/test/__init__.py | freesas/test/__init__.py | #!usr/bin/env python
# coding: utf-8
__author__ = "Jérôme Kieffer"
__license__ = "MIT"
__date__ = "05/09/2017"
__copyright__ = "2015, ESRF"
import unittest
from .test_all import suite
def run():
runner = unittest.TextTestRunner()
return runner.run(suite())
if __name__ == '__main__':
run()
| #!usr/bin/env python
# coding: utf-8
__author__ = "Jérôme Kieffer"
__license__ = "MIT"
__date__ = "15/01/2021"
__copyright__ = "2015-2021, ESRF"
import sys
import unittest
from .test_all import suite
def run_tests():
"""Run test complete test_suite"""
mysuite = suite()
runner = unittest.TextTestRunner()... | Make it compatible with Bob | Make it compatible with Bob | Python | mit | kif/freesas,kif/freesas,kif/freesas |
eaae2a1e88572e224621e242be1d15e92065f15e | mopidy_nad/__init__.py | mopidy_nad/__init__.py | from __future__ import unicode_literals
import os
import pygst
pygst.require('0.10')
import gst
import gobject
from mopidy import config, ext
__version__ = '1.0.0'
class Extension(ext.Extension):
dist_name = 'Mopidy-NAD'
ext_name = 'nad'
version = __version__
def get_default_config(self):
... | from __future__ import unicode_literals
import os
import pygst
pygst.require('0.10')
import gst
import gobject
from mopidy import config, ext
__version__ = '1.0.0'
class Extension(ext.Extension):
dist_name = 'Mopidy-NAD'
ext_name = 'nad'
version = __version__
def get_default_config(self):
... | Use new extension setup() API | Use new extension setup() API
| Python | apache-2.0 | ZenithDK/mopidy-primare,mopidy/mopidy-nad |
42f74f304d0ac404f17d6489033b6140816cb194 | fireplace/cards/gvg/neutral_common.py | fireplace/cards/gvg/neutral_common.py | from ..utils import *
##
# Minions
# Explosive Sheep
class GVG_076:
def deathrattle(self):
for target in self.game.board:
self.hit(target, 2)
# Clockwork Gnome
class GVG_082:
deathrattle = giveSparePart
# Micro Machine
class GVG_103:
def TURN_BEGIN(self, player):
# That card ID is not a mistake
self.... | from ..utils import *
##
# Minions
# Stonesplinter Trogg
class GVG_067:
def CARD_PLAYED(self, player, card):
if player is not self.controller and card.type == CardType.SPELL:
self.buff("GVG_067a")
class GVG_067a:
Atk = 1
# Burly Rockjaw Trogg
class GVG_068:
def CARD_PLAYED(self, player, card):
if player... | Implement Stonesplinter Trogg, Burly Rockjaw Trogg, Ship's Cannon | Implement Stonesplinter Trogg, Burly Rockjaw Trogg, Ship's Cannon
| Python | agpl-3.0 | Ragowit/fireplace,NightKev/fireplace,jleclanche/fireplace,smallnamespace/fireplace,smallnamespace/fireplace,amw2104/fireplace,beheh/fireplace,Meerkov/fireplace,amw2104/fireplace,oftc-ftw/fireplace,butozerca/fireplace,liujimj/fireplace,oftc-ftw/fireplace,Meerkov/fireplace,butozerca/fireplace,Ragowit/fireplace,liujimj/fi... |
7d1463fc732cdc6aef3299c6d2bbe916418e6d6e | hkisaml/api.py | hkisaml/api.py | from django.contrib.auth.models import User
from rest_framework import permissions, routers, serializers, generics, mixins
from oauth2_provider.ext.rest_framework import TokenHasReadWriteScope
class UserSerializer(serializers.ModelSerializer):
def to_representation(self, obj):
ret = super(UserSerializer, ... | from django.contrib.auth.models import User
from rest_framework import permissions, serializers, generics, mixins
from oauth2_provider.ext.rest_framework import TokenHasReadWriteScope
class UserSerializer(serializers.ModelSerializer):
def to_representation(self, obj):
ret = super(UserSerializer, self).to_... | Add full_name field to API | Add full_name field to API
| Python | mit | mikkokeskinen/tunnistamo,mikkokeskinen/tunnistamo |
15f22d7c0ac9ddce6cb14cb0cbb35c4d630605d2 | api/ud_helper.py | api/ud_helper.py | import re
from ufal.udpipe import Model, Pipeline, ProcessingError
class Parser:
MODELS = {
"swe": "data/swedish-ud-2.0-170801.udpipe",
}
def __init__(self, language):
model_path = self.MODELS.get(language, None)
if not model_path:
raise ParserException("Cannot find mod... | import re
from ufal.udpipe import Model, Pipeline, ProcessingError
class Parser:
MODELS = {
"swe": "data/swedish-ud-2.0-170801.udpipe",
}
def __init__(self, language):
model_path = self.MODELS.get(language, None)
if not model_path:
raise ParserException("Cannot find mod... | Remove period so input corresponds to output. | Remove period so input corresponds to output.
Former-commit-id: ec6debb1637304407715441ae8319787fe7f0945 | Python | mit | EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger |
9783844b1597598fad833794b4b291fce49438d4 | app/hr/tasks.py | app/hr/tasks.py | from django.conf import settings
import logging
from datetime import datetime, timedelta
from celery.decorators import task
from hr.utils import blacklist_values
from django.contrib.auth.models import User
from django.core.mail import send_mail
@task(ignore_result=True)
def blacklist_check():
log = blacklist_check... | from django.conf import settings
import logging
from datetime import datetime, timedelta
from celery.decorators import task
from hr.utils import blacklist_values
from django.contrib.auth.models import User
from django.core.mail import send_mail
@task(ignore_result=True)
def blacklist_check():
log = blacklist_check... | Send alerts as one mail | Send alerts as one mail
| Python | bsd-3-clause | nikdoof/test-auth |
7fb89e4dbe2cbed4ef37e13073d4fa3f2a650049 | InvenTree/part/apps.py | InvenTree/part/apps.py | from __future__ import unicode_literals
from django.apps import AppConfig
class PartConfig(AppConfig):
name = 'part'
| from __future__ import unicode_literals
import os
from django.db.utils import OperationalError, ProgrammingError
from django.apps import AppConfig
from django.conf import settings
class PartConfig(AppConfig):
name = 'part'
def ready(self):
"""
This function is called whenever the Part app i... | Check for missing part thumbnails when the server first runs | Check for missing part thumbnails when the server first runs
| Python | mit | inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree |
e6e0d96790d71caccb3f00487bfeeddccdc78139 | app/raw/tasks.py | app/raw/tasks.py | from __future__ import absolute_import
from celery import shared_task
from twisted.internet import reactor
from scrapy.crawler import Crawler
from scrapy import log, signals
from scrapy.utils.project import get_project_settings
import os
from raw.scraper.spiders.legco_library import LibraryAgendaSpider
from raw.scrape... | from __future__ import absolute_import
from celery import shared_task
from twisted.internet import reactor
from scrapy.crawler import Crawler
from scrapy import log, signals
from scrapy.utils.project import get_project_settings
import os
from raw.scraper.spiders.legco_library import LibraryAgendaSpider
from raw.scrape... | Fix variable and return value | Fix variable and return value
| Python | mit | legco-watch/legco-watch,comsaint/legco-watch,comsaint/legco-watch,legco-watch/legco-watch,comsaint/legco-watch,legco-watch/legco-watch,comsaint/legco-watch,legco-watch/legco-watch |
e71870736959efcde2188bdcbd89838b67ca8582 | pathvalidate/__init__.py | pathvalidate/__init__.py | """
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from .__version__ import __author__, __copyright__, __email__, __license__, __version__
from ._common import (
Platform,
ascii_symbols,
normalize_platform,
replace_ansi_escape,
replace_unprintable_char,
unprintable_ascii_ch... | """
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from .__version__ import __author__, __copyright__, __email__, __license__, __version__
from ._base import AbstractSanitizer, AbstractValidator
from ._common import (
Platform,
ascii_symbols,
normalize_platform,
replace_ansi_escape... | Add AbstractSanitizer/AbstractValidator class to import path | Add AbstractSanitizer/AbstractValidator class to import path
| Python | mit | thombashi/pathvalidate |
99818f02ebc46debe349a6c1b6bba70be6e04968 | skimage/io/_plugins/null_plugin.py | skimage/io/_plugins/null_plugin.py | __all__ = ['imshow', 'imread', 'imsave', '_app_show']
import warnings
message = '''\
No plugin has been loaded. Please refer to
skimage.io.plugins()
for a list of available plugins.'''
def imshow(*args, **kwargs):
warnings.warn(RuntimeWarning(message))
def imread(*args, **kwargs):
warnings.warn(Runtime... | __all__ = ['imshow', 'imread', 'imsave', '_app_show']
import warnings
message = '''\
No plugin has been loaded. Please refer to the docstring for ``skimage.io``
for a list of available plugins. You may specify a plugin explicitly as
an argument to ``imread``, e.g. ``imread("image.jpg", plugin='pil')``.
'''
def i... | Update error message for no plugins | Update error message for no plugins
| Python | bsd-3-clause | oew1v07/scikit-image,robintw/scikit-image,rjeli/scikit-image,vighneshbirodkar/scikit-image,Hiyorimi/scikit-image,paalge/scikit-image,juliusbierk/scikit-image,ofgulban/scikit-image,bennlich/scikit-image,bsipocz/scikit-image,chriscrosscutler/scikit-image,vighneshbirodkar/scikit-image,keflavich/scikit-image,oew1v07/scikit... |
9ee9ba34e447e99c868fcb43d40ce905cebf5fb9 | noah/noah.py | noah/noah.py | import json
class Noah(object):
pass | import json
class Noah(object):
def __init__(self, dictionary_file):
self.dictionary = json.load(dictionary_file)
def list(self):
return '\n'.join([entry['word'] for entry in self.dictionary])
def define(self, word):
entry = next((x for x in self.dictionary if x['word'] == word), ... | Add list and define functions. | Add list and define functions.
| Python | mit | maxdeviant/noah |
da5a05c27f1c19c69ce23f5cd6cd0f09edb9d7f7 | paranuara_api/views.py | paranuara_api/views.py | from rest_framework import viewsets
from paranuara_api.models import Company, Person
from paranuara_api.serializers import (
CompanySerializer, CompanyListSerializer, PersonListSerializer,
PersonSerializer
)
class CompanyViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Company.objects.all()
... | from rest_framework import viewsets
from paranuara_api.models import Company, Person
from paranuara_api.serializers import (
CompanySerializer, CompanyListSerializer, PersonListSerializer,
PersonSerializer
)
class MultiSerializerMixin(object):
def get_serializer_class(self):
return self.s... | Refactor common serializer selection code. | Refactor common serializer selection code.
| Python | bsd-3-clause | jarvis-cochrane/paranuara |
d36e17e3823af74b5a6f75191f141ec98fdf281f | plugins/irc/irc.py | plugins/irc/irc.py | from p1tr.helpers import clean_string
from p1tr.plugin import *
@meta_plugin
class Irc(Plugin):
"""Provides commands for basic IRC operations."""
@command
@require_master
def nick(self, server, channel, nick, params):
"""Usage: nick NEW_NICKNAME - changes the bot's nickname."""
if len(... | from p1tr.helpers import clean_string
from p1tr.plugin import *
@meta_plugin
class Irc(Plugin):
"""Provides commands for basic IRC operations."""
@command
@require_master
def nick(self, server, channel, nick, params):
"""Usage: nick NEW_NICKNAME - changes the bot's nickname."""
if len(... | Fix failing reconnects; add quit IRC command | Fix failing reconnects; add quit IRC command
| Python | mit | howard/p1tr-tng,howard/p1tr-tng |
cf16c64e378f64d2267f75444c568aed895f940c | setup.py | setup.py | import platform, sys
from distutils.core import setup
from distextend import *
packages, package_data = findPackages("countershape")
setup(
name = "countershape",
version = "0.1",
description = "A framework for rendering static documentation.",
author = "Nullcube Pty Ltd",
autho... | import platform, sys
from distutils.core import setup
from distextend import *
packages, package_data = findPackages("countershape")
setup(
name = "countershape",
version = "0.1",
description = "A framework for rendering static documentation.",
author = "Nullcube Pty Ltd",
autho... | Add csblog to installed scripts. | Add csblog to installed scripts.
| Python | mit | mhils/countershape,samtaufa/countershape,cortesi/countershape,cortesi/countershape,samtaufa/countershape,mhils/countershape |
4b3dc61e5cb46774cf647f8c640b280aae1e4e90 | setup.py | setup.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# © 2017-2019 qsuscs, TobiX
# Should still run with Python 2.7...
from __future__ import print_function, unicode_literals
import os
import sys
from glob import glob
os.chdir(os.path.dirname(os.path.abspath(__file__)))
exit = 0
for f in glob('dot.*'):
dst_home = '~/... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# © 2017-2021 qsuscs, TobiX
# Should still run with Python 2.7...
from __future__ import print_function, unicode_literals
import os
import sys
from glob import glob
os.chdir(os.path.dirname(os.path.abspath(__file__)))
home = os.path.realpath(os.path.expanduser('~'))
ex... | Handle symlinks in path to home directory | Handle symlinks in path to home directory
| Python | isc | TobiX/dotfiles,TobiX/dotfiles |
90c82f0936addeb4469db2c42c1cd48713e7f3cf | progress_logger.py | progress_logger.py | # Copyright Google
# BSD License
import copy
import wash
# from http://stackoverflow.com/questions/8924173/how-do-i-print-bold-text-in-python
class color:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033... | # Copyright Google
# BSD License
import copy
import wash
# from http://stackoverflow.com/questions/8924173/how-do-i-print-bold-text-in-python
class color:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033... | Switch from bold to red highlighting. | Switch from bold to red highlighting.
With many terminal fonts bold is subtle. The red is much more clear.
| Python | bsd-2-clause | adlr/wash-sale-calculator |
c0c3d63c6124549008a2dc17c1e691e799129444 | plex2myshows/modules/plex/plex.py | plex2myshows/modules/plex/plex.py | class Plex(object):
def __init__(self, plex):
self.plex = plex
def get_watched_episodes(self, section_name):
watched_episodes = set(self.plex.library.section(section_name).searchEpisodes(unwatched=False))
return watched_episodes
| class Plex(object):
def __init__(self, plex):
self.plex = plex
def get_watched_episodes(self, section_name):
watched_episodes = []
shows = self.plex.library.section(section_name).searchShows()
for show in shows:
watched_episodes.extend(show.watched())
return ... | Fix getting unwatched episodes from Plex | Fix getting unwatched episodes from Plex
| Python | mit | verdel/plex2myshows |
b34c8b94202294f63ff88d2d8085222bfa50dc46 | candidates/csv_helpers.py | candidates/csv_helpers.py | from __future__ import unicode_literals
from compat import BufferDictWriter
from .models import CSV_ROW_FIELDS
def _candidate_sort_by_name_key(row):
return (
row['name'].split()[-1],
not row['election_current'],
row['election_date'],
row['election'],
row['post_label']
... | from __future__ import unicode_literals
from compat import BufferDictWriter
from .models import CSV_ROW_FIELDS
def _candidate_sort_by_name_key(row):
return (
row['name'].split()[-1],
row['name'].rsplit(None, 1)[0],
not row['election_current'],
row['election_date'],
row['el... | Sort on first name after last name | Sort on first name after last name
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative |
e47b7e5952d4001459aee5ba570a7cc6d4c10d43 | tests/unit/directory/test_directory.py | tests/unit/directory/test_directory.py | """Contains the unit tests for the inner directory package"""
import unittest
import os
from classyfd import Directory
class TestDirectory(unittest.TestCase):
def setUp(self):
self.fake_path = os.path.abspath("hello-world-dir")
return
def test_create_directory_object(self):
d = D... | """Contains the unit tests for the inner directory package"""
import unittest
import os
from classyfd import Directory, InvalidDirectoryValueError
class TestDirectory(unittest.TestCase):
def setUp(self):
self.fake_path = os.path.abspath("hello-world-dir")
return
def test_create_directory... | Add import of the InvalidDirectoryValueError to the directory package's test file | Add import of the InvalidDirectoryValueError to the directory package's test file
| Python | mit | SizzlingVortex/classyfd |
4b7b2727a35cfcb0117b0ba4571da9a0ea81824a | greenmine/base/routers.py | greenmine/base/routers.py | # -*- coding: utf-8 -*-
from rest_framework import routers
# Special router for actions.
actions_router = routers.Route(url=r'^{prefix}/{methodname}{trailing_slash}$',
mapping={'{httpmethod}': '{methodname}'},
name='{basename}-{methodnamehyphen}',
... | # -*- coding: utf-8 -*-
from rest_framework import routers
class DefaultRouter(routers.DefaultRouter):
pass
__all__ = ["DefaultRouter"]
| Remove old reimplementation of routes. | Remove old reimplementation of routes.
| Python | agpl-3.0 | joshisa/taiga-back,joshisa/taiga-back,gam-phon/taiga-back,bdang2012/taiga-back-casting,jeffdwyatt/taiga-back,rajiteh/taiga-back,crr0004/taiga-back,crr0004/taiga-back,EvgeneOskin/taiga-back,dayatz/taiga-back,Rademade/taiga-back,joshisa/taiga-back,Rademade/taiga-back,astronaut1712/taiga-back,forging2012/taiga-back,coopso... |
b78ce84f2a36789fc0fbb6b184b5c8d8ebb23234 | run_tests.py | run_tests.py | #!/usr/bin/env python
import sys
import pytest
if __name__ == '__main__':
sys.exit(pytest.main())
| #!/usr/bin/env python
import sys
import pytest
if __name__ == '__main__':
# show output results from every test function
args = ['-v']
# show the message output for skipped and expected failure tests
args.append('-rxs')
# compute coverage stats for bluesky
args.extend(['--cov', 'bluesky'])
... | Clarify py.test arguments in run_test.py | TST: Clarify py.test arguments in run_test.py
| Python | bsd-3-clause | ericdill/bluesky,ericdill/bluesky |
3352920f7e92e2732eb2914313bdee6b5ab7f549 | setup.py | setup.py | # -*- coding: utf-8 -*-
# Copyright (C) 2012-2014 MUJIN Inc
from distutils.core import setup
try:
from mujincommon.setuptools import Distribution
except ImportError:
from distutils.dist import Distribution
version = {}
exec(open('python/mujincontrollerclient/version.py').read(), version)
setup(
distclass=... | # -*- coding: utf-8 -*-
# Copyright (C) 2012-2014 MUJIN Inc
from distutils.core import setup
try:
from mujincommon.setuptools import Distribution
except ImportError:
from distutils.dist import Distribution
version = {}
exec(open('python/mujincontrollerclient/version.py').read(), version)
setup(
distclass=... | Fix bin scripts having python2 or python3 specific path. | Fix bin scripts having python2 or python3 specific path.
| Python | apache-2.0 | mujin/mujincontrollerclientpy |
7bab32ef89d760a8cf4aeb2700725ea88e3fc31c | tests/basics/builtin_hash.py | tests/basics/builtin_hash.py | # test builtin hash function
print(hash(False))
print(hash(True))
print({():1}) # hash tuple
print({1 << 66:1}) # hash big int
print(hash in {hash:1}) # hash function
try:
hash([])
except TypeError:
print("TypeError")
class A:
def __hash__(self):
return 123
def __repr__(self):
return ... | # test builtin hash function
print(hash(False))
print(hash(True))
print({():1}) # hash tuple
print({1 << 66:1}) # hash big int
print(hash in {hash:1}) # hash function
try:
hash([])
except TypeError:
print("TypeError")
class A:
def __hash__(self):
return 123
def __repr__(self):
return ... | Add further tests for class defining __hash__. | tests: Add further tests for class defining __hash__.
| Python | mit | martinribelotta/micropython,puuu/micropython,ganshun666/micropython,suda/micropython,EcmaXp/micropython,ChuckM/micropython,mgyenik/micropython,pramasoul/micropython,infinnovation/micropython,bvernoux/micropython,xyb/micropython,lbattraw/micropython,adafruit/circuitpython,blazewicz/micropython,tobbad/micropython,kostyll... |
c4e1059b387269b6098d05d2227c085e7931b140 | setup.py | setup.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from distutils.core import setup, Extension
cpp_args = ['-std=c++11', '-stdlib=libc++', '-mmacosx-version-min=10.7']
e... | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from distutils.core import setup, Extension
cpp_args = ['-std=c++11', '-stdlib=libc++', '-mmacosx-version-min=10.7']
e... | Update module description for clarity | Update module description for clarity
| Python | mpl-2.0 | natelust/least_asymmetry,natelust/least_asymmetry,natelust/least_asymmetry |
a52c84f092d89f89130c2696c98779e955f083dc | tests/test_version_parser.py | tests/test_version_parser.py | import pytest
from leak.version_parser import versions_split
def test_versions_split():
pass
def test_wrong_versions_split():
# too many dots
assert versions_split('1.2.3.4') == [0, 0, 0]
# test missing numeric version
with pytest.raises(ValueError):
versions_split('not.numeric')
... | import pytest
from leak.version_parser import versions_split
def test_versions_split():
assert versions_split('1.8.1') == [1, 8, 1]
assert versions_split('1.4') == [1, 4, 0]
assert versions_split('2') == [2, 0, 0]
def test_versions_split_str_mapping():
assert versions_split('1.11rc1', type_applyer=... | Add tests for version splitting | Add tests for version splitting
| Python | mit | bmwant21/leak |
85d2c012bfaeeb04fa8dd31cd05a04a8dc43c14e | tests/grammar_term-nonterm_test/NonterminalsInvalidTest.py | tests/grammar_term-nonterm_test/NonterminalsInvalidTest.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from unittest import TestCase, main
from grammpy.RawGrammar import RawGrammar
class NonterminalsInvalidTest(TestCase):
pass
if __name__ == '__main__':
main()
| #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from unittest import TestCase, main
from grammpy.RawGrammar import RawGrammar as Grammar
from grammpy import Nonterminal
from grammpy.exceptions import NotNonterminalException
class TempClass(... | Add tests that have and get of nonterms raise exceptions | Add tests that have and get of nonterms raise exceptions
| Python | mit | PatrikValkovic/grammpy |
d57161b9449faa1218e4dab55fe4b2bd6f0c3436 | utils.py | utils.py | import json
import os
import time
import uuid
from google.appengine.api import urlfetch
from models import Profile
def getUserId(user, id_type="email"):
if id_type == "email":
return user.email()
if id_type == "oauth":
"""A workaround implementation for getting userid."""
auth = os.ge... | import json
import os
import time
from google.appengine.api import urlfetch
def getUserId(user, id_type="email"):
if id_type == "email":
return user.email()
if id_type == "oauth":
"""A workaround implementation for getting userid."""
auth = os.getenv('HTTP_AUTHORIZATION')
bea... | Remove unused code and get rid of flake8 errors | Remove unused code and get rid of flake8 errors
| Python | apache-2.0 | swesterveld/udacity-nd004-p4-conference-organization-app,swesterveld/udacity-nd004-p4-conference-organization-app,swesterveld/udacity-nd004-p4-conference-organization-app |
e890ac9ef00193beac77b757c62911553cebf656 | test.py | test.py | import urllib
urllib.urlretrieve('http://192.168.0.13:8080/photoaf.jpg', '/home/pi/img/img.jpg') | import urllib
urllib.urlretrieve('http://192.168.0.13:8080/photoaf.jpg', 'img.jpg') | Change save path to local path | Change save path to local path
| Python | mit | adampiskorski/lpr_poc |
0c1b0a7787bd6824815ae208edab8f208b53af09 | api/base/exceptions.py | api/base/exceptions.py |
def jsonapi_exception_handler(exc, context):
"""
Custom exception handler that returns errors object as an array with a 'detail' member
"""
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
if response is not None:
if 'detail' in response.dat... |
def jsonapi_exception_handler(exc, context):
"""
Custom exception handler that returns errors object as an array with a 'detail' member
"""
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
if response is not None:
if 'detail' in response.dat... | Add comment to override of status code | Add comment to override of status code
| Python | apache-2.0 | Ghalko/osf.io,billyhunt/osf.io,wearpants/osf.io,asanfilippo7/osf.io,ticklemepierce/osf.io,kch8qx/osf.io,GageGaskins/osf.io,njantrania/osf.io,mluke93/osf.io,baylee-d/osf.io,alexschiller/osf.io,asanfilippo7/osf.io,wearpants/osf.io,kwierman/osf.io,leb2dg/osf.io,leb2dg/osf.io,chennan47/osf.io,arpitar/osf.io,leb2dg/osf.io,e... |
a155e8654a95969abc2290d4198622991d6cb00e | ideascube/conf/idb_bdi.py | ideascube/conf/idb_bdi.py | """Generic config for Ideasbox of Burundi"""
from .idb import * # noqa
from django.utils.translation import ugettext_lazy as _
USER_FORM_FIELDS = (
('Ideasbox', ['serial', 'box_awareness']),
(_('Personal informations'), ['refugee_id', 'short_name', 'full_name', 'birth_year', 'gender', 'phone']), # noqa
(... | """Generic config for Ideasbox of Burundi"""
from .idb import * # noqa
from django.utils.translation import ugettext_lazy as _
USER_FORM_FIELDS = (
('Ideasbox', ['serial', 'box_awareness']),
(_('Personal informations'), ['refugee_id', 'short_name', 'full_name', 'birth_year', 'gender', 'phone']), # noqa
(... | Remove duplicate entry for vikidia and gutenberg in burundi boxes | Remove duplicate entry for vikidia and gutenberg in burundi boxes
| Python | agpl-3.0 | ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube |
bc199a9eaa2416b35d1d691f580e6c9ca0b1a2ae | website/discovery/views.py | website/discovery/views.py | from website import settings
from website.project import Node
from website.project import utils
from modularodm.query.querydialect import DefaultQueryDialect as Q
def activity():
node_data = utils.get_node_data()
if node_data:
hits = utils.hits(node_data)
else:
hits = {}
# New Proje... | from website import settings
from website.project import Node
from website.project import utils
from modularodm.query.querydialect import DefaultQueryDialect as Q
def activity():
"""Reads node activity from pre-generated popular projects and registrations.
New and Noteworthy projects are set manually or thro... | Remove node counts and update docstrings on new view for activity | Remove node counts and update docstrings on new view for activity
| Python | apache-2.0 | monikagrabowska/osf.io,binoculars/osf.io,monikagrabowska/osf.io,acshi/osf.io,laurenrevere/osf.io,cslzchen/osf.io,laurenrevere/osf.io,alexschiller/osf.io,monikagrabowska/osf.io,Johnetordoff/osf.io,alexschiller/osf.io,mluo613/osf.io,CenterForOpenScience/osf.io,chennan47/osf.io,mfraezz/osf.io,aaxelb/osf.io,alexschiller/os... |
e968983001cced5391a163ab282ef2f2ded492f6 | eliot/__init__.py | eliot/__init__.py | """
Eliot: An Opinionated Logging Library
Suppose we turn from outside estimates of a man, to wonder, with keener
interest, what is the report of his own consciousness about his doings or
capacity: with what hindrances he is carrying on his daily labors; what
fading of hopes, or what deeper fixity of s... | """
Eliot: Logging as Storytelling
Suppose we turn from outside estimates of a man, to wonder, with keener
interest, what is the report of his own consciousness about his doings or
capacity: with what hindrances he is carrying on his daily labors; what
fading of hopes, or what deeper fixity of self-del... | Remove link to private document. | Remove link to private document.
| Python | apache-2.0 | ScatterHQ/eliot,ClusterHQ/eliot,ScatterHQ/eliot,iffy/eliot,ScatterHQ/eliot |
4d46001296ad083df6827a9c97333f0f093f31bd | example/config.py | example/config.py | # Mnemosyne configuration
# =======================
#
# This file is a Python script. When run, the following variables will be
# defined for you; you may change or add to them as you see fit.
#
# ``entries_dir``: a Maildir containing all the blog entries.
# ``layout_dir``: the blog's layout, as a skeleton directory tr... | # Mnemosyne configuration
# =======================
#
# This file is a Python script. When run, the following variables will be
# defined for you; you may change or add to them as you see fit.
#
# * ``entries_dir``: a Maildir containing all the blog entries.
# * ``layout_dir``: the blog's layout, as a skeleton director... | Document new evil magic, and add required var. | Document new evil magic, and add required var.
| Python | isc | decklin/ennepe |
5b0386d0872d4106902655ada78389503c62a95a | yunity/models/relations.py | yunity/models/relations.py | from django.db.models import ForeignKey, DateTimeField, ManyToManyField
from yunity.models.entities import User, Location, Mappable, Message
from yunity.models.utils import BaseModel, MaxLengthCharField
from yunity.utils.decorators import classproperty
class Chat(BaseModel):
participants = ManyToManyField(User)
... | from django.db.models import ForeignKey, DateTimeField, ManyToManyField
from yunity.models.entities import User, Location, Mappable, Message
from yunity.models.utils import BaseModel, MaxLengthCharField
from yunity.utils.decorators import classproperty
class Chat(BaseModel):
participants = ManyToManyField(User)
... | Add some default feedback types for item requests | Add some default feedback types for item requests
| Python | agpl-3.0 | yunity/yunity-core,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/foodsaving-backend |
af4c5a72afb80ff59662cc6992ce3084fed75dfe | node/deduplicate.py | node/deduplicate.py | #!/usr/bin/env python
from nodes import Node
class Deduplicate(Node):
char = "}"
args = 1
results = 2
@Node.test_func([2], [4])
@Node.test_func([1.5], [3])
def double(self, inp: Node.number):
"""inp*2"""
self.results = 1
return inp*2
def func(self, seq... | #!/usr/bin/env python
from nodes import Node
class Deduplicate(Node):
char = "}"
args = 1
results = 1
@Node.test_func([2], [4])
@Node.test_func([1.5], [3])
def double(self, inp: Node.number):
"""inp*2"""
return inp*2
@Node.test_func([[1,2,3,1,1]], [[1,2,3]])
... | Fix dedupe not preserving order | Fix dedupe not preserving order
| Python | mit | muddyfish/PYKE,muddyfish/PYKE |
ab10f3d134065047a7260662d3c39295904795b8 | migration/versions/001_initial_migration.py | migration/versions/001_initial_migration.py | from __future__ import print_function
from getpass import getpass
import readline
import sys
from sqlalchemy import *
from migrate import *
from migrate.changeset.constraint import ForeignKeyConstraint
import annotateit
from annotateit import db
from annotateit.model import Consumer, User
meta = MetaData()
consumer... | from sqlalchemy import *
from migrate import *
import annotateit
from annotateit import db
from annotateit.model import Consumer, User
meta = MetaData()
consumer = Table('consumer', meta,
Column('id', Integer, primary_key=True, nullable=False),
Column('key', String),
Column('secret', String),
Column(... | Add fkey constraints at the same time | Add fkey constraints at the same time
| Python | agpl-3.0 | openannotation/annotateit,openannotation/annotateit |
1421866ac3c4e4f1f09d17019d058aa903597df5 | modules/menus_reader.py | modules/menus_reader.py | # -*- coding: utf-8 -*-
from json_reader import *
from config import *
def get_menus_data():
old_data = read_json_from_file(filenames["menus"])
if old_data == None or type(old_data) is not dict: # rewrite old_data and create new recipe dictionary
# initialize new dict
old_data = {}
old_data["menus"] = {}
elif... | # -*- coding: utf-8 -*-
from json_reader import *
from config import *
def get_menus_data():
old_data = read_json_from_file(filenames["menus"])
if old_data == None or type(old_data) is not dict: # rewrite old_data and create new recipe dictionary
# initialize new dict
old_data = {}
old_data["menus"] = {}
elif... | Add new feature: find out is current week menu created already | Add new feature: find out is current week menu created already
| Python | mit | Jntz/RuokalistaCommandLine |
10dc027ee15428d7ca210e0b74e5ae9274de0fa8 | lianXiangCi.py | lianXiangCi.py | #coding:utf-8
import urllib
import urllib2
import re
from random import choice
ipList=['120.76.115.134:80','222.83.14.145:3128','119.188.94.145:80']
thisIp=choice(ipList)
keyWord=urllib.quote('科学')
url='http://search.sina.com.cn/iframe/suggest/index.php?q='+keyWord
headers={
'Get':url,
... | #coding:utf-8
import urllib
import urllib2
import re
from random import choice
ipList=['120.76.115.134:80','222.83.14.145:3128','119.188.94.145:80']
thisIp=choice(ipList)
input = raw_input("Please input your key words:")
keyWord=urllib.quote(input)
url='http://search.sina.com.cn/iframe/suggest/index.ph... | Use raw_input instead of the unmodified words | Use raw_input instead of the unmodified words | Python | mit | YChrisZhang/PythonCrawler |
70181b3069649eddacac86dbcb49cb43733be0ec | tw_begins.py | tw_begins.py | #!/usr/bin/env python
import begin
import twitterlib
@begin.subcommand
def timeline():
"Display recent tweets from users timeline"
for status in begin.context.api.timeline:
print u"%s: %s" % (status.user.screen_name, status.text)
@begin.subcommand
def mentions():
"Display recent tweets mentionin... | #!/usr/bin/env python
import begin
import twitterlib
# sub-command definitions using subcommand decorator for each sub-command that
# implements a timeline display
@begin.subcommand
def timeline():
"Display recent tweets from users timeline"
for status in begin.context.api.timeline:
print u"%s: %s" %... | Add code comments for begins example | Add code comments for begins example
Code comments for the major sections of the begins example program.
| Python | mit | aliles/cmdline_examples |
c95bff54d8ff6534c40d60f34484f864cc04754a | lib/web/web.py | lib/web/web.py | import os, os.path
import random
import string
import json
import cherrypy
from . import get_pic
class StringGenerator(object):
@cherrypy.expose
def index(self):
return """<html>
<head>
<link href="/static/css/style.css" rel="stylesheet">
</head>
<body>
... | import os, os.path
import random
import string
import json
import cherrypy
from . import get_pic
class StringGenerator(object):
@cherrypy.expose
def index(self):
return """<html>
<head>
<link href="/static/css/style.css" rel="stylesheet">
</head>
<body>
... | Add example for when there is no book cover url | Add example for when there is no book cover url
| Python | mit | DexterLB/bookrat,DexterLB/bookrat,DexterLB/bookrat,DexterLB/bookrat,DexterLB/bookrat |
4adb78fde502faed78350233896f3efd3f42816e | cytoplasm/interpreters.py | cytoplasm/interpreters.py | '''
These are some utilites used when writing and handling interpreters.
'''
import shutil
from cytoplasm import configuration
from cytoplasm.errors import InterpreterError
def SaveReturned(fn):
'''Some potential interpreters, like Mako, don't give you an easy way to save to a destination.
In these cases, sim... | '''
These are some utilites used when writing and handling interpreters.
'''
import shutil
from cytoplasm import configuration
from cytoplasm.errors import InterpreterError
def SaveReturned(fn):
'''Some potential interpreters, like Mako, don't give you an easy way to save to a destination.
In these cases, sim... | Define a default interpreter rather than using shutil.copyfile. | Define a default interpreter rather than using shutil.copyfile.
It would choke before if it was handed a file-like object rather than a
file name. Even more bleh!.
| Python | mit | startling/cytoplasm |
5934669c0edbd914d14612e16be7c88641b50bee | test/test_chat_chatserverstatus.py | test/test_chat_chatserverstatus.py | from pytwitcherapi import chat
def test_eq_str(servers):
assert servers[0] == '192.16.64.11:80',\
"Server should be equal to the same address."
def test_noteq_str(servers):
assert servers[0] != '192.16.64.50:89',\
"""Server should not be equal to a different address"""
def test_eq(servers)... | from pytwitcherapi import chat
def test_eq_str(servers):
assert servers[0] == '192.16.64.11:80',\
"Server should be equal to the same address."
def test_noteq_str(servers):
assert servers[0] != '192.16.64.50:89',\
"""Server should not be equal to a different address"""
def test_eq(servers)... | Fix test for eq and test eq with other classes | Fix test for eq and test eq with other classes
| Python | bsd-3-clause | Pytwitcher/pytwitcherapi,Pytwitcher/pytwitcherapi |
ae916c1ee52941bb5a1ccf87abe2a9758897bd08 | IPython/utils/ulinecache.py | IPython/utils/ulinecache.py | """
Wrapper around linecache which decodes files to unicode according to PEP 263.
"""
import functools
import linecache
import sys
from IPython.utils import py3compat
from IPython.utils import openpy
getline = linecache.getline
# getlines has to be looked up at runtime, because doctests monkeypatch it.
@functools.wr... | """
This module has been deprecated since IPython 6.0.
Wrapper around linecache which decodes files to unicode according to PEP 263.
"""
import functools
import linecache
import sys
from warnings import warn
from IPython.utils import py3compat
from IPython.utils import openpy
getline = linecache.getline
# getlines ... | Add deprecation warnings and message to getlines function | Add deprecation warnings and message to getlines function
| Python | bsd-3-clause | ipython/ipython,ipython/ipython |
31381728cb8d76314c82833d4400b4140fcc573f | django_jinja/builtins/global_context.py | django_jinja/builtins/global_context.py | # -*- coding: utf-8 -*-
import logging
from django.conf import settings
from django.core.urlresolvers import reverse as django_reverse, NoReverseMatch
from django.contrib.staticfiles.storage import staticfiles_storage
JINJA2_MUTE_URLRESOLVE_EXCEPTIONS = getattr(settings, "JINJA2_MUTE_URLRESOLVE_EXCEPTIONS", False)
l... | # -*- coding: utf-8 -*-
import logging
from django.conf import settings
from django.core.urlresolvers import reverse as django_reverse, NoReverseMatch
from django.contrib.staticfiles.storage import staticfiles_storage
JINJA2_MUTE_URLRESOLVE_EXCEPTIONS = getattr(settings, "JINJA2_MUTE_URLRESOLVE_EXCEPTIONS", False)
l... | Change parameter name so it does not conflict with an url parameter called "name". | builtins/url: Change parameter name so it does not conflict with an url parameter called "name".
This reflects the same name used in https://github.com/coffin/coffin/blob/master/coffin/template/defaultfilters.py, but it's probably as bad as a solution, because now you cannot use url() with a "view_name" url parameter.... | Python | bsd-3-clause | akx/django-jinja,glogiotatidis/django-jinja,glogiotatidis/django-jinja,akx/django-jinja,akx/django-jinja,glogiotatidis/django-jinja,niwinz/django-jinja,glogiotatidis/django-jinja,niwinz/django-jinja,akx/django-jinja,niwinz/django-jinja |
7f13b29cc918f63c4d1fc24717c0a0b5d2f5f8ad | filter.py | filter.py | import numpy as np
class LowPassFilter(object):
'''
First order discrete IIR filter.
'''
def __init__(self, feedback_gain, initial_value=0.0):
self.feedback_gain = np.ones_like(initial_value) * feedback_gain
self.initial_value = initial_value
self.output_gain = 1.0 - feedback_ga... | import numpy as np
class LowPassFilter(object):
'''
First order discrete IIR filter.
'''
def __init__(self, feedback_gain, initial_value=0.0):
self.feedback_gain = np.ones_like(initial_value) * feedback_gain
self.initial_value = initial_value
self.output_gain = 1.0 - feedback_ga... | Fix problem with array values. | Fix problem with array values.
| Python | mit | jcsharp/DriveIt |
b717696b5cff69e3586e06c399be7d06c057e503 | nova/tests/fake_utils.py | nova/tests/fake_utils.py | # Copyright (c) 2013 Rackspace Hosting
#
# 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... | # Copyright (c) 2013 Rackspace Hosting
#
# 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... | Make spawn_n() stub properly ignore errors in the child thread work | Make spawn_n() stub properly ignore errors in the child thread work
When we call spawn_n() normally, we fork off a thread that can run or
die on its own, without affecting the parent. In unit tests, we stub
this out to be a synchronous call, but we allow any exceptions that
occur in that work to bubble up to the calle... | Python | apache-2.0 | barnsnake351/nova,dawnpower/nova,alvarolopez/nova,JioCloud/nova_test_latest,joker946/nova,apporc/nova,cyx1231st/nova,dims/nova,klmitch/nova,mgagne/nova,openstack/nova,orbitfp7/nova,phenoxim/nova,rajalokan/nova,Stavitsky/nova,akash1808/nova_test_latest,apporc/nova,projectcalico/calico-nova,devendermishrajio/nova_test_la... |
e76777897bed5b9396d126e384555ea230b35784 | sass_processor/apps.py | sass_processor/apps.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
from django.apps import apps, AppConfig
APPS_INCLUDE_DIRS = []
class SassProcessorConfig(AppConfig):
name = 'sass_processor'
verbose_name = "Sass Processor"
_static_dir = 'static'
_sass_exts = ('.scss', '.sass')
def ready... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
from django.apps import apps, AppConfig
from django.conf import settings
from django.core.files.storage import get_storage_class
APPS_INCLUDE_DIRS = []
class SassProcessorConfig(AppConfig):
name = 'sass_processor'
verbose_name = "Sass... | Use StaticFileStorage to determine source directories | Use StaticFileStorage to determine source directories
| Python | mit | jrief/django-sass-processor,jrief/django-sass-processor |
3199b523a67f9c241950992a07fe38d2bbee07dc | seedlibrary/migrations/0003_extendedview_fix.py | seedlibrary/migrations/0003_extendedview_fix.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2017-02-21 02:55
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('seedlibrary', '0002_auto_20170219_2058'),
]
operations = [
migrations.Rename... | # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2017-02-21 02:55
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('seedlibrary', '0002_add_extendedview'),
]
operations = [
migrations.RenameFi... | Update migration file for namechange | Update migration file for namechange
| Python | mit | RockinRobin/seednetwork,RockinRobin/seednetwork,RockinRobin/seednetwork |
17b0f5d7b718bc12755f7ddefdd76ee9312adf5f | books.py | books.py | import falcon
import template
def get_paragraphs(pathname: str) -> list:
result = []
with open(pathname) as f:
for line in f.readlines():
if line != '\n':
result.append(line[:-1])
return result
class BooksResource:
def on_get(self, req, resp):
resp.status ... | import falcon
import template
def get_paragraphs(pathname: str) -> list:
result = []
with open(pathname) as f:
for line in f.readlines():
if line != '\n':
result.append(line[:-1])
return result
class BooksResource:
def on_get(self, req, resp):
resp.status ... | Add content type text/html to response | Add content type text/html to response
| Python | agpl-3.0 | sanchopanca/reader,sanchopanca/reader |
02efde47b5cf20b7385eacaa3f21454ffa636ad7 | troposphere/codestarconnections.py | troposphere/codestarconnections.py | # Copyright (c) 2012-2020, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, Tags
VALID_CONNECTION_PROVIDERTYPE = ('Bitbucket')
def validate_connection_providertype(connection_providertype):
"""Validate ProviderType for Connection"""
if conne... | # Copyright (c) 2012-2020, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, Tags
VALID_CONNECTION_PROVIDERTYPE = ('Bitbucket')
def validate_connection_providertype(connection_providertype):
"""Validate ProviderType for Connection"""
if conne... | Update CodeStarConnections::Connection per 2020-07-23 update | Update CodeStarConnections::Connection per 2020-07-23 update
| Python | bsd-2-clause | cloudtools/troposphere,cloudtools/troposphere |
b628e466f86bc27cbe45ec27a02d4774a0efd3bb | semantic_release/pypi.py | semantic_release/pypi.py | """PyPI
"""
from invoke import run
from semantic_release import ImproperConfigurationError
def upload_to_pypi(
dists: str = 'sdist bdist_wheel',
username: str = None,
password: str = None,
skip_existing: bool = False
):
"""Creates the wheel and uploads to pypi with twine.
:pa... | """PyPI
"""
from invoke import run
from semantic_release import ImproperConfigurationError
def upload_to_pypi(
dists: str = 'sdist bdist_wheel',
username: str = None,
password: str = None,
skip_existing: bool = False
):
"""Creates the wheel and uploads to pypi with twine.
:pa... | Clean out dist and build before building | fix: Clean out dist and build before building
This should fix the problem with uploading old versions.
Fixes #86
| Python | mit | relekang/python-semantic-release,relekang/python-semantic-release |
569c056e016131ec4325185ee9fe814018d5e1fe | server/bands/__init__.py | server/bands/__init__.py | from flask import session, redirect, url_for, g, jsonify, Response
from flask.views import MethodView
from server.models import Band
class RestrictedBandPage(MethodView):
def dispatch_request(self, *args, **kwargs):
if not 'bandId' in session:
return redirect(url_for('bands.session.index'))
... | from flask import session, redirect, url_for, g, jsonify, Response
from flask.views import MethodView
from server.models import Band
class RestrictedBandPage(MethodView):
def dispatch_request(self, *args, **kwargs):
if not 'bandId' in session:
return redirect(url_for('bands.session.index'))
... | Fix problem on no-longer existing bands that are still as logged in session available | Fix problem on no-longer existing bands that are still as logged in session available
| Python | apache-2.0 | dennisausbremen/tunefish,dennisausbremen/tunefish,dennisausbremen/tunefish |
ec2456eac36a96c9819920bf8b4176e6a37ad9a5 | saleor/product/migrations/0020_attribute_data_to_class.py | saleor/product/migrations/0020_attribute_data_to_class.py | from __future__ import unicode_literals
from django.db import migrations, models
def move_data(apps, schema_editor):
Product = apps.get_model('product', 'Product')
ProductClass = apps.get_model('product', 'ProductClass')
for product in Product.objects.all():
attributes = product.attributes.all()... | from __future__ import unicode_literals
from django.db import migrations, models
def move_data(apps, schema_editor):
Product = apps.get_model('product', 'Product')
ProductClass = apps.get_model('product', 'ProductClass')
for product in Product.objects.all():
attributes = product.attributes.all()... | Rename productclass made during migration | Rename productclass made during migration
| Python | bsd-3-clause | KenMutemi/saleor,HyperManTT/ECommerceSaleor,mociepka/saleor,maferelo/saleor,maferelo/saleor,tfroehlich82/saleor,tfroehlich82/saleor,car3oon/saleor,itbabu/saleor,KenMutemi/saleor,KenMutemi/saleor,UITools/saleor,UITools/saleor,jreigel/saleor,mociepka/saleor,tfroehlich82/saleor,itbabu/saleor,car3oon/saleor,UITools/saleor,... |
f31e8215838e40960abff6c86be8c66cbf113c95 | server/rest/twofishes.py | server/rest/twofishes.py | import requests
from girder.api import access
from girder.api.describe import Description
from girder.api.rest import Resource
class TwoFishes(Resource):
def __init__(self):
self.resourceName = 'minerva_geocoder'
self.route('GET', (), self.geocode)
self.route('GET', ('autocomplete',), sel... | import requests
from shapely.wkt import loads
from shapely.geometry import mapping
from girder.api import access
from girder.api.describe import Description
from girder.api.rest import Resource
class TwoFishes(Resource):
def __init__(self):
self.resourceName = 'minerva_geocoder'
self.route('GET',... | Make the endpoint return geojson as opposed to wkt geometry | Make the endpoint return geojson as opposed to wkt geometry
| Python | apache-2.0 | Kitware/minerva,Kitware/minerva,Kitware/minerva |
3665b8859f72ec416682857ab22f7e29fc30f0df | alignment/models.py | alignment/models.py | from django.db import models
# Create your models here.
class AlignmentConsensus(models.Model):
slug = models.SlugField(max_length=100, unique=True)
alignment = models.BinaryField() | from django.db import models
# Create your models here.
class AlignmentConsensus(models.Model):
slug = models.SlugField(max_length=100, unique=True)
alignment = models.BinaryField()
gn_consensus = models.BinaryField(blank=True) # Store conservation calculation for each GN | Add field on cached alignments to store more information | Add field on cached alignments to store more information
| Python | apache-2.0 | cmunk/protwis,protwis/protwis,fosfataza/protwis,cmunk/protwis,fosfataza/protwis,protwis/protwis,protwis/protwis,fosfataza/protwis,cmunk/protwis,cmunk/protwis,fosfataza/protwis |
5d8e6e47964d80f380db27acd120136a43e80550 | aimpoint_mon/make_web_page.py | aimpoint_mon/make_web_page.py | #!/usr/bin/env python
import os
import argparse
import json
from pathlib import Path
from jinja2 import Template
import pyyaks.logger
def get_opt():
parser = argparse.ArgumentParser(description='Get aimpoint drift data '
'from aspect solution files')
parser.add_argument(... | #!/usr/bin/env python
import os
import argparse
import json
from pathlib import Path
from jinja2 import Template
import pyyaks.logger
def get_opt():
parser = argparse.ArgumentParser(description='Make aimpoint monitor web page')
parser.add_argument("--data-root",
default=".",
... | Fix tool description in argparse help | Fix tool description in argparse help | Python | bsd-2-clause | sot/aimpoint_mon,sot/aimpoint_mon |
2c03171b75b6bb4f3a77d3b46ee8fd1e5b022077 | template_engine/jinja2_filters.py | template_engine/jinja2_filters.py | from email import utils
import re
import time
import urllib
def digits(s):
if not s:
return ''
return re.sub('[^0-9]', '', s)
def floatformat(num, num_decimals):
return "%.{}f".format(num_decimals) % num
def strftime(datetime, formatstr):
"""
Uses Python's strftime with some tweaks
... | from email import utils
import re
import time
import urllib
def digits(s):
if not s:
return ''
if type(s) is int:
return s
return re.sub('[^0-9]', '', s)
def floatformat(num, num_decimals):
return "%.{}f".format(num_decimals) % num
def strftime(datetime, formatstr):
"""
Use... | Fix type error if input is int | Fix type error if input is int
| Python | mit | bdaroz/the-blue-alliance,the-blue-alliance/the-blue-alliance,jaredhasenklein/the-blue-alliance,synth3tk/the-blue-alliance,verycumbersome/the-blue-alliance,synth3tk/the-blue-alliance,the-blue-alliance/the-blue-alliance,bdaroz/the-blue-alliance,jaredhasenklein/the-blue-alliance,tsteward/the-blue-alliance,phil-lopreiato/t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.