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 |
|---|---|---|---|---|---|---|---|---|---|
d293aedf296f4b63cb11ece1c00778981afef20c | pycat/cli.py | pycat/cli.py | """Command-line interface to pycat."""
import argparse
import sys
import socket
from .talk import talk
def argument_parser():
"""Generate an `argparse` argument parser for pycat's arguments."""
parser = argparse.ArgumentParser(description='netcat, in Python')
parser.add_argument('hostname', help='host to... | """Command-line interface to pycat."""
import argparse
import sys
import socket
from .talk import talk
def argument_parser():
"""Generate an `argparse` argument parser for pycat's arguments."""
parser = argparse.ArgumentParser(description='netcat, in Python')
parser.add_argument('hostname', help='host to... | Print out nicer error messages on connection errors | Print out nicer error messages on connection errors
| Python | mit | prophile/pycat |
5b43264321e4649312050264524a6df7682a6641 | mfr/ext/md/tests/test_md.py | mfr/ext/md/tests/test_md.py | from mfr.ext.md import Handler, render
from mock import MagicMock
def test_render_html():
fakefile = MagicMock(spec=file)
fakefile.read.return_value = '# foo'
assert render.render_html(fakefile) == '<h1>foo</h1>'
fakefile.read.return_value = '_italic_'
assert render.render_html(fakefile) == '<p><em... | from mfr.ext.md import Handler, render
from mock import MagicMock
def test_render_html():
fakefile = MagicMock(spec=file)
fakefile.read.return_value = '# foo'
assert render.render_html(fakefile).content == '<h1>foo</h1>'
fakefile.read.return_value = '_italic_'
assert render.render_html(fakefile).co... | Update md test for render fix | Update md test for render fix
| Python | apache-2.0 | CenterForOpenScience/modular-file-renderer,mfraezz/modular-file-renderer,Johnetordoff/modular-file-renderer,AddisonSchiller/modular-file-renderer,mfraezz/modular-file-renderer,rdhyee/modular-file-renderer,icereval/modular-file-renderer,TomBaxter/modular-file-renderer,Johnetordoff/modular-file-renderer,rdhyee/modular-fi... |
76e5d94e12717db685b0c0c66e893d7e4365a57b | examples/connect.py | examples/connect.py | #!/usr/bin/python
# Copyright 2010 Jonathan Kinred
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | #!/usr/bin/python
# Copyright 2010 Jonathan Kinred
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | Update the script to accept arguments | Update the script to accept arguments
| Python | apache-2.0 | graphite-server/psphere,jkinred/psphere |
756e11445b3f1ba52f3c3be7029fd172d6527722 | run_tests.py | run_tests.py | import sys
import os
import subprocess
def main():
executableName = 'CuraEngine'
if len(sys.argv) > 1:
executableName = sys.argv[1]
exitValue = 0
for subPath in os.listdir('testcase_models'):
print 'Running test on %s' % (subPath)
ret = subprocess.call([executableName, os.path.join('testcase_models', subPa... | import sys
import os
import subprocess
def main():
executableName = './CuraEngine'
if len(sys.argv) > 1:
executableName = sys.argv[1]
exitValue = 0
for subPath in os.listdir('testcase_models'):
print 'Running test on %s' % (subPath)
ret = subprocess.call([executableName, os.path.join('testcase_models', sub... | Fix the python script that runs the tests. | Fix the python script that runs the tests.
| Python | agpl-3.0 | ROBO3D/CuraEngine,electrocbd/CuraEngine,derekhe/CuraEngine,alephobjects/CuraEngine,Jwis921/PersonalCuraEngine,pratikshashroff/pcura,Jwis921/PersonalCuraEngine,totalretribution/CuraEngine,Skeen/CuraJS-Engine,uus169/CuraEngine,pratikshashroff/pcura,Jwis921/PersonalCuraEngine,patrick3coffee/CuraTinyG,be3d/CuraEngine,phony... |
a9bdfe489e79aec7f3b422854c58d4fe893f2b95 | duplicate_lines.py | duplicate_lines.py | import sublime, sublime_plugin
class DuplicateLinesCommand(sublime_plugin.TextCommand):
def run(self, edit):
for region in self.view.sel():
if region.empty():
line = self.view.line(region)
line_contents = self.view.substr(line) + '\n'
self.view.in... | import sublime, sublime_plugin
class DuplicateLinesCommand(sublime_plugin.TextCommand):
def run(self, edit, **args):
for region in self.view.sel():
line = self.view.full_line(region)
line_contents = self.view.substr(line)
self.view.insert(edit, line.end() if args.get('up... | Add ability to perform 'duplicate up'. | Add ability to perform 'duplicate up'.
| Python | mit | shagabutdinov/sublime-duplicate-lines-enhanced |
d80a21abcc56192d57c987cf4b8e2057e1d4ffcd | nethud/nh_client.py | nethud/nh_client.py | """
An example client. Run simpleserv.py first before running this.
"""
import json
from twisted.internet import reactor, protocol
# a client protocol
class NethackClient(protocol.Protocol):
"""Once connected, send a message, then print the result."""
def connectionMade(self):
self.send_message('a... | """
An example client. Run simpleserv.py first before running this.
"""
from __future__ import unicode_literals
import json
from twisted.internet import reactor, protocol
# a client protocol
class NethackClient(protocol.Protocol):
"""Once connected, send a message, then print the result."""
def connection... | Make all the things unicode. | Make all the things unicode.
| Python | mit | ryansb/netHUD |
c66a2933cca12fa27b688f60b3eb70b07bcce4e5 | src/ggrc/migrations/utils.py | src/ggrc/migrations/utils.py | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: anze@reciprocitylabs.com
# Maintained By: anze@reciprocitylabs.com
from ggrc import db
from sqlalchemy import and_
from sqlalchemy.orm import alias... | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: anze@reciprocitylabs.com
# Maintained By: anze@reciprocitylabs.com
from ggrc import db
from sqlalchemy import and_
from sqlalchemy.orm import alias... | Verify that new attribute doesn't already exist in database | Verify that new attribute doesn't already exist in database
| Python | apache-2.0 | prasannav7/ggrc-core,jmakov/ggrc-core,prasannav7/ggrc-core,andrei-karalionak/ggrc-core,plamut/ggrc-core,jmakov/ggrc-core,kr41/ggrc-core,selahssea/ggrc-core,j0gurt/ggrc-core,edofic/ggrc-core,AleksNeStu/ggrc-core,j0gurt/ggrc-core,selahssea/ggrc-core,selahssea/ggrc-core,kr41/ggrc-core,josthkko/ggrc-core,prasannav7/ggrc-co... |
52a6b421f4a9b0c9956ffec8f684609d43260a85 | login/tests.py | login/tests.py | from django.test import TestCase
# Create your tests here.
| from django.contrib.auth.models import User
from django.test import TestCase, Client
class LoginTestCase(TestCase):
def setUp(self):
User.objects.create_user(
username='user',
password='password'
)
def test_login_form(self):
c = Client()
response = c.g... | Add test cases for login process | Add test cases for login process
| Python | agpl-3.0 | verleihtool/verleihtool,verleihtool/verleihtool,verleihtool/verleihtool,verleihtool/verleihtool |
a6c06c61e9fa11c6b441fdf2a5075ca35015d7e0 | tests/test_windows.py | tests/test_windows.py | import pytest
import mdct.windows
def test_kbd():
mdct.windows.kaiser_derived(50)
| import pytest
import mdct.windows
def test_kbd():
mdct.windows.kaiser_derived(50)
with pytest.raises(ValueError):
mdct.windows.kaiser_derived(51)
| Test that asserts odd numbered windows dont work | Test that asserts odd numbered windows dont work
| Python | mit | audiolabs/mdct |
342512a12868bc7dadbaf3c85b5aedd86bb990e7 | gunicorn/workers/__init__.py | gunicorn/workers/__init__.py | # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import sys
# supported gunicorn workers.
SUPPORTED_WORKERS = {
"sync": "gunicorn.workers.sync.SyncWorker",
"eventlet": "gunicorn.workers.geventlet.EventletWorker",
"gevent": "guni... | # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import sys
# supported gunicorn workers.
SUPPORTED_WORKERS = {
"sync": "gunicorn.workers.sync.SyncWorker",
"eventlet": "gunicorn.workers.geventlet.EventletWorker",
"gevent": "guni... | Add the 'gthread' worker to the gunicorn.workers.SUPPORTED_WORKERS dictionary | Add the 'gthread' worker to the gunicorn.workers.SUPPORTED_WORKERS dictionary
Fixes #1011.
| Python | mit | GitHublong/gunicorn,elelianghh/gunicorn,ephes/gunicorn,malept/gunicorn,malept/gunicorn,tempbottle/gunicorn,malept/gunicorn,ccl0326/gunicorn,keakon/gunicorn,mvaled/gunicorn,tejasmanohar/gunicorn,mvaled/gunicorn,WSDC-NITWarangal/gunicorn,gtrdotmcs/gunicorn,mvaled/gunicorn,z-fork/gunicorn,prezi/gunicorn,zhoucen/gunicorn,p... |
5daef3041ced3e8a3fc8e9d7d64ab43607bb24ae | allauth/socialaccount/providers/feedly/views.py | allauth/socialaccount/providers/feedly/views.py | from __future__ import unicode_literals
import requests
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
OAuth2LoginView,
OAuth2CallbackView)
from .provider import FeedlyProvider
... | from __future__ import unicode_literals
import requests
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
OAuth2LoginView,
OAuth2Call... | Add option FEEDLY_HOST for feedly.com provider | Add option FEEDLY_HOST for feedly.com provider | Python | mit | wli/django-allauth,rsalmaso/django-allauth,lukeburden/django-allauth,spool/django-allauth,pennersr/django-allauth,rsalmaso/django-allauth,lukeburden/django-allauth,bittner/django-allauth,AltSchool/django-allauth,joshowen/django-allauth,lukeburden/django-allauth,bittner/django-allauth,jwhitlock/django-allauth,jwhitlock/... |
1633fe8e8e3d97273256fd64cac0447737ef1594 | jsonrpcclient/__init__.py | jsonrpcclient/__init__.py | """__init__.py"""
from jsonrpcclient.request import Request
| """__init__.py"""
import logging
logging.getLogger('jsonrpcclient').addHandler(logging.NullHandler())
from jsonrpcclient.request import Request
| Add NullHandler to logger to quiet Python 2.7 | Add NullHandler to logger to quiet Python 2.7
| Python | mit | bcb/jsonrpcclient |
f2afbc2d7b47e6e28f6924b9761390c34b04ea49 | trunk/editor/test_opensave.py | trunk/editor/test_opensave.py | #!/usr/bin/env python
import unittest
from xml.etree import ElementTree
from openfilerooms import openFileRooms
from savefilerooms import saveFileRooms
class Test(unittest.TestCase):
def test1(self):
source = "world1.rooms"
dest = 'a.rooms'
openFileRooms(source)
saveFileRooms(des... | #!/usr/bin/env python
import os
import unittest
from xml.etree import ElementTree
from openfilerooms import openFileRooms
from savefilerooms import saveFileRooms
class Test(unittest.TestCase):
test_output = "a.rooms"
def test1(self):
fpath = os.path.abspath(__file__)
path, _ = os.path.split(... | Use one of the stock examples for the open/save test | Use one of the stock examples for the open/save test
| Python | mit | develersrl/rooms,develersrl/rooms,develersrl/rooms,develersrl/rooms,develersrl/rooms,develersrl/rooms,develersrl/rooms |
3b539cedd12948fde71cad29a4eee517d4adff1e | bot.py | bot.py | import os
import time
from crawl import crawl
import tweepy
class TwitterAPI:
"""
Class for accessing the Twitter API.
Requires API credentials to be available in environment
variables. These will be set appropriately if the bot was created
with init.sh included with the heroku-twitterbot-starter... | import os
import time
from crawl import crawl
import tweepy
class TwitterAPI:
"""
Class for accessing the Twitter API.
Requires API credentials to be available in environment
variables. These will be set appropriately if the bot was created
with init.sh included with the heroku-twitterbot-starter... | Put back to 12 hours. | Put back to 12 hours.
| Python | mit | gregsabo/only_keep_one,gregsabo/only_keep_one |
67b2729c1c2a7027be7ad7a9d641609e94769671 | quickstart/python/autopilot/create-hello-world-samples/create_hello_world_samples.6.x.py | quickstart/python/autopilot/create-hello-world-samples/create_hello_world_samples.6.x.py | # Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
phrases = [
'hello',
... | # Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
phrases = [
'hello',
... | Update to use unique_name for task update | Update to use unique_name for task update | Python | mit | TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets |
6de7d5059d6d5fd2569f108e83fff0ae979aad89 | train_twitter_data.py | train_twitter_data.py | from sklearn.datasets import load_files
from sklearn.feature_extraction.text import CountVectorizer
categories = ['neg', 'pos']
twitter_train = load_files('./twitter_data/twitter_data-train', categories=categories, load_content=True, shuffle=True, random_state=42)
count_vect = CountVectorizer()
X_train_counts = cou... | from sklearn.datasets import load_files
from sklearn.feature_extraction.text import CountVectorizer
categories = ['neg', 'pos']
twitter_train = load_files('./twitter_data/twitter_data-train', categories=categories, load_content=True, shuffle=True, random_state=42)
#Ignoring decode errors may harm our results, but a... | Make vectorizer Ignore decode errors | Make vectorizer Ignore decode errors
This isn't ideal and could harm our results, but it actually runs now. Figuring out the proper encoding would be better if possible.
| Python | apache-2.0 | ngrudzinski/sentiment_analysis_437 |
c1cd227e564ff1caf868068a182bf258aac47728 | python/testData/inspections/PyTypeCheckerInspection/MapArgumentsInOppositeOrderPy2.py | python/testData/inspections/PyTypeCheckerInspection/MapArgumentsInOppositeOrderPy2.py | map<warning descr="Unexpected type(s):(str, (c: Any) -> int)Possible types:(None, Iterable)((Any) -> Any, Iterable)">('foo', lambda c: 42)</warning>
| map<warning descr="Unexpected type(s):(str, (c: Any) -> int)Possible types:((Any) -> Any, Iterable)(None, Iterable)">('foo', lambda c: 42)</warning>
| Fix test data after syncing with typeshed | Fix test data after syncing with typeshed
| Python | apache-2.0 | allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/int... |
40fd8c680f335ebd1bc217f35a47f169c336530c | pyosf/tools.py | pyosf/tools.py | # -*- coding: utf-8 -*-
"""
Part of the pyosf package
https://github.com/psychopy/pyosf/
Released under MIT license
@author: Jon Peirce
"""
def find_by_key(in_list, key, val):
"""Returns the first item with key matching val
"""
return (item for item in in_list if item[key] == val).next()
def dict_from... | # -*- coding: utf-8 -*-
"""
Part of the pyosf package
https://github.com/psychopy/pyosf/
Released under MIT license
@author: Jon Peirce
"""
def find_by_key(in_list, key, val):
"""Returns the first item with key matching val
"""
return next(item for item in in_list if item[key] == val)
def dict_from_li... | Fix compatibility with Py3 (generators no longer have next()) | Fix compatibility with Py3 (generators no longer have next())
But there is a next() function as a general built-in and works in 2.6 too
| Python | mit | psychopy/pyosf |
3d91c12d3382226263ea3d660b48f1ef1125d099 | tests/basics/ordereddict1.py | tests/basics/ordereddict1.py | try:
from collections import OrderedDict
except ImportError:
try:
from ucollections import OrderedDict
except ImportError:
print("SKIP")
import sys
sys.exit()
d = OrderedDict([(10, 20), ("b", 100), (1, 2)])
print(list(d.keys()))
print(list(d.values()))
del d["b"]
print(list(... | try:
from collections import OrderedDict
except ImportError:
try:
from ucollections import OrderedDict
except ImportError:
print("SKIP")
import sys
sys.exit()
d = OrderedDict([(10, 20), ("b", 100), (1, 2)])
print(len(d))
print(list(d.keys()))
print(list(d.values()))
del d["b... | Add further tests for OrderedDict. | tests/basics: Add further tests for OrderedDict.
| Python | mit | pfalcon/micropython,kerneltask/micropython,torwag/micropython,selste/micropython,torwag/micropython,TDAbboud/micropython,blazewicz/micropython,bvernoux/micropython,TDAbboud/micropython,lowRISC/micropython,cwyark/micropython,oopy/micropython,infinnovation/micropython,dmazzella/micropython,MrSurly/micropython-esp32,MrSur... |
9b02a09be67c8ec3d3b4b652d98f2cd5c3fdc863 | app/timetables/admin.py | app/timetables/admin.py | from django.contrib import admin
from .models import Course, Meal, MealOption, Weekday, Timetable, Dish
admin.site.register(Weekday)
admin.site.register(Meal)
admin.site.register(MealOption)
admin.site.register(Course)
admin.site.register(Timetable)
admin.site.register(Dish)
| from django.contrib import admin
from .models import *
admin.site.register(Weekday)
admin.site.register(Meal)
admin.site.register(MealOption)
admin.site.register(Course)
admin.site.register(Timetable)
admin.site.register(Dish)
admin.site.register(Admin)
| Add Timetables Admin model to Django Admin Interface | Add Timetables Admin model to Django Admin Interface
| Python | mit | teamtaverna/core |
ff4e769102295280b9e5ad703c5b676f399df894 | test/test_basic.py | test/test_basic.py | import unittest
class MyTestCase(unittest.TestCase):
def test_something(self):
self.assertEqual(True, False)
if __name__ == '__main__':
unittest.main()
| import unittest
import openfigi
class MyTestCase(unittest.TestCase):
def test_wkn_ticker_anonymous(self):
"""Get an ETF by WKN and check if response makes sense"""
ofg = openfigi.OpenFigi()
ofg.enqueue_request(id_type='ID_WERTPAPIER', id_value='A0YEDG')
response = ofg.fetch_respon... | Add a basic unit test | Add a basic unit test
| Python | mit | jwergieluk/openfigi,jwergieluk/openfigi |
23e57facea49ebc093d1da7a9ae6857cd2c8dad7 | warehouse/defaults.py | warehouse/defaults.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
# The base domain name for this installation. Used to control linking to
# sub-domains.
SERVER_NAME = "warehouse.local"
# The URI for our PostgreSQL database.
SQLALCHEMY_DATABASE_URI = "postgres:///ware... | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
# The base domain name for this installation. Used to control linking to
# sub-domains.
SERVER_NAME = "warehouse.local"
# The URI for our PostgreSQL database.
SQLALCHEMY_DATABASE_URI = "postgres:///ware... | Add an explicit default for REDIS_URI | Add an explicit default for REDIS_URI
| Python | bsd-2-clause | davidfischer/warehouse |
494e7ff2e249a8202c8a71172be7f1870f56f9c3 | mcavatar/views/public/__init__.py | mcavatar/views/public/__init__.py | from flask import Blueprint
public = Blueprint('public', __name__, template_folder='templates')
@public.route('/')
def index():
return 'Hello World'
| from flask import Blueprint
public = Blueprint('public', __name__)
@public.route('/')
def index():
return 'Hello World'
| Remove blueprint specific template directories. | Remove blueprint specific template directories.
| Python | mit | joealcorn/MCAvatar |
22483d9ca6e393635ffdf371c35026f0e8ec429c | gyp/find.py | gyp/find.py | # Copyright 2015 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''
find.py is a poor-man's emulation of `find $1 -name=$2` on Unix.
Call python find.py <directory> <glob> to list all files matching glob under
directory (recursively). E.g.
$ pyt... | # Copyright 2015 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''
find.py is a poor-man's emulation of `find $1 -name=$2` on Unix.
Call python find.py <directory> <glob> to list all files matching glob under
directory (recursively). E.g.
$ pyt... | Sort build files for consistent link order. | Sort build files for consistent link order.
Prior to the introduction of find.py, GMs were liked in the order they
were listed in the gypi file, which was generally alphabetically. This
made it fairly easy to predict where slides would show up in SampleApp
and the order was consistent. This simply sorts the list of fi... | Python | bsd-3-clause | rubenvb/skia,ominux/skia,Hikari-no-Tenshi/android_external_skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,vanish87/skia,tmpvar/skia.cc,pcwalton/skia,vanish87/skia,qrealka/skia-hc,ominux/skia,shahrzadmn/skia,google/skia,pcwalton/skia,nvoron23/skia,vanish87/skia,noselhq/skia,tmpvar/skia.cc,van... |
ddfeb1e9ef60e1913bf702e58cf4696cf7c98c6d | logicmind/token_parser.py | logicmind/token_parser.py | from tokens.andd import And
from tokens.expression import Expression
from tokens.iff import Iff
from tokens.nop import Not
from tokens.orr import Or
from tokens.then import Then
from tokens.variable import Variable
class TokenParser:
"""This parser only works with atomic expressions,
so parenthesis are nee... | from tokens.andd import And
from tokens.expression import Expression
from tokens.iff import Iff
from tokens.nop import Not
from tokens.orr import Or
from tokens.then import Then
from tokens.variable import Variable
class TokenParser:
"""This parser only works with atomic expressions,
so parenthesis are nee... | Allow more representations when parsing | [logicmind] Allow more representations when parsing
| Python | mit | LonamiWebs/Py-Utils |
5167ec5f2ba30e649e6fd9b2994995a6022bfda3 | client.py | client.py | #!/usr/bin/env python
# Auto-launching using this: export PROMPT_COMMAND='/Users/putilin/client.py "`fc -nl -1`"'
import requests
import sys
import os
import re
assert len(sys.argv) == 2
history_output = sys.argv[1]
m = re.match(r"[ ]*(\d+)[ ][ ](.*)", history_output)
command_id = m.group(1)
command_text = m.group... | #!/usr/bin/env python
# Auto-launching using this: export PROMPT_COMMAND='/Users/putilin/client.py "`fc -nl -1`"'
import os
import sys
shell_pid = os.getppid()
if os.fork() != 0:
sys.exit()
import requests
import re
assert len(sys.argv) == 2
history_output = sys.argv[1]
m = re.match(r"[ ]*(\d+)[ ][ ](.*)", his... | Send command in the child process | Send command in the child process
| Python | mit | elimohl/histsync,oxyzero/histsync,eleweek/histsync,elimohl/histsync,elimohl/histsync,oxyzero/histsync,eleweek/histsync,eleweek/histsync,elimohl/histsync,oxyzero/histsync,eleweek/histsync,oxyzero/histsync |
ada0aadf9558caba7cb94125f8a8104d2fde968c | tempora/utc.py | tempora/utc.py | """
Facilities for common time operations in UTC.
Inspired by the `utc project <https://pypi.org/project/utc>`_.
>>> dt = now()
>>> dt == fromtimestamp(dt.timestamp())
True
>>> dt.tzinfo
datetime.timezone.utc
>>> from time import time as timestamp
>>> now().timestamp() - timestamp() < 0.1
True
>>> datetime(2018, 6,... | """
Facilities for common time operations in UTC.
Inspired by the `utc project <https://pypi.org/project/utc>`_.
>>> dt = now()
>>> dt == fromtimestamp(dt.timestamp())
True
>>> dt.tzinfo
datetime.timezone.utc
>>> from time import time as timestamp
>>> now().timestamp() - timestamp() < 0.1
True
>>> (now() - fromtime... | Add test demonstrating aware comparisons | Add test demonstrating aware comparisons
| Python | mit | jaraco/tempora |
78ecac7c97445fd24a9d00f5fea671aab99d4c3b | monitor-notifier-slack.py | monitor-notifier-slack.py | #!/usr/bin/env python
import pika
import json
import requests
import os
RABBIT_MQ_SERVER = os.environ["RABBIT_MQ_SERVER"]
RABBIT_MQ_USER = os.environ["RABBIT_MQ_USER"]
RABBIT_MQ_PWD = os.environ["RABBIT_MQ_PWD"]
credentials = pika.PlainCredentials(RABBIT_MQ_USER, RABBIT_MQ_PWD)
connection = pika.BlockingConnection(p... | #!/usr/bin/env python
import pika
import json
import requests
import os
RABBIT_MQ_SERVER = os.environ["RABBIT_MQ_SERVER"]
RABBIT_MQ_USER = os.environ["RABBIT_MQ_USER"]
RABBIT_MQ_PWD = os.environ["RABBIT_MQ_PWD"]
credentials = pika.PlainCredentials(RABBIT_MQ_USER, RABBIT_MQ_PWD)
connection = pika.BlockingConnection(p... | Improve message posted to slack | Improve message posted to slack
| Python | mit | observer-hackaton/monitor-notifier-slack |
37dc483fd381aa14eddddb13c991bbf647bb747b | data/global-configuration/packs/core-functions/module/node.py | data/global-configuration/packs/core-functions/module/node.py | from opsbro.evaluater import export_evaluater_function
from opsbro.gossip import gossiper
FUNCTION_GROUP = 'gossip'
@export_evaluater_function(function_group=FUNCTION_GROUP)
def is_in_group(group):
"""**is_in_group(group)** -> return True if the node have the group, False otherwise.
* group: (string) group to ... | from opsbro.evaluater import export_evaluater_function
from opsbro.gossip import gossiper
FUNCTION_GROUP = 'gossip'
@export_evaluater_function(function_group=FUNCTION_GROUP)
def is_in_group(group):
"""**is_in_group(group)** -> return True if the node have the group, False otherwise.
* group: (string) group to ... | Declare the is_in_defined_group function, even if it is an alias of the is_in_group | Enh: Declare the is_in_defined_group function, even if it is an alias of the is_in_group
| Python | mit | naparuba/kunai,naparuba/kunai,naparuba/opsbro,naparuba/kunai,naparuba/kunai,naparuba/kunai,naparuba/opsbro,naparuba/opsbro,naparuba/kunai,naparuba/opsbro |
174eb11bf4bdd65e269f0792ddcb1e589bca8b0d | boto3/compat.py | boto3/compat.py | # Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... | # Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... | Handle the case where OSError is not because file does not exist | Handle the case where OSError is not because file does not exist
| Python | apache-2.0 | boto/boto3 |
e8c1ba2c63a1ea66aa2c08e606ac0614e6854565 | interrupt.py | interrupt.py | import signal
import sys
from threading import Event
def GetInterruptEvent():
e = Event()
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
e.set()
signal.signal(signal.SIGINT, signal_handler)
return e
| import signal
import sys
from threading import Event
def GetInterruptEvent():
e = Event()
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
e.set()
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
return e
| Handle sigterm as well as sigint. | Handle sigterm as well as sigint.
| Python | mit | rickbassham/videoencode,rickbassham/videoencode |
441cccc340afeb205da75762ce6e145215a858b3 | src/zephyr/delayed_stream.py | src/zephyr/delayed_stream.py |
import threading
import collections
import itertools
import time
import zephyr
class DelayedRealTimeStream(threading.Thread):
def __init__(self, signal_collector, callbacks, delay):
threading.Thread.__init__(self)
self.signal_collector = signal_collector
self.callbacks = callb... |
import threading
import collections
import itertools
import time
import zephyr
class DelayedRealTimeStream(threading.Thread):
def __init__(self, signal_collector, callbacks, default_delay, specific_delays={}):
threading.Thread.__init__(self)
self.signal_collector = signal_collector
... | Split delay configuration into default_delay and specific_delays | Split delay configuration into default_delay and specific_delays | Python | bsd-2-clause | jpaalasm/zephyr-bt |
1fc1e160143b5a35741cf3fce9ced827a433d640 | tests/test__pycompat.py | tests/test__pycompat.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import dask_distance._pycompat
def test_irange():
r = dask_distance._pycompat.irange(5)
assert not isinstance(r, list)
assert list(r) == [0, 1, 2, 3, 4]
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import dask_distance._pycompat
def test_irange():
r = dask_distance._pycompat.irange(5)
assert not isinstance(r, list)
assert list(r) == [0, 1, 2, 3, 4]
def test_izip():
r = dask_distance._pycompat.izip([1, 2, ... | Add a test for izip | Add a test for izip
Make sure that it generates an iterator on both Python 2 and Python 3.
Also check that it can be converted to a `list`.
| Python | bsd-3-clause | jakirkham/dask-distance |
2f0f560808e07c31ffb88e4b8c9d272536f58e5c | api/commands.py | api/commands.py | import json
import requests
from Suchary.local_settings import GCM_API_KEY
from api.models import Device
URL = 'https://android.googleapis.com/gcm/send'
HEADER = {'Authorization': 'key=' + GCM_API_KEY, 'Content-Type': 'application/json'}
def get_reg_ids():
reg_ids = [device.registration_id for device in Device.o... | import json
import requests
from Suchary.local_settings import GCM_API_KEY
from api.models import Device
URL = 'https://android.googleapis.com/gcm/send'
HEADER = {'Authorization': 'key=' + GCM_API_KEY, 'Content-Type': 'application/json'}
def get_reg_ids():
reg_ids = [device.registration_id for device in Device.o... | Add command to send messages via GCM | Add command to send messages via GCM
| Python | mit | jchmura/suchary-django,jchmura/suchary-django,jchmura/suchary-django |
343e3bd0e16df1106d82fa6087a7247dc67bb52b | oslo_concurrency/_i18n.py | oslo_concurrency/_i18n.py | # Copyright 2014 Mirantis Inc.
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... | # Copyright 2014 Mirantis Inc.
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... | Drop use of namespaced oslo.i18n | Drop use of namespaced oslo.i18n
Related-blueprint: drop-namespace-packages
Change-Id: Ic8247cb896ba6337932d7a74618debd698584fa0
| Python | apache-2.0 | JioCloud/oslo.concurrency,openstack/oslo.concurrency,varunarya10/oslo.concurrency |
d14c0aeba5304ba66649c9d6a0a9d144a9ef1e43 | api/teams/admin.py | api/teams/admin.py | from django.contrib import admin
from .models import Team
from nucleus.admin import TeamMemberInline
class TeamAdmin(admin.ModelAdmin):
inlines = (TeamMemberInline, )
raw_id_fields = ('captain', 'creator', )
list_display = (
'name',
'get_player_count',
'get_player_list',
'... | from django.contrib import admin
from django.db.models import Count
from .models import Team
from nucleus.admin import TeamMemberInline
class TeamAdmin(admin.ModelAdmin):
inlines = (TeamMemberInline, )
raw_id_fields = ('captain', 'creator', )
list_display = (
'name',
'get_player_count',
... | Allow team num players column to be ordered | Allow team num players column to be ordered
| Python | mit | prattl/wepickheroes,prattl/wepickheroes,prattl/wepickheroes,prattl/wepickheroes |
a69bd95c2e732f22aac555884904bbe7d9d0a1b9 | src/dynamic_fixtures/management/commands/load_dynamic_fixtures.py | src/dynamic_fixtures/management/commands/load_dynamic_fixtures.py | from django.core.management.base import BaseCommand
from dynamic_fixtures.fixtures.runner import LoadFixtureRunner
class Command(BaseCommand):
help_text = 'Load fixtures while keeping dependencies in mind.'
args = '[app_label] [fixture_name]'
def handle(self, *args, **options):
runner = LoadFix... | from django.core.management.base import BaseCommand
from dynamic_fixtures.fixtures.runner import LoadFixtureRunner
class Command(BaseCommand):
help_text = 'Load fixtures while keeping dependencies in mind.'
args = '[app_label] [fixture_name]'
def add_arguments(self, parser):
parser.add_argument... | Fix Command compatibility with Django>= 1.8 | Fix Command compatibility with Django>= 1.8
| Python | mit | Peter-Slump/django-factory-boy-fixtures,Peter-Slump/django-dynamic-fixtures |
30ebc069634673c6a3b52c7f4285c2ce3c88472a | app/users/models.py | app/users/models.py | from datetime import datetime, timedelta
from app import db, bcrypt
from app.utils.misc import make_code
def expiration_date():
return datetime.now() + timedelta(days=1)
class User(db.Model):
id = db.Column(db.Integer(), primary_key=True)
email = db.Column(db.String(255), unique=True)
password = d... | from datetime import datetime, timedelta
from app import db, bcrypt
from app.utils.misc import make_code
def expiration_date():
return datetime.now() + timedelta(days=1)
class AppUser(db.Model):
id = db.Column(db.Integer(), primary_key=True)
email = db.Column(db.String(255), unique=True)
password ... | Rename User model to AppUser | Rename User model to AppUser
| Python | mit | projectweekend/Flask-PostgreSQL-API-Seed |
c6229fc20f8bb37d185f90b032c0dc3817834256 | linguist/mixins.py | linguist/mixins.py | # -*- coding: utf-8 -*-
from .models import Translation
from .utils import get_cache_key
class LinguistMixin(object):
def clear_translations_cache(self):
self._linguist.clear()
@property
def language(self):
return self._linguist.language
@language.setter
def language(self, value... | # -*- coding: utf-8 -*-
from .models import Translation
from .utils.i18n import get_cache_key
class LinguistMixin(object):
def clear_translations_cache(self):
self._linguist.clear()
@property
def identifier(self):
return self._linguist.identifier
@property
def language(self):
... | Add identifier property to mixin. | Add identifier property to mixin.
| Python | mit | ulule/django-linguist |
8b5cfb11235d419d729a69a638a39489322fe547 | api/provider.py | api/provider.py | """
atmosphere service provider rest api.
"""
from rest_framework.views import APIView
from rest_framework.response import Response
from authentication.decorators import api_auth_token_required
from core.models.group import Group
from api.serializers import ProviderSerializer
class ProviderList(APIView):
"""... | """
atmosphere service provider rest api.
"""
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from authentication.decorators import api_auth_token_required
from core.models.group import Group
from core.models.provider import Provider as CoreProv... | Fix problem where Provider DoesNotExist. | Fix problem where Provider DoesNotExist.
* Occurs on provider and providerlist endpoints.
* Came to attention as a side effect of fixing ATMO-176.
* Similar changes need to be made all over atmosphere. I'll
create a ticket.
modified: api/provider.py
| Python | apache-2.0 | CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend |
a512af54d5c843aa8f232a73dcfe79870341a8db | ppadb/command/transport_async/__init__.py | ppadb/command/transport_async/__init__.py | import logging
import re
import time
class TransportAsync:
async def transport(self, connection):
cmd = "host:transport:{}".format(self.serial)
await connection.send(cmd)
return connection
async def shell(self, cmd, timeout=None):
conn = await self.create_connection(timeout=t... | import logging
import re
import time
class TransportAsync:
async def transport(self, connection):
cmd = "host:transport:{}".format(self.serial)
await connection.send(cmd)
return connection
async def shell(self, cmd, timeout=None):
conn = await self.create_connection(timeout=t... | Check the length of the screencap before indexing into it | Check the length of the screencap before indexing into it
| Python | mit | Swind/pure-python-adb,Swind/pure-python-adb |
92a5d02b3e052fb0536e51aba043ff2f026c6484 | appengine_config.py | appengine_config.py | import logging
def appstats_should_record(env):
from gae_mini_profiler.config import should_profile
if should_profile():
return True
def gae_mini_profiler_should_profile_production():
from google.appengine.api import users
return users.is_current_user_admin()
def gae_mini_profiler_should_profile_develo... | import logging
def appstats_should_record(env):
#from gae_mini_profiler.config import should_profile
#if should_profile():
# return True
return False
def gae_mini_profiler_should_profile_production():
from google.appengine.api import users
return users.is_current_user_admin()
def gae_mini_profiler_sho... | Disable GAE mini profiler by default | Disable GAE mini profiler by default
| Python | mit | bbondy/brianbondy.gae,bbondy/brianbondy.gae,bbondy/brianbondy.gae,bbondy/brianbondy.gae |
3e42ee0d9bd712b0e757af66279eaff838b0f004 | django_lti_tool_provider/tests/urls.py | django_lti_tool_provider/tests/urls.py | from django.conf.urls import url
from django_lti_tool_provider import views as lti_views
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='home'),
url('^accounts/login/$', 'django.contrib.auth.views.login'),
url(r'^lti$', lti_views.LTIView.as_view(), name='lti')
] | from django.conf.urls import url
from django.contrib.auth.views import login
from django_lti_tool_provider import views as lti_views
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='home'),
url('^accounts/login/$', login),
url(r'^lti$', lti_views.LTIView.as_view(), name='lti')
]
| Replace string "view" argument to url() function with callable. | Replace string "view" argument to url() function with callable.
Support for string "view" arguments to url() function no longer available starting with Django 1.10.
Cf. https://docs.djangoproject.com/en/2.1/releases/1.10/#features-removed-in-1-10
| Python | agpl-3.0 | open-craft/django-lti-tool-provider |
d70f19106a7dc63182a3a0ea4fe6702eedc23322 | mlog/db.py | mlog/db.py | import sqlite3
def init(conn):
c = conn.cursor()
c.execute(
'''CREATE TABLE IF NOT EXISTS email_log (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`param` TEXT,
`email` TEXT,
`stage` INTEGER DEFAULT 0,
`sender` TE... | import sqlite3
def init(conn):
c = conn.cursor()
c.execute(
'''CREATE TABLE IF NOT EXISTS email_log (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`param` TEXT,
`email` TEXT,
`stage` INTEGER DEFAULT 0,
`sender` TE... | Add index to the message_id column | Add index to the message_id column
| Python | agpl-3.0 | fajran/mlog |
81cf2085bb43742b722e833f8cec6e65e2906ec0 | pyes/tests/errors.py | pyes/tests/errors.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Unit tests for pyes. These require an es server with thrift plugin running on the default port (localhost:9500).
"""
import unittest
from pyes.tests import ESTestCase
import pyes.exceptions
class ErrorReportingTestCase(ESTestCase):
def setUp(self):
super(Error... | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Unit tests for pyes. These require an es server with thrift plugin running on the default port (localhost:9500).
"""
import unittest
from pyes.tests import ESTestCase
import pyes.exceptions
class ErrorReportingTestCase(ESTestCase):
def setUp(self):
super(Error... | Test that various exceptions are correctly converted | Test that various exceptions are correctly converted
| Python | bsd-3-clause | jayzeng/pyes,Fiedzia/pyes,HackLinux/pyes,mavarick/pyes,haiwen/pyes,aparo/pyes,haiwen/pyes,aparo/pyes,aparo/pyes,jayzeng/pyes,Fiedzia/pyes,mavarick/pyes,mavarick/pyes,HackLinux/pyes,mouadino/pyes,rookdev/pyes,haiwen/pyes,rookdev/pyes,mouadino/pyes,HackLinux/pyes,Fiedzia/pyes,jayzeng/pyes |
4604cf73a45e8bcecf38238366cfdac37cdb7897 | pyfr/readers/base.py | pyfr/readers/base.py | # -*- coding: utf-8 -*-
import re
import uuid
import itertools as it
from abc import ABCMeta, abstractmethod
import numpy as np
class BaseReader(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def _op... | # -*- coding: utf-8 -*-
import re
import uuid
from abc import ABCMeta, abstractmethod
import numpy as np
class BaseReader(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def _optimize(self, mesh):
... | Fix a bug in the mesh optimizer. | Fix a bug in the mesh optimizer.
| Python | bsd-3-clause | iyer-arvind/PyFR,tjcorona/PyFR,tjcorona/PyFR,BrianVermeire/PyFR,Aerojspark/PyFR,tjcorona/PyFR |
3a7428723c66010dec1d246beb63be371428d3fe | qipipe/staging/staging_helpers.py | qipipe/staging/staging_helpers.py | """Pipeline utility functions."""
import re
_SSS_REGEX = '(\w+\d{2})/(session\d{2})/(series\d{3})'
"""The subject/session/series regexp pattern."""
def match_session_hierarchy(path):
"""
Matches the subject, session and series names from the given input path.
@param path: the path to match
@retu... | """Pipeline utility functions."""
import re
from .staging_error import StagingError
_SSS_REGEX = '(\w+\d{2})/(session\d{2})/(series\d{3})'
"""The subject/session/series regexp pattern."""
def match_series_hierarchy(path):
"""
Matches the subject, session and series names from the given input path.
@... | Raise error if no match. | Raise error if no match.
| Python | bsd-2-clause | ohsu-qin/qipipe |
6dfcee473ef860fe9abb4971baabf62f9f51e314 | inpassing/util.py | inpassing/util.py | # Copyright (c) 2016 Luke San Antonio Bialecki
# All rights reserved.
from functools import wraps
from flask_jwt_extended import utils
from flask_jwt_extended.utils import ctx_stack
from flask_jwt_extended.exceptions import NoAuthorizationError
from datetime import timedelta
def jwt_optional(fn):
@wraps(fn)
... | # Copyright (c) 2016 Luke San Antonio Bialecki
# All rights reserved.
from functools import wraps
from flask_jwt_extended import utils
from flask_jwt_extended.utils import ctx_stack
from flask_jwt_extended.exceptions import NoAuthorizationError
from datetime import timedelta
def jwt_optional(fn):
@wraps(fn)
... | Add daystate_dict function to serialize daystates to dictionaries | Add daystate_dict function to serialize daystates to dictionaries
| Python | mit | lukesanantonio/inpassing-backend,lukesanantonio/inpassing-backend |
71df45002746b162e04a125403cad390accb949e | backend/main.py | backend/main.py | # [START app]
import logging
from firebase import firebase
from flask import Flask, jsonify, request
import flask_cors
from google.appengine.ext import ndb
import google.auth.transport.requests
import google.oauth2.id_token
import requests_toolbelt.adapters.appengine
requests_toolbelt.adapters.appengine.monkeypatch()... | # [START app]
import logging
from firebase import firebase
from flask import Flask, jsonify, request
import flask_cors
from google.appengine.ext import ndb
import google.auth.transport.requests
import google.oauth2.id_token
import requests_toolbelt.adapters.appengine
requests_toolbelt.adapters.appengine.monkeypatch()... | Add proper authentication for db (without actual key). | Add proper authentication for db (without actual key).
| Python | apache-2.0 | google/playhvz,google/playhvz,google/playhvz,google/playhvz,google/playhvz,google/playhvz,google/playhvz,google/playhvz |
0aa6a648fff39b013f9b644d9a894db39706df43 | amplpy/amplpython/__init__.py | amplpy/amplpython/__init__.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
import ctypes
import platform
if platform.system() == 'Windows':
lib32 = os.path.join(os.path.dirname(__file__), 'lib32')
lib64 = os.path.join(os.path.dirname(__file__), 'lib64')
from glob import glob
try:
if ctypes.sizeo... | # -*- coding: utf-8 -*-
import os
import sys
import ctypes
import platform
if platform.system() == 'Windows':
lib32 = os.path.join(os.path.dirname(__file__), 'lib32')
lib64 = os.path.join(os.path.dirname(__file__), 'lib64')
from glob import glob
try:
if ctypes.sizeof(ctypes.c_voidp) == 4:
... | Fix 'ModuleNotFoundError: No module named amplpython' | Fix 'ModuleNotFoundError: No module named amplpython'
| Python | bsd-3-clause | ampl/amplpy,ampl/amplpy,ampl/amplpy |
895ca15591938f07f1e913b08726f991c2d9e964 | libs/googleapis.py | libs/googleapis.py | import os
import time
import json
import requests
def get_timezone(lat, long):
response = requests.get('https://maps.googleapis.com/maps/api/timezone/json', params={
'location': '{},{}'.format(lat, long),
'timestamp': int(time.time()),
'key': os.environ['GOOGLE_API_TOKEN']
}).json()
... | import os
import time
import json
import requests
def get_timezone(lat, long):
response = requests.get('https://maps.googleapis.com/maps/api/timezone/json', params={
'location': '{},{}'.format(lat, long),
'timestamp': int(time.time()),
'key': os.environ['GOOGLE_API_TOKEN']
}).json()
... | Fix url shortening for small domains | Fix url shortening for small domains
| Python | mit | sevazhidkov/leonard |
c9dfb5b59d5f51200df938f3da176a577842a390 | openquake/engine/tests/export/core_test.py | openquake/engine/tests/export/core_test.py |
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distr... |
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distr... | Fix a broken export test | Fix a broken export test
Former-commit-id: fea471180d544a95f3d0adf87a7a46f51c067324 [formerly 4b369edfcb5782a2461742547f5b6af3bab4f759] [formerly 4b369edfcb5782a2461742547f5b6af3bab4f759 [formerly e37e964bf9d2819c0234303d31ed2839c317be04]]
Former-commit-id: 5b8a20fa99eab2f33c8f293a505a2dbadad36eee
Former-commit-id: 1... | Python | agpl-3.0 | gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine |
7b50adc607f0e0e970c6f5793eadd9fb42027d0a | Tools/scripts/setup.py | Tools/scripts/setup.py | from distutils.core import setup
if __name__ == '__main__':
setup(
scripts=[
'byteyears.py',
'checkpyc.py',
'copytime.py',
'crlf.py',
'dutree.py',
'ftpmirror.py',
'h2py.py',
'lfcr.py',
'logmerge.py',
'../../Lib/tabnanny.py',
... | from distutils.core import setup
if __name__ == '__main__':
setup(
scripts=[
'byteyears.py',
'checkpyc.py',
'copytime.py',
'crlf.py',
'dutree.py',
'ftpmirror.py',
'h2py.py',
'lfcr.py',
'../i18n/pygettext.py',
'logmerge.py',
... | Install pygettext (once the scriptsinstall target is working again). | Install pygettext (once the scriptsinstall target is working again).
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator |
e43c1335bb48e8ba3321ddd9471ac04fd75a4250 | broker/ivorn_db.py | broker/ivorn_db.py | # VOEvent receiver.
# John Swinbank, <swinbank@transientskp.org>, 2011-12.
# Python standard library
import os
import anydbm
import datetime
from contextlib import closing
from threading import Lock
class IVORN_DB(object):
# Using one big lock for all the databases is a little clunky.
def __init__(self, root)... | # VOEvent receiver.
# John Swinbank, <swinbank@transientskp.org>, 2011-12.
# Python standard library
import os
import anydbm
import datetime
from threading import Lock
from collections import defaultdict
class IVORN_DB(object):
def __init__(self, root):
self.root = root
self.locks = defaultdict(Lo... | Use a separate lock per ivorn database | Use a separate lock per ivorn database
| Python | bsd-2-clause | jdswinbank/Comet,jdswinbank/Comet |
cb71bc8767fbc07a27df4049b95c7dacf5975c9d | pinax/app_name/tests/urls.py | pinax/app_name/tests/urls.py | try:
from django.conf.urls import patterns, include
except ImportError:
from django.conf.urls.defaults import patterns, include
urlpatterns = patterns(
"",
(r"^", include("pinax.{{ app_name }}.urls")),
)
| from django.conf.urls import include
urlpatterns = [
(r"^", include("pinax.{{ app_name }}.urls")),
]
| Fix django 1.9 warning and drop support django < 1.7 | Fix django 1.9 warning and drop support django < 1.7
Fixes a warning that happens when running with Django 1.9:
RemovedInDjango110Warning: django.conf.urls.patterns() is deprecated and will be removed in Django 1.10. Update your urlpatterns to be a list of django.conf.urls.url() instances instead.
Drop support of dja... | Python | mit | pinax/pinax-starter-app |
09ae343b2abe0a0a325437396c995abe5aa560b4 | shuup/api/mixins.py | shuup/api/mixins.py | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from django.db.models.deletion import ProtectedError
from rest_fra... | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from django.db.models.deletion import ProtectedError
from rest_fra... | Add Searchable Mixin for API | Add Searchable Mixin for API
| Python | agpl-3.0 | shoopio/shoop,shoopio/shoop,shoopio/shoop |
28bacd5c3318aff52c0758ad97909ff08c7bfffb | api/base/exceptions.py | api/base/exceptions.py |
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.view... |
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.view... | Add spaces to increase readability. | Add spaces to increase readability.
"OSF-4419"
| Python | apache-2.0 | asanfilippo7/osf.io,saradbowman/osf.io,acshi/osf.io,amyshi188/osf.io,HalcyonChimera/osf.io,brandonPurvis/osf.io,mattclark/osf.io,Nesiehr/osf.io,cwisecarver/osf.io,Johnetordoff/osf.io,abought/osf.io,monikagrabowska/osf.io,pattisdr/osf.io,pattisdr/osf.io,njantrania/osf.io,samchrisinger/osf.io,jnayak1/osf.io,cwisecarver/o... |
511aab30006a5fb4c7ff52bc2cd1a1e42551fad1 | bmi_ilamb/config.py | bmi_ilamb/config.py | """Reads and parses a configuration file for the ILAMB BMI."""
from os.path import join
import yaml
ilamb_root_key = 'ilamb_root'
model_root_key = 'model_root'
models_key = 'models'
class Configuration(object):
def __init__(self):
self._config = {}
def load(self, filename):
with open(file... | """Reads and parses a configuration file for the ILAMB BMI."""
from os.path import join
import yaml
ilamb_root_key = 'ilamb_root'
model_root_key = 'model_root'
models_key = 'models'
confrontations_key = 'confrontations'
class Configuration(object):
def __init__(self):
self._config = {}
def load(s... | Allow confrontations to be passed to ilamb-run | Allow confrontations to be passed to ilamb-run
| Python | mit | permamodel/bmi-ilamb |
f40dd24af6788e7de7d06254850b83edb179b423 | bootcamp/lesson4.py | bootcamp/lesson4.py | import datetime
import math
from core import test_helper
# Question 1
# ----------
# Using the datetime module return a datetime object with the year of 2015, the month of June, and the day of 1
def playing_with_dt():
return datetime.datetime(2015, 06, 01)
# Question 2
# ----------
# Using the math module retu... | import datetime
import math
from core import test_helper
# Question 1
# ----------
# Using the datetime module return a datetime object with the year of 2015, the month of June, and the day of 1
def playing_with_dt():
# Write code here
pass
# Question 2
# ----------
# Using the math module return pi
def pl... | Revert "Added solutions for lesson 4" | Revert "Added solutions for lesson 4"
This reverts commit 58d049c78b16ec5b61f9681b605dc4e937ea7e3e.
| Python | mit | infoscout/python-bootcamp-pv |
805f77ac20952c6015a26403041b9b7b3a543ab4 | danceschool/core/migrations/0041_invoiceitem_calculate_taxrate.py | danceschool/core/migrations/0041_invoiceitem_calculate_taxrate.py | # Generated by Django 3.1.6 on 2021-02-20 15:24
from django.db import migrations
from django.db.models import F
def calculate_taxrate(apps, schema_editor):
'''
Calculate the tax rate based on current totals for any InvoiceItem that
does not currently have a tax rate, so that we can make taxRate non-nulla... | # Generated by Django 3.1.6 on 2021-02-20 15:24
from django.db import migrations
from django.db.models import F
def calculate_taxrate(apps, schema_editor):
'''
Calculate the tax rate based on current totals for any InvoiceItem that
does not currently have a tax rate, so that we can make taxRate non-nulla... | Fix division by zero error when calculating tax rate on migration. | Fix division by zero error when calculating tax rate on migration.
| Python | bsd-3-clause | django-danceschool/django-danceschool,django-danceschool/django-danceschool,django-danceschool/django-danceschool |
e1d61d945300dde9cb5ac07228b7892b224a984c | tests/commands/load/test_load_cnv_report_cmd.py | tests/commands/load/test_load_cnv_report_cmd.py | # -*- coding: utf-8 -*-
import os
from scout.demo import cnv_report_path
from scout.commands import cli
def test_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
# Make sure the path to delivery report is a valid path
assert os.path.isfile(cnv_report_path)
run... | # -*- coding: utf-8 -*-
import os
from scout.demo import cnv_report_path
from scout.commands import cli
def test_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
# Make sure the path to delivery report is a valid path
assert os.path.isfile(cnv_report_path)
run... | Fix code style issues with Black | Fix code style issues with Black
| Python | bsd-3-clause | Clinical-Genomics/scout,Clinical-Genomics/scout,Clinical-Genomics/scout |
e9df4858631d9efdcb6a5b960c25f64cae875661 | blog/models.py | blog/models.py | from django.db import models
from organizer.models import Startup, Tag
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Post(models.Model):
title = models.CharField(max_length=63)
slug = models.SlugField()
text = models.TextField()
pub_date = models.DateField... | from django.db import models
from organizer.models import Startup, Tag
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Post(models.Model):
title = models.CharField(max_length=63)
slug = models.SlugField(
max_length=63,
help_text='A label for URL conf... | Add options to Post model fields. | Ch03: Add options to Post model fields. [skip ci]
| Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 |
d45391429f01d5d4ea22e28bef39a2bb419df04f | djangae/apps.py | djangae/apps.py | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ImproperlyConfigured
class DjangaeConfig(AppConfig):
name = 'djangae'
verbose_name = _("Djangae")
def ready(self):
from djangae.db.backends.appengine.caching import reset_c... | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ImproperlyConfigured
class DjangaeConfig(AppConfig):
name = 'djangae'
verbose_name = _("Djangae")
def ready(self):
from djangae.db.backends.appengine.caching import reset_c... | Raise configuration error if django.contrib.contenttypes comes after djangae.contrib.contenttypes | Raise configuration error if django.contrib.contenttypes comes after djangae.contrib.contenttypes
| Python | bsd-3-clause | potatolondon/djangae,grzes/djangae,kirberich/djangae,kirberich/djangae,kirberich/djangae,grzes/djangae,potatolondon/djangae,grzes/djangae |
f213984ad3dfd8922578346baeeb97d60fab742a | cinje/inline/use.py | cinje/inline/use.py | # encoding: utf-8
from ..util import pypy, ensure_buffer
PREFIX = '_buffer.extend(' if pypy else '__w('
class Use(object):
"""Consume the result of calling another template function, extending the local buffer.
This is meant to consume non-wrapping template functions. For wrapping functions see ": using" inst... | # encoding: utf-8
from ..util import py, pypy, ensure_buffer
PREFIX = '_buffer.extend(' if pypy else '__w('
class Use(object):
"""Consume the result of calling another template function, extending the local buffer.
This is meant to consume non-wrapping template functions. For wrapping functions see ": using" ... | Handle buffering and Python 3 "yield from" optimization. | Handle buffering and Python 3 "yield from" optimization.
| Python | mit | marrow/cinje |
45086d11fcdc071427e8c5a2ac909dceac2b43ec | tests/test_auditory.py | tests/test_auditory.py | from __future__ import division, print_function
import pytest
import numpy as np
from pambox import auditory as aud
import scipy.io as sio
from numpy.testing import assert_allclose
def test_lowpass_filtering_of_envelope():
mat = sio.loadmat("./test_files/test_hilbert_env_and_lp_filtering_v1.mat",
... | from __future__ import division, print_function
import pytest
import numpy as np
from pambox import auditory as aud
import scipy.io as sio
from numpy.testing import assert_allclose
def test_lowpass_filtering_of_envelope():
mat = sio.loadmat("./test_files/test_hilbert_env_and_lp_filtering_v1.mat",
... | Add test, which fails, of the gammatone filtering. | Add test, which fails, of the gammatone filtering.
| Python | bsd-3-clause | achabotl/pambox |
08e2099f173bce115ba93c2b960bb1f09ef11269 | models.py | models.py | from django.db import models
from django.core.exceptions import ValidationError
class OrderedModel(models.Model):
order = models.PositiveIntegerField(blank=True, unique=True)
class Meta:
abstract = True
ordering = ['order']
def save(self, swapping=False, *args, **kwargs):
if not self.id:
try... | from django.db import models
from django.core.exceptions import ValidationError
class OrderedModel(models.Model):
order = models.PositiveIntegerField(blank=True, unique=True)
class Meta:
abstract = True
ordering = ['order']
def save(self, swapping=False, *args, **kwargs):
if not self.id:
try... | Fix critical stupid copypaste error | Fix critical stupid copypaste error
| Python | bsd-3-clause | MagicSolutions/django-orderedmodel,MagicSolutions/django-orderedmodel,kirelagin/django-orderedmodel |
a58a1f511e0dfb54ca5168180e9f191340f7afde | osgtest/tests/test_11_condor_cron.py | osgtest/tests/test_11_condor_cron.py | import os
import osgtest.library.core as core
import unittest
class TestStartCondorCron(unittest.TestCase):
def test_01_start_condor_cron(self):
core.config['condor-cron.lockfile'] = '/var/lock/subsys/condor-cron'
core.state['condor-cron.started-service'] = False
core.state['condor-cron.ru... | import os
from osgtest.library import core, osgunittest
import unittest
class TestStartCondorCron(osgunittest.OSGTestCase):
def test_01_start_condor_cron(self):
core.config['condor-cron.lockfile'] = '/var/lock/subsys/condor-cron'
core.state['condor-cron.started-service'] = False
core.state... | Update 11_condor_cron to use OkSkip functionality | Update 11_condor_cron to use OkSkip functionality
git-svn-id: 884a03e47e2adb735d896e55bb5ad6bc3421ba19@16523 4e558342-562e-0410-864c-e07659590f8c
| Python | apache-2.0 | efajardo/osg-test,efajardo/osg-test |
fb0fa15ce9618aac58f45fee0ecda852f3b00ed6 | testdoc/tests/test_finder.py | testdoc/tests/test_finder.py | import unittest
from testdoc.finder import find_tests
class MockFinder(object):
def __init__(self):
self.log = []
def got_module(self, module):
self.log.append(('module', module))
def got_test_class(self, klass):
self.log.append(('class', klass))
def got_test(self, method):... | import unittest
from testdoc.finder import find_tests
class MockCollector(object):
def __init__(self):
self.log = []
def got_module(self, module):
self.log.append(('module', module))
def got_test_class(self, klass):
self.log.append(('class', klass))
def got_test(self, metho... | Document finder tests better and use better terminology (the thing that collects found objects isn't a finder, it's a collector) | Document finder tests better and use better terminology (the thing that
collects found objects isn't a finder, it's a collector)
| Python | mit | testing-cabal/testdoc |
1e6aeb9c7b07313a9efe7cb0e1380f4f2219c7dc | tests/utils.py | tests/utils.py | import os
from carrot.connection import BrokerConnection
AMQP_HOST = os.environ.get('AMQP_HOST', "localhost")
AMQP_PORT = os.environ.get('AMQP_PORT', 5672)
AMQP_VHOST = os.environ.get('AMQP_VHOST', "/")
AMQP_USER = os.environ.get('AMQP_USER', "guest")
AMQP_PASSWORD = os.environ.get('AMQP_PASSWORD', "guest")
STOMP_H... | import os
from carrot.connection import BrokerConnection
AMQP_HOST = os.environ.get('AMQP_HOST', "localhost")
AMQP_PORT = os.environ.get('AMQP_PORT', 5672)
AMQP_VHOST = os.environ.get('AMQP_VHOST', "/")
AMQP_USER = os.environ.get('AMQP_USER', "guest")
AMQP_PASSWORD = os.environ.get('AMQP_PASSWORD', "guest")
STOMP_H... | Add test configuration vars: STOMP_HOST + STOMP_PORT | Add test configuration vars: STOMP_HOST + STOMP_PORT
| Python | bsd-3-clause | ask/carrot,ask/carrot |
1159939ebd193eef809d5d0f27fcb9ef60b7e283 | src/auspex/instruments/utils.py | src/auspex/instruments/utils.py | from . import bbn
import auspex.config
from auspex.log import logger
from QGL import *
ChannelLibrary()
def pulse_marker(marker_name, length = 100e-9):
""" Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line
marker_name as defined i... | from . import bbn
import auspex.config
from auspex.log import logger
def pulse_marker(marker_name, length = 100e-9):
""" Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line
marker_name as defined in measure.yaml """
from QGL im... | Move QGL import inside function | Move QGL import inside function
A channel library is not always available
| Python | apache-2.0 | BBN-Q/Auspex,BBN-Q/Auspex,BBN-Q/Auspex,BBN-Q/Auspex |
8dcab3b18b603e520f12c3fd5a873a08f32d4a9a | nnsave_app/urls.py | nnsave_app/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^location$',views.location, name='location'),
]
| from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^locations/?(?P<id>[0-9]+)?$',views.location, name='location'),
]
| Add id parameter to URL | Add id parameter to URL
| Python | mit | legonigel/nnsave_backend,legonigel/nnsave_backend,legonigel/nnsave_backend,legonigel/nnsave_backend |
17b9749f2a36499c74effc27ec442a4bb957e877 | typescript/commands/build.py | typescript/commands/build.py | import sublime_plugin
from ..libs.global_vars import *
from ..libs import cli
class TypescriptBuildCommand(sublime_plugin.WindowCommand):
def run(self):
if get_node_path() is None:
print("Cannot found node. Build cancelled.")
return
file_name = self.window.active_view().f... | import sublime_plugin
from ..libs.global_vars import *
from ..libs import cli
class TypescriptBuildCommand(sublime_plugin.WindowCommand):
def run(self):
if get_node_path() is None:
print("Cannot found node. Build cancelled.")
return
file_name = self.window.active_view().f... | Remove shell requirement to avoid escaping | Remove shell requirement to avoid escaping
| Python | apache-2.0 | fongandrew/TypeScript-Sublime-JSX-Plugin,Microsoft/TypeScript-Sublime-Plugin,fongandrew/TypeScript-Sublime-JSX-Plugin,zhengbli/TypeScript-Sublime-Plugin,kungfusheep/TypeScript-Sublime-Plugin,RyanCavanaugh/TypeScript-Sublime-Plugin,zhengbli/TypeScript-Sublime-Plugin,kungfusheep/TypeScript-Sublime-Plugin,RyanCavanaugh/Ty... |
a14fcec19471bffcb1dcbad1d0cff7100d0ef6bc | web/blueprints/host/forms.py | web/blueprints/host/forms.py | from wtforms.validators import DataRequired, Optional
from web.blueprints.facilities.forms import SelectRoomForm
from web.form.fields.core import TextField, QuerySelectField, \
SelectMultipleField
from web.form.fields.custom import UserIDField, MacField
from flask_wtf import FlaskForm as Form
from web.form.fields... | from wtforms.validators import DataRequired, Optional
from web.blueprints.facilities.forms import SelectRoomForm
from web.form.fields.core import TextField, QuerySelectField, \
SelectMultipleField
from web.form.fields.custom import UserIDField, MacField
from flask_wtf import FlaskForm as Form
from web.form.fields... | Make interface name optional and remove unicode prefixes | Make interface name optional and remove unicode prefixes
| Python | apache-2.0 | agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft |
1e3f60518402835336c16017b5ba172dc0ef6087 | opps/core/admin.py | opps/core/admin.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.utils import timezone
from django.conf import settings
from django.contrib.sites.models import Site
from django.contrib.auth import get_user_model
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.M... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.utils import timezone
from django.conf import settings
from django.contrib.sites.models import Site
from django.contrib.auth import get_user_model
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.M... | Remove prin on save_model PublishableAdmin | Remove prin on save_model PublishableAdmin
| Python | mit | jeanmask/opps,YACOWS/opps,opps/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,williamroot/opps,opps/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,opps/opps,jeanmask/opps,YACOWS/opps,opps/opps,williamroot/opps |
da01999b6adcb79955a416ce3b3de50769adfe34 | opps/core/utils.py | opps/core/utils.py | # coding: utf-8
from django.db.models import get_models, get_app
def get_app_model(appname, suffix=""):
app_label = appname.split('.')[-1]
models = [model for model in get_models(get_app(app_label))
if (model.__name__.endswith(suffix) or not suffix)
and model._meta.app_label == ap... | # coding: utf-8
from django.db.models import get_models, get_app
from django.template import loader, TemplateDoesNotExist
def get_app_model(appname, suffix=""):
app_label = appname.split('.')[-1]
models = [model for model in get_models(get_app(app_label))
if (model.__name__.endswith(suffix) or ... | Add new module, get template path return absolut file path | Add new module, get template path
return absolut file path
| Python | mit | opps/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,YACOWS/opps,opps/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,williamroot/opps,opps/opps,jeanmask/opps,williamroot/opps,opps/opps,jeanmask/opps,williamroot/opps |
379be172944f8ae0111842e199470effd4afdaf5 | rest/authUtils.py | rest/authUtils.py | # Author: Braedy Kuzma
from rest_framework import authentication
from rest_framework import exceptions
from ipware.ip import get_ip
from .models import RemoteNode
class nodeToNodeBasicAuth(authentication.BaseAuthentication):
def authenticate(self, request):
"""
This is an authentication backend fo... | # Author: Braedy Kuzma
import base64
from rest_framework import authentication
from rest_framework import exceptions
from ipware.ip import get_ip
from .models import RemoteNode
def createBasicAuthToken(username, password):
"""
This creates an HTTP Basic Auth token from a username and password.
"""
# ... | Add basic auth create and parse utils. | Add basic auth create and parse utils.
| Python | apache-2.0 | CMPUT404W17T06/CMPUT404-project,CMPUT404W17T06/CMPUT404-project,CMPUT404W17T06/CMPUT404-project |
a312348380a495c99c1be8adca331e2eec2d1720 | topo/tests/__init__.py | topo/tests/__init__.py | """
Unit tests for Topographica
$Id$
"""
__version__='$Revision$'
### JABALERT!
###
### Should change this to be like topo/patterns/__init__.py, i.e.
### to automatically discover the test files. That way new tests
### can be just dropped in.
import unittest, os
import testboundingregion
import testdummy
import tes... | """
Unit tests for Topographica
$Id$
"""
__version__='$Revision$'
### JABALERT!
###
### Should change this to be like topo/patterns/__init__.py, i.e.
### to automatically discover the test files. That way new tests
### can be just dropped in.
import unittest, os
import testboundingregion
import testdummy
import tes... | Test of optimized output functions runs automatically. | Test of optimized output functions runs automatically.
| Python | bsd-3-clause | ioam/svn-history,ioam/svn-history,ioam/svn-history,ioam/svn-history,ioam/svn-history |
80448aa6664d13dd58ed42c06248ca4532431aab | dakota_utils/convert.py | dakota_utils/convert.py | #! /usr/bin/env python
#
# Dakota utility programs for converting output.
#
# Mark Piper (mark.piper@colorado.edu)
import shutil
from subprocess import check_call, CalledProcessError
from dakota_utils.read import get_names
def has_interface_column(tab_file):
'''
Returns True if the tabular output file has th... | #! /usr/bin/env python
#
# Dakota utility programs for converting output.
#
# Mark Piper (mark.piper@colorado.edu)
import shutil
from subprocess import check_call, CalledProcessError
from .read import get_names
def has_interface_column(tab_file):
'''
Returns True if the tabular output file has the v6.1 'inte... | Use a relative import to get the read module | Use a relative import to get the read module
| Python | mit | mdpiper/dakota-experiments,mdpiper/dakota-experiments,mcflugen/dakota-experiments,mdpiper/dakota-experiments,mcflugen/dakota-experiments |
2a763b32b4794e97d1ea7bf22ec39c1eeb559804 | pycroft/model/alembic/versions/fb8d553a7268_add_account_pattern.py | pycroft/model/alembic/versions/fb8d553a7268_add_account_pattern.py | """add account_pattern
Revision ID: fb8d553a7268
Revises: 28e56bf6f62c
Create Date: 2021-04-26 22:16:41.772282
"""
from alembic import op
import sqlalchemy as sa
import pycroft
# revision identifiers, used by Alembic.
revision = 'fb8d553a7268'
down_revision = '28e56bf6f62c'
branch_labels = None
depends_on = None
... | """add account_pattern
Revision ID: fb8d553a7268
Revises: 28e56bf6f62c
Create Date: 2021-04-26 22:16:41.772282
"""
from alembic import op
import sqlalchemy as sa
import pycroft
# revision identifiers, used by Alembic.
revision = 'fb8d553a7268'
down_revision = '0b69e80a9388'
branch_labels = None
depends_on = None
... | Rebase most recent alembic change onto HEAD | Rebase most recent alembic change onto HEAD
| Python | apache-2.0 | agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft |
dbb9792871d9b1d8f1678dbafeed760098547a28 | pdf_parser/pdf_types/compound_types.py | pdf_parser/pdf_types/compound_types.py | from .common import PdfType
class PdfArray(PdfType, list):
def __init__(self, *args, **kwargs):
PdfType.__init__(self)
list.__init__(self, *args, **kwargs)
class PdfDict(PdfType, dict):
def __init__(self, *args, **kwargs):
PdfType.__init__(self)
dict.__init__(self, *args, **kwa... | from .common import PdfType
class PdfArray(PdfType, list):
def __init__(self, *args, **kwargs):
PdfType.__init__(self)
list.__init__(self, *args, **kwargs)
class PdfDict(PdfType, dict):
def __init__(self, *args, **kwargs):
PdfType.__init__(self)
dict.__init__(self, *args, **kwa... | Add read-only attribute style access to PdfDict elements with object parsing. | Add read-only attribute style access to PdfDict elements with object parsing.
| Python | mit | ajmarks/gymnast,ajmarks/gymnast |
8de9c51eedaadc68cc64ca7f5763b48a6448dca3 | main.py | main.py | from dogbot.bot import bot
from dogbot.web import app
from mongoengine import connect
from config import config
import getopt
import sys
import threading
from importlib import reload
reload(threading)
def bot_main():
print("QQBot is running...")
try:
bot.start()
except KeyboardInterrupt:
p... | from dogbot.bot import bot
from dogbot.web import app
from mongoengine import connect
from config import config
import getopt
import sys
import threading
from importlib import reload
reload(threading)
def bot_main():
print("QQBot is running...")
try:
bot.start()
except KeyboardInterrupt:
p... | Edit host from 127.0.0.1 -> 0.0.0.0 | Edit host from 127.0.0.1 -> 0.0.0.0
| Python | apache-2.0 | moondropx/dogbot,moondropx/dogbot |
d8502569f0e4c562294415242f096eefdf361ca0 | pyonep/__init__.py | pyonep/__init__.py | __version__ = '0.12.4'
| """An API library with Python bindings for Exosite One Platform APIs."""
__version__ = '0.12.4'
from .onep import OnepV1, DeferredRequests
from .provision import Provision
| Add docstring and imports to package. | Add docstring and imports to package.
| Python | bsd-3-clause | gavinsunde/pyonep,exosite-labs/pyonep,asolz/pyonep,asolz/pyonep,gavinsunde/pyonep,exosite-labs/pyonep |
0be63749c039e16aa1fcc64cfd8227b50829254e | pyvisa/__init__.py | pyvisa/__init__.py | # -*- coding: utf-8 -*-
"""
pyvisa
~~~~~~
Python wrapper of National Instrument (NI) Virtual Instruments Software
Architecture library (VISA).
This file is part of PyVISA.
:copyright: (c) 2014 by the PyVISA authors.
:license: MIT, see COPYING for more details.
"""
from __future__ import ... | # -*- coding: utf-8 -*-
"""
pyvisa
~~~~~~
Python wrapper of National Instrument (NI) Virtual Instruments Software
Architecture library (VISA).
This file is part of PyVISA.
:copyright: (c) 2014 by the PyVISA authors.
:license: MIT, see COPYING for more details.
"""
from __future__ import ... | Load legacy visa_library taking user settings into account | Load legacy visa_library taking user settings into account
See #7
| Python | mit | pyvisa/pyvisa,rubund/debian-pyvisa,MatthieuDartiailh/pyvisa,hgrecco/pyvisa |
fb8cfa8eb7d088ebe11075bff42bea54c97e9c18 | hermes/views.py | hermes/views.py | from django.views.generic import ListView, DetailView
from .models import Post
class PostListView(ListView):
context_object_name = 'posts'
model = Post
template_name = 'hermes/post_list.html'
def get_queryset(self):
return self.model.objects.order_by('created_on')
class CategoryPostLis... | from django.views.generic import ListView, DetailView
from .models import Post
class PostListView(ListView):
context_object_name = 'posts'
model = Post
template_name = 'hermes/post_list.html'
def get_queryset(self):
return self.model.objects.order_by('created_on')
class CategoryPostLis... | Add slug variable to pass in the URL | Add slug variable to pass in the URL | Python | mit | emilian/django-hermes |
51c9413eb1375ff191e03d38933a772923fa55cf | app/__init__.py | app/__init__.py | from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
bootstrap = Bootstrap()
def create_app(config_name):
application = Flask(__name__)
application.config['DEBUG'] = True
application.config.from_object(config[config_name])
config[config_name].init_app(applicat... | from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
from .main import main as main_blueprint
def create_app(config_name):
application = Flask(__name__,
static_folder='static/',
static_url_path=config[config_name].STATIC_URL_... | Add /supplier prefix to main blueprint and static URLs | Add /supplier prefix to main blueprint and static URLs
| Python | mit | alphagov/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,alphag... |
6e9159b66cd791561a24bd935aaaab2a4ea6a6af | sgapi/__init__.py | sgapi/__init__.py | from .core import Shotgun, ShotgunError
# For API compatibility
Fault = ShotgunError
| from .core import Shotgun, ShotgunError, TransportError
# For API compatibility
Fault = ShotgunError
| Add TransportError to top-level package | Add TransportError to top-level package
| Python | bsd-3-clause | westernx/sgapi |
a90411116617096c73ba6d188322613a1b529a62 | books/CrackingCodesWithPython/Chapter20/vigenereDictionaryHacker.py | books/CrackingCodesWithPython/Chapter20/vigenereDictionaryHacker.py | # Vigenère Cipher Dictionary Hacker
# https://www.nostarch.com/crackingcodes/ (BSD Licensed)
import detectEnglish, vigenereCipher, pyperclip
def main():
ciphertext = """Tzx isnz eccjxkg nfq lol mys bbqq I lxcz."""
hackedMessage = hackVigenereDictionary(ciphertext)
if hackedMessage != None:
print... | # Vigenère Cipher Dictionary Hacker
# https://www.nostarch.com/crackingcodes/ (BSD Licensed)
import detectEnglish, vigenereCipher, pyperclip
def main():
ciphertext = """Tzx isnz eccjxkg nfq lol mys bbqq I lxcz."""
hackedMessage = hackVigenereDictionary(ciphertext)
if not hackedMessage:
print('Co... | Update vigenereDicitonaryHacker: simplified comparison with None | Update vigenereDicitonaryHacker: simplified comparison with None
| Python | mit | JoseALermaIII/python-tutorials,JoseALermaIII/python-tutorials |
c69974ffabc0855db153b7f5a4af6105fae698f9 | docassemble_base/docassemble/base/pdfa.py | docassemble_base/docassemble/base/pdfa.py | import tempfile
import subprocess
import shutil
from docassemble.base.error import DAError
#from docassemble.base.logger import logmessage
def pdf_to_pdfa(filename):
outfile = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
directory = tempfile.mkdtemp()
commands = ['gs', '-dPDFA', '-dBATCH', '-dN... | import tempfile
import subprocess
import shutil
from docassemble.base.error import DAError
#from docassemble.base.logger import logmessage
def pdf_to_pdfa(filename):
outfile = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
directory = tempfile.mkdtemp()
commands = ['gs', '-dPDFA', '-dBATCH', '-dN... | Make ghostscript handle PDF/A colorspace correctly | Make ghostscript handle PDF/A colorspace correctly
Previously, if you tried to verify files generated by pdf_to_pdfa in a
verifier (like https://tools.pdfforge.org/validate-pdfa), you would get
errors relating to the lack of OutputIntent (6.2.3). The info in
https://stackoverflow.com/a/56459053/11416267 and
https://ww... | Python | mit | jhpyle/docassemble,jhpyle/docassemble,jhpyle/docassemble,jhpyle/docassemble,jhpyle/docassemble |
884e7254bffcef4e5d3733b26f6eb0ea34b11da6 | core/project/Project.py | core/project/Project.py | """
Project
:Authors:
Berend Klein Haneveld
"""
class Project(object):
"""
Project holds the basic information of a project for RegistrationShop
"""
def __init__(self, title=None, fixedData=None, movingData=None, isReference=None):
super(Project, self).__init__()
self.title = title
self.fixedData = fixe... | """
Project
:Authors:
Berend Klein Haneveld
"""
class Project(object):
"""
Project holds the basic information of a project for RegistrationShop
"""
def __init__(self, title=None, fixedData=None, movingData=None, isReference=None):
super(Project, self).__init__()
self.title = title
self.fixedData = fixe... | Add transformations property to projects. | Add transformations property to projects.
| Python | mit | berendkleinhaneveld/Registrationshop,berendkleinhaneveld/Registrationshop |
e68e03fe5e858e9c5c65788d2d1126b8bf37772b | subversion/bindings/swig/python/tests/run_all.py | subversion/bindings/swig/python/tests/run_all.py | import sys, os
bindir = os.path.dirname(sys.argv[0])
sys.path[0:0] = [ os.getcwd(), "%s/.libs" % os.getcwd(), \
"%s/.." % bindir, "%s/../.libs" % bindir ]
import unittest
import pool
import trac.versioncontrol.tests
# Run all tests
def suite():
"""Run all tests"""
suite = unittest.TestSuite()
... | import sys, os
bindir = os.path.dirname(sys.argv[0])
sys.path[0:0] = [ os.getcwd(), "%s/.libs" % os.getcwd(), \
"%s/.." % bindir, "%s/../.libs" % bindir ]
# OSes without RPATH support are going to have to do things here to make
# the correct shared libraries be found.
if sys.platform == 'cygwin':
i... | Make the Python bindings testsuite be able to find the needed shared libraries on Cygwin. Needed to compensate for Windows' complete lack of library RPATHs. | Make the Python bindings testsuite be able to find the needed shared libraries
on Cygwin. Needed to compensate for Windows' complete lack of library RPATHs.
* subversion/bindings/swig/python/tests/run_all.py: On Cygwin, manipulate $PATH
so that the relevant shared libraries are found.
git-svn-id: f8a4e5e023278da... | Python | apache-2.0 | wbond/subversion,YueLinHo/Subversion,YueLinHo/Subversion,YueLinHo/Subversion,wbond/subversion,wbond/subversion,YueLinHo/Subversion,wbond/subversion,wbond/subversion,YueLinHo/Subversion,YueLinHo/Subversion,wbond/subversion,wbond/subversion,YueLinHo/Subversion,YueLinHo/Subversion |
3b5f1749a8065bb9241d6a8ed77c047a05b3f6e2 | bcbio/distributed/sge.py | bcbio/distributed/sge.py | """Commandline interaction with SGE cluster schedulers.
"""
import re
import subprocess
_jobid_pat = re.compile('Your job (?P<jobid>\d+) \("')
def submit_job(scheduler_args, command):
"""Submit a job to the scheduler, returning the supplied job ID.
"""
cl = ["qsub", "-cwd", "-b", "y", "-j", "y"] + schedul... | """Commandline interaction with SGE cluster schedulers.
"""
import re
import time
import subprocess
_jobid_pat = re.compile('Your job (?P<jobid>\d+) \("')
def submit_job(scheduler_args, command):
"""Submit a job to the scheduler, returning the supplied job ID.
"""
cl = ["qsub", "-cwd", "-b", "y", "-j", "y... | Handle temporary errors returned from SGE qstat | Handle temporary errors returned from SGE qstat
| Python | mit | biocyberman/bcbio-nextgen,Cyberbio-Lab/bcbio-nextgen,mjafin/bcbio-nextgen,chapmanb/bcbio-nextgen,lpantano/bcbio-nextgen,fw1121/bcbio-nextgen,brainstorm/bcbio-nextgen,fw1121/bcbio-nextgen,elkingtonmcb/bcbio-nextgen,verdurin/bcbio-nextgen,mjafin/bcbio-nextgen,vladsaveliev/bcbio-nextgen,SciLifeLab/bcbio-nextgen,SciLifeLab... |
6b07646f085de7f5eae2c0695584bce48f812b44 | save_na_results.py | save_na_results.py | #!/usr/bin/python
import os
import sys
def save_na_results(folder_path=None):
"""Move the results of a Neighborhood Algorithm run to a folder with metadata.
This will copy all files with extensions of:
npy, txt, eps, png and dat
to the specified folder_path.
For now there is nothing stor... | #!/usr/bin/python
import os
import sys
def save_na_results(folder_path=None):
"""Move the results of a Neighborhood Algorithm run to a folder with metadata.
This will copy all files with extensions of:
npy, txt, eps, png and dat
to the specified folder_path.
For now there is nothing stor... | Save svg files, eps are not used anymore because they don't hand transparency. | Save svg files, eps are not used anymore because they don't hand transparency.
| Python | bsd-2-clause | cosmolab/cosmogenic |
a391b9d990c01cdf036bc92dd6bafc03bdd69b63 | instructions.py | instructions.py | class Instruction:
def __init__(self,prev):
self.prev = prev
if prev:
self.prev.next = self
self.partner = None
self.next = None
def execute(self, node):
return (self.next, node)
class LBracket(Instruction):
symbol = "["
def execute(self, node):
return (self.next, node)
class RBr... | import sys
class Instruction:
def __init__(self,prev):
self.prev = prev
if prev:
self.prev.next = self
self.partner = None
self.next = None
def execute(self, node):
return (self.next, node)
class LBracket(Instruction):
symbol = "["
def execute(self, node):
return (self.next, node... | Write directly to standard out instead of 'print' | Write directly to standard out instead of 'print'
| Python | mit | Detry322/brainfuck-interpreter |
5d63de144891c0672e67741ada93351f6aa8b20e | controllers/main.py | controllers/main.py | # -*- coding: utf-8 -*-
import openerp
from ..helpers.usbscale.scale import Scale
from ..helpers.usbscale.scale_manager import ScaleManager
from ..helpers.usbscale.tests import mocks
class ScaleController(openerp.addons.web.http.Controller):
_cp_path = '/scale_proxy'
def __init__(self, *args, **kwargs):
... | # -*- coding: utf-8 -*-
import openerp
from ..helpers.usbscale.scale import Scale
from ..helpers.usbscale.scale_manager import ScaleManager
from ..helpers.usbscale.tests import mocks
class ScaleController(openerp.addons.web.http.Controller):
_cp_path = '/scale_proxy'
def __init__(self, *args, **kwargs):
... | Allow calls to 'weigh' to run forever when 'max_attempts' is set to 'inf'. | Allow calls to 'weigh' to run forever when 'max_attempts' is set to 'inf'.
| Python | agpl-3.0 | ryepdx/scale_proxy,ryepdx/scale_proxy |
78eaa907ea986c12716b27fc6a4533d83242b97a | bci/__init__.py | bci/__init__.py | from fakebci import FakeBCI | import os
import sys
import platform
import shutil
import inspect
#
#def machine():
# """Return type of machine."""
# if os.name == 'nt' and sys.version_info[:2] < (2,7):
# return os.environ.get("PROCESSOR_ARCHITEW6432",
# os.environ.get('PROCESSOR_ARCHITECTURE', ''))
# else:
# re... | Make some changes to the bci package file. | Make some changes to the bci package file.
| Python | bsd-3-clause | NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock |
0e7939b0027cbc203505c636bc732d860b81e78d | sort/merge_sort/python/merge_sort.py | sort/merge_sort/python/merge_sort.py | def merge(left, right):
"""Merge sort merging function."""
left_index, right_index = 0, 0
result = []
while left_index < len(left) and right_index < len(right):
if left[left_index] < right[right_index]:
result.append(left[left_index])
left_index += 1
els... | def merge(left, right):
"""Merge sort merging function."""
left_index, right_index = 0, 0
result = []
while left_index < len(left) and right_index < len(right):
if left[left_index] < right[right_index]:
result.append(left[left_index])
left_index += 1
els... | Add test for merge sort | Add test for merge sort
| Python | cc0-1.0 | manikTharaka/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,EUNIX-TRIX/al-go-rithms,ZoranPandovski/al-go-rithms,arijitkar98/al-go-rithms,Cnidarias/al-go-rithms,EUNIX-TRIX/al-go-rithms,arijitkar98/al-go-rithms,manikTharaka/al-go-rithms,manikTharaka/al-go-rithms,Cnidarias/al-go-rithms,ZoranPandovski... |
33aa691298ed5c306c3b32965b38c287e65e174a | tests/functional/driver/test_driver_del.py | tests/functional/driver/test_driver_del.py | import pytest
from tests.utils.targetdriver import TargetDriver, if_feature
from tests.utils.testdriver import TestDriver
def get_services():
return TargetDriver('rep1'), TestDriver('rep2')
@pytest.fixture(autouse=True)
def _(module_launcher_launch):
pass
@if_feature.del_file_from_onitu
def test_driver_d... | import pytest
from tests.utils.targetdriver import TargetDriver, if_feature
from tests.utils.testdriver import TestDriver
from tests.utils.loop import CounterLoop
def get_services():
return TargetDriver('rep1'), TestDriver('rep2')
@pytest.fixture(autouse=True)
def _(module_launcher_launch):
pass
@if_feat... | Add test for detection of deleted files on launch | Add test for detection of deleted files on launch
| Python | mit | onitu/onitu,onitu/onitu,onitu/onitu |
b1f173fdbfb60e26a3923c7b024bc3e65e5abf80 | selvbetjening/scheckin/now/urls.py | selvbetjening/scheckin/now/urls.py | from django.conf.urls import *
import views
urlpatterns = patterns('',
url(r'^(?P<event_id>[0-9]+)/$', views.checkin),
)
| from django.conf.urls import *
from django.conf import settings
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from selvbetjening.sadmin.base.nav import RemoteSPage
import views
urlpatterns = patterns('',
url(r'^(?P<event_id>[0-9]+)/$', views.checkin, name='now_ch... | Add links to easy check-in in sadmin | Add links to easy check-in in sadmin
| Python | mit | animekita/selvbetjening,animekita/selvbetjening,animekita/selvbetjening,animekita/selvbetjening |
8ae5079a2963a356a6073a245305fff98fcc7461 | dbaas/logical/tasks.py | dbaas/logical/tasks.py | from logical.models import Database
from dbaas.celery import app
from util.decorators import only_one
@app.task
@only_one(key="purgequarantinekey", timeout=20)
def purge_quarantine():
Database.purge_quarantine()
return
| from logical.models import Database
from system.models import Configuration
from datetime import date, timedelta
from dbaas.celery import app
from util.decorators import only_one
from util.providers import destroy_infra
from simple_audit.models import AuditRequest
from notification.models import TaskHistory
from accoun... | Change purge quarantine to deal with cloudstack databases | Change purge quarantine to deal with cloudstack databases
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service |
10f7b7db3b7912c74ca0320ac70da425bd2718ed | scripts/fabfile.py | scripts/fabfile.py | from fabric import task
CODE_DIR = '~/django-projects/test-osale/foodbank-campaign/src'
# for FreeBSD compatibility
SHELL = '/bin/sh -c'
@task
def deploy(c):
c.shell = SHELL
with c.cd(CODE_DIR):
pull_changes(c)
with c.prefix('. ../venv/bin/activate'):
update_dependencies(c)
... | from fabric import task
CODE_DIR = '~/django-projects/test-osale/foodbank-campaign/src'
# for FreeBSD compatibility
SHELL = '/bin/sh -c'
@task
def deploy(c):
c.shell = SHELL
with c.cd(CODE_DIR):
pull_changes(c)
with c.prefix('. ../venv/bin/activate'):
update_dependencies(c)
... | Add --upgrade to pip install in Fabfile | Add --upgrade to pip install in Fabfile
| Python | mit | mrts/foodbank-campaign,mrts/foodbank-campaign,mrts/foodbank-campaign,mrts/foodbank-campaign |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.