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 |
|---|---|---|---|---|---|---|---|---|---|---|
a08e7d9949059b95b2eda16c94f0a3fd8853dc73 | src/run_algorithm.py | src/run_algorithm.py | import argparse
from project import corpus, knn_corpus, lda_corpus, word2vec_corpus
algorithms = {"lda": lda_corpus.LDACorpus,
"knn": knn_corpus.KNNCorpus,
"w2v": word2vec_corpus.W2VCorpus}
def main():
parser = argparse.ArgumentParser(description='Build bow corpus on the arxiv corpus.'... | Add script to apply algorithms to corpus | Add script to apply algorithms to corpus
| Python | mit | PinPinIre/Final-Year-Project,PinPinIre/Final-Year-Project,PinPinIre/Final-Year-Project | ---
+++
@@ -0,0 +1,20 @@
+import argparse
+from project import corpus, knn_corpus, lda_corpus, word2vec_corpus
+
+algorithms = {"lda": lda_corpus.LDACorpus,
+ "knn": knn_corpus.KNNCorpus,
+ "w2v": word2vec_corpus.W2VCorpus}
+
+def main():
+ parser = argparse.ArgumentParser(description='Bu... | |
d8fab96a12047969971b5d777408177b87eb578a | geotrek/tourism/tests/test_forms.py | geotrek/tourism/tests/test_forms.py |
from django.test import TestCase
from geotrek.authent.tests.factories import UserFactory
from geotrek.tourism.forms import TouristicEventForm
class PathFormTest(TestCase):
def test_begin_end_date(self):
user = UserFactory()
form1 = TouristicEventForm(
user=user,
data={
... | Add test form error when begin date is after end date | Add test form error when begin date is after end date
| Python | bsd-2-clause | GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin | ---
+++
@@ -0,0 +1,20 @@
+
+from django.test import TestCase
+
+from geotrek.authent.tests.factories import UserFactory
+from geotrek.tourism.forms import TouristicEventForm
+
+
+class PathFormTest(TestCase):
+ def test_begin_end_date(self):
+ user = UserFactory()
+ form1 = TouristicEventForm(
+ ... | |
0f0c3bb7b54c69bf121c11ea0d8e5a0b259bfb15 | test/trainer_test.py | test/trainer_test.py | import theanets
import util
class TestTrainer(util.MNIST):
def setUp(self):
super(TestTrainer, self).setUp()
self.exp = theanets.Experiment(
theanets.Autoencoder,
layers=(self.DIGIT_SIZE, 10, self.DIGIT_SIZE))
def assert_progress(self, algo, **kwargs):
trainer... | import theanets
import util
class TestTrainer(util.MNIST):
def setUp(self):
super(TestTrainer, self).setUp()
self.exp = theanets.Experiment(
theanets.Autoencoder,
layers=(self.DIGIT_SIZE, 10, self.DIGIT_SIZE))
def assert_progress(self, algo, **kwargs):
trainer... | Exclude hf from tested trainers. :-/ | Exclude hf from tested trainers. :-/
| Python | mit | lmjohns3/theanets,chrinide/theanets,devdoer/theanets | ---
+++
@@ -32,9 +32,6 @@
def test_adadelta(self):
self.assert_progress('adadelta', learning_rate=1e-4)
- def test_hf(self):
- self.assert_progress('hf', num_updates=3)
-
def test_cg(self):
self.assert_progress('cg')
|
9c504147511c7f1fadcb1effb61f482cd4fe132e | tests/test_runner.py | tests/test_runner.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from multiprocessing import Lock
import git
import mock
import pytest
from badwolf.runner import TestContext, TestRunner
@pytest.fixture(scope='function')
def push_context():
return TestContext(
'deepanalyzer/badwolf',
... | Add basic runner tests, will add more later | Add basic runner tests, will add more later
| Python | mit | bosondata/badwolf,bosondata/badwolf,bosondata/badwolf | ---
+++
@@ -0,0 +1,40 @@
+# -*- coding: utf-8 -*-
+from __future__ import absolute_import, unicode_literals
+from multiprocessing import Lock
+
+import git
+import mock
+import pytest
+
+from badwolf.runner import TestContext, TestRunner
+
+
+@pytest.fixture(scope='function')
+def push_context():
+ return TestCont... | |
d57bf8b0995496d8cabc81410154ab64a0673e01 | databroker/sources/dummy_sources/_metadataStore/api/analysis.py | databroker/sources/dummy_sources/_metadataStore/api/analysis.py | headers = []
beamline_configs = []
event_descriptors = []
events = []
def find2(header_id=None, scan_id=None, owner=None, start_time=None,
beamline_id=None, end_time=None):
return {'headers': headers, 'beamline_configs': beamline_configs,
'event_descriptors': event_descriptors, 'events': eve... | from datetime import datetime as dt
class DummyEventDescriptor(object):
def __init__(self):
self.keys = {'temp': {'source': 'PV:blah'},
'picture': {'source': 'CCD:blah',
'external': 'FILESTORE!!!!'}}
class DummyEvent(object):
def __init__(self):
... | Update dummy MDS to use find and return a list of events. | Update dummy MDS to use find and return a list of events.
| Python | bsd-3-clause | ericdill/databroker,NSLS-II/datamuxer,ericdill/datamuxer,NSLS-II/dataportal,NSLS-II/dataportal,ericdill/databroker,danielballan/datamuxer,danielballan/dataportal,danielballan/dataportal,tacaswell/dataportal,ericdill/datamuxer,tacaswell/dataportal,danielballan/datamuxer | ---
+++
@@ -1,10 +1,22 @@
-headers = []
-beamline_configs = []
-event_descriptors = []
-events = []
+from datetime import datetime as dt
-def find2(header_id=None, scan_id=None, owner=None, start_time=None,
- beamline_id=None, end_time=None):
- return {'headers': headers, 'beamline_configs': beamline_... |
45b91fd2cf8c679ba791e6f96c1e51d2a7ef4082 | python/31_bfs_dfs/graph_application.py | python/31_bfs_dfs/graph_application.py | # -*- coding:utf-8 -*-
from collections import deque
from graph import Undigraph
def find_vertex_by_degree(graph, s, degree):
if len(graph) <= 1:
return []
if degree == 0:
return [s]
d_vertices = []
queue = deque()
prev = [-1] * len(graph)
visited = [False] * len(graph)
v... | Add function , which is to find all the vertices of one vertex given the specific degree by using broad first search policy | Add function , which is to find all the vertices of one vertex given the specific degree by using broad first search policy
| Python | apache-2.0 | wangzheng0822/algo,wangzheng0822/algo,wangzheng0822/algo,wangzheng0822/algo,wangzheng0822/algo,wangzheng0822/algo,wangzheng0822/algo,wangzheng0822/algo,wangzheng0822/algo,wangzheng0822/algo,wangzheng0822/algo,wangzheng0822/algo,wangzheng0822/algo,wangzheng0822/algo | ---
+++
@@ -0,0 +1,45 @@
+# -*- coding:utf-8 -*-
+
+
+
+from collections import deque
+from graph import Undigraph
+
+def find_vertex_by_degree(graph, s, degree):
+ if len(graph) <= 1:
+ return []
+ if degree == 0:
+ return [s]
+ d_vertices = []
+ queue = deque()
+ prev = [-1] * len(graph... | |
0ce164529f0b53dd25b4cc6b0c66fb8bbecc6ef5 | test/create_image.py | test/create_image.py | import Image
from PIL import Image
import ImageFont
img = Image.new("RGB", (1250, 480), (255, 255, 255))
import ImageDraw
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("/System/Library/Fonts/Monaco.dfont", 20, encoding="armn")
draw.text((20, 20), "<- 10 ->" * 10, font=font, fill="black")
draw.text((20, 40), "... | Test script for playing with PIL | Test script for playing with PIL
| Python | mit | hugs/detour | ---
+++
@@ -0,0 +1,10 @@
+import Image
+from PIL import Image
+import ImageFont
+img = Image.new("RGB", (1250, 480), (255, 255, 255))
+import ImageDraw
+draw = ImageDraw.Draw(img)
+font = ImageFont.truetype("/System/Library/Fonts/Monaco.dfont", 20, encoding="armn")
+draw.text((20, 20), "<- 10 ->" * 10, font=font, ... | |
5c201b159d844e317c60665180760e8ecad957a2 | server/tests/test_api.py | server/tests/test_api.py | from server.tests.base import BaseTestCase
from server.models import db, Lecturer, Course, Lecture, Comment
import json
class GetCommentsApiTest(BaseTestCase):
def setUp(self):
super(GetCommentsApiTest, self).setUp()
simon = Lecturer('Simon', 'McCallum')
db.session.add(simon)
imt3... | Add tests for 'get comments' API | Add tests for 'get comments' API
Note that because of a bug in the testing setup the tests will fail when there are more than one.
Each individual test has been successfully tested.
| Python | mit | MACSIFS/IFS,MACSIFS/IFS,MACSIFS/IFS,MACSIFS/IFS | ---
+++
@@ -0,0 +1,46 @@
+from server.tests.base import BaseTestCase
+from server.models import db, Lecturer, Course, Lecture, Comment
+import json
+
+class GetCommentsApiTest(BaseTestCase):
+ def setUp(self):
+ super(GetCommentsApiTest, self).setUp()
+
+ simon = Lecturer('Simon', 'McCallum')
+ ... | |
c80bdbaffe40f0f6877b36498175f7e8b80085d3 | migrations/versions/0143_remove_reply_to.py | migrations/versions/0143_remove_reply_to.py | """
Revision ID: 0143_remove_reply_to
Revises: 0142_validate_constraint
Create Date: 2017-11-21 10:42:25.045444
"""
from alembic import op
import sqlalchemy as sa
revision = '0143_remove_reply_to'
down_revision = '0142_validate_constraint'
def upgrade():
op.drop_column('services', 'letter_contact_block')
... | Remove email_reply_to and letter_contact_block from Services | Remove email_reply_to and letter_contact_block from Services
| Python | mit | alphagov/notifications-api,alphagov/notifications-api | ---
+++
@@ -0,0 +1,28 @@
+"""
+
+Revision ID: 0143_remove_reply_to
+Revises: 0142_validate_constraint
+Create Date: 2017-11-21 10:42:25.045444
+
+"""
+from alembic import op
+import sqlalchemy as sa
+
+
+revision = '0143_remove_reply_to'
+down_revision = '0142_validate_constraint'
+
+
+def upgrade():
+ op.drop_col... | |
f5bcac9a49b8bb259955d6ee1f585b3db251f59b | second/blog/migrations/0002_comment.py | second/blog/migrations/0002_comment.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-07-18 03:30
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
]
... | Add migration to add model for Comments | Add migration to add model for Comments
| Python | mit | ugaliguy/Django-Tutorial-Projects,ugaliguy/Django-Tutorial-Projects | ---
+++
@@ -0,0 +1,28 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.9.7 on 2016-07-18 03:30
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+import django.db.models.deletion
+import django.utils.timezone
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ... | |
6e513cfb73857b8a15efadcaa66492599f749853 | oidc_provider/tests/test_logout_endpoint.py | oidc_provider/tests/test_logout_endpoint.py | from django.core.urlresolvers import reverse
from django.test import TestCase
from oidc_provider.views import *
from oidc_provider.tests.app.utils import *
class UserInfoTestCase(TestCase):
def setUp(self):
self.user = create_fake_user()
self.url = reverse('oidc_provider:logout')
def test_sh... | Add tests for logout view | Add tests for logout view
| Python | mit | juanifioren/django-oidc-provider,nmohoric/django-oidc-provider,ByteInternet/django-oidc-provider,torreco/django-oidc-provider,bunnyinc/django-oidc-provider,bunnyinc/django-oidc-provider,wayward710/django-oidc-provider,ByteInternet/django-oidc-provider,wayward710/django-oidc-provider,torreco/django-oidc-provider,nmohori... | ---
+++
@@ -0,0 +1,30 @@
+from django.core.urlresolvers import reverse
+from django.test import TestCase
+
+from oidc_provider.views import *
+from oidc_provider.tests.app.utils import *
+
+
+class UserInfoTestCase(TestCase):
+ def setUp(self):
+ self.user = create_fake_user()
+ self.url = reverse('o... | |
e53d101827491bcee3fffa99314cbe9561884cb2 | librisxl-tools/scripts/crunch-lddb-lines.py | librisxl-tools/scripts/crunch-lddb-lines.py | from __future__ import print_function
import json
import sys
import re
def parse_select(sel_str):
steps = []
match_rule = None
for word in sel_str.strip().split(' '):
if match_rule:
if match_rule == '=':
steps.append(lambda data, word=word: data == word)
elif... | Add simple crunch and query LDDB script | Add simple crunch and query LDDB script
| Python | apache-2.0 | libris/librisxl,libris/librisxl,libris/librisxl | ---
+++
@@ -0,0 +1,97 @@
+from __future__ import print_function
+import json
+import sys
+import re
+
+def parse_select(sel_str):
+ steps = []
+ match_rule = None
+ for word in sel_str.strip().split(' '):
+ if match_rule:
+ if match_rule == '=':
+ steps.append(lambda data, wo... | |
b85a316edc3362c898f935f7bb4dea1a324b7ac6 | CodeFights/functionsComposition.py | CodeFights/functionsComposition.py | #!/usr/local/bin/python
# Code Fights Functions Composition Problem
from functools import reduce
import math
def compose(functions):
return reduce(lambda f, g: lambda x: f(g(x)), functions, lambda x: x)
def functionsComposition(functions, x):
return compose(map(eval, functions))(x)
def main():
tests ... | Solve Code Fights functions composition problem | Solve Code Fights functions composition problem
| Python | mit | HKuz/Test_Code | ---
+++
@@ -0,0 +1,38 @@
+#!/usr/local/bin/python
+# Code Fights Functions Composition Problem
+
+from functools import reduce
+import math
+
+
+def compose(functions):
+ return reduce(lambda f, g: lambda x: f(g(x)), functions, lambda x: x)
+
+
+def functionsComposition(functions, x):
+ return compose(map(eval,... | |
57c2a013d3f3c671cfedd6e66aa176572d09d87e | setup.py | setup.py | import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def get_docs():
result = []
in_docs = False
f = open(os.path.join(os.path.dirname(__file__), 'speaklater.py'))
try:
for line in f:
if in_docs:
if line.lstrip().st... | import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def get_docs():
result = []
in_docs = False
f = open(os.path.join(os.path.dirname(__file__), 'speaklater.py'))
try:
for line in f:
if in_docs:
if line.lstrip().st... | Switch to git part two, this time URL for website | Switch to git part two, this time URL for website
| Python | bsd-3-clause | quokkaproject/speaklater,ThomasWaldmann/speaklater,jmagnusson/speaklater,mitsuhiko/speaklater | ---
+++
@@ -25,7 +25,7 @@
author='Armin Ronacher',
author_email='armin.ronacher@active-4.com',
version='1.2',
- url='http://dev.pocoo.org/hg/speaklater-main',
+ url='http://github.com/mitsuhiko/speaklater',
py_modules=['speaklater'],
description='implements a lazy string for python usef... |
23696a4ba6b721248d10957fb70c2b9bd6433b84 | tools/gyp-explain.py | tools/gyp-explain.py | #!/usr/bin/env python
# Copyright (c) 2011 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.
"""Prints paths between gyp targets.
"""
import json
import os
import sys
import time
from collections import deque
def usage():... | Add a small tool to answer questions like "Why does target A depend on target B". | Add a small tool to answer questions like "Why does target A depend on target B".
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/8672006
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@111430 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | M4sse/chromium.src,axinging/chromium-crosswalk,dednal/chromium.src,dushu1203/chromium.src,ltilve/chromium,jaruba/chromium.src,mogoweb/chromium-crosswalk,junmin-zhu/chromium-rivertrail,mogoweb/chromium-crosswalk,nacl-webkit/chrome_deps,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,ondra-n... | ---
+++
@@ -0,0 +1,92 @@
+#!/usr/bin/env python
+# Copyright (c) 2011 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.
+
+"""Prints paths between gyp targets.
+"""
+
+import json
+import os
+import sys
+import time
+
+fr... | |
32a592c82ab0b727c56084063d49039bb693a2b0 | corehq/apps/reports/commtrack/util.py | corehq/apps/reports/commtrack/util.py | from corehq.apps.locations.models import all_locations
from corehq.apps.commtrack.models import SupplyPointCase
from corehq.apps.products.models import Product
def supply_point_ids(locations):
keys = [[loc.domain, loc._id] for loc in locations]
rows = SupplyPointCase.get_db().view(
'commtrack/supply_p... | from corehq.apps.locations.models import SQLLocation
from corehq.apps.commtrack.models import SupplyPointCase
from corehq.apps.products.models import Product
def supply_point_ids(locations):
keys = [[loc.domain, loc._id] for loc in locations]
rows = SupplyPointCase.get_db().view(
'commtrack/supply_poi... | Switch supply point id list lookup to SQL | Switch supply point id list lookup to SQL
Locally with 1000 users this took the product_data method from 1.7
seconds to .2 seconds.
| Python | bsd-3-clause | puttarajubr/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -1,4 +1,4 @@
-from corehq.apps.locations.models import all_locations
+from corehq.apps.locations.models import SQLLocation
from corehq.apps.commtrack.models import SupplyPointCase
from corehq.apps.products.models import Product
@@ -14,10 +14,30 @@
def get_relevant_supply_point_ids(domain, active_l... |
ee662e6119ef31978eec62491b6e7ce35f292518 | python2.7-src/fibonacci_sequence.py | python2.7-src/fibonacci_sequence.py | #!/usr/bin/python
import sys
def fib(n):
a,b = 0,1
yield a
if n>0 :
yield b
for i in range(2,n+1):
a,b = b, a+b
yield b
num = int(sys.argv[1])
gen = fib(num)
for i in gen:
print i
| Add function for Fibonacci sequence | Add function for Fibonacci sequence
| Python | mit | diptin/dipti-coding-samples,diptin/dipti-coding-samples | ---
+++
@@ -0,0 +1,17 @@
+#!/usr/bin/python
+
+import sys
+
+def fib(n):
+ a,b = 0,1
+ yield a
+ if n>0 :
+ yield b
+ for i in range(2,n+1):
+ a,b = b, a+b
+ yield b
+
+num = int(sys.argv[1])
+gen = fib(num)
+for i in gen:
+ print i | |
348b7a2df539779e95cb72d00e7577db6740424f | corker/tests/test_main.py | corker/tests/test_main.py | """ Inspired by: http://blog.ianbicking.org/2010/03/12/a-webob-app-example/
"""
from __future__ import absolute_import
from webob import Request, Response, exc
from routes import Mapper
from corker.controller import BaseController, route
from corker.app import Application
class Index(BaseController):
@route('')
... | """ Inspired by: http://blog.ianbicking.org/2010/03/12/a-webob-app-example/
"""
from __future__ import absolute_import
from webob import Request, Response, exc
from routes import Mapper
from corker.controller import BaseController, route
from corker.app import Application
class Index(BaseController):
@route('')
... | Add a test to demo config passing. | Add a test to demo config passing.
| Python | bsd-2-clause | jd-boyd/corker,vs-networks/corker | ---
+++
@@ -42,3 +42,19 @@
ret = app.get('/bob/')
eq_(ret.body, "Bob!")
+
+def test_config():
+ mapper = Mapper()
+
+ def bob(request, link, **config):
+ def inner():
+ print "C:", config
+ return Response("Bob! %r" % config)
+ return inner
+ mapper.connect... |
97aa284612af51f3550052788f8a2e505d2f8cb9 | tests/test_0div.py | tests/test_0div.py | import angr
import nose
import os
test_location = os.path.join(os.path.dirname(__file__), '../../binaries/tests')
def run_0div(arch):
# check that we run in unicorn up to the zero-div site, fall back, try again in angr, and error correctly.
p = angr.Project(os.path.join(test_location, arch, 'test_0div'))
... | Add tests for correct behavior on divide-by-zero | Add tests for correct behavior on divide-by-zero
| Python | bsd-2-clause | iamahuman/angr,chubbymaggie/angr,chubbymaggie/angr,chubbymaggie/angr,iamahuman/angr,axt/angr,tyb0807/angr,angr/angr,schieb/angr,f-prettyland/angr,angr/angr,axt/angr,axt/angr,f-prettyland/angr,angr/angr,f-prettyland/angr,schieb/angr,tyb0807/angr,schieb/angr,iamahuman/angr,tyb0807/angr | ---
+++
@@ -0,0 +1,24 @@
+import angr
+import nose
+import os
+
+test_location = os.path.join(os.path.dirname(__file__), '../../binaries/tests')
+
+def run_0div(arch):
+ # check that we run in unicorn up to the zero-div site, fall back, try again in angr, and error correctly.
+ p = angr.Project(os.path.join(tes... | |
ab4f9340adf6d20cdd7585fd3ee97ce8425b1458 | tests/data_layer/conftest.py | tests/data_layer/conftest.py | import os
from pytest import fixture
from smif.data_layer import DatafileInterface
from smif.data_layer.load import dump
@fixture(scope='function')
def get_handler_csv(setup_folder_structure, project_config):
basefolder = setup_folder_structure
project_config_path = os.path.join(
str(basefolder), 'co... | Move fixtures into data layer | Move fixtures into data layer
| Python | mit | willu47/smif,willu47/smif,nismod/smif,nismod/smif,tomalrussell/smif,nismod/smif,tomalrussell/smif,willu47/smif,tomalrussell/smif,nismod/smif,tomalrussell/smif,willu47/smif | ---
+++
@@ -0,0 +1,23 @@
+import os
+
+from pytest import fixture
+from smif.data_layer import DatafileInterface
+from smif.data_layer.load import dump
+
+
+@fixture(scope='function')
+def get_handler_csv(setup_folder_structure, project_config):
+ basefolder = setup_folder_structure
+ project_config_path = os.p... | |
06aa3468bf67760ddc15c50e3ff98218264fdfce | migrations/versions/194_extend_eas_folder_id.py | migrations/versions/194_extend_eas_folder_id.py | """extend size of eas_folder_id and eas_parent_id
Revision ID: 211e93aff1e1
Revises: 2493281d621
Create Date: 2015-03-20 18:50:29.961734
"""
# revision identifiers, used by Alembic.
revision = '69e93aef3e9'
down_revision = '691fa97024d'
from alembic import op
from sqlalchemy.sql import text
from sqlalchemy.ext.decl... | Fix EAS folder id length | Fix EAS folder id length
Summary:
Fixes T2458. Note that because we're using MySQL 5.6, the migration happens offline and locks the table. However, since we only have about 20k columns, it shouldn't take too long.
Test Plan: Upgraded a db dump.
Reviewers: kav-ya, emfree
Reviewed By: emfree
Subscribers: spang
Mani... | Python | agpl-3.0 | ErinCall/sync-engine,jobscore/sync-engine,Eagles2F/sync-engine,closeio/nylas,gale320/sync-engine,ErinCall/sync-engine,gale320/sync-engine,Eagles2F/sync-engine,nylas/sync-engine,nylas/sync-engine,gale320/sync-engine,jobscore/sync-engine,closeio/nylas,closeio/nylas,Eagles2F/sync-engine,jobscore/sync-engine,nylas/sync-eng... | ---
+++
@@ -0,0 +1,43 @@
+"""extend size of eas_folder_id and eas_parent_id
+
+Revision ID: 211e93aff1e1
+Revises: 2493281d621
+Create Date: 2015-03-20 18:50:29.961734
+
+"""
+
+# revision identifiers, used by Alembic.
+revision = '69e93aef3e9'
+down_revision = '691fa97024d'
+
+from alembic import op
+from sqlalchemy... | |
1b673070e73b44d2c65039367d3d7cbe780cadc7 | tests/test_trips_ontology.py | tests/test_trips_ontology.py | from bioagents.resources.trips_ont_manager import trips_isa
def test_isa_disease():
assert trips_isa('diabetes', 'disease')
assert not trips_isa('disease', 'diabetes')
assert trips_isa('cancer', 'medical-disorders-and-conditions')
assert trips_isa('ONT::CANCER', 'disease')
assert trips_isa('ont::ca... | Test TRIPS ontology with disease names | Test TRIPS ontology with disease names
| Python | bsd-2-clause | bgyori/bioagents,sorgerlab/bioagents | ---
+++
@@ -0,0 +1,9 @@
+from bioagents.resources.trips_ont_manager import trips_isa
+
+def test_isa_disease():
+ assert trips_isa('diabetes', 'disease')
+ assert not trips_isa('disease', 'diabetes')
+ assert trips_isa('cancer', 'medical-disorders-and-conditions')
+ assert trips_isa('ONT::CANCER', 'diseas... | |
2340167e3be058973415a1d53a358e08a396f76e | bin/split_allseq.py | bin/split_allseq.py | #! /usr/bin/env python3
import os, argparse
def split_fs(output_dir_fn):
i = 0
while True:
i += 1
fn = output_dir_fn + '/' + str(i) + '.fna'
yield open(fn, 'w'), i
parser = argparse.ArgumentParser(
description='Split a file containing all the sequences in multiple files')
parser.add_argument('input_file', h... | Add script to split HMP fasta into multiple files | Add script to split HMP fasta into multiple files
Former-commit-id: c7ec294cec9435208ab552ff76df0245a6825082 | Python | mit | karel-brinda/prophyle,karel-brinda/prophyle,karel-brinda/prophyle,karel-brinda/prophyle | ---
+++
@@ -0,0 +1,35 @@
+#! /usr/bin/env python3
+
+import os, argparse
+
+def split_fs(output_dir_fn):
+ i = 0
+ while True:
+ i += 1
+ fn = output_dir_fn + '/' + str(i) + '.fna'
+ yield open(fn, 'w'), i
+
+parser = argparse.ArgumentParser(
+ description='Split a file containing all the sequences in multiple fil... | |
21f7d9d34b4e5483319372b2ca07b49a7ded8b23 | bin/gensim2sense.py | bin/gensim2sense.py | from sense2vec.vectors import VectorMap
from gensim.models import Word2Vec
import plac
@plac.annotations(
gensim_model_path=("Location of gensim's .bin file"),
out_dir=("Location of output directory"),
min_count=("Min count", "option", "m", int),
)
def main(gensim_model_path, out_dir, min_count=None):
... | Add gensim to sense2vec format converter script | Add gensim to sense2vec format converter script
| Python | mit | spacy-io/sense2vec,spacy-io/sense2vec,spacy-io/sense2vec | ---
+++
@@ -0,0 +1,30 @@
+from sense2vec.vectors import VectorMap
+from gensim.models import Word2Vec
+import plac
+
+@plac.annotations(
+ gensim_model_path=("Location of gensim's .bin file"),
+ out_dir=("Location of output directory"),
+ min_count=("Min count", "option", "m", int),
+)
+def main(gensim_model... | |
59ecd26da00145c7122dd371e2f116acbafee387 | confusion_matrix.py | confusion_matrix.py | import matplotlib.pylab as plt
import numpy as np
import seaborn as sns
from sklearn.metrics import confusion_matrix
np.random.seed(314151692)
y_pred = np.random.random_integers(0, 1, 1000)
y_true = np.random.random_integers(0, 1, 1000)
data = confusion_matrix(y_true, y_pred)
fig, ax = plt.subplots(1)
sns.heatmap(d... | Add a confusion matrix plot | Add a confusion matrix plot
| Python | mit | yassineAlouini/ml-experiments,yassineAlouini/ml-experiments | ---
+++
@@ -0,0 +1,18 @@
+import matplotlib.pylab as plt
+import numpy as np
+import seaborn as sns
+from sklearn.metrics import confusion_matrix
+
+np.random.seed(314151692)
+y_pred = np.random.random_integers(0, 1, 1000)
+y_true = np.random.random_integers(0, 1, 1000)
+
+
+data = confusion_matrix(y_true, y_pred)
+
... | |
b36380aa5a4b10846a2888184135349048415d7c | ph_unfolder/analysis/time_measurer.py | ph_unfolder/analysis/time_measurer.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
__author__ = "Yuji Ikeda"
import time
class TimeMeasurer(object):
"""Measure method execution time.
This class is made based on the suggestion in the fo... | Add the module to measure computational times | Add the module to measure computational times
| Python | mit | yuzie007/ph_unfolder,yuzie007/upho | ---
+++
@@ -0,0 +1,30 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+from __future__ import (absolute_import, division,
+ print_function, unicode_literals)
+
+__author__ = "Yuji Ikeda"
+
+import time
+
+
+class TimeMeasurer(object):
+ """Measure method execution time.
+
+ This class ... | |
34f618a17fea9c8172d91a825f3992baf7255832 | 2009/qualification_round/welcome_to_code_jam.py | 2009/qualification_round/welcome_to_code_jam.py | #!/usr/bin/env python
# Google Code Jam
# Google Code Jam 2009
# Qualification Round 2009
# Problem C. Welcome to Code Jam
from __future__ import print_function
SUBSTRING = 'welcome to code jam'
def count_welcome(s):
if len(s) < len(SUBSTRING):
return 0
count = 1
indexes = []
last_index = ... | Add welcome to code jam | Add welcome to code jam
| Python | apache-2.0 | laichunpongben/CodeJam | ---
+++
@@ -0,0 +1,40 @@
+#!/usr/bin/env python
+
+# Google Code Jam
+# Google Code Jam 2009
+# Qualification Round 2009
+# Problem C. Welcome to Code Jam
+
+from __future__ import print_function
+
+SUBSTRING = 'welcome to code jam'
+
+def count_welcome(s):
+ if len(s) < len(SUBSTRING):
+ return 0
+
+ co... | |
60ed9500ce5e252c088bf5c90c4db4e35ef6a978 | setup.py | setup.py | import pip
import os
projectName = ''
def install(package):
pip.main(['install', package])
def installAll():
allPackages = [
'deap',
'numpy',
]
for p in allPackages:
install(p)
def getProjectName():
initialDir = os.getcwd()
os.chdir('../')
dirList1 = os.listdir('.... | Add set up scripts to install dependencies | Add set up scripts to install dependencies
| Python | mit | cameronlai/EXT_GEN,cameronlai/EXT_GEN | ---
+++
@@ -0,0 +1,33 @@
+import pip
+import os
+
+projectName = ''
+
+def install(package):
+ pip.main(['install', package])
+
+def installAll():
+ allPackages = [
+ 'deap',
+ 'numpy',
+ ]
+ for p in allPackages:
+ install(p)
+
+def getProjectName():
+ initialDir = os.getcwd()
+ ... | |
4c4564c7e00adeb56f18a192f9544145d8512232 | test/cbio_client_test.py | test/cbio_client_test.py | from bioagents import cbio_client
def test_get_cancer_studies():
study_ids = cbio_client.get_cancer_studies('pancreatic')
assert(len(study_ids) > 0)
assert('paad_tcga' in study_ids)
def test_get_cancer_types():
type_ids = cbio_client.get_cancer_types('lung')
assert(len(type_ids) > 0)
def test_get... | Add tests for cbio client | Add tests for cbio client
| Python | bsd-2-clause | sorgerlab/bioagents,bgyori/bioagents | ---
+++
@@ -0,0 +1,19 @@
+from bioagents import cbio_client
+
+def test_get_cancer_studies():
+ study_ids = cbio_client.get_cancer_studies('pancreatic')
+ assert(len(study_ids) > 0)
+ assert('paad_tcga' in study_ids)
+
+def test_get_cancer_types():
+ type_ids = cbio_client.get_cancer_types('lung')
+ as... | |
890a15bc40d51a83345887eb320bc5b74216effd | neurokernel/pm_gpu.py | neurokernel/pm_gpu.py | #!/usr/bin/env python
"""
Port mapper for GPU memory.
"""
import numpy as np
import pycuda.gpuarray as gpuarray
from plsel import BasePortMapper
class GPUPortMapper(PortMapper):
def __init__(self, selector, data=None, portmap=None):
super(PortMapper, self).__init__(selector, portmap)
N = len(sel... | Add initial version of GPU-based port mapper class. | Add initial version of GPU-based port mapper class.
| Python | bsd-3-clause | cerrno/neurokernel | ---
+++
@@ -0,0 +1,44 @@
+#!/usr/bin/env python
+
+"""
+Port mapper for GPU memory.
+"""
+
+import numpy as np
+import pycuda.gpuarray as gpuarray
+
+from plsel import BasePortMapper
+
+class GPUPortMapper(PortMapper):
+ def __init__(self, selector, data=None, portmap=None):
+ super(PortMapper, self).__init... | |
c93f4ded0b3eb33a9a06c784963845dd80144989 | setup.py | setup.py | import multiprocessing # noqa # stop tests breaking tox
from setuptools import setup
import tvrenamr
requires = ['pyyaml', 'requests']
setup_requires = ('minimock', 'mock', 'nose', 'pyyaml')
setup(
name=tvrenamr.__title__,
version=tvrenamr.__version__,
description='Rename tv show files using online dat... | import multiprocessing # noqa # stop tests breaking tox
from setuptools import setup
import tvrenamr
requires = ['pyyaml', 'requests']
setup_requires = ('minimock', 'mock', 'nose', 'pyyaml')
setup(
name=tvrenamr.__title__,
version=tvrenamr.__version__,
description='Rename tv show files using online dat... | Update trove classifiers with generic language versions | Update trove classifiers with generic language versions
| Python | mit | ghickman/tvrenamr,wintersandroid/tvrenamr | ---
+++
@@ -27,9 +27,14 @@
'Natural Language :: English',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX',
+ 'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
+ 'Progra... |
7e55b58960a2b2e320d115818c2ba052a8b17270 | scrape.py | scrape.py | import requests, json, sys
from bs4 import BeautifulSoup
def print_stats(data, hero, stats):
print(hero + " " + stats)
header = ["Rarity: ", "HP: ", "ATK: ", "SPD: ", "DEF: ", "RES: "]
stat_counter = 0
rarity_counter = 0
for row in data:
table = data[rarity_counter].find_all("td")
for head in header:
prin... | Update for Fire Emblem Heroes | Update for Fire Emblem Heroes
| Python | mit | tyrenyabe/simple-scrape | ---
+++
@@ -0,0 +1,50 @@
+import requests, json, sys
+from bs4 import BeautifulSoup
+
+def print_stats(data, hero, stats):
+ print(hero + " " + stats)
+ header = ["Rarity: ", "HP: ", "ATK: ", "SPD: ", "DEF: ", "RES: "]
+ stat_counter = 0
+ rarity_counter = 0
+ for row in data:
+ table = data[rarity_counter].find_al... | |
cc4d601b2b3e12ad3087f8cb959940192e945df3 | gem/tests/test_celery.py | gem/tests/test_celery.py | from django.test import TestCase
from mock import patch
class TestCelery(TestCase):
@patch('django.core.management.call_command')
def test_ensure_search_index_doesnt_call_command(self, call_command_patch):
from gem.celery import ensure_search_index_updated
ensure_search_index_updated('sender'... | Add basic test for celery.py task | Add basic test for celery.py task
This file isn't being run by any of the tests so we have no guarantee
that it's even valid Python. Let's at least run it a little bit.
| Python | bsd-2-clause | praekelt/molo-gem,praekelt/molo-gem,praekelt/molo-gem | ---
+++
@@ -0,0 +1,12 @@
+from django.test import TestCase
+
+from mock import patch
+
+
+class TestCelery(TestCase):
+ @patch('django.core.management.call_command')
+ def test_ensure_search_index_doesnt_call_command(self, call_command_patch):
+ from gem.celery import ensure_search_index_updated
+ ... | |
88a59ea0d0ca72d6ca8351169c78e84f9afdb454 | mozillians/users/migrations/0037_auto_20180720_0305.py | mozillians/users/migrations/0037_auto_20180720_0305.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-07-20 10:05
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0036_auto_20180704_0634'),
]
operations = [
migrations.AlterField... | Add a schema migration for Mozilla Phabricator External Account. | Add a schema migration for Mozilla Phabricator External Account.
| Python | bsd-3-clause | johngian/mozillians,johngian/mozillians,mozilla/mozillians,mozilla/mozillians,mozilla/mozillians,akatsoulas/mozillians,akatsoulas/mozillians,akatsoulas/mozillians,johngian/mozillians,johngian/mozillians,akatsoulas/mozillians,mozilla/mozillians | ---
+++
@@ -0,0 +1,20 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.13 on 2018-07-20 10:05
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('users', '0036_auto_20180704_0634'),
+ ]
+
+ ope... | |
dec30baf66f852c272642e8b7857001767875a5f | cmfieldguide/cmsdetector/signatures/hippo.py | cmfieldguide/cmsdetector/signatures/hippo.py | """
This signature contains tests to see if the site is running on Hippo CMS.
"""
__author__ = "Jeroen Reijn"
__copyright__ = "CM Fieldguide"
__credits__ = ["Jeroen Reijn",]
__license__ = "Unlicense"
__version__ = "0.1"
__maintainer__ = "Jeroen Reijn"
__email__ = "j.reijn@onehippo.com"
__status__ = "Experimental"
fro... | Add first working attempt at Hippo CMS signature | Add first working attempt at Hippo CMS signature
| Python | unlicense | sggottlieb/cmfieldguide | ---
+++
@@ -0,0 +1,34 @@
+"""
+This signature contains tests to see if the site is running on Hippo CMS.
+"""
+__author__ = "Jeroen Reijn"
+__copyright__ = "CM Fieldguide"
+__credits__ = ["Jeroen Reijn",]
+__license__ = "Unlicense"
+__version__ = "0.1"
+__maintainer__ = "Jeroen Reijn"
+__email__ = "j.reijn@onehippo.c... | |
7564e35bbf9a4d09fb24326dae55d14fe987fbcf | workflows/logging/test_logging.py | workflows/logging/test_logging.py | from __future__ import absolute_import, division
import logging
import mock
import workflows.logging
def test_callback_handler_works_within_logging_framework():
cbmock = mock.Mock()
logmsg = 'Test message for callback'
log = logging.getLogger('workflows.tests.logging.callback')
log.setLevel(logging.INFO)
cb... | Add test for logging callback handler | Add test for logging callback handler
| Python | bsd-3-clause | DiamondLightSource/python-workflows,xia2/workflows | ---
+++
@@ -0,0 +1,23 @@
+from __future__ import absolute_import, division
+import logging
+import mock
+import workflows.logging
+
+def test_callback_handler_works_within_logging_framework():
+ cbmock = mock.Mock()
+ logmsg = 'Test message for callback'
+ log = logging.getLogger('workflows.tests.logging.callback'... | |
18fa807ad107fe4c6301087137920f4a563341b3 | Instanssi/arkistoija/forms.py | Instanssi/arkistoija/forms.py | # -*- coding: utf-8 -*-
from django import forms
from uni_form.helper import FormHelper
from uni_form.layout import Submit, Layout, Fieldset, ButtonHolder
from django.core.exceptions import ValidationError
import os
class EventForm(forms.Form):
name = forms.CharField(label=u'Nimi', max_length=32)
date = forms... | Add form for getting event data on Arkistoija app | Add form for getting event data on Arkistoija app
| Python | mit | Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org | ---
+++
@@ -0,0 +1,19 @@
+# -*- coding: utf-8 -*-
+
+from django import forms
+from uni_form.helper import FormHelper
+from uni_form.layout import Submit, Layout, Fieldset, ButtonHolder
+from django.core.exceptions import ValidationError
+import os
+
+class EventForm(forms.Form):
+ name = forms.CharField(label=u'N... | |
e66f9b6e6cb85392e1be9cf0733a3b358c43f340 | hacks/compress_folder.py | hacks/compress_folder.py | #!/bin/env python
"""
Compress and delete a folder if 50% of the files inside it are less than 2MB.
It only considers files in the first level of the folder.
"""
import os
import shutil
import sys
import tarfile
from contextlib import contextmanager
@contextmanager
def cd(newdir):
prevdir = os.getcwd()
os.... | Compress folder with small files | [hacks] Compress folder with small files
| Python | mit | escorciav/linux-utils,escorciav/linux-utils | ---
+++
@@ -0,0 +1,77 @@
+#!/bin/env python
+"""
+
+Compress and delete a folder if 50% of the files inside it are less than 2MB.
+
+It only considers files in the first level of the folder.
+
+"""
+import os
+import shutil
+import sys
+import tarfile
+from contextlib import contextmanager
+
+
+@contextmanager
+def c... | |
c31bde7660d8fbaa6d2e1404defb3f9d1ca13fea | chandra_aca/tests/test_dark_scale.py | chandra_aca/tests/test_dark_scale.py | import numpy as np
from .. import dark_scale
def test_dark_temp_scale():
scale = dark_scale.dark_temp_scale(-10., -14)
assert np.allclose(scale, 0.70)
scale = dark_scale.dark_temp_scale(-10., -14, scale_4c=2.0)
assert scale == 0.5 # Should be an exact match
| Add dark cal scale test | Add dark cal scale test
| Python | bsd-2-clause | sot/chandra_aca,sot/chandra_aca | ---
+++
@@ -0,0 +1,9 @@
+import numpy as np
+from .. import dark_scale
+
+def test_dark_temp_scale():
+ scale = dark_scale.dark_temp_scale(-10., -14)
+ assert np.allclose(scale, 0.70)
+
+ scale = dark_scale.dark_temp_scale(-10., -14, scale_4c=2.0)
+ assert scale == 0.5 # Should be an exact match | |
4c8990d2e5a872da6083f2027e9c0d91e021bafd | samples/python/queue_create_alias.py | samples/python/queue_create_alias.py | '''
This sample will create a new alias queue.
MQWeb runs on localhost and is listening on port 8081.
'''
import sys
import json
import httplib
import socket
import argparse
parser = argparse.ArgumentParser(
description='MQWeb - Python sample - Create alias queue',
epilog="For more information: http://www.mqweb.or... | Add create alias queue sample | Add create alias queue sample
| Python | mit | fbraem/mqweb,fbraem/mqweb,fbraem/mqweb | ---
+++
@@ -0,0 +1,52 @@
+'''
+ This sample will create a new alias queue.
+ MQWeb runs on localhost and is listening on port 8081.
+'''
+import sys
+import json
+import httplib
+import socket
+import argparse
+
+parser = argparse.ArgumentParser(
+ description='MQWeb - Python sample - Create alias queue',
+ epilog="F... | |
cbaf9d3c8cf8f11e49f0edfa87b15bc925dc7d92 | core/management/commands/delete_old_sessions.py | core/management/commands/delete_old_sessions.py | from datetime import datetime
from django.core.management.base import BaseCommand
from django.contrib.sessions.models import Session
"""
>>> def clean(count):
... for idx, s in enumerate(Session.objects.filter(expire_date__lt=now)[:count+1]):
... s.delete()
... if str(idx).endswith('000'): print idx
... p... | Add delete old sessions command | Add delete old sessions command
| Python | mit | QLGu/djangopackages,pydanny/djangopackages,pydanny/djangopackages,nanuxbe/djangopackages,QLGu/djangopackages,nanuxbe/djangopackages,nanuxbe/djangopackages,QLGu/djangopackages,pydanny/djangopackages | ---
+++
@@ -0,0 +1,34 @@
+from datetime import datetime
+
+from django.core.management.base import BaseCommand
+from django.contrib.sessions.models import Session
+
+"""
+>>> def clean(count):
+... for idx, s in enumerate(Session.objects.filter(expire_date__lt=now)[:count+1]):
+... s.delete()
+... if str(id... | |
f8d5db373333145f8751ce8a4630eaf2ab02fcc7 | Lib/test/crashers/file_threads.py | Lib/test/crashers/file_threads.py | # An example for http://bugs.python.org/issue815646
import thread
while 1:
f = open("/tmp/dupa", "w")
thread.start_new_thread(f.close, ())
f.close()
| Add a crasher for the thread-unsafety of file objects. | Add a crasher for the thread-unsafety of file objects.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -0,0 +1,8 @@
+# An example for http://bugs.python.org/issue815646
+
+import thread
+
+while 1:
+ f = open("/tmp/dupa", "w")
+ thread.start_new_thread(f.close, ())
+ f.close() | |
f182dc362c40b7dc1a0afe7cad5721a271bccbe0 | DBNsite/testing_DBNlogic/sets_test.py | DBNsite/testing_DBNlogic/sets_test.py | import pytest
import os
import numpy as np
import sys
myPath = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(myPath, '..'))
from DBNlogic.sets import exists, DataSet, MNIST, SmallerMNIST
def test_exists_true():
"""The function `exists` returns True if
given the path of an existin... | Add tests for back end | Add tests for back end
| Python | mit | ggiuffre/DBNsim,ggiuffre/DBNsim,ggiuffre/DBNsim | ---
+++
@@ -0,0 +1,22 @@
+import pytest
+import os
+import numpy as np
+
+import sys
+myPath = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, os.path.join(myPath, '..'))
+
+from DBNlogic.sets import exists, DataSet, MNIST, SmallerMNIST
+
+def test_exists_true():
+ """The function `exists` returns T... | |
ba0e03cfdf3495b96d68f264e9e6406cd7ab0a59 | tests/integration/test_end_to_end.py | tests/integration/test_end_to_end.py | """Tests updating config of a real org and repo under the dothub-sandbox organization"""
import pytest
from click.testing import CliRunner
import tempfile
from dothub._main import dothub
from dothub import utils
import os
DOTHUB_TOKEN = os.environ.get("DOTHUB_USER_TOKEN")
CLI_BASE_ARGS = ["--user=dothub-user", "--tok... | Add org end to end testing | Add org end to end testing
| Python | mit | Mariocj89/dothub | ---
+++
@@ -0,0 +1,84 @@
+"""Tests updating config of a real org and repo under the dothub-sandbox organization"""
+
+import pytest
+from click.testing import CliRunner
+import tempfile
+from dothub._main import dothub
+from dothub import utils
+import os
+
+DOTHUB_TOKEN = os.environ.get("DOTHUB_USER_TOKEN")
+CLI_BAS... | |
cdf33a078e8d50ee58ae86000e9e21a326b014c6 | capple.py | capple.py | # http://www.codechef.com/DEC14/problems/CAPPLE
def pluck(trees):
# find the biggest and the second biggest number in the list
maximum = max(trees)
second_max = max( map(lambda x: -1 if x == maximum else x, trees) )
if maximum == second_max:
return [0]*len(trees)
else:
diff = maximum - second_max
return m... | Write solution to Chef and Apples problem. | Write solution to Chef and Apples problem.
| Python | mit | paramsingh/cp,paramsingh/cp,paramsingh/codechef-solutions,paramsingh/codechef-solutions,paramsingh/codechef-solutions,paramsingh/cp,paramsingh/cp,paramsingh/cp,paramsingh/codechef-solutions | ---
+++
@@ -0,0 +1,28 @@
+# http://www.codechef.com/DEC14/problems/CAPPLE
+
+def pluck(trees):
+
+ # find the biggest and the second biggest number in the list
+ maximum = max(trees)
+ second_max = max( map(lambda x: -1 if x == maximum else x, trees) )
+
+ if maximum == second_max:
+ return [0]*len(trees)
+ else:
+ ... | |
09a592e12fb6b6d37bc9e1b760aebdba999992e9 | debugger/chrome_tab_finder.py | debugger/chrome_tab_finder.py | from util import *
import json
class ChromeTabFinder(object):
def __init__(self, host, port):
self._next_seq = 0
self._timer = Timer(250)
self._timer.tick.add_listener(self._tick)
self._host = host
self._port = port
self._session = None
self._get_tab_list_pending = False
self._tick... | Make code that simply finds chrome tabs to attach to. | Make code that simply finds chrome tabs to attach to.
| Python | apache-2.0 | natduca/ndbg,natduca/ndbg,natduca/ndbg,natduca/ndbg,natduca/ndbg | ---
+++
@@ -0,0 +1,80 @@
+from util import *
+import json
+
+class ChromeTabFinder(object):
+ def __init__(self, host, port):
+ self._next_seq = 0
+ self._timer = Timer(250)
+ self._timer.tick.add_listener(self._tick)
+
+ self._host = host
+ self._port = port
+
+ self._session = None
+ self._get... | |
d2041e5b47d5eb239d55b71ef93c3ec3d468e508 | etc/crates-graph.py | etc/crates-graph.py | #!/usr/bin/env python3
# Copyright 2013 The Servo Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/... | Add a minimal alternative to `cargo graph` | Add a minimal alternative to `cargo graph`
I tried `cargo graph` and some of its successors,
but didn’t manage to make them produce what I wanted
(or in some cases make them work at all.)
This Python script reimplements similar functionality
based on parsing the (JSON) output of `cargo metadata`.
Graphviz graphs can... | Python | mpl-2.0 | splav/servo,splav/servo,KiChjang/servo,splav/servo,KiChjang/servo,splav/servo,KiChjang/servo,KiChjang/servo,KiChjang/servo,KiChjang/servo,KiChjang/servo,splav/servo,splav/servo,splav/servo,KiChjang/servo,splav/servo,splav/servo,splav/servo,KiChjang/servo,KiChjang/servo | ---
+++
@@ -0,0 +1,51 @@
+#!/usr/bin/env python3
+
+# Copyright 2013 The Servo Project Developers. See the COPYRIGHT
+# file at the top-level directory of this distribution.
+#
+# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+# <LI... | |
f2193d7b9b88e85d8e6385d9e6778f1e70a03c3f | peas-demo/plugins/pythonhello/pythonhello.py | peas-demo/plugins/pythonhello/pythonhello.py | # -*- coding: utf-8 -*-
# ex:set ts=4 et sw=4 ai:
import gobject
from gi.repository import Peas
from gi.repository import Gtk
LABEL_STRING="Python Says Hello!"
class PythonHelloPlugin(gobject.GObject, Peas.Activatable):
__gtype_name__ = 'PythonHelloPlugin'
def do_activate(self, window):
print "Pytho... | # -*- coding: utf-8 -*-
# ex:set ts=4 et sw=4 ai:
import gobject
from gi.repository import Peas
from gi.repository import Gtk
LABEL_STRING="Python Says Hello!"
class PythonHelloPlugin(gobject.GObject, Peas.Activatable):
__gtype_name__ = 'PythonHelloPlugin'
def do_activate(self, window):
print "Pytho... | Fix the sample python plugin. | [Python] Fix the sample python plugin.
PyGI doesn't handle default values for introspected methods,
so we need to specify all the arguments for pack_start()
| Python | lgpl-2.1 | gregier/libpeas,gregier/libpeas,Distrotech/libpeas,Distrotech/libpeas,gregier/libpeas,GNOME/libpeas,chergert/libpeas,chergert/libpeas,GNOME/libpeas,Distrotech/libpeas,gregier/libpeas,chergert/libpeas | ---
+++
@@ -15,7 +15,7 @@
window._pythonhello_label = Gtk.Label()
window._pythonhello_label.set_text(LABEL_STRING)
window._pythonhello_label.show()
- window.get_child().pack_start(window._pythonhello_label)
+ window.get_child().pack_start(window._pythonhello_label, True, True,... |
5068efc63026cb55d521e265b4d263d584594dbc | elpiwear/proximity_warning.py | elpiwear/proximity_warning.py | import Edison.i2c as I2C
import sharp2y0a21
import ads1015
import time
import thread
class proximity_warning:
def __init__(self, sensorid, calibration, sensing_freq):
self.sensing_freq = sensing_freq
self.warning = []
adc = ads1015.ads1015(I2C.i2c(1,0x48))
adc.setchannel(sensorid, ... | Add the proximity warning detector class | Add the proximity warning detector class
| Python | mit | fjacob21/pycon2015 | ---
+++
@@ -0,0 +1,42 @@
+import Edison.i2c as I2C
+import sharp2y0a21
+import ads1015
+import time
+import thread
+
+class proximity_warning:
+
+ def __init__(self, sensorid, calibration, sensing_freq):
+ self.sensing_freq = sensing_freq
+ self.warning = []
+ adc = ads1015.ads1015(I2C.i2c(1,0... | |
1fe81e1c086b0f8476dbc3b58f249de6b12b13af | tests/v6/test_spawn_derived_generators.py | tests/v6/test_spawn_derived_generators.py | import pytest
#from .exemplar_generators import EXEMPLAR_PRIMITIVE_GENERATORS
from .context import tohu
from tohu.v6.primitive_generators import Integer
from tohu.v6.derived_generators import Apply
def test_spawn_apply_generator():
"""
Test that an Apply generator can be spawned and the spawned version produce... | Add test that an Apply generator can be spawned and the spawned version produces the same elements | Add test that an Apply generator can be spawned and the spawned version produces the same elements
| Python | mit | maxalbert/tohu | ---
+++
@@ -0,0 +1,41 @@
+import pytest
+#from .exemplar_generators import EXEMPLAR_PRIMITIVE_GENERATORS
+from .context import tohu
+from tohu.v6.primitive_generators import Integer
+from tohu.v6.derived_generators import Apply
+
+def test_spawn_apply_generator():
+ """
+ Test that an Apply generator can be spa... | |
4c3f4b5a19832d965714997652ad245ac8abf310 | animal.py | animal.py | #!/usr/bin/python3
import sys
import json
TEXT_FILE_PATH = './text.json'
messages = None
def traverse(parent, path):
node = parent[path]
if (isinstance(node, str)):
if not ask_yes_no_question('{}{}'.format(messages.get('isItA'), node)):
animal = input(messages.get('itWas'))
q... | Implement 'Guess The Animal' game in Python 3 | Implement 'Guess The Animal' game in Python 3
Resolves #6
| Python | mit | drom/animal,drom/animal,drom/animal,drom/animal,drom/animal,drom/animal | ---
+++
@@ -0,0 +1,91 @@
+#!/usr/bin/python3
+
+import sys
+import json
+
+TEXT_FILE_PATH = './text.json'
+messages = None
+
+def traverse(parent, path):
+ node = parent[path]
+
+ if (isinstance(node, str)):
+ if not ask_yes_no_question('{}{}'.format(messages.get('isItA'), node)):
+ animal = i... | |
54fe88a3b8151c1a41ecd597ccf6a17db32d9af7 | ooni/nettests/blocking/meek_fronted_requests.py | ooni/nettests/blocking/meek_fronted_requests.py | # -*- encoding: utf-8 -*-
#
# :licence: see LICENSE
from twisted.python import usage
from ooni.templates import httpt
from ooni.utils import log
class UsageOptions(usage.Options):
optParameters = [ ['ExpectedBody', 'B',
'I’m just a happy little web server.\n',
'E... | Add meek fronted requests test | Add meek fronted requests test
| Python | bsd-2-clause | lordappsec/ooni-probe,juga0/ooni-probe,0xPoly/ooni-probe,0xPoly/ooni-probe,kdmurray91/ooni-probe,kdmurray91/ooni-probe,0xPoly/ooni-probe,Karthikeyan-kkk/ooni-probe,juga0/ooni-probe,kdmurray91/ooni-probe,kdmurray91/ooni-probe,lordappsec/ooni-probe,juga0/ooni-probe,0xPoly/ooni-probe,Karthikeyan-kkk/ooni-probe,juga0/ooni-... | ---
+++
@@ -0,0 +1,74 @@
+# -*- encoding: utf-8 -*-
+#
+# :licence: see LICENSE
+
+from twisted.python import usage
+from ooni.templates import httpt
+from ooni.utils import log
+
+class UsageOptions(usage.Options):
+ optParameters = [ ['ExpectedBody', 'B',
+ 'I’m just a happy little web se... | |
08f2f0dce2669bb0afd471dbf51c9aacc553989c | tests/test_experiments/test_utils.py | tests/test_experiments/test_utils.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from unittest.mock import patch
import os
from experiments.utils import (
create_experiment_logs_path,
get_experiment_logs_path,
delete_experiment_logs,
get_experiment_outputs_path,
create_experiment_outputs_... | Add experiment utils function tests | Add experiment utils function tests
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon | ---
+++
@@ -0,0 +1,41 @@
+# -*- coding: utf-8 -*-
+from __future__ import absolute_import, division, print_function
+
+from unittest.mock import patch
+
+import os
+
+from experiments.utils import (
+ create_experiment_logs_path,
+ get_experiment_logs_path,
+ delete_experiment_logs,
+ get_experiment_outpu... | |
20bd20f84a37f732f097628b01a3bce4f46ef022 | 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
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... | |
7f9eea2f981b8e852ce049aea1cf8a911363335d | mutual_information.py | mutual_information.py | from skimage.viewer import ImageViewer
from skimage import data, img_as_float
from skimage.viewer.plugins.plotplugin import PlotPlugin
from skimage.viewer.widgets import Slider
from skimage.exposure import rescale_intensity
from skimage.transform import rotate
import numpy as np
import matplotlib.pyplot as plt
clas... | Add example of a 2-D histogram, illustrating mutual information. | Add example of a 2-D histogram, illustrating mutual information.
| Python | bsd-3-clause | scikit-image/skimage-demos | ---
+++
@@ -0,0 +1,78 @@
+from skimage.viewer import ImageViewer
+from skimage import data, img_as_float
+
+from skimage.viewer.plugins.plotplugin import PlotPlugin
+from skimage.viewer.widgets import Slider
+from skimage.exposure import rescale_intensity
+from skimage.transform import rotate
+
+import numpy as np
+i... | |
ccda4d9c3e737161e0477c569e074ffb884a541c | src/sentry/api/authentication.py | src/sentry/api/authentication.py | from __future__ import absolute_import
from django.contrib.auth.models import AnonymousUser
from django.utils.crypto import constant_time_compare
from rest_framework.authentication import BasicAuthentication
from rest_framework.exceptions import AuthenticationFailed
from sentry.app import raven
from sentry.models imp... | from __future__ import absolute_import
from django.contrib.auth.models import AnonymousUser
from django.utils.crypto import constant_time_compare
from rest_framework.authentication import BasicAuthentication
from rest_framework.exceptions import AuthenticationFailed
from sentry.app import raven
from sentry.models imp... | Raise hard error when API key is invalid | Raise hard error when API key is invalid
| Python | bsd-3-clause | fotinakis/sentry,ifduyue/sentry,JamesMura/sentry,daevaorn/sentry,looker/sentry,gencer/sentry,JamesMura/sentry,fotinakis/sentry,fotinakis/sentry,gencer/sentry,zenefits/sentry,looker/sentry,jean/sentry,BuildingLink/sentry,mvaled/sentry,mvaled/sentry,mvaled/sentry,ifduyue/sentry,jean/sentry,nicholasserra/sentry,gencer/sen... | ---
+++
@@ -22,7 +22,7 @@
try:
key = ApiKey.objects.get_from_cache(key=userid)
except ApiKey.DoesNotExist:
- return None
+ raise AuthenticationFailed('API key is not valid')
if not key.is_active:
raise AuthenticationFailed('Key is disabled') |
426b3cac7932289f24be7dc6dba6197a4d65740b | benchmarks/benchmarks/bench_scalar.py | benchmarks/benchmarks/bench_scalar.py | from .common import Benchmark, TYPES1
import numpy as np
class ScalarMath(Benchmark):
# Test scalar math, note that each of these is run repeatedly to offset
# the function call overhead to some degree.
params = [TYPES1]
param_names = ["type"]
def setup(self, typename):
self.num = np.dtyp... | Add simple scalar math benchmarks | BENCH: Add simple scalar math benchmarks
| Python | bsd-3-clause | mhvk/numpy,grlee77/numpy,simongibbons/numpy,mhvk/numpy,madphysicist/numpy,endolith/numpy,pbrod/numpy,grlee77/numpy,anntzer/numpy,anntzer/numpy,numpy/numpy,jakirkham/numpy,endolith/numpy,jakirkham/numpy,anntzer/numpy,simongibbons/numpy,mhvk/numpy,rgommers/numpy,abalkin/numpy,pbrod/numpy,mattip/numpy,seberg/numpy,simongi... | ---
+++
@@ -0,0 +1,33 @@
+from .common import Benchmark, TYPES1
+
+import numpy as np
+
+
+class ScalarMath(Benchmark):
+ # Test scalar math, note that each of these is run repeatedly to offset
+ # the function call overhead to some degree.
+ params = [TYPES1]
+ param_names = ["type"]
+ def setup(self,... | |
dda35fad4cb12b8b2fa4c54412f005d16d4a36ff | PDBMap.py | PDBMap.py | import gzip
from xml.parsers import expat
class PDBMap(object):
"""Parse PDBML file for mappings between indexes of auth_seq_num
+ pdb_ind_code (residue index in PDB) and seq_id (starts with 1
and includes unobserved residues).
"""
def __init__(self, pdb):
self.parser = expat.ParserCreate()... | Add parser to parse the mapping between seqid and author assigned PDB indexes from PDBML format. | Add parser to parse the mapping between seqid and author assigned PDB
indexes from PDBML format.
| Python | mit | tryptochan/domain_utils | ---
+++
@@ -0,0 +1,61 @@
+import gzip
+from xml.parsers import expat
+
+class PDBMap(object):
+ """Parse PDBML file for mappings between indexes of auth_seq_num
+ + pdb_ind_code (residue index in PDB) and seq_id (starts with 1
+ and includes unobserved residues).
+ """
+ def __init__(self, pdb):
+ ... | |
e3e6d2acfc94927f145b132c69597fb1883646a9 | src/test/test_util.py | src/test/test_util.py | #! /usr/bin/python
import unittest
sys.path.append(
os.path.join(
os.path.dirname(
os.path.realpath(
__file__)),
"..",
"lib"))
import util
def test_data_dir():
return os.path.join(
os.path.dirname(
os.path.realpath(
__... | Add skeleton unittest file for util.py . | Add skeleton unittest file for util.py .
| Python | bsd-2-clause | rubasov/opensub-utils,rubasov/opensub-utils | ---
+++
@@ -0,0 +1,33 @@
+#! /usr/bin/python
+
+import unittest
+
+sys.path.append(
+ os.path.join(
+ os.path.dirname(
+ os.path.realpath(
+ __file__)),
+ "..",
+ "lib"))
+
+import util
+
+
+def test_data_dir():
+
+ return os.path.join(
+ os.path.dirname(
+ ... | |
307e105ff075a4702169ca5b38e3f3307bfdad5a | tools/clean_submitted_plugins.py | tools/clean_submitted_plugins.py | """Prints out submitted plugins that we don't already know about.
Also deletes any empty submissions.
"""
import json
import re
import rethinkdb as r
import db.github_repos
import db.util
r_conn = db.util.r_conn
_GITHUB_LINK_REGEX = re.compile(r'github.com/(.*?)/([^/?#]*)')
def delete_empty_submissions():
... | Add a script to easily view new submitted plugins | Add a script to easily view new submitted plugins
Summary: That is, submitted plugins that we don't already know about and are non-empty.
Test Plan:
- imported the `submitted_plugins` table from prod
- ran `PYTHONPATH=. python tools/clean_submitted_plugins.py`
- saw the output looked reasonable
Reviewers: xymostech,... | Python | mit | divad12/vim-awesome,vim-awesome/vim-awesome,divad12/vim-awesome,shaialon/vim-awesome,jonafato/vim-awesome,shaialon/vim-awesome,starcraftman/vim-awesome,jonafato/vim-awesome,vim-awesome/vim-awesome,vim-awesome/vim-awesome,divad12/vim-awesome,starcraftman/vim-awesome,shaialon/vim-awesome,jonafato/vim-awesome,starcraftman... | ---
+++
@@ -0,0 +1,86 @@
+"""Prints out submitted plugins that we don't already know about.
+
+Also deletes any empty submissions.
+"""
+
+import json
+import re
+
+import rethinkdb as r
+
+import db.github_repos
+import db.util
+
+r_conn = db.util.r_conn
+
+
+_GITHUB_LINK_REGEX = re.compile(r'github.com/(.*?)/([^/?#... | |
a6b6439e0c142936248e1be46b575595a4b951b9 | custom/enikshay/management/commands/get_users_for_bets.py | custom/enikshay/management/commands/get_users_for_bets.py | import csv
from django.core.management.base import BaseCommand
from corehq.apps.locations.models import SQLLocation
from corehq.apps.users.models import CommCareUser
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('domain')
def confirm(self):
return raw_input... | Add one-off script to get a csv of agency data | Add one-off script to get a csv of agency data
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -0,0 +1,59 @@
+import csv
+from django.core.management.base import BaseCommand
+from corehq.apps.locations.models import SQLLocation
+from corehq.apps.users.models import CommCareUser
+
+
+class Command(BaseCommand):
+
+ def add_arguments(self, parser):
+ parser.add_argument('domain')
+
+ def ... | |
0771bb8d5e1747df6b929d2473f97e687d9e3963 | functionaltests/common/cleanup.py | functionaltests/common/cleanup.py | """
Copyright 2015 IBM
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
distribute... | Create Common functions used for cleaning up items used for testing | Create Common functions used for cleaning up items used for testing
Creates common functions used to cleanup secrets, containers, and
orders used in client functional tests.
Change-Id: I3c37ab78c8c2c1d9a6e5299f303d11d786f39b5e
| Python | apache-2.0 | openstack/python-barbicanclient | ---
+++
@@ -0,0 +1,76 @@
+"""
+Copyright 2015 IBM
+
+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 agre... | |
5847190f8954e7da2871a8419495014bab0e7326 | examples/mnist_mlp.py | examples/mnist_mlp.py | from __future__ import print_function
import plac
from thinc.neural.vec2vec import ReLu, Softmax
from thinc.api import clone, chain
from thinc.extra import datasets
from thinc.neural.loss import categorical_crossentropy
from thinc.neural.util import score_model
import pickle
def main(depth=2, width=512, nb_epoch=... | Change MNIST example for future API | Change MNIST example for future API
| Python | mit | spacy-io/thinc,explosion/thinc,explosion/thinc,spacy-io/thinc,spacy-io/thinc,explosion/thinc,explosion/thinc | ---
+++
@@ -0,0 +1,43 @@
+from __future__ import print_function
+import plac
+
+from thinc.neural.vec2vec import ReLu, Softmax
+from thinc.api import clone, chain
+
+from thinc.extra import datasets
+from thinc.neural.loss import categorical_crossentropy
+from thinc.neural.util import score_model
+
+import pickle
+
... | |
a7449b94b4171e86cd0b5260464949bc4ece7883 | src/sentry/api/serializers/models/project.py | src/sentry/api/serializers/models/project.py | from __future__ import absolute_import
from sentry.api.serializers import Serializer, register
from sentry.models import OrganizationMemberType, Project, Team
@register(Project)
class ProjectSerializer(Serializer):
def get_attrs(self, item_list, user):
organization = item_list[0].team.organization
... | from __future__ import absolute_import
from sentry.api.serializers import Serializer, register
from sentry.models import OrganizationMemberType, Project, Team
@register(Project)
class ProjectSerializer(Serializer):
def get_attrs(self, item_list, user):
organization = item_list[0].team.organization
... | Add Project.first_event to API serializer | Add Project.first_event to API serializer
| Python | bsd-3-clause | mvaled/sentry,fotinakis/sentry,JamesMura/sentry,mvaled/sentry,BuildingLink/sentry,imankulov/sentry,JackDanger/sentry,looker/sentry,zenefits/sentry,daevaorn/sentry,nicholasserra/sentry,looker/sentry,JamesMura/sentry,mitsuhiko/sentry,looker/sentry,nicholasserra/sentry,nicholasserra/sentry,BuildingLink/sentry,JackDanger/s... | ---
+++
@@ -46,6 +46,7 @@
'name': obj.name,
'isPublic': obj.public,
'dateCreated': obj.date_added,
+ 'firstEvent': obj.first_event,
'features': feature_list,
'permission': {
'owner': attrs['access_type'] <= OrganizationMember... |
1b921e83d000d024e38b0d7f81984b699cb49fac | fmriprep/cli/sample_openfmri_tasks_list.py | fmriprep/cli/sample_openfmri_tasks_list.py | # -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
A tool to generate a tasks_list.sh file for running fmriprep
on subjects downloaded with datalad with sample_openfmri.py
"""
import os
import glob
CMDLINE = """\
{fmriprep_cm... | Add simple script to write tasks_list file | [skip ci] Add simple script to write tasks_list file
| Python | bsd-3-clause | poldracklab/fmriprep,poldracklab/preprocessing-workflow,oesteban/preprocessing-workflow,poldracklab/fmriprep,poldracklab/fmriprep,oesteban/fmriprep,oesteban/fmriprep,oesteban/fmriprep,poldracklab/preprocessing-workflow,oesteban/preprocessing-workflow | ---
+++
@@ -0,0 +1,85 @@
+# -*- coding: utf-8 -*-
+# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
+# vi: set ft=python sts=4 ts=4 sw=4 et:
+"""
+A tool to generate a tasks_list.sh file for running fmriprep
+on subjects downloaded with datalad with sample_openfmri.py
+
+
+"""
+
+import os
+i... | |
f4eec09a414157b423ac4790dfe22bc09e55bcdf | misc/mac2lla.py | misc/mac2lla.py | def mac_to_lladdr(mac):
macpieces = []
mac = mac.replace('-', ':')
for byte in mac.split(':'):
macpieces.append(int(byte, 16))
macpieces[0] = macpieces[0] ^ 2
llapieces = [(macpieces[0] << 8) + macpieces[1], (macpieces[2] << 8) + 0xff, 0xfe00 + macpieces[3], (macpieces[4] << 8) + macp... | ADd a sample for converting mac to lla | ADd a sample for converting mac to lla
| Python | apache-2.0 | jjohnson42/confluent,xcat2/confluent,xcat2/confluent,xcat2/confluent,xcat2/confluent,jjohnson42/confluent,xcat2/confluent,jjohnson42/confluent,jjohnson42/confluent,jjohnson42/confluent | ---
+++
@@ -0,0 +1,12 @@
+def mac_to_lladdr(mac):
+ macpieces = []
+ mac = mac.replace('-', ':')
+ for byte in mac.split(':'):
+ macpieces.append(int(byte, 16))
+ macpieces[0] = macpieces[0] ^ 2
+ llapieces = [(macpieces[0] << 8) + macpieces[1], (macpieces[2] << 8) + 0xff, 0xfe00 + macpie... | |
0bca0dfa3fdde298f615e0cbd5239a25bb3cc410 | fortin.py | fortin.py | from __future__ import absolute_import, print_function, division
from firedrake import *
mesh = UnitSquareMesh(2, 2)
RT = FiniteElement("RT", triangle, 1)
BRT = BrokenElement(RT)
U = FunctionSpace(mesh, RT)
Ud = FunctionSpace(mesh, BRT)
x = SpatialCoordinate(mesh)
fct = as_vector([x[0] ** 2, x[1] ** 2])
u0 = Funct... | Add a custom kernel for repairing continuity of broken solutions | Add a custom kernel for repairing continuity of broken solutions
| Python | mit | thomasgibson/firedrake-hybridization | ---
+++
@@ -0,0 +1,64 @@
+from __future__ import absolute_import, print_function, division
+
+from firedrake import *
+
+mesh = UnitSquareMesh(2, 2)
+
+RT = FiniteElement("RT", triangle, 1)
+BRT = BrokenElement(RT)
+
+U = FunctionSpace(mesh, RT)
+Ud = FunctionSpace(mesh, BRT)
+
+x = SpatialCoordinate(mesh)
+fct = as_... | |
002925683bf5d1e8dae12923a248eca77db4e5c7 | tests/azure_disk_integration_test.py | tests/azure_disk_integration_test.py | # Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | Add Azure disk integration test | Add Azure disk integration test
Test that we can actually create a disk in an Azure VM. This is very
similar to the GCP and AWS disk integration tests.
| Python | apache-2.0 | syed/PerfKitBenchmarker,AdamIsrael/PerfKitBenchmarker,GoogleCloudPlatform/PerfKitBenchmarker,GoogleCloudPlatform/PerfKitBenchmarker,syed/PerfKitBenchmarker,kivio/PerfKitBenchmarker,mateusz-blaszkowski/PerfKitBenchmarker,GoogleCloudPlatform/PerfKitBenchmarker,GoogleCloudPlatform/PerfKitBenchmarker,meteorfox/PerfKitBench... | ---
+++
@@ -0,0 +1,82 @@
+# Copyright 2015 Google Inc. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unle... | |
a79c82b58443082827d8817ec15ae1283e5c0e21 | tests/test_string_template.py | tests/test_string_template.py | #!/usr/bin/env python
from __future__ import print_function
import unittest
import engines
HANDLE = 'string.Template'
class TestStringTemplate(unittest.TestCase):
def test_valid_engine(self):
self.assertIn(HANDLE, engines.engines)
engine = engines.engines[HANDLE]
assert issubclass(e... | Add tests for string.Template engine. | Add tests for string.Template engine.
| Python | mit | blubberdiblub/eztemplate | ---
+++
@@ -0,0 +1,116 @@
+#!/usr/bin/env python
+
+from __future__ import print_function
+
+import unittest
+
+
+import engines
+
+
+HANDLE = 'string.Template'
+
+
+class TestStringTemplate(unittest.TestCase):
+
+ def test_valid_engine(self):
+ self.assertIn(HANDLE, engines.engines)
+ engine = engin... | |
22a96b46a5fdcd0359febdeb8372e6655087674d | tests/test_filters.py | tests/test_filters.py | from nose.tools import assert_raises
from helpers import TempEnvironmentHelper
class TestFilters(TempEnvironmentHelper):
def test_pyscss(self):
"""This filter used to make trouble because if required
Environment.url and Environment.directory to be set.
"""
self.create_files({'foo'... | Add a test for the PyScss filter. | Add a test for the PyScss filter.
The new webassets master adds configuration values that make the filter
usable with Flask-Assets.
| Python | bsd-2-clause | miracle2k/flask-assets,0x1997/flask-assets,0x1997/flask-assets,miracle2k/flask-assets | ---
+++
@@ -0,0 +1,21 @@
+from nose.tools import assert_raises
+from helpers import TempEnvironmentHelper
+
+
+class TestFilters(TempEnvironmentHelper):
+
+ def test_pyscss(self):
+ """This filter used to make trouble because if required
+ Environment.url and Environment.directory to be set.
+ ... | |
b826571c35de75a62d23b2b92530508a9466b7d0 | tests/test_simdata.py | tests/test_simdata.py | import nose
import cle
import os
test_location = os.path.join(os.path.dirname(os.path.realpath(__file__)),
os.path.join('..', '..', 'binaries', 'tests'))
def test_progname():
filename = os.path.join(test_location, 'x86_64', 'cat')
ld = cle.Loader(filename, auto_loa... | Add test for simdata and GOT relocations | Add test for simdata and GOT relocations
| Python | bsd-2-clause | angr/cle | ---
+++
@@ -0,0 +1,36 @@
+import nose
+import cle
+
+import os
+test_location = os.path.join(os.path.dirname(os.path.realpath(__file__)),
+ os.path.join('..', '..', 'binaries', 'tests'))
+
+def test_progname():
+ filename = os.path.join(test_location, 'x86_64', 'cat')
+ ... | |
abb2bf0cfff38a94392d32a68cec912da09f2f79 | test/part_gpt.py | test/part_gpt.py | #!/usr/bin/env python
#
# Windows Azure Linux Agent
#
# Copyright 2014 Microsoft Corporation
#
# 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... | Add test script to create gpt partition for test | Add test script to create gpt partition for test
| Python | apache-2.0 | yuezh/WALinuxAgent,thomas1206/WALinuxAgent,yuezh/WALinuxAgent,lizzha/WALinuxAgent,imikushin/WALinuxAgent,jerickso/WALinuxAgent,karataliu/WALinuxAgent,SuperScottz/WALinuxAgent,AbelHu/WALinuxAgent,AbelHu/WALinuxAgent,thomas1206/WALinuxAgent,SuperScottz/WALinuxAgent,fieryorc/WALinuxAgent,jerickso/WALinuxAgent,lizzha/WALin... | ---
+++
@@ -0,0 +1,33 @@
+#!/usr/bin/env python
+#
+# Windows Azure Linux Agent
+#
+# Copyright 2014 Microsoft Corporation
+#
+# 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... | |
61b7ccb6b48e8894ab9212d88c58a49423aacc33 | nap/utils/ripper.py | nap/utils/ripper.py | '''
Extremely light-weight serialiser for very simple cases.
'''
from operator import attrgetter
from collections import namedtuple
class Ripper(object):
def __init__(self, *args, **kwargs):
for arg in args:
kwargs.setdefault(arg, arg)
self.getter = attrgetter(kwargs.values())
... | Add Ripper class to utils | Add Ripper class to utils
| Python | bsd-3-clause | limbera/django-nap | ---
+++
@@ -0,0 +1,16 @@
+'''
+Extremely light-weight serialiser for very simple cases.
+'''
+from operator import attrgetter
+from collections import namedtuple
+
+
+class Ripper(object):
+ def __init__(self, *args, **kwargs):
+ for arg in args:
+ kwargs.setdefault(arg, arg)
+ self.getter... | |
739be6f9d80b95fc4c0918f64be8438eb04736a1 | manage.py | manage.py | from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import db, create_app
from app.models import User, BucketList, Item
app = create_app("development")
manager = Manager(app)
migrate = Migrate(app, db)
@manager.command
def createdb():
db.create_all()
print("database ta... | Add database migrations and creation script | Add database migrations and creation script
| Python | mit | brayoh/bucket-list-api | ---
+++
@@ -0,0 +1,23 @@
+from flask_script import Manager
+from flask_migrate import Migrate, MigrateCommand
+
+from app import db, create_app
+from app.models import User, BucketList, Item
+
+app = create_app("development")
+manager = Manager(app)
+migrate = Migrate(app, db)
+
+@manager.command
+def createdb():
+ ... | |
f61ad947c8fc38201da452d2cfd7d4ce9540912f | scripts/export_glclient_error_codes.py | scripts/export_glclient_error_codes.py | import inspect
import string
import sys
import os
globaleaks_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
sys.path.append(globaleaks_path)
from globaleaks.rest import errors
def return_exception(klass):
reason_string = ""
arguments = inspect.getargspec(klass.__init__).args
argumen... | Add script for generating error code handling in GLCLient | Add script for generating error code handling in GLCLient
| Python | agpl-3.0 | vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks | ---
+++
@@ -0,0 +1,63 @@
+import inspect
+import string
+import sys
+import os
+globaleaks_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
+sys.path.append(globaleaks_path)
+
+from globaleaks.rest import errors
+
+def return_exception(klass):
+ reason_string = ""
+ arguments = inspect.geta... | |
0b95e92c41cf9a0a266912e9db081aa7f6bc99d7 | scripts/lwtnn-test-keras-functional.py | scripts/lwtnn-test-keras-functional.py | #!/usr/bin/env python3
"""
Run Keras as a compainion to lwtnn-test-lightweight-graph
"""
_help_arch_file = "NN archetecture file from Keras"
_help_vars_file = "Variable description file"
_help_hdf5_file = "Weights file from Keras"
from argparse import ArgumentParser, RawDescriptionHelpFormatter
from numpy import lins... | Add a script to test keras functional models | Add a script to test keras functional models
We have a C++ script to test functional models using lwtnn, this adds
a short script to test the same model in Keras. At the moment it only
tests a dummy "ramp" pattern, i.e. np.linspace(-1, 1, n_features).
| Python | mit | lwtnn/lwtnn,lwtnn/lwtnn,lwtnn/lwtnn | ---
+++
@@ -0,0 +1,53 @@
+#!/usr/bin/env python3
+
+"""
+Run Keras as a compainion to lwtnn-test-lightweight-graph
+"""
+_help_arch_file = "NN archetecture file from Keras"
+_help_vars_file = "Variable description file"
+_help_hdf5_file = "Weights file from Keras"
+
+from argparse import ArgumentParser, RawDescriptio... | |
9e5b505cfa4c3f1bfca09588c14219fc1d71c009 | modules/probablity_manipulation.py | modules/probablity_manipulation.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed May 3 12:12:53 2017
@author: daniele
"""
import numpy as np
def minmaxlog(value):
"""
Rounds the value as max(min(value,1−10^{-15},10^{-15})), wrapped by the
natural logarithm. This is useful for calculating the cross-entropy on
(reg... | Include module for probability manipulations | feat: Include module for probability manipulations
| Python | mit | dangall/Kaggle-MobileODT-Cancer-Screening | ---
+++
@@ -0,0 +1,77 @@
+#!/usr/bin/env python2
+# -*- coding: utf-8 -*-
+"""
+Created on Wed May 3 12:12:53 2017
+
+@author: daniele
+"""
+
+import numpy as np
+
+
+def minmaxlog(value):
+ """
+ Rounds the value as max(min(value,1−10^{-15},10^{-15})), wrapped by the
+ natural logarithm. This is useful for... | |
ad7cd889a9346763baa802248ab92c771dbd9c6f | test/util/test_pivoted_cholesky.py | test/util/test_pivoted_cholesky.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import torch
import unittest
from torch.autograd import Variable
from gpytorch.utils import pivoted_cholesky, approx_equal
from gpytorch.kernels import RBFKernel
class ... | Add unit test for pivoted cholesky | Add unit test for pivoted cholesky
| Python | mit | jrg365/gpytorch,jrg365/gpytorch,jrg365/gpytorch | ---
+++
@@ -0,0 +1,40 @@
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+from __future__ import unicode_literals
+
+import torch
+import unittest
+from torch.autograd import Variable
+from gpytorch.utils import pivoted_cholesky, approx_equal
+from gpyto... | |
8798a525cbb0c38f1c31a86dff81c6b2bae1ac42 | pony_barn/build-compressor.py | pony_barn/build-compressor.py | import sys
from base import BaseBuild
from pony_build import client as pony
class PonyBuild(BaseBuild):
def __init__(self):
super(PonyBuild, self).__init__()
self.repo_url = "git://github.com/mintchaos/django_compressor.git"
self.name = "django_compressor"
self.required = ['django'... | Add a build for django_compressor. | Add a build for django_compressor. | Python | mit | ericholscher/pony_barn,ericholscher/pony_barn | ---
+++
@@ -0,0 +1,21 @@
+import sys
+from base import BaseBuild
+from pony_build import client as pony
+
+class PonyBuild(BaseBuild):
+
+ def __init__(self):
+ super(PonyBuild, self).__init__()
+ self.repo_url = "git://github.com/mintchaos/django_compressor.git"
+ self.name = "django_compress... | |
982182bef55925eb02e15e819fa7e6c41ba3c12f | demos/ant.core/02-capabilities-USB.py | demos/ant.core/02-capabilities-USB.py | """
Interrogate stick for supported capabilities.
"""
import sys
from ant.core import driver
from ant.core import node
from config import *
# Initialize
stick = driver.USB2Driver(SERIAL, log=LOG, debug=DEBUG)
antnode = node.Node(stick)
antnode.start()
# Interrogate stick
# Note: This method will return immediatel... | Add an example of how to use the USB driver | Add an example of how to use the USB driver
| Python | mit | mvillalba/python-ant,baderj/python-ant,ramunasd/python-ant,mch/python-ant,mch/python-ant,ramunasd/python-ant,tomwardill/python-ant,SamyCookie/python-ant,SamyCookie/python-ant,mvillalba/python-ant,baderj/python-ant | ---
+++
@@ -0,0 +1,30 @@
+"""
+Interrogate stick for supported capabilities.
+
+"""
+
+import sys
+
+from ant.core import driver
+from ant.core import node
+
+from config import *
+
+# Initialize
+stick = driver.USB2Driver(SERIAL, log=LOG, debug=DEBUG)
+antnode = node.Node(stick)
+antnode.start()
+
+# Interrogate sti... | |
afcf211801e3b84dd6a1b1c069b7e020db053e46 | scripts/top_couplings.py | scripts/top_couplings.py | #!/usr/bin/env python
import numpy as np
import optparse
def main():
parser = optparse.OptionParser(usage="%prog [options] coupling_matrix")
parser.add_option("-s", "--min-separation", type=int, default=7, help="Set the minimum sequence separation of pairs to be outputted [default: %default]")
parser.add... | Add script to extract top couplings | Add script to extract top couplings
| Python | agpl-3.0 | soedinglab/CCMpred,soedinglab/CCMpred,soedinglab/CCMpred,soedinglab/CCMpred | ---
+++
@@ -0,0 +1,43 @@
+#!/usr/bin/env python
+
+import numpy as np
+import optparse
+
+
+def main():
+ parser = optparse.OptionParser(usage="%prog [options] coupling_matrix")
+ parser.add_option("-s", "--min-separation", type=int, default=7, help="Set the minimum sequence separation of pairs to be outputted ... | |
8ed78d362cc24d10a0b692ad673c9cd55080b01c | gostop.py | gostop.py | import sys
import random
import argparse
from gostop import GameState, HumanAgent, RandomAgent
def main(argv):
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-f', '--fixed-random-seed', dest='fixed_random_seed',
help='Use... | Add basic state machine and game mechanics. | Add basic state machine and game mechanics.
| Python | mit | reidlindsay/gostop | ---
+++
@@ -0,0 +1,41 @@
+import sys
+import random
+import argparse
+
+from gostop import GameState, HumanAgent, RandomAgent
+
+
+def main(argv):
+ parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
+
+ parser.add_argument('-f', '--fixed-random-seed', dest='fixed_random_se... | |
a7f763d19a28be34d7a9a745a536c97d59720b24 | checks/check_canny.py | checks/check_canny.py | from __future__ import print_function, division
import imgaug as ia
import imgaug.augmenters as iaa
def main():
black_and_white = iaa.RandomColorsBinaryImageColorizer(
color_fg=255, color_bg=0)
print("alpha=1.0, black and white")
image = ia.quokka_square((128, 128))
aug = iaa.Canny(alpha=1.0,... | Add check script for canny | Add check script for canny
| Python | mit | aleju/ImageAugmenter,aleju/imgaug,aleju/imgaug | ---
+++
@@ -0,0 +1,39 @@
+from __future__ import print_function, division
+import imgaug as ia
+import imgaug.augmenters as iaa
+
+
+def main():
+ black_and_white = iaa.RandomColorsBinaryImageColorizer(
+ color_fg=255, color_bg=0)
+
+ print("alpha=1.0, black and white")
+ image = ia.quokka_square((128... | |
e8d56263545966520a1479e09e53836122b69923 | models.py | models.py | import datetime
from flask import url_for
from Simpoll import db
class Poll(db.Document):
created_at = db.DateTimeField(default=datetime.datetime.now, required=True)
question = db.StringField(max_length=255, required=True)
option1 = db.StringField(max_length=255, required=True)
option2 = db.StringFiel... | Add model for polls db | Add model for polls db
| Python | mit | dpuleri/simpoll_backend,dpuleri/simpoll_backend,dpuleri/simpoll_backend,dpuleri/simpoll_backend | ---
+++
@@ -0,0 +1,30 @@
+import datetime
+from flask import url_for
+from Simpoll import db
+
+
+class Poll(db.Document):
+ created_at = db.DateTimeField(default=datetime.datetime.now, required=True)
+ question = db.StringField(max_length=255, required=True)
+ option1 = db.StringField(max_length=255, requir... | |
b2e91b9f05b7556c224c4b74566caed953075f95 | open-hackathon-server/test/unittest/hk8s/test_k8s_expr_starter.py | open-hackathon-server/test/unittest/hk8s/test_k8s_expr_starter.py | # -*- coding: utf-8 -*-
"""
This file is covered by the LICENSING file in the root of this project.
"""
import unittest
from mock import Mock
# setup import path
try:
import hackathon # noqa
except ImportError:
import os
import sys
BASE_DIR = os.path.dirname(__file__)
sys.path.append(os.path.real... | Add unit test cases for k8s expr starter | Add unit test cases for k8s expr starter
1, start_expr
Signed-off-by: chensong <ae7d166f23a6fc29809e39146fc64585e5c46680@linuxep.com>
| Python | mit | juniwang/open-hackathon,juniwang/open-hackathon,juniwang/open-hackathon,msopentechcn/open-hackathon,juniwang/open-hackathon,msopentechcn/open-hackathon,msopentechcn/open-hackathon,msopentechcn/open-hackathon,juniwang/open-hackathon,msopentechcn/open-hackathon,msopentechcn/open-hackathon,juniwang/open-hackathon | ---
+++
@@ -0,0 +1,39 @@
+# -*- coding: utf-8 -*-
+"""
+This file is covered by the LICENSING file in the root of this project.
+"""
+
+import unittest
+from mock import Mock
+
+# setup import path
+try:
+ import hackathon # noqa
+except ImportError:
+ import os
+ import sys
+ BASE_DIR = os.path.dirname(... | |
317c1b8fcc64bb591e87bf3838c068ef979488c3 | tools_webrtc/coverage/generate_coverage_command.py | tools_webrtc/coverage/generate_coverage_command.py | #!/usr/bin/env python
# Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All c... | Add script for generating coverage.py commands. | Add script for generating coverage.py commands.
It's only correct for Linux for now.
Bug: chromium:844647
Change-Id: I8fce28d88a4d060553e30fe0862d34815988ba61
Reviewed-on: https://webrtc-review.googlesource.com/79149
Reviewed-by: Mirko Bonadei <d2c43c210eae6feef04f53bae50885e8152edcca@webrtc.org>
Commit-Queue: Patrik... | Python | bsd-3-clause | TimothyGu/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,ShiftMediaProject/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc | ---
+++
@@ -0,0 +1,55 @@
+#!/usr/bin/env python
+# Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
+#
+# Use of this source code is governed by a BSD-style license
+# that can be found in the LICENSE file in the root of the source
+# tree. An additional intellectual property rights grant can be fo... | |
8c2350db0106853b06d8889e873992873f4bf00a | smt_markdown.py | smt_markdown.py | #import pylab
#import numpy as npf
from sumatra.projects import load_project
from texttable import Texttable
from sumatra.formatting import HTMLFormatter
def markdown_table(records):
fields = ['label', 'timestamp', 'reason', 'duration']
table = Texttable()
table.set_cols_dtype(['t'] * len(fields))
rows... | Add module to create markdown/HTML table entry and update ipynb. | Add module to create markdown/HTML table entry and update ipynb.
| Python | mit | wd15/extremefill2D,wd15/extremefill2D | ---
+++
@@ -0,0 +1,34 @@
+#import pylab
+#import numpy as npf
+from sumatra.projects import load_project
+from texttable import Texttable
+from sumatra.formatting import HTMLFormatter
+
+def markdown_table(records):
+ fields = ['label', 'timestamp', 'reason', 'duration']
+ table = Texttable()
+ table.set_col... | |
aa64072c2cc08e1b5fee872216377d14a567a223 | metric.py | metric.py | import string
pct = string.punctuation
articles = ['a','an','the']
def _clean_string(x):
# lowercase, remove articles, remove punctuation,
# and return as a single string without whitespace
toks = filter(lambda t:t not in articles, x.lower().split())
return ''.join([''.join(filter(lambda c:c not in p... | Add script computing exact_match and f1_match for Quasar-T | Add script computing exact_match and f1_match for Quasar-T | Python | bsd-2-clause | bdhingra/quasar | ---
+++
@@ -0,0 +1,28 @@
+import string
+
+pct = string.punctuation
+articles = ['a','an','the']
+
+def _clean_string(x):
+ # lowercase, remove articles, remove punctuation,
+ # and return as a single string without whitespace
+ toks = filter(lambda t:t not in articles, x.lower().split())
+ return ''.joi... | |
87456ed686e3ed55ce8abca68647f71653de709d | proximitySwTest.py | proximitySwTest.py | import RPi.GPIO as GPIO
import time
# Use GPIO numbers, not pin numbers (alt=BOARD for the numbers on the GPIO header pins)
GPIO.setmode(GPIO.BCM)
#set up the GPIO BCM channel 17 for input
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_UP)
lv=True;
cv=True;
while (Tr... | Test script for machanical and optical limit switches on GPIO | Test script for machanical and optical limit switches on GPIO
| Python | agpl-3.0 | NohWayJose/PanCam | ---
+++
@@ -0,0 +1,30 @@
+import RPi.GPIO as GPIO
+import time
+
+# Use GPIO numbers, not pin numbers (alt=BOARD for the numbers on the GPIO header pins)
+GPIO.setmode(GPIO.BCM)
+
+#set up the GPIO BCM channel 17 for input
+GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
+GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.P... | |
01edb715a7716627fe3c73af74fa3c5bdd30995e | acq4/modules/MultiPatch/tests/test_logfile.py | acq4/modules/MultiPatch/tests/test_logfile.py | import numpy as np
from acq4.modules.MultiPatch.logfile import MultiPatchLog, IrregularTimeSeries
def test_timeseries_index():
ts1 = [
(10, 0.5),
(12, 13.4),
(29.8, 5),
(29.9, 6),
(30.0, 7),
(30.1, 8),
(35, 0),
]
ts2 = [
(10, (0.5, ... | Add multipatch logfile unit tests | Add multipatch logfile unit tests
| Python | mit | pbmanis/acq4,meganbkratz/acq4,meganbkratz/acq4,meganbkratz/acq4,acq4/acq4,pbmanis/acq4,pbmanis/acq4,pbmanis/acq4,acq4/acq4,campagnola/acq4,acq4/acq4,campagnola/acq4,acq4/acq4,campagnola/acq4,meganbkratz/acq4,campagnola/acq4 | ---
+++
@@ -0,0 +1,66 @@
+import numpy as np
+from acq4.modules.MultiPatch.logfile import MultiPatchLog, IrregularTimeSeries
+
+
+def test_timeseries_index():
+
+ ts1 = [
+ (10, 0.5),
+ (12, 13.4),
+ (29.8, 5),
+ (29.9, 6),
+ (30.0, 7),
+ (30.1, 8),
+ (35, 0),
+... | |
6f9f87547ed193d01d00a6c0e6f3e3ad5206e4ed | sprotbot/notify.py | sprotbot/notify.py |
import boto3
import os
def get_aws_creds():
"""
Pulls the AWS credentials from the current environment.
This assumes the following two environment variables are set:
- AWS_ACCESS_KEY_ID -- the public part of the AWS credential
- AWS_SECRET_ACCESS_KEY -- the private part of the AWS credent... | Add code for the mechanical aspects of sending te emails via AWS. | Add code for the mechanical aspects of sending te emails via AWS.
| Python | mit | SUWS/sprotbot | ---
+++
@@ -0,0 +1,51 @@
+
+import boto3
+import os
+
+def get_aws_creds():
+ """
+ Pulls the AWS credentials from the current environment.
+ This assumes the following two environment variables are set:
+
+ - AWS_ACCESS_KEY_ID -- the public part of the AWS credential
+ - AWS_SECRET_ACCESS_KEY ... | |
25cb6af32c79466989b7d5404b885c3586740b53 | zerver/management/commands/create_default_stream_groups.py | zerver/management/commands/create_default_stream_groups.py |
from typing import Any
from argparse import ArgumentParser
from confirmation.models import Confirmation, create_confirmation_link
from zerver.lib.management import ZulipBaseCommand
from zerver.lib.actions import create_stream_if_needed
from zerver.models import MultiuseInvite, DefaultStream, DefaultStreamGroup
clas... | Create command for creating default stream groups. | mangement: Create command for creating default stream groups.
| Python | apache-2.0 | jackrzhang/zulip,brainwane/zulip,showell/zulip,punchagan/zulip,hackerkid/zulip,hackerkid/zulip,brainwane/zulip,shubhamdhama/zulip,tommyip/zulip,shubhamdhama/zulip,rht/zulip,Galexrt/zulip,eeshangarg/zulip,synicalsyntax/zulip,brainwane/zulip,brockwhittaker/zulip,hackerkid/zulip,timabbott/zulip,synicalsyntax/zulip,Galexrt... | ---
+++
@@ -0,0 +1,59 @@
+
+from typing import Any
+
+from argparse import ArgumentParser
+from confirmation.models import Confirmation, create_confirmation_link
+from zerver.lib.management import ZulipBaseCommand
+from zerver.lib.actions import create_stream_if_needed
+from zerver.models import MultiuseInvite, Defau... | |
262ec846a2ab961329c5a08a6f059cefb2c27de8 | shapes.py | shapes.py | import tensorflow as tf
def shape(tt):
"""Returns the shape of a TensorTrain.
This operation returns a 1-D integer tensor representing the shape of
the input. For TT-matrices the shape would have two values, see raw_shape for
the tensor shape.
Args:
tt: `TensorTrain` object.
Returns:
A `Tensor`... | Implement dynamic shape and raw_shape | Implement dynamic shape and raw_shape
| Python | mit | Bihaqo/t3f | ---
+++
@@ -0,0 +1,48 @@
+import tensorflow as tf
+
+
+def shape(tt):
+ """Returns the shape of a TensorTrain.
+
+ This operation returns a 1-D integer tensor representing the shape of
+ the input. For TT-matrices the shape would have two values, see raw_shape for
+ the tensor shape.
+
+ Args:
+ tt: `TensorTr... | |
d7d07ca5416e78c4c5eccc8cf80a9e3620beadba | tests/test_reuse.py | tests/test_reuse.py |
from django.template import TemplateSyntaxError
from django.template.loader import get_template
from django.test import SimpleTestCase
from .utils import TemplateTestMixin
class TestReuse(TemplateTestMixin, SimpleTestCase):
TEMPLATES = {
'base': '''{% block main %}{% endblock %}''',
'reuse': '''... | Add simple test for reuse | Add simple test for reuse
| Python | mit | funkybob/django-sniplates,wengole/django-sniplates,sergei-maertens/django-sniplates,funkybob/django-sniplates,sergei-maertens/django-sniplates,kezabelle/django-sniplates,wengole/django-sniplates,kezabelle/django-sniplates,sergei-maertens/django-sniplates,kezabelle/django-sniplates | ---
+++
@@ -0,0 +1,19 @@
+
+from django.template import TemplateSyntaxError
+from django.template.loader import get_template
+from django.test import SimpleTestCase
+
+from .utils import TemplateTestMixin
+
+
+class TestReuse(TemplateTestMixin, SimpleTestCase):
+ TEMPLATES = {
+ 'base': '''{% block main %}{... | |
e5495db9f28b3fc1bd44c56c21e3aedb9a19e777 | string.py | string.py | # Basic string exercises
# Fill in the definitions for the required functions. The main functions and the testing
# has been handled, so when you run a program, you will get an output of how many testcases
# passed and how many didn't.
# A. Odd Rotation
def odd_rotation(number, word):
"""
The function takes a numb... | Add first set of exercises | Add first set of exercises
| Python | mit | AlexMathew/csipy-exercises | ---
+++
@@ -0,0 +1,60 @@
+# Basic string exercises
+# Fill in the definitions for the required functions. The main functions and the testing
+# has been handled, so when you run a program, you will get an output of how many testcases
+# passed and how many didn't.
+
+
+# A. Odd Rotation
+def odd_rotation(number, wor... | |
a11bca7772de655a6629d0070181cd4e027fc0d4 | accelerator/tests/test_utils.py | accelerator/tests/test_utils.py | from bullet_train import BulletTrain
from mock import patch
from django.test import TestCase
from ..utils import flag_smith_has_feature
class TestUtils(TestCase):
def test_flag_smith_has_feature(self):
with patch("bullet_train.BulletTrain.has_feature") as mock_function:
flag_smith_has_feature... | Add quick unit test for flag_smith_has_feature | [AC-8173] Add quick unit test for flag_smith_has_feature
| Python | mit | masschallenge/django-accelerator,masschallenge/django-accelerator | ---
+++
@@ -0,0 +1,13 @@
+from bullet_train import BulletTrain
+from mock import patch
+from django.test import TestCase
+
+from ..utils import flag_smith_has_feature
+
+
+class TestUtils(TestCase):
+ def test_flag_smith_has_feature(self):
+ with patch("bullet_train.BulletTrain.has_feature") as mock_functio... | |
2e7bff01ce3b15b943691a82e766ceffda0cc355 | fourth_edition/ch2_linked_lists/python/2.1.py | fourth_edition/ch2_linked_lists/python/2.1.py | '''
Write code to remove duplicates from an unsorted linked list.
FOLLOW UP
How would you solve this problem if a temporary buffer is not allowed?
'''
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next_node = next_node
def get_data(self):
ret... | Remove duplicates from an unsorted linked list | Remove duplicates from an unsorted linked list
| Python | mit | roommen/CtCI | ---
+++
@@ -0,0 +1,103 @@
+'''
+Write code to remove duplicates from an unsorted linked list.
+FOLLOW UP
+How would you solve this problem if a temporary buffer is not allowed?
+'''
+
+
+class Node(object):
+ def __init__(self, data=None, next_node=None):
+ self.data = data
+ self.next_node = next_no... | |
3e51aa99f27f5e61737cc900cbbdfe53bd8c212b | docstamp/filenames.py | docstamp/filenames.py | # coding=utf-8
# -------------------------------------------------------------------------------
# Author: Alexandre Manhaes Savio <alexsavio@gmail.com>
# Grupo de Inteligencia Computational <www.ehu.es/ccwintco>
# Universidad del Pais Vasco UPV/EHU
#
# 2015, Alexandre Manhaes Savio
# Use this at your own risk!
# -----... | Add helpers to manage file names | Add helpers to manage file names
| Python | apache-2.0 | PythonSanSebastian/docstamp | ---
+++
@@ -0,0 +1,103 @@
+# coding=utf-8
+# -------------------------------------------------------------------------------
+# Author: Alexandre Manhaes Savio <alexsavio@gmail.com>
+# Grupo de Inteligencia Computational <www.ehu.es/ccwintco>
+# Universidad del Pais Vasco UPV/EHU
+#
+# 2015, Alexandre Manhaes Savio
+... | |
b1b0f1b58c0f14e4778a5a3f5342ee8064e805e7 | src/htmgenerator.py | src/htmgenerator.py | '''
Created on 06 Jan 2016
Copyright (c) 2014 Brendan Gray and Sylvermyst Technologies
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 limit... | Add empty module for html generation | Add empty module for html generation
| Python | mit | AlphaSheep/ZBLL-Sorter,AlphaSheep/ZBLL-Sorter,AlphaSheep/ZBLL-Sorter | ---
+++
@@ -0,0 +1,29 @@
+'''
+Created on 06 Jan 2016
+
+ Copyright (c) 2014 Brendan Gray and Sylvermyst Technologies
+
+ 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 r... | |
c0fb4702f091e83f190ef84bb4f66c7521e83436 | wunder.py | wunder.py | #!/usr/bin/env python
'''
Wunderground API command line script.
'''
import sys
import requests
# todo: raise error if no config file
from config import WUAPI
class Wunder(object):
''' Wunderground API class. '''
lookup_zip = 'http://api.wunderground.com/api/{}/geolookup/q/{}.json'
us_city_current_condi... | Add basic Wunderground API wrapper. | Add basic Wunderground API wrapper.
| Python | mit | abshinn/weather | ---
+++
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+'''
+Wunderground API command line script.
+'''
+
+import sys
+import requests
+
+# todo: raise error if no config file
+from config import WUAPI
+
+
+class Wunder(object):
+ ''' Wunderground API class. '''
+
+ lookup_zip = 'http://api.wunderground.com/api/{}/geo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.