commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
05f87be4c85036c69abc9404acb824c58d71f101 | slice_ops.py | slice_ops.py | import slicer
import shapely.ops
import shapely.geometry
def border(sli, amount):
cuts = [cut.polygon(True) for cut in sli.cuts]
cut_outline = shapely.ops.cascaded_union(cuts) \
.buffer(amount / 2)
shape_outline = sli.poly.boundary.buffer(amount)
outlines = cut_outline.unio... | Add border operation... Damn that was easy | Add border operation... Damn that was easy
| Python | mit | meshulam/sly | ---
+++
@@ -0,0 +1,13 @@
+import slicer
+import shapely.ops
+import shapely.geometry
+
+def border(sli, amount):
+ cuts = [cut.polygon(True) for cut in sli.cuts]
+ cut_outline = shapely.ops.cascaded_union(cuts) \
+ .buffer(amount / 2)
+ shape_outline = sli.poly.boundary.buffer(amo... | |
4dfc0c49cec86f3c03b90fa66e1fc9de2ac665e6 | samples/migrations/0012_auto_20170512_1138.py | samples/migrations/0012_auto_20170512_1138.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-12 14:38
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('samples', '0011_fluvaccine_date_applied'),
]
operations = [
migrations.AlterF... | Add migration file (fix fields) | :rocket: Add migration file (fix fields)
| Python | mit | gems-uff/labsys,gems-uff/labsys,gems-uff/labsys | ---
+++
@@ -0,0 +1,25 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11 on 2017-05-12 14:38
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('samples', '0011_fluvaccine_date_applied'),
+ ]
+
+ ... | |
bc0aa69adc5b1e290941c221ddd498d3fb92244e | test.py | test.py | import nltk
from nltk.classify import MaxentClassifier
# Set up our training material in a nice dictionary.
training = {
'ingredients': [
'Pastry for 9-inch tart pan',
'Apple cider vinegar',
'3 eggs',
'1/4 cup sugar',
],
'steps': [
'Sift the powdered sugar and cocoa ... | Add simple recipe tagger experiment | Add simple recipe tagger experiment
| Python | isc | recipi/recipi,recipi/recipi,recipi/recipi | ---
+++
@@ -0,0 +1,68 @@
+import nltk
+from nltk.classify import MaxentClassifier
+
+# Set up our training material in a nice dictionary.
+training = {
+ 'ingredients': [
+ 'Pastry for 9-inch tart pan',
+ 'Apple cider vinegar',
+ '3 eggs',
+ '1/4 cup sugar',
+ ],
+ 'steps': [
+ ... | |
7bace5ca301124f03d7ff98669ac08c0c32da55f | labs/lab-5/oop.py | labs/lab-5/oop.py | #!/usr/bin/python
#
# Copyright 2016 BMC Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | Add example OOP python script | Add example OOP python script
| Python | apache-2.0 | boundary/tsi-lab,jdgwartney/tsi-lab,jdgwartney/tsi-lab,boundary/tsi-lab,jdgwartney/tsi-lab,jdgwartney/tsi-lab,boundary/tsi-lab,boundary/tsi-lab | ---
+++
@@ -0,0 +1,46 @@
+#!/usr/bin/python
+#
+# Copyright 2016 BMC Software, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
... | |
a83a48f6c9276b86c3cc13aeb000611036a6e3c4 | jedihttp/handlers.py | jedihttp/handlers.py | import bottle
from bottle import response, request
import json
import jedi
import logging
app = bottle.Bottle( __name__ )
logger = logging.getLogger( __name__ )
@app.get( '/healthy' )
def healthy():
return _Json({})
@app.get( '/ready' )
def ready():
return _Json({})
@app.post( '/completions' )
def completio... | import bottle
from bottle import response, request
import json
import jedi
import logging
app = bottle.Bottle( __name__ )
logger = logging.getLogger( __name__ )
@app.post( '/healthy' )
def healthy():
return _Json({})
@app.post( '/ready' )
def ready():
return _Json({})
@app.post( '/completions' )
def complet... | Make all end-points accepting post | Make all end-points accepting post
| Python | apache-2.0 | micbou/JediHTTP,micbou/JediHTTP,vheon/JediHTTP,vheon/JediHTTP | ---
+++
@@ -9,12 +9,12 @@
logger = logging.getLogger( __name__ )
-@app.get( '/healthy' )
+@app.post( '/healthy' )
def healthy():
return _Json({})
-@app.get( '/ready' )
+@app.post( '/ready' )
def ready():
return _Json({})
|
d35f2d7310c277625ea6e2e15b887ac9620696a7 | tests/unit/glacier/test_vault.py | tests/unit/glacier/test_vault.py | #!/usr/bin/env python
# Copyright (c) 2012 Amazon.com, Inc. or its affiliates. All Rights Reserved
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without ... | Add unit test for glacier vault | Add unit test for glacier vault
Just verifies the args are forwarded to layer1 properly.
| Python | mit | felix-d/boto,lochiiconnectivity/boto,weebygames/boto,abridgett/boto,appneta/boto,alex/boto,j-carl/boto,appneta/boto,rayluo/boto,lochiiconnectivity/boto,weka-io/boto,jameslegg/boto,drbild/boto,alfredodeza/boto,ocadotechnology/boto,janslow/boto,disruptek/boto,campenberger/boto,trademob/boto,elainexmas/boto,israelbenatar/... | ---
+++
@@ -0,0 +1,58 @@
+#!/usr/bin/env python
+# Copyright (c) 2012 Amazon.com, Inc. or its affiliates. All Rights Reserved
+#
+# Permission is hereby granted, free of charge, to any person obtaining a
+# copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without ... | |
b6b65f0ca7253af5325eafc6b19e7cfecda231b3 | hw3/hw3_2b.py | hw3/hw3_2b.py | import sympy
x1, x2 = sympy.symbols('x1 x2')
f = 8*x1 + 12*x2 + x1**2 -2*x2**2
df_dx1 = sympy.diff(f,x1)
df_dx2 = sympy.diff(f,x2)
H = sympy.hessian(f, (x1, x2))
xs = sympy.solve([df_dx1, df_dx2], [x1, x2])
H_xs = H.subs([(x1,xs[x1]), (x2,xs[x2])])
lambda_xs = H_xs.eigenvals()
count = 0
for i in lambda_xs.keys():
... | Add solution for exercise 2b of hw3 | Add solution for exercise 2b of hw3
| Python | bsd-2-clause | escorciav/amcs211,escorciav/amcs211 | ---
+++
@@ -0,0 +1,25 @@
+import sympy
+
+x1, x2 = sympy.symbols('x1 x2')
+f = 8*x1 + 12*x2 + x1**2 -2*x2**2
+
+df_dx1 = sympy.diff(f,x1)
+df_dx2 = sympy.diff(f,x2)
+H = sympy.hessian(f, (x1, x2))
+
+xs = sympy.solve([df_dx1, df_dx2], [x1, x2])
+
+H_xs = H.subs([(x1,xs[x1]), (x2,xs[x2])])
+lambda_xs = H_xs.eigenvals(... | |
71b0af732e6d151a22cc0d0b28b55020780af8b6 | ftools.py | ftools.py | from functools import wraps
def memoize(obj):
# This is taken from the Python Decorator Library on the official Python
# wiki. https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize
# Unfortunately we're using Python 2.x here and lru_cache isn't available
cache = obj.cache = {}
@wraps(obj)... | Add memoize function for python 2.x | Add memoize function for python 2.x
| Python | mit | ironman5366/W.I.L.L,ironman5366/W.I.L.L | ---
+++
@@ -0,0 +1,17 @@
+from functools import wraps
+
+
+def memoize(obj):
+ # This is taken from the Python Decorator Library on the official Python
+ # wiki. https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize
+ # Unfortunately we're using Python 2.x here and lru_cache isn't available
+
+ cac... | |
27788308891d9cd82da7782d62b5920ea7a54f80 | employees/management/commands/dailycheck.py | employees/management/commands/dailycheck.py | from constance import config
from datetime import datetime
from django.core.management.base import BaseCommand
from django.core.mail import EmailMessage
from django.shortcuts import get_list_or_404
from employees.models import Employee
class Command(BaseCommand):
help = "Update scores daily."
def change_day(... | Add custom command to daily check scores | Add custom command to daily check scores
| Python | apache-2.0 | belatrix/BackendAllStars | ---
+++
@@ -0,0 +1,79 @@
+from constance import config
+from datetime import datetime
+from django.core.management.base import BaseCommand
+from django.core.mail import EmailMessage
+from django.shortcuts import get_list_or_404
+from employees.models import Employee
+
+
+class Command(BaseCommand):
+ help = "Updat... | |
8aac73fdc26fd838c3f91ffa9bc58e25777a5179 | properties/tests/test_mach_angle.py | properties/tests/test_mach_angle.py | #!/usr/bin/env python
"""Test Mach angle functions.
Test data is obtained from http://www.grc.nasa.gov/WWW/k-12/airplane/machang.html.
"""
import nose
import nose.tools as nt
from properties.prandtl_meyer_function import mu_in_deg
@nt.raises(ValueError)
def test_mach_lesser_than_one():
m = 0.1
mu_in_deg(... | Add tests for mach angle | Add tests for mach angle
| Python | mit | iwarobots/TunnelDesign | ---
+++
@@ -0,0 +1,30 @@
+#!/usr/bin/env python
+
+"""Test Mach angle functions.
+
+Test data is obtained from http://www.grc.nasa.gov/WWW/k-12/airplane/machang.html.
+"""
+
+
+import nose
+import nose.tools as nt
+
+from properties.prandtl_meyer_function import mu_in_deg
+
+
+@nt.raises(ValueError)
+def test_mach_le... | |
d0c2ee2e0d848a586cc03ba5ac5da697b333ef32 | Misc/listOfRandomNum.py | Misc/listOfRandomNum.py | #List of randoms
import random
import math
numList = []
for i in range(10):
numList.append(random.randrange(1, 20))
for i in numList:
print("Rand num = " + str(i))
| Create list of random num | Create list of random num
| Python | mit | JLJTECH/TutorialTesting | ---
+++
@@ -0,0 +1,12 @@
+#List of randoms
+
+import random
+import math
+
+numList = []
+
+for i in range(10):
+ numList.append(random.randrange(1, 20))
+
+for i in numList:
+ print("Rand num = " + str(i)) | |
cd3f59026b9026d62537b38d4e9d70a740e88018 | tests/test_java_mode.py | tests/test_java_mode.py | import editor_manager
import editor_common
import curses
import curses.ascii
import keytab
from ped_test_util import read_str,validate_screen,editor_test_suite,play_macro,screen_size,match_attr
def test_java_mode(testdir,capsys):
with capsys.disabled():
def main(stdscr):
lines_to_test = [
... | Add tests for java mode | Add tests for java mode
| Python | mit | jpfxgood/ped | ---
+++
@@ -0,0 +1,57 @@
+import editor_manager
+import editor_common
+import curses
+import curses.ascii
+import keytab
+from ped_test_util import read_str,validate_screen,editor_test_suite,play_macro,screen_size,match_attr
+
+def test_java_mode(testdir,capsys):
+ with capsys.disabled():
+ def main(stdscr)... | |
f03f976696077db4146ea78e0d0b1ef5767f00ca | tests/unit/test_sign.py | tests/unit/test_sign.py | # Import libnacl libs
import libnacl.sign
# Import pythonlibs
import unittest
class TestSigning(unittest.TestCase):
'''
'''
def test_sign(self):
msg = ('Well, that\'s no ordinary rabbit. That\'s the most foul, '
'cruel, and bad-tempered rodent you ever set eyes on.')
signe... | Add high level signing capabilities | Add high level signing capabilities
| Python | apache-2.0 | cachedout/libnacl,saltstack/libnacl,johnttan/libnacl,mindw/libnacl,coinkite/libnacl,RaetProtocol/libnacl | ---
+++
@@ -0,0 +1,19 @@
+# Import libnacl libs
+import libnacl.sign
+
+# Import pythonlibs
+import unittest
+
+
+class TestSigning(unittest.TestCase):
+ '''
+ '''
+ def test_sign(self):
+ msg = ('Well, that\'s no ordinary rabbit. That\'s the most foul, '
+ 'cruel, and bad-tempered rode... | |
bb7031385af7931f9e12a8987375f929bcfb6b5a | scripts/devdeps.py | scripts/devdeps.py | from __future__ import print_function
import sys
try:
import colorama
def blue(text): return "%s%s%s" % (colorama.Fore.BLUE, text, colorama.Style.RESET_ALL)
def red(text): return "%s%s%s" % (colorama.Fore.RED, text, colorama.Style.RESET_ALL)
except ImportError:
def blue(text) : return text
def red... | Create script that checks for dev and docs dependencies. | Create script that checks for dev and docs dependencies.
| Python | bsd-3-clause | justacec/bokeh,schoolie/bokeh,aiguofer/bokeh,ChinaQuants/bokeh,lukebarnard1/bokeh,roxyboy/bokeh,jakirkham/bokeh,khkaminska/bokeh,srinathv/bokeh,msarahan/bokeh,Karel-van-de-Plassche/bokeh,CrazyGuo/bokeh,rothnic/bokeh,clairetang6/bokeh,quasiben/bokeh,birdsarah/bokeh,azjps/bokeh,mindriot101/bokeh,khkaminska/bokeh,timothyd... | ---
+++
@@ -0,0 +1,55 @@
+from __future__ import print_function
+
+import sys
+
+try:
+ import colorama
+ def blue(text): return "%s%s%s" % (colorama.Fore.BLUE, text, colorama.Style.RESET_ALL)
+ def red(text): return "%s%s%s" % (colorama.Fore.RED, text, colorama.Style.RESET_ALL)
+except ImportError:
+ def... | |
f0da1774514c839b4b97fa92d2202437932dc99a | analysis/plot-skeleton.py | analysis/plot-skeleton.py | #!/usr/bin/env python
import climate
import database
import plots
@climate.annotate(
root='plot data rooted at this path',
pattern=('plot data from files matching this pattern', 'option'),
)
def main(root, pattern='*/*block02/*trial00*.csv.gz'):
with plots.space() as ax:
for trial in database.Ex... | Add a small driver for plotting skeletons. | Add a small driver for plotting skeletons.
| Python | mit | lmjohns3/cube-experiment,lmjohns3/cube-experiment,lmjohns3/cube-experiment | ---
+++
@@ -0,0 +1,21 @@
+#!/usr/bin/env python
+
+import climate
+
+import database
+import plots
+
+
+@climate.annotate(
+ root='plot data rooted at this path',
+ pattern=('plot data from files matching this pattern', 'option'),
+)
+def main(root, pattern='*/*block02/*trial00*.csv.gz'):
+ with plots.space(... | |
872dd45173e889db06e9b16105492c241f7badae | examples/rpc_dynamic.py | examples/rpc_dynamic.py | import asyncio
import aiozmq
import aiozmq.rpc
class DynamicHandler(aiozmq.rpc.AttrHandler):
def __init__(self, namespace=()):
self.namespace = namespace
def __getitem__(self, key):
try:
return getattr(self, key)
except AttributeError:
return DynamicHandler(se... | Add an example for dynamic RPC lookup. | Add an example for dynamic RPC lookup.
| Python | bsd-2-clause | claws/aiozmq,aio-libs/aiozmq,asteven/aiozmq,MetaMemoryT/aiozmq | ---
+++
@@ -0,0 +1,51 @@
+import asyncio
+import aiozmq
+import aiozmq.rpc
+
+
+class DynamicHandler(aiozmq.rpc.AttrHandler):
+
+ def __init__(self, namespace=()):
+ self.namespace = namespace
+
+ def __getitem__(self, key):
+ try:
+ return getattr(self, key)
+ except AttributeEr... | |
d41005d14239a93237fb839084f029208b94539d | common/profile_default/ipython_notebook_config.py | common/profile_default/ipython_notebook_config.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Configuration file for ipython-notebook.
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.open_browser = False
c.NotebookApp.port = 8888
# Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-
# For headerssent by the upstream reverse proxy... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Configuration file for ipython-notebook.
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.open_browser = False
c.NotebookApp.port = 8888
# Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-
# For headerssent by the upstream reverse proxy... | Use the custom.js as served from the CDN for try | Use the custom.js as served from the CDN for try
| Python | bsd-3-clause | dietmarw/jupyter-docker-images,iamjakob/docker-demo-images,Zsailer/docker-jupyter-teaching,odewahn/docker-demo-images,jupyter/docker-demo-images,tanyaschlusser/docker-demo-images,iamjakob/docker-demo-images,Zsailer/docker-demo-images,CognitiveScale/docker-demo-images,Zsailer/docker-jupyter-teaching,ericdill/docker-demo... | ---
+++
@@ -22,5 +22,5 @@
'headers': {
'Content-Security-Policy': "frame-ancestors 'self' https://*.jupyter.org https://jupyter.github.io https://*.tmpnb.org"
},
- 'static_url_prefix': 'https://cdn.jupyter.org/notebook/3.1.0/'
+ 'static_url_prefix': 'https://cdn.jupyter.org/notebook/try/'
} |
2b380d501b80afad8c7c5ec27537bcc682ed2775 | commands/handle.py | commands/handle.py | import commands.cmds as cmds
def handle(self, chat_raw):
self.logger.info("Handling command: " + chat_raw + " (for player" + self.fquid + ")")
_atmp1 = chat_raw.split(" ")
_atmp2 = list(_atmp1[0])
del _atmp2[0]
del _atmp1[0]
cmdobj = {
"base": _atmp2,
"args_raw": _atmp1,
... | import commands.cmds as cmds
def handle(self, chat_raw):
self.logger.info("Handling command: " + chat_raw + " (for player" + self.fquid + ")")
_atmp1 = chat_raw.split(" ")
_atmp2 = list(_atmp1[0])
del _atmp2[0]
del _atmp1[0]
cmdobj = {
"base": _atmp2,
"args_raw": _atmp1,
... | Fix some scope mistakes. This fix was part of the reverted commit. | Fix some scope mistakes. This fix was part of the reverted commit.
| Python | mit | TiberiumPY/puremine,Armored-Dragon/pymineserver | ---
+++
@@ -12,4 +12,4 @@
"scope": self,
"chat_raw": chat_raw
}
- commands.cmds.InvalidCommand.begin(self, cmdobj) if _atmp2 not in commands.cmds.baseList else commands.cmds.baseList[_atmp2].begin(self, cmdobj)
+ cmds.InvalidCommand.begin(self, cmdobj) if _atmp2 not in cmds.baseList else ... |
b37f31b5adbdda3e5d40d2d8a9dde19b2e305c2c | ckanext/wirecloudview/tests/test_controller.py | ckanext/wirecloudview/tests/test_controller.py | # -*- coding: utf-8 -*-
# Copyright (c) 2018 Future Internet Consulting and Development Solutions S.L.
# This file is part of CKAN WireCloud View Extension.
# CKAN WireCloud View Extension is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as publish... | Add tests for the controller module | Add tests for the controller module
| Python | agpl-3.0 | conwetlab/ckanext-wirecloud_view,conwetlab/ckanext-wirecloud_view,conwetlab/ckanext-wirecloud_view,conwetlab/ckanext-wirecloud_view | ---
+++
@@ -0,0 +1,67 @@
+# -*- coding: utf-8 -*-
+
+# Copyright (c) 2018 Future Internet Consulting and Development Solutions S.L.
+
+# This file is part of CKAN WireCloud View Extension.
+
+# CKAN WireCloud View Extension is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affer... | |
545af0493cf08cb15d262f3a5333df6d1fce6848 | brake/utils.py | brake/utils.py | from decorators import _backend
"""Access limits and increment counts without using a decorator."""
def get_limits(request, label, field, periods):
limits = []
count = 10
for period in periods:
limits.extend(_backend.limit(
label,
request,
field=field,
... | Add util convenience functions for accessing data without decorators | Add util convenience functions for accessing data without decorators
| Python | bsd-3-clause | SilentCircle/django-brake,SilentCircle/django-brake,skorokithakis/django-brake,skorokithakis/django-brake | ---
+++
@@ -0,0 +1,22 @@
+from decorators import _backend
+
+"""Access limits and increment counts without using a decorator."""
+
+def get_limits(request, label, field, periods):
+ limits = []
+ count = 10
+ for period in periods:
+ limits.extend(_backend.limit(
+ label,
+ reque... | |
2c900f8bddc9efb40d900bf28f8c6b3188add71e | test/test_trix_parse.py | test/test_trix_parse.py | #!/usr/bin/env python
from rdflib.graph import ConjunctiveGraph
import unittest
class TestTrixParse(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testAperture(self):
g=ConjunctiveGraph()
g.parse("test/trix/aperture.trix",format="trix")
... | #!/usr/bin/env python
from rdflib.graph import ConjunctiveGraph
import unittest
class TestTrixParse(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testAperture(self):
g=ConjunctiveGraph()
g.parse("test/trix/aperture.trix",format="trix")
... | Disable trix parser tests with Jython | Disable trix parser tests with Jython
| Python | bsd-3-clause | RDFLib/rdflib,avorio/rdflib,yingerj/rdflib,ssssam/rdflib,ssssam/rdflib,marma/rdflib,armandobs14/rdflib,armandobs14/rdflib,dbs/rdflib,dbs/rdflib,RDFLib/rdflib,marma/rdflib,RDFLib/rdflib,yingerj/rdflib,avorio/rdflib,ssssam/rdflib,armandobs14/rdflib,RDFLib/rdflib,dbs/rdflib,marma/rdflib,marma/rdflib,ssssam/rdflib,armandob... | ---
+++
@@ -35,8 +35,18 @@
#print "Parsed %d triples"%len(g)
+ def testNG4j(self):
+ g=ConjunctiveGraph()
+
+ g.parse("test/trix/ng4jtest.trix",format="trix")
+
+ #print "Parsed %d triples"%len(g)
+import platform
+if platform.system() == 'Java... |
24b8437003269ebd10c46d0fbdaa3e432d7535d6 | genotype-likelihoods.py | genotype-likelihoods.py | from __future__ import print_function
import sys
import cyvcf
from argparse import ArgumentParser, FileType
import toolz as tz
description = ("Create a table of probability of a non reference call for each "
"genotype for each sample. This is PL[0]. -1 is output for samples "
"with a miss... | Add VCF -> non-reference likelihood table script. | Add VCF -> non-reference likelihood table script.
| Python | mit | roryk/junkdrawer,roryk/junkdrawer | ---
+++
@@ -0,0 +1,27 @@
+from __future__ import print_function
+import sys
+import cyvcf
+from argparse import ArgumentParser, FileType
+import toolz as tz
+
+description = ("Create a table of probability of a non reference call for each "
+ "genotype for each sample. This is PL[0]. -1 is output for sa... | |
0970115f9bc1bab019c23ab46e64b26d5e754313 | led_display.py | led_display.py | import math
from gpiozero import LED
from time import sleep
g0 = LED(12)
f0 = LED(16)
a0 = LED(20)
b0 = LED(21)
e0 = LED(17)
d0 = LED(27)
c0 = LED(22)
g1 = LED(25)
f1 = LED(24)
a1 = LED(23)
b1 = LED(18)
e1 = LED(5)
d1 = LED(6)
c1 = LED(13)
PITCHES = {
'E2': ((a0, d0, e0, f0, g0), (b0, c0)),
'A2': ((a0, b0, ... | Implement function for displaying tuning guidance on a DIY 8-segment LEDs display | Implement function for displaying tuning guidance on a DIY 8-segment LEDs display
| Python | mit | Bastien-Brd/pi-tuner | ---
+++
@@ -0,0 +1,44 @@
+import math
+from gpiozero import LED
+from time import sleep
+
+
+g0 = LED(12)
+f0 = LED(16)
+a0 = LED(20)
+b0 = LED(21)
+e0 = LED(17)
+d0 = LED(27)
+c0 = LED(22)
+
+g1 = LED(25)
+f1 = LED(24)
+a1 = LED(23)
+b1 = LED(18)
+e1 = LED(5)
+d1 = LED(6)
+c1 = LED(13)
+
+PITCHES = {
+ 'E2': ((a0... | |
550d8bcd49e5ec591286f3f42de7dd54ef853bb8 | find_dupes.py | find_dupes.py | #!/usr/bin/env python3
import json
import os
import random
scriptpath = os.path.dirname(__file__)
data_dir = os.path.join(scriptpath, 'data')
all_json = [f for f in os.listdir(data_dir) if os.path.isfile(os.path.join(data_dir, f))]
quotes = []
for f in all_json:
filename = os.path.join(data_dir, f)
with open(filena... | Add a utility script to print duplicates | Add a utility script to print duplicates | Python | mit | mubaris/motivate,mubaris/motivate | ---
+++
@@ -0,0 +1,24 @@
+#!/usr/bin/env python3
+
+import json
+import os
+import random
+
+scriptpath = os.path.dirname(__file__)
+data_dir = os.path.join(scriptpath, 'data')
+all_json = [f for f in os.listdir(data_dir) if os.path.isfile(os.path.join(data_dir, f))]
+quotes = []
+for f in all_json:
+ filename = os.p... | |
501c38ac9e8b9fbb35b64321e103a0dfe064e718 | QGL/BasicSequences/BlankingSweeps.py | QGL/BasicSequences/BlankingSweeps.py | """
Sequences for optimizing gating timing.
"""
from ..PulsePrimitives import *
from ..Compiler import compile_to_hardware
def sweep_gateDelay(qubit, sweepPts):
"""
Sweep the gate delay associated with a qubit channel using a simple Id, Id, X90, X90
seqeuence.
Parameters
---------
qubit : ... | Add a sequence module for optimizing gating | Add a sequence module for optimizing gating
--CAR
| Python | apache-2.0 | calebjordan/PyQLab,Plourde-Research-Lab/PyQLab,BBN-Q/PyQLab,rmcgurrin/PyQLab | ---
+++
@@ -0,0 +1,33 @@
+"""
+Sequences for optimizing gating timing.
+"""
+from ..PulsePrimitives import *
+from ..Compiler import compile_to_hardware
+
+def sweep_gateDelay(qubit, sweepPts):
+ """
+ Sweep the gate delay associated with a qubit channel using a simple Id, Id, X90, X90
+ seqeuence.
+
+ ... | |
fdd2a50445d2f2cb92480f8f42c463b312411361 | mapit/management/commands/mapit_print_areas.py | mapit/management/commands/mapit_print_areas.py | # For each generation, show every area, grouped by type
from django.core.management.base import NoArgsCommand
from mapit.models import Area, Generation, Type, NameType, Country, CodeType
class Command(NoArgsCommand):
help = 'Show all areas by generation and area type'
def handle_noargs(self, **options):
... | Add a simple command to print all areas in all generations | Add a simple command to print all areas in all generations
| Python | agpl-3.0 | Sinar/mapit,chris48s/mapit,chris48s/mapit,Code4SA/mapit,opencorato/mapit,New-Bamboo/mapit,Sinar/mapit,opencorato/mapit,New-Bamboo/mapit,chris48s/mapit,Code4SA/mapit,opencorato/mapit,Code4SA/mapit | ---
+++
@@ -0,0 +1,17 @@
+# For each generation, show every area, grouped by type
+
+from django.core.management.base import NoArgsCommand
+from mapit.models import Area, Generation, Type, NameType, Country, CodeType
+
+class Command(NoArgsCommand):
+ help = 'Show all areas by generation and area type'
+ def ha... | |
92f799d0584b598f368df44201446531dffd7d13 | python/utilities/transform_mp3_filenames.py | python/utilities/transform_mp3_filenames.py | # Extract the artist name from songs with filenames in this format:
# (number) - (artist) - (title).mp3
# and add the artists name to songs with filenames in this format:
# (number)..(title).mp3
# to make filenames in this format:
# (number)..(artist)..(title).mp3
#
# eg.: 14 - 13th Floor Elevators -... | Copy paste artist from filename1 to filename2 | Copy paste artist from filename1 to filename2
Utility to help consolidate groups of mp3s while preserving metadata in their filenames | Python | mit | daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various | ---
+++
@@ -0,0 +1,51 @@
+# Extract the artist name from songs with filenames in this format:
+# (number) - (artist) - (title).mp3
+# and add the artists name to songs with filenames in this format:
+# (number)..(title).mp3
+# to make filenames in this format:
+# (number)..(artist)..(title).mp3
+#
+# eg.:... | |
58e0ea4b555cf89ace4f5d97c579dbba905e7eeb | jsk_arc2017_common/scripts/list_objects.py | jsk_arc2017_common/scripts/list_objects.py | #!/usr/bin/env python
import os.path as osp
import rospkg
PKG_PATH = rospkg.RosPack().get_path('jsk_arc2017_common')
object_names = ['__background__']
with open(osp.join(PKG_PATH, 'data/names/objects.txt')) as f:
object_names += [x.strip() for x in f]
object_names.append('__shelf__')
for obj_id, obj in enumer... | Add script to list objects | Add script to list objects
| Python | bsd-3-clause | pazeshun/jsk_apc,pazeshun/jsk_apc,pazeshun/jsk_apc,pazeshun/jsk_apc,pazeshun/jsk_apc | ---
+++
@@ -0,0 +1,16 @@
+#!/usr/bin/env python
+
+import os.path as osp
+
+import rospkg
+
+
+PKG_PATH = rospkg.RosPack().get_path('jsk_arc2017_common')
+
+object_names = ['__background__']
+with open(osp.join(PKG_PATH, 'data/names/objects.txt')) as f:
+ object_names += [x.strip() for x in f]
+object_names.append... | |
836845abde53ee55bca93f098ece78880ab6b5c6 | examples/events/create_massive_dummy_events.py | examples/events/create_massive_dummy_events.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from pymisp import PyMISP
from keys import misp_url, misp_key, misp_verifycert
import argparse
import tools
def init(url, key):
return PyMISP(url, key, misp_verifycert, 'json')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Create a give... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from pymisp import PyMISP
from keys import url, key
import argparse
import tools
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Create a given number of event containing a given number of attributes eachh.')
parser.add_argument("-l", "--... | Use same variable names as testing environment | Use same variable names as testing environment
| Python | bsd-2-clause | pombredanne/PyMISP,iglocska/PyMISP | ---
+++
@@ -2,12 +2,10 @@
# -*- coding: utf-8 -*-
from pymisp import PyMISP
-from keys import misp_url, misp_key, misp_verifycert
+from keys import url, key
import argparse
import tools
-def init(url, key):
- return PyMISP(url, key, misp_verifycert, 'json')
if __name__ == '__main__':
parser = argpa... |
a635a8d58e46cf4ef1bc225f8824d73984971fee | countVowels.py | countVowels.py | """ Q6- Write a program that counts up the number of vowels contained in the string s. Valid vowels are: 'a', 'e', 'i',
'o', and 'u'. For example, if s = 'azcbobobegghakl', your program should print: Number of vowels: 5
"""
# Using the isVowel function from isVowel.py module (Answer of fifth question of Assignment 3)
... | Add the answer to the sixth question of Assignment 3 | Add the answer to the sixth question of Assignment 3
| Python | mit | SuyashD95/python-assignments | ---
+++
@@ -0,0 +1,44 @@
+""" Q6- Write a program that counts up the number of vowels contained in the string s. Valid vowels are: 'a', 'e', 'i',
+'o', and 'u'. For example, if s = 'azcbobobegghakl', your program should print: Number of vowels: 5
+"""
+
+# Using the isVowel function from isVowel.py module (Answer of ... | |
a6137714c55ada55571759b851e1e4afa7818f29 | app/utils/scripts/delete-docs.py | app/utils/scripts/delete-docs.py | #!/usr/bin/python
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope t... | Add cli tool to delete documents. | Add cli tool to delete documents.
Change-Id: I16c99d4b625e627c693c6354aaaa191c5076344b
| Python | lgpl-2.1 | kernelci/kernelci-backend,joyxu/kernelci-backend,kernelci/kernelci-backend,joyxu/kernelci-backend,joyxu/kernelci-backend | ---
+++
@@ -0,0 +1,104 @@
+#!/usr/bin/python
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# This ... | |
163da52a48eb0d84cde47f7cfe99e1188350db47 | mobib_basic.py | mobib_basic.py | #!/bin/env python3
import sys
from smartcard.System import readers
CALYPSO_CLA = [0x94]
SELECT_INS = [0xA4]
READ_RECORD_INS = [0xB2]
GET_RESPONSE_INS = [0xC0]
TICKETING_COUNTERS_FILE_ID = [0x20, 0x69]
def main():
local_readers = readers()
if local_readers:
if len(local_readers) == 1:
re... | Add MOBIB Basic reader script | Add MOBIB Basic reader script
| Python | mit | bparmentier/mobib-reader | ---
+++
@@ -0,0 +1,52 @@
+#!/bin/env python3
+
+import sys
+
+from smartcard.System import readers
+
+CALYPSO_CLA = [0x94]
+SELECT_INS = [0xA4]
+READ_RECORD_INS = [0xB2]
+GET_RESPONSE_INS = [0xC0]
+TICKETING_COUNTERS_FILE_ID = [0x20, 0x69]
+
+def main():
+ local_readers = readers()
+
+ if local_readers:
+ ... | |
f0392ebda49fa0222a3b317f50002d7e03659f47 | bluebottle/funding_flutterwave/tests/test_states.py | bluebottle/funding_flutterwave/tests/test_states.py | from bluebottle.files.tests.factories import PrivateDocumentFactory
from bluebottle.funding.tests.factories import FundingFactory, PlainPayoutAccountFactory, \
BudgetLineFactory
from bluebottle.funding_flutterwave.tests.factories import FlutterwaveBankAccountFactory
from bluebottle.test.utils import BluebottleTestC... | Test we can approve Flutterwave bank accounts | Test we can approve Flutterwave bank accounts
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle | ---
+++
@@ -0,0 +1,28 @@
+from bluebottle.files.tests.factories import PrivateDocumentFactory
+from bluebottle.funding.tests.factories import FundingFactory, PlainPayoutAccountFactory, \
+ BudgetLineFactory
+from bluebottle.funding_flutterwave.tests.factories import FlutterwaveBankAccountFactory
+from bluebottle.t... | |
4fe4cad49367b462c2201b98cce4382bff3a0206 | DataWrangling/CaseStudy/mapparser.py | DataWrangling/CaseStudy/mapparser.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Your task is to use the iterative parsing to process the map file and
find out not only what tags are there, but also how many, to get the
feeling on how much of which data you can expect to have in the map.
Fill out the count_tags function. It should return a dictionar... | Add a script which use the iterative parsing to process the map file and find out not only what tags are there, but also how many, to get the feeling on how much of which data you can expect to have in the map. | feat: Add a script which use the iterative parsing to process the map file and find out not only what tags are there, but also how many, to get the feeling on how much of which data you can expect to have in the map.
| Python | mit | aguijarro/DataSciencePython | ---
+++
@@ -0,0 +1,45 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+Your task is to use the iterative parsing to process the map file and
+find out not only what tags are there, but also how many, to get the
+feeling on how much of which data you can expect to have in the map.
+Fill out the count_tags func... | |
3d18f6e3ba3519422aa30bd25f3511f62361d5ca | tests/chainer_tests/test_chainer_objects.py | tests/chainer_tests/test_chainer_objects.py | import importlib
import inspect
import pkgutil
import types
import six
import unittest
import chainer
from chainer import testing
def walk_modules():
root = chainer.__path__
for loader, modname, ispkg in pkgutil.walk_packages(root, 'chainer.'):
# Skip modules generated by protobuf.
if '_pb2'... | Add test to ensure no mutable default arguments | Add test to ensure no mutable default arguments
| Python | mit | wkentaro/chainer,niboshi/chainer,chainer/chainer,niboshi/chainer,wkentaro/chainer,pfnet/chainer,niboshi/chainer,hvy/chainer,wkentaro/chainer,chainer/chainer,okuta/chainer,wkentaro/chainer,okuta/chainer,okuta/chainer,chainer/chainer,chainer/chainer,hvy/chainer,niboshi/chainer,hvy/chainer,okuta/chainer,hvy/chainer | ---
+++
@@ -0,0 +1,93 @@
+import importlib
+import inspect
+import pkgutil
+import types
+
+import six
+import unittest
+
+import chainer
+from chainer import testing
+
+
+def walk_modules():
+ root = chainer.__path__
+ for loader, modname, ispkg in pkgutil.walk_packages(root, 'chainer.'):
+ # Skip modul... | |
fcb07c7cd94f96cd533c55d18a657673f9eeac7f | SpicyTwitch/Log_tools.py | SpicyTwitch/Log_tools.py | # Imports-----------------------------------------------------------------------
import logging
import os
from inspect import stack, getmodulename
from . import Storage
# Base setup--------------------------------------------------------------------
log_to_stdout = True
log_to_file = True
logging_level = logging.DEBU... | Move log related functions over to this file | Move log related functions over to this file
Meant for global use in SpicyTwitch
| Python | mit | NekoGamiYuki/SpicyTwitch | ---
+++
@@ -0,0 +1,44 @@
+# Imports-----------------------------------------------------------------------
+import logging
+import os
+from inspect import stack, getmodulename
+from . import Storage
+
+
+# Base setup--------------------------------------------------------------------
+log_to_stdout = True
+log_to_fil... | |
4061e5db7097a680405282e371ab3bf07758648a | projects/DensePose/tests/test_setup.py | projects/DensePose/tests/test_setup.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import os
import unittest
from detectron2.config import get_cfg
from detectron2.engine import default_setup
from densepose import add_densepose_config
_CONFIG_DIR = "configs"
_QUICK_SCHEDULES_CONFIG_SUB_DIR = "quick_schedules"
_CONFIG_FILE_PREF... | Add simple unit tests to validate all configs | Add simple unit tests to validate all configs
Summary: Add simple unit tests to validate all configs: as demonstrated by the previous diff, this can not hurt :)
Reviewed By: vkhalidov
Differential Revision: D20491383
fbshipit-source-id: 1c7b82dfbf9cde43d38ece64a5fb1692d1c03a9b
| Python | apache-2.0 | facebookresearch/detectron2,facebookresearch/detectron2,facebookresearch/detectron2 | ---
+++
@@ -0,0 +1,61 @@
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
+
+import os
+import unittest
+
+from detectron2.config import get_cfg
+from detectron2.engine import default_setup
+
+from densepose import add_densepose_config
+
+_CONFIG_DIR = "configs"
+_QUICK_SCHEDULES_CONFIG_SUB_DI... | |
e07c699caf699852c98b3396150b343553a386c4 | server/tests/api/test_language_api.py | server/tests/api/test_language_api.py | import json
from server.tests.helpers import FlaskTestCase, fixtures
class TestLanguageAPI(FlaskTestCase):
@fixtures('base.json')
def test_get_empty_languages(self):
"""Test GET /api/languages endpoint with no data"""
response, data = self.api_request('get', '/api/languages')
assert d... | Add tests for language api | Add tests for language api
| Python | mit | ganemone/ontheside,ganemone/ontheside,ganemone/ontheside | ---
+++
@@ -0,0 +1,67 @@
+import json
+from server.tests.helpers import FlaskTestCase, fixtures
+
+
+class TestLanguageAPI(FlaskTestCase):
+
+ @fixtures('base.json')
+ def test_get_empty_languages(self):
+ """Test GET /api/languages endpoint with no data"""
+ response, data = self.api_request('get... | |
dcca93fbb66e5cd8bf0e0500aca3f187922e8806 | scrapy_espn/scrapy_espn/spiders/team_spider.py | scrapy_espn/scrapy_espn/spiders/team_spider.py | import scrapy
class TeamSpider(scrapy.Spider):
name = "team"
start_urls = [
'http://www.espn.com/mens-college-basketball/teams',
]
def parse(self, response):
for conf in response.css('ul'):
for team in conf.css('li'):
yield {
'team':team.css('h5 a::text').extract(),
'id':team.css('h5 a::attr(... | Add in team id spider | Add in team id spider
| Python | mit | danmoeller/ncaa-bball-attendance,danmoeller/ncaa-bball-attendance,danmoeller/ncaa-bball-attendance | ---
+++
@@ -0,0 +1,15 @@
+import scrapy
+
+class TeamSpider(scrapy.Spider):
+ name = "team"
+ start_urls = [
+ 'http://www.espn.com/mens-college-basketball/teams',
+ ]
+
+ def parse(self, response):
+ for conf in response.css('ul'):
+ for team in conf.css('li'):
+ yield {
+ 'team':team.css('h5 a::text').ex... | |
458cf526a4ebb72b4fad84e8cd2b665e0f093c1b | senlin/tests/functional/test_cluster_health.py | senlin/tests/functional/test_cluster_health.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
# distributed under t... | Add functional test for cluster check recover | Add functional test for cluster check recover
Change-Id: Icb4ef7f754ba3b5764cf8f6d8f5999f0e2d2f3c2
| Python | apache-2.0 | openstack/senlin,openstack/senlin,tengqm/senlin-container,openstack/senlin,stackforge/senlin,stackforge/senlin,tengqm/senlin-container | ---
+++
@@ -0,0 +1,65 @@
+# 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 writi... | |
48c008b4ac08114e30f4bee7a208d5d3fb925296 | problem1/steiner-simplegreedy.py | problem1/steiner-simplegreedy.py | import networkx as nx
from sys import argv
def main():
# G = nx.read_gml(argv[1])
G = nx.read_gml("steiner-small.gml")
T = [] # terminals
for v,d in G.nodes_iter(data=True):
if d['T'] == 1:
T.append(v)
U = T[:] # Steiner tree vertices
F = [] # Steiner tree edges
D = [] # cand... | Add partial simple greedy algorithm (baseline). | Add partial simple greedy algorithm (baseline).
| Python | mit | karulont/combopt | ---
+++
@@ -0,0 +1,55 @@
+import networkx as nx
+from sys import argv
+
+def main():
+ # G = nx.read_gml(argv[1])
+ G = nx.read_gml("steiner-small.gml")
+
+ T = [] # terminals
+ for v,d in G.nodes_iter(data=True):
+ if d['T'] == 1:
+ T.append(v)
+
+ U = T[:] # Steiner tree vertices
+ F = [] # Steiner t... | |
084ebff19703c42c50621eb94ac070c6a471e983 | Home/mostWantedLetter.py | Home/mostWantedLetter.py | def checkio(word):
word = word.lower()
arr = dict()
for i in range(len(word)):
char = word[i]
if not str.isalpha(char):
continue
if not arr.__contains__(char):
arr[char] = 0
arr[char] = arr[char] + 1
result = ""
counter = 0
for k, v in arr.... | Solve the most wanted letter problem. | Solve the most wanted letter problem.
| Python | mit | edwardzhu/checkio-solution | ---
+++
@@ -0,0 +1,24 @@
+def checkio(word):
+ word = word.lower()
+ arr = dict()
+ for i in range(len(word)):
+ char = word[i]
+ if not str.isalpha(char):
+ continue
+ if not arr.__contains__(char):
+ arr[char] = 0
+ arr[char] = arr[char] + 1
+ result = "... | |
8fb4df5367b5c03d2851532063f6fa781fe2f980 | Maths/fibonacciSeries.py | Maths/fibonacciSeries.py | # Fibonacci Sequence Using Recursion
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
limit = int(input("How many terms to include in fionacci series:"))
if limit <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci series:")
for ... | Add Fibonacci Series Using Recursion | Add Fibonacci Series Using Recursion
| Python | mit | TheAlgorithms/Python | ---
+++
@@ -0,0 +1,16 @@
+# Fibonacci Sequence Using Recursion
+
+def recur_fibo(n):
+ if n <= 1:
+ return n
+ else:
+ return(recur_fibo(n-1) + recur_fibo(n-2))
+
+limit = int(input("How many terms to include in fionacci series:"))
+
+if limit <= 0:
+ print("Plese enter a positive integer")
+els... | |
97ae80b08958646e0c937f65a1b396171bf61e72 | Lib/test/test_xreload.py | Lib/test/test_xreload.py | """Doctests for module reloading.
>>> from xreload import xreload
>>> from test.test_xreload import make_mod
>>> make_mod()
>>> import x
>>> C = x.C
>>> Cfoo = C.foo
>>> Cbar = C.bar
>>> Cstomp = C.stomp
>>> b = C()
>>> bfoo = b.foo
>>> b.foo()
42
>>> bfoo()
42
>>> Cfoo(b)
42
>>> Cbar()
42 42
>>> Cstomp()
42 42 42
>>>... | Add a proper unit test for xreload.py. | Add a proper unit test for xreload.py.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -0,0 +1,103 @@
+"""Doctests for module reloading.
+
+>>> from xreload import xreload
+>>> from test.test_xreload import make_mod
+>>> make_mod()
+>>> import x
+>>> C = x.C
+>>> Cfoo = C.foo
+>>> Cbar = C.bar
+>>> Cstomp = C.stomp
+>>> b = C()
+>>> bfoo = b.foo
+>>> b.foo()
+42
+>>> bfoo()
+42
+>>> Cfoo(b)
... | |
dd1d0893823561efec203cdfbb927b8edac7a72a | tests/unit/beanstalk/test_exception.py | tests/unit/beanstalk/test_exception.py | # Copyright (c) 2014 Amazon.com, Inc. or its affiliates.
# All Rights Reserved
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights... | Add a coupld tests to create exception classes from error code names | Add a coupld tests to create exception classes from error code names
| Python | mit | darjus-amzn/boto,Asana/boto,vishnugonela/boto,podhmo/boto,weebygames/boto,SaranyaKarthikeyan/boto,clouddocx/boto,bleib1dj/boto,TiVoMaker/boto,tpodowd/boto,rayluo/boto,tpodowd/boto,disruptek/boto,stevenbrichards/boto,revmischa/boto,pfhayes/boto,ekalosak/boto,ryansb/boto,shaunbrady/boto,acourtney2015/boto,alfredodeza/bot... | ---
+++
@@ -0,0 +1,49 @@
+# Copyright (c) 2014 Amazon.com, Inc. or its affiliates.
+# All Rights Reserved
+#
+# Permission is hereby granted, free of charge, to any person obtaining a
+# copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, includin... | |
de38b3e7b3d8458920b913316b06bb10b886df9f | thinglang/symbols/argument_selector.py | thinglang/symbols/argument_selector.py | import collections
import copy
from thinglang.compiler.errors import NoMatchingOverload
from thinglang.lexer.values.identifier import Identifier
SymbolOption = collections.namedtuple('SymbolOption', ['symbol', 'remaining_arguments'])
class ArgumentSelector(object):
"""
Aids in disambiguating overloaded meth... | Implement ArgumentSelector for overload disambiguation | Implement ArgumentSelector for overload disambiguation
| Python | mit | ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang | ---
+++
@@ -0,0 +1,58 @@
+import collections
+import copy
+
+from thinglang.compiler.errors import NoMatchingOverload
+from thinglang.lexer.values.identifier import Identifier
+
+SymbolOption = collections.namedtuple('SymbolOption', ['symbol', 'remaining_arguments'])
+
+
+class ArgumentSelector(object):
+ """
+ ... | |
4d16ae6d1ad8b308c14c23e802349001b81ae461 | thinglang/compiler/opcodes.py | thinglang/compiler/opcodes.py | import os
import re
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ENUM_PARSER = re.compile(r'(.*)\s*?=\s*?(\d+)')
def read_opcodes():
with open(os.path.join(BASE_DIR, '..', '..', 'thingc', 'execution', 'Opcode.h')) as f:
for line in f:
if 'enum class Opcode' in line:
b... | Add Python-based opcode enum parser | Add Python-based opcode enum parser
| Python | mit | ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang | ---
+++
@@ -0,0 +1,28 @@
+import os
+
+import re
+
+BASE_DIR = os.path.dirname(os.path.abspath(__file__))
+ENUM_PARSER = re.compile(r'(.*)\s*?=\s*?(\d+)')
+
+def read_opcodes():
+ with open(os.path.join(BASE_DIR, '..', '..', 'thingc', 'execution', 'Opcode.h')) as f:
+ for line in f:
+ if 'enum cl... | |
ac823e61fd214f9818bb7a893a8ed52a3bfa3af4 | neurokernel/conn_utils.py | neurokernel/conn_utils.py | #!/usr/bin/env python
import itertools
import os
import tempfile
import conn
import matplotlib.pyplot as plt
import networkx as nx
def imdisp(f):
"""
Display the specified image file using matplotlib.
"""
im = plt.imread(f)
plt.imshow(im)
plt.axis('off')
plt.draw()
return im
def... | Add utils for graph visualization. | Add utils for graph visualization.
| Python | bsd-3-clause | cerrno/neurokernel | ---
+++
@@ -0,0 +1,74 @@
+#!/usr/bin/env python
+
+import itertools
+import os
+import tempfile
+
+import conn
+import matplotlib.pyplot as plt
+import networkx as nx
+
+def imdisp(f):
+ """
+ Display the specified image file using matplotlib.
+ """
+
+ im = plt.imread(f)
+ plt.imshow(im)
+ plt.... | |
525a8438bd601592c4f878ca5d42d3dab8943be0 | ooni/tests/test_errors.py | ooni/tests/test_errors.py | from twisted.trial import unittest
import ooni.errors
class TestErrors(unittest.TestCase):
def test_catch_child_failures_before_parent_failures(self):
"""
Verify that more specific Failures are caught first by
handleAllFailures() and failureToString().
Fails if a subclass is list... | Test that specific Failures are caught before parent Failures | Test that specific Failures are caught before parent Failures
| Python | bsd-2-clause | 0xPoly/ooni-probe,0xPoly/ooni-probe,0xPoly/ooni-probe,0xPoly/ooni-probe | ---
+++
@@ -0,0 +1,20 @@
+from twisted.trial import unittest
+
+import ooni.errors
+
+class TestErrors(unittest.TestCase):
+
+ def test_catch_child_failures_before_parent_failures(self):
+ """
+ Verify that more specific Failures are caught first by
+ handleAllFailures() and failureToString().... | |
90d079928eaf48e370d21417e4d6e649ec0f5f6f | taskwiki/taskwiki.py | taskwiki/taskwiki.py | import sys
import re
import vim
from tasklib.task import TaskWarrior, Task
# Insert the taskwiki on the python path
sys.path.insert(0, vim.eval("s:plugin_path") + '/taskwiki')
from regexp import *
from task import VimwikiTask
from cache import TaskCache
"""
How this plugin works:
1.) On startup, it reads all t... | import sys
import re
import vim
from tasklib.task import TaskWarrior, Task
# Insert the taskwiki on the python path
sys.path.insert(0, vim.eval("s:plugin_path") + '/taskwiki')
from regexp import *
from task import VimwikiTask
from cache import TaskCache
"""
How this plugin works:
1.) On startup, it reads all t... | Update tasks and evaluate viewports on saving | Taskwiki: Update tasks and evaluate viewports on saving
| Python | mit | phha/taskwiki,Spirotot/taskwiki | ---
+++
@@ -43,8 +43,10 @@
cache.reset()
cache.load_buffer()
+ cache.update_tasks()
cache.save_tasks()
cache.update_buffer()
+ cache.evaluate_viewports()
if __name__ == '__main__': |
eb71a3d3319480b3f99cb44f934a51bfb1b5bd67 | pyatv/auth/hap_channel.py | pyatv/auth/hap_channel.py | """Base class for HAP based channels (connections)."""
from abc import ABC, abstractmethod
import asyncio
import logging
from typing import Callable, Tuple, cast
from pyatv.auth.hap_pairing import PairVerifyProcedure
from pyatv.auth.hap_session import HAPSession
from pyatv.support import log_binary
_LOGGER = logging.... | Add abstract class for HAP channels | auth: Add abstract class for HAP channels
Relates to #1255
| Python | mit | postlund/pyatv,postlund/pyatv | ---
+++
@@ -0,0 +1,76 @@
+"""Base class for HAP based channels (connections)."""
+from abc import ABC, abstractmethod
+import asyncio
+import logging
+from typing import Callable, Tuple, cast
+
+from pyatv.auth.hap_pairing import PairVerifyProcedure
+from pyatv.auth.hap_session import HAPSession
+from pyatv.support i... | |
bd01797f18012927202b87872dc33caf685306c0 | gdb.py | gdb.py | deadbeef = 0xdeadbeefdeadbeef
abc_any = gdb.lookup_type("union any")
def color(s, c):
return "\x1b[" + str(c) + "m" + s + "\x1b[0m"
def gray(s):
return color(s, 90)
def red(s):
return color(s, "1;31")
def p(indent, tag, value):
print(" " * indent + tag + ": " + str(value))
def print_abc(i, v):
... | Add GDB plugin for printing ABC values | Add GDB plugin for printing ABC values
| Python | bsd-3-clause | klkblake/abcc,klkblake/abcc,klkblake/abcc,klkblake/abcc | ---
+++
@@ -0,0 +1,74 @@
+deadbeef = 0xdeadbeefdeadbeef
+
+abc_any = gdb.lookup_type("union any")
+
+def color(s, c):
+ return "\x1b[" + str(c) + "m" + s + "\x1b[0m"
+
+def gray(s):
+ return color(s, 90)
+
+def red(s):
+ return color(s, "1;31")
+
+def p(indent, tag, value):
+ print(" " * indent + tag + ":... | |
2d320058c96f88348d8226fa4a827a6c2c973237 | mds.py | mds.py | """
Simple implementation of classical MDS.
See http://www.stat.cmu.edu/~ryantibs/datamining/lectures/09-dim3-marked.pdf for more details.
"""
import numpy as np
import numpy.linalg as linalg
import matplotlib.pyplot as plt
def square_points(size):
nsensors = size**2
return np.array([(i/size, i%size) for i in range... | Add Classical multidimensional scaling algorithm. | Add Classical multidimensional scaling algorithm.
| Python | mit | ntduong/ML | ---
+++
@@ -0,0 +1,76 @@
+"""
+Simple implementation of classical MDS.
+See http://www.stat.cmu.edu/~ryantibs/datamining/lectures/09-dim3-marked.pdf for more details.
+"""
+
+import numpy as np
+import numpy.linalg as linalg
+import matplotlib.pyplot as plt
+
+def square_points(size):
+ nsensors = size**2
+ return np... | |
a78d879c9c097c32c58f5246d46a4a188b17d99c | workup/migrations/0002_add_verbose_names.py | workup/migrations/0002_add_verbose_names.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('workup', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='historicalworkup',
nam... | Add workup vebose name change migration. | Add workup vebose name change migration.
| Python | mit | SaturdayNeighborhoodHealthClinic/clintools,SaturdayNeighborhoodHealthClinic/clintools,SaturdayNeighborhoodHealthClinic/clintools | ---
+++
@@ -0,0 +1,74 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('workup', '0001_initial'),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ mode... | |
1e050f30e8307a75976a52b8f1258a5b14e43733 | wsgi_static.py | wsgi_static.py | import wsgi_server
import os
from werkzeug.wsgi import SharedDataMiddleware
application = SharedDataMiddleware(wsgi_server.application, {
'/static': os.path.join(os.path.dirname(__file__), 'static')
})
| Add middleware for static serving | Add middleware for static serving
| Python | agpl-3.0 | cggh/DQXServer | ---
+++
@@ -0,0 +1,7 @@
+import wsgi_server
+import os
+from werkzeug.wsgi import SharedDataMiddleware
+
+application = SharedDataMiddleware(wsgi_server.application, {
+ '/static': os.path.join(os.path.dirname(__file__), 'static')
+}) | |
a086307e6aac341ed8a6596d0a05b7a8d198c7ec | zephyr/management/commands/dump_pointers.py | zephyr/management/commands/dump_pointers.py | from optparse import make_option
from django.core.management.base import BaseCommand
from zephyr.models import Realm, UserProfile
import simplejson
def dump():
pointers = []
for u in UserProfile.objects.select_related("user__email").all():
pointers.append((u.user.email, u.pointer))
file("dumped-poi... | Add command to dump and restore user pointers. | Add command to dump and restore user pointers.
For use in database migrations.
(imported from commit f06ae569fe986da5e7d144c277bf27be534c04f9)
| Python | apache-2.0 | brainwane/zulip,dwrpayne/zulip,dotcool/zulip,nicholasbs/zulip,ikasumiwt/zulip,DazWorrall/zulip,xuanhan863/zulip,tdr130/zulip,alliejones/zulip,brainwane/zulip,vabs22/zulip,Qgap/zulip,DazWorrall/zulip,souravbadami/zulip,developerfm/zulip,mdavid/zulip,mohsenSy/zulip,rishig/zulip,shubhamdhama/zulip,kaiyuanheshang/zulip,hac... | ---
+++
@@ -0,0 +1,29 @@
+from optparse import make_option
+from django.core.management.base import BaseCommand
+from zephyr.models import Realm, UserProfile
+import simplejson
+
+def dump():
+ pointers = []
+ for u in UserProfile.objects.select_related("user__email").all():
+ pointers.append((u.user.ema... | |
eb91b11930319369bc9cfc3b1b15c0b92fb4d85c | tests/sentry/models/test_organizationoption.py | tests/sentry/models/test_organizationoption.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from sentry.models import OrganizationOption
from sentry.testutils import TestCase
class OrganizationOptionManagerTest(TestCase):
def test_set_value(self):
OrganizationOption.objects.set_value(self.organization, 'foo', 'bar')
assert ... | Add `OrganizationOption` tests based on `ProjectOption`. | Add `OrganizationOption` tests based on `ProjectOption`.
| Python | bsd-3-clause | JamesMura/sentry,gencer/sentry,nicholasserra/sentry,gencer/sentry,fotinakis/sentry,looker/sentry,JackDanger/sentry,gencer/sentry,looker/sentry,fotinakis/sentry,looker/sentry,jean/sentry,daevaorn/sentry,ifduyue/sentry,beeftornado/sentry,zenefits/sentry,alexm92/sentry,mvaled/sentry,mitsuhiko/sentry,nicholasserra/sentry,z... | ---
+++
@@ -0,0 +1,39 @@
+# -*- coding: utf-8 -*-
+
+from __future__ import absolute_import
+
+from sentry.models import OrganizationOption
+from sentry.testutils import TestCase
+
+
+class OrganizationOptionManagerTest(TestCase):
+ def test_set_value(self):
+ OrganizationOption.objects.set_value(self.organ... | |
f264f8804c208f2b55471f27f92a9e8c1ab5d778 | tests/correlations/test_views.py | tests/correlations/test_views.py | # -*- coding: utf-8 -*-
import datetime
import pytest
from django.core.urlresolvers import reverse
from components.people.factories import GroupFactory, IdolFactory
@pytest.mark.django_db
def test_happenings_by_year_view(client):
[GroupFactory(started=datetime.date(2013, 1, 1)) for i in xrange(5)]
response ... | Test our new happenings-by-year view. | Test our new happenings-by-year view.
| Python | apache-2.0 | hello-base/web,hello-base/web,hello-base/web,hello-base/web | ---
+++
@@ -0,0 +1,17 @@
+# -*- coding: utf-8 -*-
+import datetime
+import pytest
+
+from django.core.urlresolvers import reverse
+
+from components.people.factories import GroupFactory, IdolFactory
+
+
+@pytest.mark.django_db
+def test_happenings_by_year_view(client):
+ [GroupFactory(started=datetime.date(2013, 1... | |
43c4595ae26a7663538e712af37553c7a64fade7 | teuthology/test/test_parallel.py | teuthology/test/test_parallel.py | from ..parallel import parallel
def identity(item, input_set=None, remove=False):
if input_set is not None:
assert item in input_set
if remove:
input_set.remove(item)
return item
class TestParallel(object):
def test_basic(self):
in_set = set(range(10))
with pa... | Add a couple unit tests for teuthology.parallel | Add a couple unit tests for teuthology.parallel
Signed-off-by: Zack Cerza <f801c831581d4150a2793939287636221d62131e@inktank.com>
| Python | mit | michaelsevilla/teuthology,caibo2014/teuthology,ceph/teuthology,SUSE/teuthology,SUSE/teuthology,t-miyamae/teuthology,zhouyuan/teuthology,ktdreyer/teuthology,robbat2/teuthology,yghannam/teuthology,yghannam/teuthology,dmick/teuthology,dreamhost/teuthology,zhouyuan/teuthology,dmick/teuthology,ivotron/teuthology,caibo2014/t... | ---
+++
@@ -0,0 +1,28 @@
+from ..parallel import parallel
+
+
+def identity(item, input_set=None, remove=False):
+ if input_set is not None:
+ assert item in input_set
+ if remove:
+ input_set.remove(item)
+ return item
+
+
+class TestParallel(object):
+ def test_basic(self):
+ ... | |
173565f7f2b9ffa548b355a0cbc8f972f1445a50 | tests/test_guess.py | tests/test_guess.py | from rdopkg import guess
from collections import namedtuple
import pytest
VersionTestCase = namedtuple('VersionTestCase', ('expected', 'input_data'))
data_table_good = [
VersionTestCase(('1.2.3', None), '1.2.3'),
VersionTestCase(('1.2.3', 'vX.Y.Z'), 'v1.2.3'),
VersionTestCase(('1.2.3', 'VX.Y.Z'), 'V1.2.3... | Add test coverage for rdopkg.guess version2tag and tag2version | Add test coverage for rdopkg.guess version2tag and tag2version
adding coverage unittest, there are some not well handled input cases
but better to capture existing behavior and update tests and code to
handle things better
Change-Id: I16dfb60886a1ac5ddfab86100e08ac23f8cf6c65
| Python | apache-2.0 | redhat-openstack/rdopkg,redhat-openstack/rdopkg,openstack-packages/rdopkg,openstack-packages/rdopkg | ---
+++
@@ -0,0 +1,58 @@
+from rdopkg import guess
+from collections import namedtuple
+import pytest
+
+VersionTestCase = namedtuple('VersionTestCase', ('expected', 'input_data'))
+
+
+data_table_good = [
+ VersionTestCase(('1.2.3', None), '1.2.3'),
+ VersionTestCase(('1.2.3', 'vX.Y.Z'), 'v1.2.3'),
+ Versio... | |
45cb6df45df84cb9ae85fc8aa15710bde6a15bad | nova/tests/functional/test_images.py | nova/tests/functional/test_images.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
# d... | Add create image functional negative tests | Add create image functional negative tests
The negative tests of create image API are not covered enough
in functional tests. We want to add the conflict tests of
when the create image API runs in the unexpected state
(e.g. not ACTIVE) of server.
Change-Id: I0c0b9e4d9ef1c5311113177dec46432f35b5ed63
| Python | apache-2.0 | rahulunair/nova,rahulunair/nova,mahak/nova,vmturbo/nova,klmitch/nova,hanlind/nova,openstack/nova,mikalstill/nova,jianghuaw/nova,klmitch/nova,hanlind/nova,vmturbo/nova,Juniper/nova,rajalokan/nova,Juniper/nova,klmitch/nova,gooddata/openstack-nova,rajalokan/nova,Juniper/nova,klmitch/nova,rajalokan/nova,phenoxim/nova,mahak... | ---
+++
@@ -0,0 +1,60 @@
+# 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 agr... | |
c6f6278c1915ef90e8825f94cc33a4dea4124722 | network/http_server_cat.py | network/http_server_cat.py | #!/bin/env python3
import http.server
import string
import click
import pathlib
import urllib.parse
import os
@click.command()
@click.argument("port", required=False)
@click.option("-s", "--server", default="0.0.0.0")
def main(port, server):
if not port:
port = 8888
http_server = http.server.HTTPServe... | Add http directory listing with content display | Add http directory listing with content display
| Python | mit | dgengtek/scripts,dgengtek/scripts | ---
+++
@@ -0,0 +1,74 @@
+#!/bin/env python3
+import http.server
+import string
+import click
+import pathlib
+import urllib.parse
+import os
+
+
+@click.command()
+@click.argument("port", required=False)
+@click.option("-s", "--server", default="0.0.0.0")
+def main(port, server):
+ if not port:
+ port = 88... | |
6dfc5a3d7845633570b83aac06c47756292cf8ac | st2common/tests/unit/test_db_model_uids.py | st2common/tests/unit/test_db_model_uids.py | # contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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 ... | Add tests for get_uid() method for common DB models. | Add tests for get_uid() method for common DB models.
| Python | apache-2.0 | dennybaa/st2,StackStorm/st2,pixelrebel/st2,Itxaka/st2,Plexxi/st2,pixelrebel/st2,nzlosh/st2,punalpatel/st2,nzlosh/st2,Itxaka/st2,emedvedev/st2,dennybaa/st2,tonybaloney/st2,Plexxi/st2,punalpatel/st2,peak6/st2,dennybaa/st2,StackStorm/st2,tonybaloney/st2,peak6/st2,StackStorm/st2,StackStorm/st2,armab/st2,alfasin/st2,nzlosh/... | ---
+++
@@ -0,0 +1,47 @@
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+#... | |
8b4bbd23bf37fb946b664f5932e4903f802c6e0d | flake8/tests/test_integration.py | flake8/tests/test_integration.py | from __future__ import with_statement
import os
import unittest
try:
from unittest import mock
except ImportError:
import mock # < PY33
from flake8 import engine
class IntegrationTestCase(unittest.TestCase):
"""Integration style tests to exercise different command line options."""
def this_file(se... | Add first pass at integration style tests | Add first pass at integration style tests
In order to better prevent regressions (such as related to concurrency),
Add a integration test framework to simulate running flake8 with
arguments.
| Python | mit | wdv4758h/flake8,lericson/flake8 | ---
+++
@@ -0,0 +1,71 @@
+from __future__ import with_statement
+
+import os
+import unittest
+try:
+ from unittest import mock
+except ImportError:
+ import mock # < PY33
+
+from flake8 import engine
+
+
+class IntegrationTestCase(unittest.TestCase):
+ """Integration style tests to exercise different comma... | |
77af87198d1116b77df431d9139b30f76103dd64 | fellowms/migrations/0023_auto_20160617_1350.py | fellowms/migrations/0023_auto_20160617_1350.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-06-17 13:50
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fellowms', '0022_event_report_url'),
]
operations = [
migrations.AddField(
... | Add migration for latitute and longitude of event | Add migration for latitute and longitude of event
| Python | bsd-3-clause | softwaresaved/fat,softwaresaved/fat,softwaresaved/fat,softwaresaved/fat | ---
+++
@@ -0,0 +1,25 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.9.5 on 2016-06-17 13:50
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('fellowms', '0022_event_report_url'),
+ ]
+
+ oper... | |
b920f5aeecf7843fcc699db4a70a9a0f124fa198 | tests/test_protonate.py | tests/test_protonate.py | import propka.atom
import propka.protonate
def test_protonate_atom():
atom = propka.atom.Atom(
"HETATM 4479 V VO4 A1578 -19.097 16.967 0.500 1.00 17.21 V "
)
assert not atom.is_protonated
p = propka.protonate.Protonate()
p.protonate_atom(atom)
assert atom.is_proto... | Add unit test for protonate.py | Add unit test for protonate.py
| Python | lgpl-2.1 | jensengroup/propka | ---
+++
@@ -0,0 +1,13 @@
+import propka.atom
+import propka.protonate
+
+
+def test_protonate_atom():
+ atom = propka.atom.Atom(
+ "HETATM 4479 V VO4 A1578 -19.097 16.967 0.500 1.00 17.21 V "
+ )
+ assert not atom.is_protonated
+ p = propka.protonate.Protonate()
+ p.protona... | |
2bf763e39e91ef989c121bba420e4ae09ea0a569 | algorithms/diagonal_difference/kevin.py | algorithms/diagonal_difference/kevin.py | #!/usr/bin/env python
def get_matrix_row_from_input():
return [int(index) for index in input().strip().split(' ')]
n = int(input().strip())
primary_diag_sum = 0
secondary_diag_sum = 0
for row_count in range(n):
row = get_matrix_row_from_input()
primary_diag_sum += row[row_count]
secondary_diag_sum +... | Add Diagonal Difference HackerRank Problem | Add Diagonal Difference HackerRank Problem
* https://www.hackerrank.com/challenges/diagonal-difference
| Python | mit | PlattsSEC/HackerRank,PlattsSEC/HackerRank,PlattsSEC/HackerRank,PlattsSEC/HackerRank,PlattsSEC/HackerRank,PlattsSEC/HackerRank | ---
+++
@@ -0,0 +1,16 @@
+#!/usr/bin/env python
+
+
+def get_matrix_row_from_input():
+ return [int(index) for index in input().strip().split(' ')]
+
+
+n = int(input().strip())
+primary_diag_sum = 0
+secondary_diag_sum = 0
+for row_count in range(n):
+ row = get_matrix_row_from_input()
+ primary_diag_sum +=... | |
9e6a016c5a59b25199426f6825b2c83571997e68 | build/android/buildbot/tests/bb_run_bot_test.py | build/android/buildbot/tests/bb_run_bot_test.py | #!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import subprocess
import sys
BUILDBOT_DIR = os.path.join(os.path.dirname(__file__), '..')
sys.path.append(BUILDBOT_DIR)
... | #!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import subprocess
import sys
BUILDBOT_DIR = os.path.join(os.path.dirname(__file__), '..')
sys.path.append(BUILDBOT_DIR)
... | Refactor buildbot tests so that they can be used downstream. | [Android] Refactor buildbot tests so that they can be used downstream.
I refactored in the wrong way in r211209 (https://chromiumcodereview.appspot.com/18325030/). This CL fixes that. Note that r211209 is not broken; it is just not usable downstream.
BUG=249997
NOTRY=True
Review URL: https://chromiumcodereview.appsp... | Python | bsd-3-clause | ondra-novak/chromium.src,hgl888/chromium-crosswalk,jaruba/chromium.src,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,fujunwei/chromium-crosswalk,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,jaruba/chromium.src,ltilve/chromium,Ch... | ---
+++
@@ -11,24 +11,24 @@
sys.path.append(BUILDBOT_DIR)
import bb_run_bot
-def RunBotsWithTesting(bot_step_map):
+def RunBotProcesses(bot_process_map):
code = 0
- procs = [
- (bot, subprocess.Popen(
- [os.path.join(BUILDBOT_DIR, 'bb_run_bot.py'), '--bot-id', bot,
- '--testing'], stdou... |
eb9f9d8bfa5ea278e1fb39c59ed660a223b1f6a9 | api/__init__.py | api/__init__.py | from flask_sqlalchemy import SQLAlchemy
import connexion
from config import config
db = SQLAlchemy()
def create_app(config_name):
app = connexion.FlaskApp(__name__, specification_dir='swagger/')
app.add_api('swagger.yaml')
application = app.app
application.config.from_object(config[config_name])
... | Add flask api app creation to init | Add flask api app creation to init
| Python | mit | EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list | ---
+++
@@ -0,0 +1,18 @@
+from flask_sqlalchemy import SQLAlchemy
+import connexion
+
+from config import config
+
+db = SQLAlchemy()
+
+
+def create_app(config_name):
+ app = connexion.FlaskApp(__name__, specification_dir='swagger/')
+ app.add_api('swagger.yaml')
+ application = app.app
+ application.con... | |
24f21146b01ff75a244df40d1626c54883abeb1a | lib/helpers.py | lib/helpers.py | #! /usr/bin/env python2.7
import datetime
def typecast_json(o):
if isinstance(o, datetime.datetime) or isinstance(o, datetime.date):
return o.isoformat()
else:
return o
def split_dict(src, keys):
result = dict()
for k in set(src.keys()) & set(keys):
result[k] = src[k]
return result
| Add helper-lib for json object conversion and split dicts | Add helper-lib for json object conversion and split dicts
| Python | bsd-3-clause | UngaForskareStockholm/medlem2 | ---
+++
@@ -0,0 +1,15 @@
+#! /usr/bin/env python2.7
+
+import datetime
+
+def typecast_json(o):
+ if isinstance(o, datetime.datetime) or isinstance(o, datetime.date):
+ return o.isoformat()
+ else:
+ return o
+
+def split_dict(src, keys):
+ result = dict()
+ for k in set(src.keys()) & set(keys):
+ result[k] = src[... | |
0f5c0168b257436882f837e5d521cce46a740ad6 | finat/greek_alphabet.py | finat/greek_alphabet.py | """Translation table from utf-8 to greek variable names, taken from:
https://gist.github.com/piquadrat/765262#file-greek_alphabet-py
"""
def translate_symbol(symbol):
"""Translates utf-8 sub-strings into compilable variable names"""
name = symbol.decode("utf-8")
for k, v in greek_alphabet.iteritems():
... | Add symbol translator to make utf-8 variables compilable | Coffee: Add symbol translator to make utf-8 variables compilable
| Python | mit | FInAT/FInAT | ---
+++
@@ -0,0 +1,63 @@
+"""Translation table from utf-8 to greek variable names, taken from:
+https://gist.github.com/piquadrat/765262#file-greek_alphabet-py
+"""
+
+
+def translate_symbol(symbol):
+ """Translates utf-8 sub-strings into compilable variable names"""
+ name = symbol.decode("utf-8")
+ for k, ... | |
9e128fdd5af0598a233416de5a1e8f2d3a74fdc0 | spaces/migrations/0006_unique_space_document.py | spaces/migrations/0006_unique_space_document.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2015-12-15 02:12
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('spaces', '0005_document_space_doc'),
]
operations = [
migrations.AlterField(
... | Enforce unique paths and names | Enforce unique paths and names
| Python | mit | jgillick/Spaces,jgillick/Spaces,jgillick/Spaces,jgillick/Spaces,jgillick/Spaces,jgillick/Spaces | ---
+++
@@ -0,0 +1,29 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.9 on 2015-12-15 02:12
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('spaces', '0005_document_space_doc'),
+ ]
+
+ operat... | |
8249d33898500d9d39e8bee3d44d39c2a6034659 | scripts/create_overlays.py | scripts/create_overlays.py | """Varcan smart tool."""
import click
from dtoolcore import DataSet
@click.command()
@click.argument('dataset_uri')
@click.option('--config-path', type=click.Path(exists=True))
def main(dataset_uri, config_path=None):
dataset = DataSet.from_uri(dataset_uri, config_path=config_path)
def name_from_identifie... | Add script to create overlays | Add script to create overlays
| Python | mit | JIC-Image-Analysis/senescence-in-field,JIC-Image-Analysis/senescence-in-field,JIC-Image-Analysis/senescence-in-field | ---
+++
@@ -0,0 +1,29 @@
+"""Varcan smart tool."""
+
+import click
+
+from dtoolcore import DataSet
+
+
+@click.command()
+@click.argument('dataset_uri')
+@click.option('--config-path', type=click.Path(exists=True))
+def main(dataset_uri, config_path=None):
+
+ dataset = DataSet.from_uri(dataset_uri, config_path=c... | |
0ba11dd47dac04f3f7a314cf320558ccbc9eb148 | integration-test/1477-water-layer-too-big.py | integration-test/1477-water-layer-too-big.py | # -*- encoding: utf-8 -*-
from . import FixtureTest
class WaterLayerTooBigTest(FixtureTest):
def test_drop_label(self):
from tilequeue.tile import calc_meters_per_pixel_area
from shapely.ops import transform
from tilequeue.tile import reproject_mercator_to_lnglat
import math
... | Add test for water polygon name dropping. | Add test for water polygon name dropping.
| Python | mit | mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource | ---
+++
@@ -0,0 +1,56 @@
+# -*- encoding: utf-8 -*-
+from . import FixtureTest
+
+
+class WaterLayerTooBigTest(FixtureTest):
+
+ def test_drop_label(self):
+ from tilequeue.tile import calc_meters_per_pixel_area
+ from shapely.ops import transform
+ from tilequeue.tile import reproject_mercato... | |
865dc29421c1e9ef4bf340bf32164863cc5f2006 | app/raw/management/commands/list_spiders.py | app/raw/management/commands/list_spiders.py | from django.core.management import BaseCommand
from raw.utils import list_spiders
class Command(BaseCommand):
help = 'List installed spiders'
def handle(self, *args, **options):
for spider in list_spiders():
print spider
| Add management command to list installed spiders | Add management command to list installed spiders
| Python | mit | legco-watch/legco-watch,comsaint/legco-watch,legco-watch/legco-watch,comsaint/legco-watch,legco-watch/legco-watch,comsaint/legco-watch,comsaint/legco-watch,legco-watch/legco-watch | ---
+++
@@ -0,0 +1,10 @@
+from django.core.management import BaseCommand
+from raw.utils import list_spiders
+
+
+class Command(BaseCommand):
+ help = 'List installed spiders'
+
+ def handle(self, *args, **options):
+ for spider in list_spiders():
+ print spider | |
5f12ada7fe0ddb44274e18decbaea0d05ab4471f | CodeFights/lineUp.py | CodeFights/lineUp.py | #!/usr/local/bin/python
# Code Fights Lineup Problem
def lineUp(commands):
aligned, tmp = 0, 0
com_dict = {"L": 1, "A": 0, "R": -1}
for c in commands:
tmp += com_dict[c]
if tmp % 2 == 0:
aligned += 1
return aligned
def main():
tests = [
["LLARL", 3],
[... | Solve Code Fights lineup problem | Solve Code Fights lineup problem
| Python | mit | HKuz/Test_Code | ---
+++
@@ -0,0 +1,39 @@
+#!/usr/local/bin/python
+# Code Fights Lineup Problem
+
+
+def lineUp(commands):
+ aligned, tmp = 0, 0
+ com_dict = {"L": 1, "A": 0, "R": -1}
+ for c in commands:
+ tmp += com_dict[c]
+ if tmp % 2 == 0:
+ aligned += 1
+ return aligned
+
+
+def main():
+ ... | |
c486b8df5861fd883b49ea8118d40d73f5b4e7b8 | tardis/tardis_portal/tests/test_download_apikey.py | tardis/tardis_portal/tests/test_download_apikey.py | # -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.test import TestCase
from tastypie.test import ResourceTestCase
from django.test.client import Client
from django.conf import settings
from django.contrib.auth.models import User
class ApiKeyDownloadTestCase(ResourceTestCase):
def ... | Add download apikey test case | Add download apikey test case
| Python | bsd-3-clause | pansapiens/mytardis,pansapiens/mytardis,pansapiens/mytardis,pansapiens/mytardis | ---
+++
@@ -0,0 +1,45 @@
+# -*- coding: utf-8 -*-
+
+from django.core.urlresolvers import reverse
+from django.test import TestCase
+from tastypie.test import ResourceTestCase
+from django.test.client import Client
+
+from django.conf import settings
+from django.contrib.auth.models import User
+
+class ApiKeyDownloa... | |
65f6f78008d4f961c9ebe5d8047b0f2c742fe15f | tests/qtgui/qinputdialog_get_test.py | tests/qtgui/qinputdialog_get_test.py | import unittest
from PySide import QtCore, QtGui
from helper import UsesQApplication, TimedQApplication
class TestInputDialog(TimedQApplication):
def testGetDouble(self):
QtGui.QInputDialog.getDouble(None, "title", "label")
def testGetInt(self):
QtGui.QInputDialog.getInt(None, "title", "labe... | Add unittest for QInputDialog.getXXX() methods | Add unittest for QInputDialog.getXXX() methods
| Python | lgpl-2.1 | RobinD42/pyside,RobinD42/pyside,enthought/pyside,BadSingleton/pyside2,M4rtinK/pyside-bb10,pankajp/pyside,BadSingleton/pyside2,M4rtinK/pyside-android,IronManMark20/pyside2,pankajp/pyside,BadSingleton/pyside2,pankajp/pyside,gbaty/pyside2,RobinD42/pyside,qtproject/pyside-pyside,M4rtinK/pyside-android,M4rtinK/pyside-bb10,M... | ---
+++
@@ -0,0 +1,25 @@
+import unittest
+
+from PySide import QtCore, QtGui
+from helper import UsesQApplication, TimedQApplication
+
+class TestInputDialog(TimedQApplication):
+
+ def testGetDouble(self):
+ QtGui.QInputDialog.getDouble(None, "title", "label")
+
+ def testGetInt(self):
+ QtGui.Q... | |
52189e2161e92b36df47a04c2150dff38f81f5e9 | tests/unit/tests/test_activations.py | tests/unit/tests/test_activations.py | from unittest import mock
from django.test import TestCase
from viewflow import activation, flow
from viewflow.models import Task
class TestActivations(TestCase):
def test_start_activation_lifecycle(self):
flow_task_mock = mock.Mock(spec=flow.Start())
act = activation.StartActivation()
a... | Add mocked tests for activation | Add mocked tests for activation
| Python | agpl-3.0 | pombredanne/viewflow,ribeiro-ucl/viewflow,codingjoe/viewflow,codingjoe/viewflow,pombredanne/viewflow,viewflow/viewflow,viewflow/viewflow,viewflow/viewflow,ribeiro-ucl/viewflow,codingjoe/viewflow,ribeiro-ucl/viewflow | ---
+++
@@ -0,0 +1,41 @@
+from unittest import mock
+from django.test import TestCase
+
+from viewflow import activation, flow
+from viewflow.models import Task
+
+
+class TestActivations(TestCase):
+ def test_start_activation_lifecycle(self):
+ flow_task_mock = mock.Mock(spec=flow.Start())
+
+ act =... | |
27cb9279670bd513a1559f4865500d84869bb9f0 | tests/test_predictor.py | tests/test_predictor.py | #! /usr/env/bin python
import numpy as np
from pyboas import predictor, models
# Build random 3-parameter normal posterior.
posterior = np.random.randn(100, 3)
def toy_model(param, time):
time = np.atleast_1d(time)[:, np.newaxis]
a = param[:, 0]
b = param[:, 1]
c = param[:, 2]
return a*time**2... | Test module for Predictor class. | Test module for Predictor class.
| Python | mit | exord/pyboas | ---
+++
@@ -0,0 +1,94 @@
+#! /usr/env/bin python
+import numpy as np
+
+from pyboas import predictor, models
+
+# Build random 3-parameter normal posterior.
+posterior = np.random.randn(100, 3)
+
+
+def toy_model(param, time):
+ time = np.atleast_1d(time)[:, np.newaxis]
+
+ a = param[:, 0]
+ b = param[:, 1]
... | |
34d5b5cdc058f1c9055b82151b518251fa3b4f74 | tools/join-contracts.py | tools/join-contracts.py | import os
import click
import re
from click.types import File
IMPORT_RE = re.compile(r'^import +["\'](?P<contract>[^"\']+.sol)["\'];$')
"""
Utility to join solidity contracts into a single output file by recursively
resolving imports.
example usage:
$ cd raiden/smart_contracts
$ python ../../tools/join-contracts.p... | Add tool to create combined smart contract files | Add tool to create combined smart contract files
Useful for various cases where a single source file is needed e.g. when
verifying contracts on etherscan.
| Python | mit | tomashaber/raiden,hackaugusto/raiden,tomashaber/raiden,tomashaber/raiden,hackaugusto/raiden,tomashaber/raiden,tomashaber/raiden | ---
+++
@@ -0,0 +1,62 @@
+import os
+
+import click
+import re
+from click.types import File
+
+IMPORT_RE = re.compile(r'^import +["\'](?P<contract>[^"\']+.sol)["\'];$')
+
+"""
+Utility to join solidity contracts into a single output file by recursively
+resolving imports.
+
+example usage:
+
+$ cd raiden/smart_contr... | |
e06416a61826229ebd0cccdc519b6dc39d8a0fd9 | server/migrations/0088_auto_20190304_1313.py | server/migrations/0088_auto_20190304_1313.py | # Generated by Django 2.1.4 on 2019-03-04 18:13
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('server', '0087_auto_20190301_1424'),
]
operations = [
migrations.AlterUniqueTogether(
name='installedupdate',
unique_togethe... | Add migration to remove models. | Add migration to remove models.
| Python | apache-2.0 | sheagcraig/sal,sheagcraig/sal,sheagcraig/sal,salopensource/sal,salopensource/sal,salopensource/sal,salopensource/sal,sheagcraig/sal | ---
+++
@@ -0,0 +1,53 @@
+# Generated by Django 2.1.4 on 2019-03-04 18:13
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('server', '0087_auto_20190301_1424'),
+ ]
+
+ operations = [
+ migrations.AlterUniqueTogether(
+ name='ins... | |
66137a8710bf3b778c860af8d6278ee0c97bbab4 | scripts/delete-unused-users.py | scripts/delete-unused-users.py | #!/usr/bin/env python3
"""
Delete unused users from a JupyterHub.
JupyterHub performance sometimes scales with *total* number
of users, rather than running number of users. While that should
be fixed, we can work around it by deleting unused users once in
a while. This script will delete anyone who hasn't registered
a... | Add script to delete unused users on JupyterHub | Add script to delete unused users on JupyterHub
Note that this doesn't actually delete their home directories
or any data - just the entry in the JupyterHub DB. As soon as
they log in again, a new entry is created.
This is really just a performance optimization.
| Python | bsd-3-clause | ryanlovett/datahub,berkeley-dsep-infra/datahub,ryanlovett/datahub,berkeley-dsep-infra/datahub,berkeley-dsep-infra/datahub,ryanlovett/datahub | ---
+++
@@ -0,0 +1,50 @@
+#!/usr/bin/env python3
+"""
+Delete unused users from a JupyterHub.
+
+JupyterHub performance sometimes scales with *total* number
+of users, rather than running number of users. While that should
+be fixed, we can work around it by deleting unused users once in
+a while. This script will de... | |
5a77678a44ec9838e943b514a586dbd96b8bdfdc | modelview/migrations/0042_auto_20171215_0953.py | modelview/migrations/0042_auto_20171215_0953.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-12-15 08:53
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('modelview', '0041_merge_20171211_1420'),
]
operations = [
migrations.AlterF... | Add migration for license change | Add migration for license change
| Python | agpl-3.0 | openego/oeplatform,tom-heimbrodt/oeplatform,openego/oeplatform,openego/oeplatform,tom-heimbrodt/oeplatform,tom-heimbrodt/oeplatform,openego/oeplatform | ---
+++
@@ -0,0 +1,19 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.10.5 on 2017-12-15 08:53
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('modelview', '0041_merge_20171211_1420'),
+ ]
+
+ ... | |
f5970d1488d28f27c5f20dd11619187d0c13c960 | os/win_registry.py | os/win_registry.py | import _winreg
keyName = "myKey"
def write_to_registry():
try:
key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, "Software\\" + keyName)
_winreg.SetValueEx(key, "myVal", 0, _winreg.REG_SZ, "This is a value.")
print("value created")
except Exception as e:
print(e)
def read_f... | Add simple windows registry read/write functions | Add simple windows registry read/write functions
| Python | mit | ddubson/code-dojo-py | ---
+++
@@ -0,0 +1,27 @@
+import _winreg
+
+keyName = "myKey"
+
+
+def write_to_registry():
+ try:
+ key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, "Software\\" + keyName)
+ _winreg.SetValueEx(key, "myVal", 0, _winreg.REG_SZ, "This is a value.")
+ print("value created")
+ except Excepti... | |
1de668219f618a0632fac80fd892a0a229b8fa05 | CodeFights/additionWithoutCarrying.py | CodeFights/additionWithoutCarrying.py | #!/usr/local/bin/python
# Code Fights Addition Without Carrying Problem
def additionWithoutCarrying(param1, param2):
s1, s2 = str(param1), str(param2)
shorter = s1 if len(s1) < len(s2) else s2
longer = s2 if shorter == s1 else s1
if len(shorter) < len(longer):
shorter = shorter.zfill(len(longe... | Solve Code Fights addition without carrying problem | Solve Code Fights addition without carrying problem
| Python | mit | HKuz/Test_Code | ---
+++
@@ -0,0 +1,36 @@
+#!/usr/local/bin/python
+# Code Fights Addition Without Carrying Problem
+
+
+def additionWithoutCarrying(param1, param2):
+ s1, s2 = str(param1), str(param2)
+ shorter = s1 if len(s1) < len(s2) else s2
+ longer = s2 if shorter == s1 else s1
+ if len(shorter) < len(longer):
+ ... | |
7f4bd900d1e647fe017ce4c01e279dd41a71a349 | lms/djangoapps/verify_student/management/commands/set_software_secure_status.py | lms/djangoapps/verify_student/management/commands/set_software_secure_status.py | """
Manually set Software Secure verification status.
"""
import sys
from django.core.management.base import BaseCommand
from verify_student.models import (
SoftwareSecurePhotoVerification, VerificationCheckpoint, VerificationStatus
)
class Command(BaseCommand):
"""
Command to trigger the actions that w... | Add management command to set SoftwareSecure verification status. | Add management command to set SoftwareSecure verification status.
| Python | agpl-3.0 | procangroup/edx-platform,fintech-circle/edx-platform,devs1991/test_edx_docmode,a-parhom/edx-platform,pomegranited/edx-platform,zubair-arbi/edx-platform,JCBarahona/edX,naresh21/synergetics-edx-platform,jjmiranda/edx-platform,a-parhom/edx-platform,deepsrijit1105/edx-platform,IONISx/edx-platform,mitocw/edx-platform,zubair... | ---
+++
@@ -0,0 +1,60 @@
+"""
+Manually set Software Secure verification status.
+"""
+
+import sys
+
+from django.core.management.base import BaseCommand
+from verify_student.models import (
+ SoftwareSecurePhotoVerification, VerificationCheckpoint, VerificationStatus
+)
+
+
+class Command(BaseCommand):
+ """
... | |
4dd66150c922e1c700fad74727955ef72c045f37 | minecraft/FindCommand.py | minecraft/FindCommand.py | # MCEdit filter
from albow import alert
displayName = "Find Command"
inputs = (
("Command:", ("string", "value=")),
)
def perform(level, box, options):
command = options["Command:"]
n = 0
result = ""
for (chunk, slices, point) in level.getChunkSlices(box):
for e in chunk.TileEntities:
... | Add Find Command MCEdit filter | Add Find Command MCEdit filter
| Python | mit | satgo1546/dot-product,satgo1546/dot-product,satgo1546/dot-product,satgo1546/dot-product,satgo1546/dot-product | ---
+++
@@ -0,0 +1,28 @@
+# MCEdit filter
+
+from albow import alert
+
+displayName = "Find Command"
+
+inputs = (
+ ("Command:", ("string", "value=")),
+)
+
+def perform(level, box, options):
+ command = options["Command:"]
+ n = 0
+ result = ""
+ for (chunk, slices, point) in level.getChunkSlices(box... | |
eea33e6207da7446e1713eb4d78b76d37ae5eaf2 | with_celery.py | with_celery.py | from celery import Celery
# The host in which RabbitMQ is running
HOST = 'amqp://guest@localhost'
app = Celery('pages_celery', broker=HOST)
@app.task
def work(msg):
print msg
# To execute the task:
#
# $ python
# >>> from with_celery import work
# >>> work.delay('Hi there!!')
| Add sample of scheduler using celery | Add sample of scheduler using celery
| Python | apache-2.0 | jovannypcg/python_scheduler | ---
+++
@@ -0,0 +1,16 @@
+from celery import Celery
+
+# The host in which RabbitMQ is running
+HOST = 'amqp://guest@localhost'
+
+app = Celery('pages_celery', broker=HOST)
+
+@app.task
+def work(msg):
+ print msg
+
+# To execute the task:
+#
+# $ python
+# >>> from with_celery import work
+# >>> work.delay('Hi th... | |
b4b2b80cb1d0c0729e8e98085c2cfc3bc55ddda3 | LongestLines.py | LongestLines.py | # Longest Lines
#
# https://www.codeeval.com/open_challenges/2/
#
# Challenge Description: Write a program which reads a file and prints to
# stdout the specified number of the longest lines that are sorted based on
# their length in descending order.
import sys
input_file = sys.argv[1]
with open(input_file, 'r') a... | Solve the Longest Lines challenge using Python3 | Solve the Longest Lines challenge using Python3
| Python | mit | TommyN94/CodeEvalSolutions,TommyN94/CodeEvalSolutions | ---
+++
@@ -0,0 +1,20 @@
+# Longest Lines
+#
+# https://www.codeeval.com/open_challenges/2/
+#
+# Challenge Description: Write a program which reads a file and prints to
+# stdout the specified number of the longest lines that are sorted based on
+# their length in descending order.
+import sys
+
+
+input_file = sy... | |
37e674f05547c7b6b93f447477443644865975d1 | urls.py | urls.py | __author__ = 'ankesh'
from django.conf.urls import patterns, include, url
from django.http import HttpResponseRedirect
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'upload.views.home', name='home')... | Bring back the Root URL config | Bring back the Root URL config
The file was probably deleted by a mistake, we need it, so took it back.
| Python | bsd-2-clause | ankeshanand/benchmark,ankeshanand/benchmark,ankeshanand/benchmark,ankeshanand/benchmark | ---
+++
@@ -0,0 +1,27 @@
+__author__ = 'ankesh'
+from django.conf.urls import patterns, include, url
+from django.http import HttpResponseRedirect
+
+# Uncomment the next two lines to enable the admin:
+from django.contrib import admin
+admin.autodiscover()
+
+urlpatterns = patterns('',
+ # Examples:
+ # url(r'... | |
90399f50a3f50d9193ae1e6b2042215fb388230f | VideoStream.py | VideoStream.py | import cv2
import numpy as np
cap = cv2.VideoCapture(0)
print('Beginning Capture Device opening...\n')
print('Capture device opened?', cap.isOpened())
while True:
ret, frame = cap.read()
gray_image = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame', gray_image)
if cv2.wait... | Create Video Stream program for webcam | Create Video Stream program for webcam
| Python | apache-2.0 | SentientCNC/Sentient-CNC | ---
+++
@@ -0,0 +1,21 @@
+import cv2
+import numpy as np
+
+cap = cv2.VideoCapture(0)
+
+print('Beginning Capture Device opening...\n')
+print('Capture device opened?', cap.isOpened())
+
+while True:
+
+ ret, frame = cap.read()
+ gray_image = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
+
+ cv2.imshow('frame', gr... | |
1437bb868844731d3fdb13c6dd52dfd706df6f63 | bin/ext_service/clean_habitica_user.py | bin/ext_service/clean_habitica_user.py | import argparse
import sys
import logging
import emission.core.get_database as edb
import emission.net.ext_service.habitica.proxy as proxy
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
parser = argparse.ArgumentParser()
parser.add_argument("user_email",
help="the email addre... | Add a new script to clean up a habitica user given user email | Add a new script to clean up a habitica user given user email
- Looks up uuid
- uses that to lookup password
- calls delete method
Simple!
| Python | bsd-3-clause | sunil07t/e-mission-server,shankari/e-mission-server,sunil07t/e-mission-server,yw374cornell/e-mission-server,e-mission/e-mission-server,yw374cornell/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,yw374cornell/e-mission-server,shankari/e-mission-server,yw374cornell/e-miss... | ---
+++
@@ -0,0 +1,23 @@
+import argparse
+import sys
+import logging
+
+import emission.core.get_database as edb
+import emission.net.ext_service.habitica.proxy as proxy
+
+if __name__ == '__main__':
+ logging.basicConfig(level=logging.DEBUG)
+
+ parser = argparse.ArgumentParser()
+ parser.add_argument("use... | |
83d4ac6c3565044727c9b3fcbada9966d529a80e | lib/font_loader.py | lib/font_loader.py | import os
import sys
import logging
FONT_FILE_NAME_LIST = (
"fontawesome-webfont.ttf",
)
FONT_DIRECTORY = "share"
FONT_DIRECTORY_SYSTEM = "/usr/share/fonts"
FONT_DIRECTORY_USER = os.path.join(os.environ['HOME'], ".local/share/fonts")
class FontLoader:
def __init__(self):
self.fonts_loaded... | Add forgotten font leader lib | Add forgotten font leader lib
| Python | mit | Nadeflore/dakara-player-vlc | ---
+++
@@ -0,0 +1,65 @@
+import os
+import sys
+import logging
+
+FONT_FILE_NAME_LIST = (
+ "fontawesome-webfont.ttf",
+ )
+
+FONT_DIRECTORY = "share"
+FONT_DIRECTORY_SYSTEM = "/usr/share/fonts"
+FONT_DIRECTORY_USER = os.path.join(os.environ['HOME'], ".local/share/fonts")
+
+class FontLoader:
+ def ... | |
151e8fc71e5ef2e31db13730bff57bc8fd915c30 | paystackapi/tests/test_invoice.py | paystackapi/tests/test_invoice.py | import httpretty
from paystackapi.tests.base_test_case import BaseTestCase
from paystackapi.invoice import Invoice
class TestInvoice(BaseTestCase):
@httpretty.activate
def test_create_invoice(self):
"""Method defined to test create Invoice."""
httpretty.register_uri(
httpretty.PO... | Add test case for list invoice | Add test case for list invoice
| Python | mit | andela-sjames/paystack-python | ---
+++
@@ -0,0 +1,45 @@
+import httpretty
+
+from paystackapi.tests.base_test_case import BaseTestCase
+from paystackapi.invoice import Invoice
+
+
+class TestInvoice(BaseTestCase):
+
+ @httpretty.activate
+ def test_create_invoice(self):
+ """Method defined to test create Invoice."""
+ httpretty... | |
dcd1d962feec4f3cd914677545f74924ad9e6351 | testing/test_direct_wrapper.py | testing/test_direct_wrapper.py | import os
from cffitsio._cfitsio import ffi, lib
def test_create_file(tmpdir):
filename = str(tmpdir.join('test.fits'))
f = ffi.new('fitsfile **')
status = ffi.new('int *')
lib.fits_create_file(f, filename, status)
assert status[0] == 0
assert os.path.isfile(filename)
| Add test for file creation of low level library | Add test for file creation of low level library
| Python | mit | mindriot101/fitsio-cffi | ---
+++
@@ -0,0 +1,12 @@
+import os
+
+from cffitsio._cfitsio import ffi, lib
+
+
+def test_create_file(tmpdir):
+ filename = str(tmpdir.join('test.fits'))
+ f = ffi.new('fitsfile **')
+ status = ffi.new('int *')
+ lib.fits_create_file(f, filename, status)
+ assert status[0] == 0
+ assert os.path.is... | |
e426afbe9ccbc72a1aa0d00032144e8b9b2b8cdc | gusset/colortable.py | gusset/colortable.py | """
Pretty table generation.
"""
from itertools import cycle
from string import capwords
from fabric.colors import red, green, blue, magenta, white, yellow
class ColorRow(dict):
"""
Ordered collection of column values.
"""
def __init__(self, table, **kwargs):
super(ColorRow, self).__init__(sel... | Implement utility for colored, tabular output using fabric's color controls. | Implement utility for colored, tabular output using fabric's color controls.
| Python | apache-2.0 | locationlabs/gusset | ---
+++
@@ -0,0 +1,84 @@
+"""
+Pretty table generation.
+"""
+from itertools import cycle
+from string import capwords
+from fabric.colors import red, green, blue, magenta, white, yellow
+
+
+class ColorRow(dict):
+ """
+ Ordered collection of column values.
+ """
+ def __init__(self, table, **kwargs):
+ ... | |
0882c8885b88618ea55b97ace256cdf833a1547d | tests/test_pylama_isort.py | tests/test_pylama_isort.py | import os
from isort.pylama_isort import Linter
class TestLinter:
instance = Linter()
def test_allow(self):
assert not self.instance.allow("test_case.pyc")
assert not self.instance.allow("test_case.c")
assert self.instance.allow("test_case.py")
def test_run(self, src_dir, tmpdir... | Add tests for pylama isort | Add tests for pylama isort
| Python | mit | PyCQA/isort,PyCQA/isort | ---
+++
@@ -0,0 +1,19 @@
+import os
+
+from isort.pylama_isort import Linter
+
+
+class TestLinter:
+ instance = Linter()
+
+ def test_allow(self):
+ assert not self.instance.allow("test_case.pyc")
+ assert not self.instance.allow("test_case.c")
+ assert self.instance.allow("test_case.py")
... | |
280e72331d99a8c49783196951287627a933a659 | py/repeated-substring-pattern.py | py/repeated-substring-pattern.py | class Solution(object):
def repeatedSubstringPattern(self, s):
"""
:type s: str
:rtype: bool
"""
for i in xrange(1, len(s) / 2 + 1):
if len(s) % i == 0 and len(set(s[j:j+i] for j in xrange(0, len(s), i))) == 1:
return True
return False
| Add py solution for 459. Repeated Substring Pattern | Add py solution for 459. Repeated Substring Pattern
459. Repeated Substring Pattern: https://leetcode.com/problems/repeated-substring-pattern/
| Python | apache-2.0 | ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode | ---
+++
@@ -0,0 +1,10 @@
+class Solution(object):
+ def repeatedSubstringPattern(self, s):
+ """
+ :type s: str
+ :rtype: bool
+ """
+ for i in xrange(1, len(s) / 2 + 1):
+ if len(s) % i == 0 and len(set(s[j:j+i] for j in xrange(0, len(s), i))) == 1:
+ r... | |
75dc32ef71fd32c7728269b01a74faf840690473 | examples/too_slow_bot.py | examples/too_slow_bot.py | import random
import asyncio
import sc2
from sc2 import Race, Difficulty
from sc2.constants import *
from sc2.player import Bot, Computer
from proxy_rax import ProxyRaxBot
class SlowBot(ProxyRaxBot):
async def on_step(self, state, iteration):
await asyncio.sleep(random.random())
await super().on_... | Add a slow bot to test timeout feature | Add a slow bot to test timeout feature
| Python | mit | Dentosal/python-sc2 | ---
+++
@@ -0,0 +1,23 @@
+import random
+import asyncio
+
+import sc2
+from sc2 import Race, Difficulty
+from sc2.constants import *
+from sc2.player import Bot, Computer
+
+from proxy_rax import ProxyRaxBot
+
+class SlowBot(ProxyRaxBot):
+ async def on_step(self, state, iteration):
+ await asyncio.sleep(ra... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.