commit
stringlengths
40
40
subject
stringlengths
1
3.25k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
old_contents
stringlengths
0
26.3k
lang
stringclasses
3 values
proba
float64
0
1
diff
stringlengths
0
7.82k
c556ac78efe4b9a9453016dfdf39219852b42676
test app, certain to fail
tests/app.py
tests/app.py
Python
0
@@ -0,0 +1,268 @@ +import tornado.ioloop%0Aimport tornado.web%0Afrom graphnado import GraphQLHandler%0A%0Aif __name__ == '__main__':%0A application = tornado.web.Application(%5B%0A (r'/graphql', GraphQLHandler)%0A %5D)%0A application.listen(8888)%0A tornado.ioloop.IOLoop.current().start()%0A
15eb41ba9ac22eb2ecc60b82807ca7f333f578b9
Add basic methods for accessing user data
iatidq/dqusers.py
iatidq/dqusers.py
Python
0.000005
@@ -0,0 +1,1164 @@ +%0A# IATI Data Quality, tools for Data QA on IATI-formatted publications%0A# by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith%0A#%0A# Copyright (C) 2013 Publish What You Fund%0A#%0A# This programme is free software; you may redistribute and/or modify%0A# it under the terms of the GNU Affero General Public License v3.0%0A%0Afrom iatidq import db%0A%0Aimport models%0A%0Adef user(user_id=None):%0A if user_id:%0A user = models.User.query.filter_by(id=user_id%0A ).first()%0A return user%0A return None%0A%0Adef user_by_username(username=None):%0A if username:%0A user = models.User.query.filter_by(username=username%0A ).first()%0A return user%0A return None%0A%0Adef addUser(data):%0A checkU = models.User.query.filter_by(username=data%5B%22username%22%5D%0A ).first()%0A if not checkU:%0A newU = models.User()%0A newU.setup(%0A username = data%5B%22username%22%5D,%0A password = app.config%5B%22ADMIN_PASSWORD%22%5D,%0A name = data.get('name'),%0A email_address = data.get('name')%0A )%0A db.session.add(newU)%0A db.session.commit()%0A return user%0A return None%0A
8c287ca7b3f184c692356c81a93007936a7a5b01
fix import torngas but not found tornado
torngas/__init__.py
torngas/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'mqingyn' __version__ = '1.8.1' version = tuple(map(int, __version__.split('.'))) from settings_manager import settings from webserver import Server, run from exception import ConfigError, ArgumentError from urlhelper import Url, route, include from utils import is_future, RWLock, cached_property, lazyimport, Null, \ safestr, safeunicode, strips, iterbetter, sleep, request_context from storage import storage, storify, sorteddict, ThreadedDict
Python
0
@@ -81,17 +81,17 @@ = '1.8. -1 +2 '%0A%0Aversi @@ -135,17 +135,25 @@ ('.')))%0A -%0A +try:%0A from set @@ -182,16 +182,20 @@ ettings%0A + from web @@ -220,16 +220,20 @@ er, run%0A + from exc @@ -273,16 +273,20 @@ ntError%0A + from url @@ -319,16 +319,20 @@ include%0A + from uti @@ -397,16 +397,20 @@ Null, %5C%0A + safe @@ -470,16 +470,20 @@ context%0A + from sto @@ -537,8 +537,24 @@ dedDict%0A +except:%0A pass
19b588e4ac9811879fba7e98943cf5925a774a00
add migration 102bbf265d4
migrations/versions/102bbf265d4_.py
migrations/versions/102bbf265d4_.py
Python
0.000004
@@ -0,0 +1,606 @@ +%22%22%22empty message%0A%0ARevision ID: 102bbf265d4%0ARevises: 3d1138bbc68%0ACreate Date: 2015-06-12 01:35:12.398937%0A%0A%22%22%22%0A%0A# revision identifiers, used by Alembic.%0Arevision = '102bbf265d4'%0Adown_revision = '3d1138bbc68'%0A%0Afrom alembic import op%0Aimport sqlalchemy as sa%0A%0A%0Adef upgrade():%0A ### commands auto generated by Alembic - please adjust! ###%0A op.add_column('user', sa.Column('openid', sa.String(length=200), nullable=True))%0A ### end Alembic commands ###%0A%0A%0Adef downgrade():%0A ### commands auto generated by Alembic - please adjust! ###%0A op.drop_column('user', 'openid')%0A ### end Alembic commands ###%0A
dd25e263b099b86e7b9538e474ad875798514be5
Add StorageDevice class
Cura/StorageDevice.py
Cura/StorageDevice.py
Python
0
@@ -0,0 +1,863 @@ +%0A## Encapsulates a number of different ways of storing file data.%0A#%0Aclass StorageDevice(object):%0A def __init__(self):%0A super(StorageDevice, self).__init__()%0A self._properties = %7B%7D%0A %0A ## Open a file so it can be read from or written to.%0A # %5Cparam file_name The name of the file to open. Can be ignored if not applicable.%0A # %5Cparam mode What mode to open the file with. See Python's open() function for details. Can be ignored if not applicable.%0A # %5Creturn An open stream that can be read from or written to.%0A def openFile(self, file_name, mode):%0A raise NotImplementedError()%0A %0A def getStorageProperty(self, name):%0A try:%0A return self._properties%5Bname%5D%0A except KeyError:%0A return None%0A %0A def setStorageProperty(self, name, value):%0A self._properties%5Bname%5D = value%0A
dbc1e4c5348e1a64279018910d1e73542c016313
Fix TestAccountElsewhere.test_github_oauth_url_not_susceptible_to_injection_attack.
tests/test_elsewhere.py
tests/test_elsewhere.py
from __future__ import print_function, unicode_literals from aspen.website import Website from gittip.elsewhere.twitter import TwitterAccount from gittip.testing import Harness from gittip.elsewhere import bitbucket, github, twitter # I ended up using TwitterAccount to test even though this is generic # functionality, because the base class is too abstract. class TestAccountElsewhere(Harness): def test_opt_in_can_change_username(self): account = TwitterAccount("alice", {}) expected = "bob" actual = account.opt_in("bob")[0].participant.username assert actual == expected def test_opt_in_doesnt_have_to_change_username(self): self.make_participant("bob") account = TwitterAccount("alice", {}) expected = account.participant # A random one. actual = account.opt_in("bob")[0].participant.username assert actual == expected # https://github.com/gittip/www.gittip.com/issues/1042 # ==================================================== xss = '/on/twitter/"><img src=x onerror=prompt(1);>/' def test_twitter_oauth_url_percent_encodes_then(self): expected = '/on/twitter/redirect?action=opt-in&then=L29uL3R3aXR0ZXIvIj48aW1nIHNyYz14IG9uZXJyb3I9cHJvbXB0KDEpOz4v' actual = twitter.oauth_url( website=None , action='opt-in' , then=self.xss ) assert actual == expected def test_bitbucket_oauth_url_percent_encodes_then(self): expected = '/on/bitbucket/redirect?action=opt-in&then=L29uL3R3aXR0ZXIvIj48aW1nIHNyYz14IG9uZXJyb3I9cHJvbXB0KDEpOz4v' actual = self.platforms.bitbucket.oauth_url( action='opt-in', then=self.xss, ) assert actual == expected def test_github_oauth_url_not_susceptible_to_injection_attack(self): expected = 'https://github.com/login/oauth/authorize?client_id=cheese&redirect_uri=nuts?data=b3B0LWluLC9vbi90d2l0dGVyLyI+PGltZyBzcmM9eCBvbmVycm9yPXByb21wdCgxKTs+Lw==' website = Website([]) website.github_client_id = 'cheese' website.github_callback= 'nuts' actual = github.oauth_url( website=website , action='opt-in' , then=self.xss ) assert actual == expected
Python
0
@@ -2205,16 +2205,31 @@ ctual = +self.platforms. github.o @@ -2229,32 +2229,44 @@ ithub.oauth_url( +%0A website=website @@ -2265,16 +2265,17 @@ =website +, %0A @@ -2278,39 +2278,16 @@ - , action= @@ -2286,32 +2286,33 @@ action='opt-in' +, %0A @@ -2312,71 +2312,23 @@ - , then=self.xss%0A +then=self.xss,%0A
0543bfa278e1bb2a8eb37bc0c8f065ddde2ed21f
Add object doubling as lxml Element and string #274
judge/lxml_tree.py
judge/lxml_tree.py
Python
0
@@ -0,0 +1,266 @@ +from lxml import html%0A%0A%0Aclass HTMLTreeString(object):%0A def __init__(self, str):%0A self.tree = html.fromstring(str)%0A%0A def __getattr__(self, attr):%0A return getattr(self.tree, attr)%0A%0A def __unicode__(self):%0A return html.tostring(self.tree)%0A
7082a99135811815c27c3d6ef484a7ee89e84008
Manually backfill lti_config dicts
lti_consumer/migrations/0010_backfill-empty-string-lti-config.py
lti_consumer/migrations/0010_backfill-empty-string-lti-config.py
Python
0.999895
@@ -0,0 +1,1298 @@ +%22%22%22%0ABackfill empty lti_config records%0A%0AWe need to do this with raw SQL,%0Aotherwise the model fails upon instantiation,%0Aas the empty string is an invalid JSON dictionary.%0A%22%22%22%0Aimport uuid%0A%0Afrom django.db import connection%0Afrom django.db import migrations%0A%0A%0Asql_forward = %22%22%22%5C%0AUPDATE%0A lti_consumer_lticonfiguration%0ASET%0A lti_config = %25s%0AWHERE%0A id = %25s%0A;%5C%0A%22%22%22%0A%0Asql_select_empty = %22%22%22%5C%0ASELECT%0A id%0AFROM%0A lti_consumer_lticonfiguration%0AWHERE%0A lti_config = %22%22%0A;%5C%0A%22%22%22%0A%0A%0Adef _get_ids_with_empty_lti_config():%0A %22%22%22%0A Retrieve the list of primary keys for each entry with a blank lti_config%0A %22%22%22%0A with connection.cursor() as cursor:%0A cursor.execute(sql_select_empty)%0A for row in cursor.fetchall():%0A yield row%5B0%5D%0A%0A%0Adef _forward(apps, schema_editor):%0A %22%22%22%0A Generate an empty JSON dict for rows missing one%0A %22%22%22%0A for _id in _get_ids_with_empty_lti_config():%0A lti_config = '%7B%7D'%0A schema_editor.execute(sql_forward, %5B%0A lti_config,%0A _id,%0A %5D)%0A%0A%0Aclass Migration(migrations.Migration):%0A %22%22%22%0A Backfill empty lti_config records%0A %22%22%22%0A%0A dependencies = %5B%0A ('lti_consumer', '0009_backfill-empty-string-config-id'),%0A %5D%0A%0A operations = %5B%0A migrations.RunPython(_forward, atomic=False),%0A %5D%0A
cf664a5dce20da4af5ce1962f38613c8122cb111
reverse iqtreenames
iqtree_namefix.py
iqtree_namefix.py
Python
0.999495
@@ -0,0 +1,1722 @@ +#!/usr/bin/env python%0A%0Aimport sys%0Aimport os%0Aimport re%0Afrom sys import argv%0A%0A%0Adef name_catalog(logFile):%0A catalog = %7B%7D%0A switch = 0%0A try:%0A log= open(logFile, 'r')%0A except:%0A print %22There was a problem reading the file %25s%22 %25logFile%0A exit(1)%0A for line in log:%0A if line == %22WARNING: Some sequence names are changed as follows:%5Cn%22:%0A # print %22Catalog begins%22%0A switch = 1%0A continue%0A while switch == 1:%0A if re.search('-%3E', line):%0A try:%0A original= re.split('-%3E', line)%5B0%5D%0A original =re.sub('%5B %5Cn%5D', '', original)%0A iqname= re.split('-%3E', line)%5B1%5D%0A iqname=re.sub('%5B %5Cn%5D', '', iqname)%0A catalog%5Boriginal%5D=iqname%0A break%0A except:%0A print %22ERROR IN: %25s%22 %25 line%0A %0A else:%0A #print %22Done with the catalog%22%0A #print line%0A switch = 0%0A%0A log.close()%0A return catalog%0A %0Adef replaceNames(treefile, catalog):%0A with open(treefile, 'r') as infile:%0A tree = infile.readline()%0A for k in catalog.iterkeys():%0A fro = catalog%5Bk%5D%0A to = k%0A tree=re.sub(fro, to, tree)%0A return tree%0A %0A%0Adef main():%0A fname= sys.argv%5B1%5D%0A log = fname.replace('treefile', 'log')%0A out = open(fname.replace('fa.treefile', 'tre'), 'w')%0A cat = name_catalog(log)%0A out.write(replaceNames(fname, cat))%0A out.close%0A%0A%0A %0Aif __name__ == %22__main__%22:%0A if len(argv) == 2:%0A main()%0A else:%0A print %22Error: Need the name of iqtree tree file as argument to process.%22%0A
1d5f23bf090e4a6d51beb310b5ecf4048afcc347
add debug runner
tools/debug_run_game.py
tools/debug_run_game.py
Python
0.000001
@@ -0,0 +1,704 @@ +import logging%0Aimport sys%0Afrom mpf.core.config_loader import YamlMultifileConfigLoader%0A%0Afrom mpf.core.machine import MachineController%0A%0Amachine_path = sys.argv%5B1%5D%0A%0Aconfig_loader = YamlMultifileConfigLoader(machine_path, %5B%22config.yaml%22%5D, False, False)%0Aconfig = config_loader.load_mpf_config()%0A%0Aoptions = %7B%0A 'force_platform': 'smart_virtual',%0A 'production': False,%0A 'mpfconfigfile': %5B%22mpfconfig.yaml%22%5D,%0A 'configfile': %5B%22config.yaml%22%5D,%0A 'debug': True,%0A 'bcp': True,%0A 'no_load_cache': False,%0A 'create_config_cache': True,%0A 'text_ui': False,%0A 'consoleloglevel': logging.DEBUG,%0A%7D%0Alogging.basicConfig(level=logging.DEBUG)%0Amachine = MachineController(options, config)%0Amachine.run()%0A
d4a5feaaddb88b79809646b7ddab36d29ebf0830
Create swig.py
wigs/swig.py
wigs/swig.py
Python
0.000002
@@ -0,0 +1,179 @@ +class swig(Wig):%0A tarball_uri = 'https://github.com/swig/swig/archive/rel-$RELEASE_VERSION$.tar.gz'%0A last_release_version = 'v3.0.10'%0A git_uri = 'https://github.com/swig/swig'%0A
956aff18c4791e0fda10b8e0a1103f3a0d53e4f1
Add simple performance test suite
tests/perf/perf.py
tests/perf/perf.py
Python
0.000001
@@ -0,0 +1,1718 @@ +import redact%0A%0A%0Aclass Prisoner(redact.BaseModel):%0A def __init__(self, key, name=None, password=None):%0A super(Prisoner, self).__init__(key)%0A self.name = redact.KeyValueField('n', name)%0A self.password = redact.KeyValueField('p', password)%0A%0Ai = 0%0A%0A%0Adef save_model():%0A global i%0A prisoner = Prisoner('num_%7B%7D'.format(i), %22Patrick McGoohan%22, %22iamnotanumber6%22)%0A redact.save(prisoner)%0A i += 1%0A%0A%0Adef delete_model():%0A global i%0A prisoner = Prisoner('num_%7B%7D'.format(i))%0A redact.delete(prisoner)%0A i += 1%0A%0A%0Adef read_model():%0A global i%0A prisoner = Prisoner('num_%7B%7D'.format(i), %22Patrick McGoohan%22, %22iamnotanumber6%22)%0A redact.load(prisoner)%0A i += 1%0A%0Adef update_model():%0A global i%0A prisoner = Prisoner('num_%7B%7D'.format(i), %22Patrick McGoohan%22, %22iamnotanumber6%22)%0A redact.load(prisoner)%0A i += 1%0A redact.save(prisoner)%0A%0A%0Aif __name__ == '__main__':%0A global i%0A import timeit%0A n_writes = 10000%0A write_time = timeit.timeit(%22save_model()%22, setup=%22from __main__ import save_model%22, number=n_writes)%0A print(%22%7B%7D writes completed in %7B%7D seconds%22.format(n_writes, write_time))%0A%0A i = 0%0A read_time = timeit.timeit(%22read_model()%22, setup=%22from __main__ import read_model%22, number=n_writes)%0A print(%22%7B%7D reads completed in %7B%7D seconds%22.format(n_writes, read_time))%0A%0A i = 0%0A update_time = timeit.timeit(%22update_model()%22, setup=%22from __main__ import update_model%22, number=n_writes)%0A print(%22%7B%7D updates completed in %7B%7D seconds%22.format(n_writes, update_time))%0A%0A i = 0%0A delete_time = timeit.timeit(%22delete_model()%22, setup=%22from __main__ import delete_model%22, number=n_writes)%0A print(%22%7B%7D deletes completed in %7B%7D seconds%22.format(n_writes, delete_time))%0A
68c664117612b15dab5add78e7b5614daf1c2c18
Add missing __init__.py
ivi/agilent/test/__init__.py
ivi/agilent/test/__init__.py
Python
0.999965
@@ -0,0 +1,1133 @@ +%22%22%22%0A%0APython Interchangeable Virtual Instrument Library%0A%0ACopyright (c) 2014 Alex Forencich%0A%0APermission is hereby granted, free of charge, to any person obtaining a copy%0Aof this software and associated documentation files (the %22Software%22), to deal%0Ain the Software without restriction, including without limitation the rights%0Ato use, copy, modify, merge, publish, distribute, sublicense, and/or sell%0Acopies of the Software, and to permit persons to whom the Software is%0Afurnished to do so, subject to the following conditions:%0A%0AThe above copyright notice and this permission notice shall be included in%0Aall copies or substantial portions of the Software.%0A%0ATHE SOFTWARE IS PROVIDED %22AS IS%22, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR%0AIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY%0AFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE%0AAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER%0ALIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,%0AOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN%0ATHE SOFTWARE.%0A%0A%22%22%22%0A%0A__all__ = %5B%5D%0A%0A
4f1b7b2a29fcb8802fbdee6ce832d9c5fb4a6f89
add jobq tests
tests/test_jobq.py
tests/test_jobq.py
Python
0.000001
@@ -0,0 +1,2331 @@ +%22%22%22%0ATest JobQ%0A%22%22%22%0Afrom hstestcase import HSTestCase%0A%0A%0Aclass ActivityTest(HSTestCase):%0A%0A def setUp(self):%0A super(ActivityTest, self).setUp()%0A self.jobq = self.hsclient.get_jobq(self.projectid)%0A%0A def test_basic(self):%0A #authpos(JOBQ_PUSH_URL, data=%22%22, expect=400)%0A spider1 = self.jobq.push('spidey')%0A spider2 = self.jobq.push(spider='spidey')%0A spider3 = self.jobq.push(spider='spidey', metatest='somekey')%0A spider4 = self.jobq.push('spidey')%0A summary = dict((s%5B'name'%5D, s) for s in self.jobq.summary())%0A pending = summary%5B'pending'%5D%0A pending_summaries = pending%5B'summary'%5D%0A assert len(pending_summaries) %3E= 4%0A assert len(pending_summaries) %3C= 8 # 8 are requested%0A assert pending%5B'count'%5D %3E= len(pending_summaries)%0A%0A # expected keys, in the order they should be in the queue%0A expected_keys = %5Bspider4%5B'key'%5D, spider3%5B'key'%5D, spider2%5B'key'%5D, spider1%5B'key'%5D%5D%0A # only count the keys we inserted, as other tests may be running%0A def filter_test(summary):%0A %22%22%22filter out all summaries not in our test%22%22%22%0A return %5Bs%5B'key'%5D for s in summary if s%5B'key'%5D in expected_keys%5D%0A%0A received_keys = filter_test(pending_summaries)%0A assert expected_keys == received_keys%0A%0A # change some job states%0A job1 = self.hsclient.get_job(spider1%5B'key'%5D)%0A job1.finished()%0A job2 = self.hsclient.get_job(spider2%5B'key'%5D)%0A job2.started()%0A%0A # check job queues again%0A summary = dict((s%5B'name'%5D, s) for s in self.jobq.summary())%0A assert summary%5B'pending'%5D%5B'count'%5D %3E= 2%0A assert summary%5B'running'%5D%5B'count'%5D %3E= 1%0A assert summary%5B'finished'%5D%5B'count'%5D %3E= 1%0A%0A pending_keys = filter_test(summary%5B'pending'%5D%5B'summary'%5D)%0A assert pending_keys == %5Bspider4%5B'key'%5D, spider3%5B'key'%5D%5D%0A running_keys = filter_test(summary%5B'running'%5D%5B'summary'%5D)%0A assert running_keys == %5Bspider2%5B'key'%5D%5D%0A finished_keys = filter_test(summary%5B'finished'%5D%5B'summary'%5D)%0A assert finished_keys == %5Bspider1%5B'key'%5D%5D%0A%0A job2.finished()%0A summary = dict((s%5B'name'%5D, s) for s in self.jobq.summary())%0A finished_keys = filter_test(summary%5B'finished'%5D%5B'summary'%5D)%0A assert finished_keys == %5Bspider2%5B'key'%5D, spider1%5B'key'%5D%5D%0A
ff698bf20eb400f9e6f6cadb3e809fcb684bdcc9
Add simple main test
tests/test_main.py
tests/test_main.py
Python
0
@@ -0,0 +1,329 @@ +from unittest import TestCase%0Afrom src.main.main import main%0A%0A%0Aclass TestMain(TestCase):%0A def test_read_commands(self):%0A s0 = main(%5B%5D)%0A s1 = main(%5B%22one%22%5D)%0A s2 = main(%5B%22one%22, %22-2%22%5D)%0A%0A self.assertTrue(0 == 0, %22Testing if 0 equals 0.%22)%0A self.assertFalse(0 == 1, %22Testing if 0 doesn't equal 1.%22)
a22f713ff4a366c0f05ffd6a7e513bc8fda7aa26
add a maxcall test
tests/test_misc.py
tests/test_misc.py
Python
0
@@ -0,0 +1,894 @@ +import numpy as np%0Aimport dynesty%0A%22%22%22%0ARun a series of basic tests of the 2d eggbox%0A%22%22%22%0A%0A# seed the random number generator%0Anp.random.seed(56432)%0A%0Anlive = 100%0A%0A%0Adef loglike(x):%0A return -0.5 * np.sum(x**2)%0A%0A%0Adef prior_transform(x):%0A return (2 * x - 1) * 10%0A%0A%0Adef test_maxcall():%0A # hard test of dynamic sampler with high dlogz_init and small number%0A # of live points%0A ndim = 2%0A sampler = dynesty.NestedSampler(loglike,%0A prior_transform,%0A ndim,%0A nlive=nlive)%0A sampler.run_nested(dlogz=1, maxcall=1000)%0A%0A sampler = dynesty.DynamicNestedSampler(loglike,%0A prior_transform,%0A ndim,%0A nlive=nlive)%0A sampler.run_nested(dlogz_init=1, maxcall=1000)%0A
0ce616d3c787060c6d1bfeacb0a53c5085494927
Create tutorial2.py
tutorial2.py
tutorial2.py
Python
0
@@ -0,0 +1,12 @@ +placeholder%0A
287cd795c92a86ee16a623230d0c59732a2f767d
Add demo on how to write unstructured point meshes in Vtk.
examples/vtk-unstructured-points.py
examples/vtk-unstructured-points.py
Python
0
@@ -0,0 +1,896 @@ +import numpy as np%0Afrom pyvisfile.vtk import ( %0A UnstructuredGrid, DataArray,%0A AppendedDataXMLGenerator,%0A VTK_VERTEX, VF_LIST_OF_VECTORS, VF_LIST_OF_COMPONENTS)%0A%0An = 5000%0Apoints = np.random.randn(n, 3)%0A%0Adata = %5B%0A (%22p%22, np.random.randn(n)),%0A (%22vel%22, np.random.randn(3, n)),%0A%5D%0Afile_name = %22points.vtu%22%0Acompressor = None%0A%0Agrid = UnstructuredGrid(%0A (n, DataArray(%22points%22, points, vector_format=VF_LIST_OF_VECTORS)),%0A cells=np.arange(n, dtype=np.uint32),%0A cell_types=np.asarray(%5BVTK_VERTEX%5D * n, dtype=np.uint8))%0A%0Afor name, field in data:%0A grid.add_pointdata(DataArray(name, field,%0A vector_format=VF_LIST_OF_COMPONENTS))%0A%0Afrom os.path import exists%0Aif exists(file_name):%0A raise RuntimeError(%22output file '%25s' already exists%22%0A %25 file_name)%0A%0Aoutf = open(file_name, %22w%22)%0AAppendedDataXMLGenerator(compressor)(grid).write(outf)%0Aoutf.close()%0A
8b050af9c5f680c67412271cd5744a2c60b288d5
Remove test case for linux-32.
conda_smithy/tests/test_configure_feedstock.py
conda_smithy/tests/test_configure_feedstock.py
from contextlib import contextmanager import os import shutil import tempfile import unittest import conda_build.metadata import conda.api import conda_smithy.configure_feedstock as cnfgr_fdstk from conda_build_all.resolved_distribution import ResolvedDistribution @contextmanager def tmp_directory(): tmp_dir = tempfile.mkdtemp('_recipe') yield tmp_dir shutil.rmtree(tmp_dir) class Test_fudge_subdir(unittest.TestCase): def test_metadata_reading(self): with tmp_directory() as recipe_dir: with open(os.path.join(recipe_dir, 'meta.yaml'), 'w') as fh: fh.write(""" package: name: foo_win # [win] name: foo_osx # [osx] name: foo_the_rest # [not (win or osx)] """) meta = conda_build.metadata.MetaData(recipe_dir) config = cnfgr_fdstk.meta_config(meta) kwargs = {} if hasattr(conda_build, 'api'): kwargs['config'] = config with cnfgr_fdstk.fudge_subdir('win-64', config): meta.parse_again(**kwargs) self.assertEqual(meta.name(), 'foo_win') with cnfgr_fdstk.fudge_subdir('osx-64', config): meta.parse_again(**kwargs) self.assertEqual(meta.name(), 'foo_osx') def test_fetch_index(self): if hasattr(conda_build, 'api'): config = conda_build.api.Config() else: config = conda_build.config # Get the index for OSX and Windows. They should be different. with cnfgr_fdstk.fudge_subdir('win-64', config): win_index = conda.api.get_index(channel_urls=['defaults'], platform='win-64') with cnfgr_fdstk.fudge_subdir('osx-64', config): osx_index = conda.api.get_index(channel_urls=['defaults'], platform='osx-64') self.assertNotEqual(win_index.keys(), osx_index.keys(), ('The keys for the Windows and OSX index were the same.' ' Subdir is not working and will result in mis-rendering ' '(e.g. https://github.com/SciTools/conda-build-all/issues/49).')) def test_r(self): with tmp_directory() as recipe_dir: with open(os.path.join(recipe_dir, 'meta.yaml'), 'w') as fh: fh.write(""" package: name: r-test version: 1.0.0 build: skip: True # [win] requirements: build: - r-base run: - r-base """) meta = conda_build.metadata.MetaData(recipe_dir) config = cnfgr_fdstk.meta_config(meta) kwargs = {} if hasattr(conda_build, 'api'): kwargs['config'] = config def test(expect_skip=False): meta.parse_again(**kwargs) if expect_skip: self.assertEqual(meta.skip(), True) matrix = cnfgr_fdstk.compute_build_matrix( meta ) cases_not_skipped = [] for case in matrix: pkgs, vars = cnfgr_fdstk.split_case(case) with cnfgr_fdstk.enable_vars(vars): if not ResolvedDistribution(meta, pkgs).skip(): cases_not_skipped.append(vars + sorted(pkgs)) if expect_skip: self.assertEqual(cases_not_skipped, []) with cnfgr_fdstk.fudge_subdir('linux-32', config): test() with cnfgr_fdstk.fudge_subdir('linux-64', config): test() with cnfgr_fdstk.fudge_subdir('win-32', config): test(expect_skip=True) with cnfgr_fdstk.fudge_subdir('win-64', config): test(expect_skip=True) with cnfgr_fdstk.fudge_subdir('osx-64', config): test() if __name__ == '__main__': unittest.main()
Python
0
@@ -3234,32 +3234,16 @@ kwargs)%0A - %0A @@ -3864,95 +3864,8 @@ %5D)%0A%0A - with cnfgr_fdstk.fudge_subdir('linux-32', config):%0A test()%0A%0A
11111351f67afd3dc8ee2ec904a9cea595d68fb3
Add script to calculate perplexity results
DilipadTopicModelling/experiment_calculate_perplexity.py
DilipadTopicModelling/experiment_calculate_perplexity.py
Python
0
@@ -0,0 +1,1548 @@ +import pandas as pd%0Aimport logging%0A%0Afrom CPTCorpus import CPTCorpus%0Afrom CPT_Gibbs import GibbsSampler%0A%0A%0Alogger = logging.getLogger(__name__)%0Alogging.basicConfig(format='%25(levelname)s : %25(message)s', level=logging.INFO)%0A%0A# load corpus%0Adata_dir = '/home/jvdzwaan/data/tmp/generated/test_exp/'%0Acorpus = CPTCorpus.load('%7B%7Dcorpus.json'.format(data_dir))%0A#corpus = CPTCorpus.load('%7B%7Dcorpus.json'.format(data_dir),%0A# topicDict='%7B%7D/topicDict.dict'.format(data_dir),%0A# opinionDict='%7B%7D/opinionDict.dict'.format(data_dir))%0A%0AnIter = 200%0Abeta = 0.02%0Aout_dir = '/home/jvdzwaan/data/tmp/generated/test_exp/%7B%7D'%0A%0AnTopics = range(20, nIter+1, 20)%0AnPerplexity = range(0, nIter+1, 10)%0A%0Atopic_perp = pd.DataFrame(columns=nTopics, index=nPerplexity)%0Aopinion_perp = pd.DataFrame(columns=nTopics, index=nPerplexity)%0A%0Afor n in nTopics:%0A # load sampler%0A sampler = GibbsSampler(corpus, nTopics=n, nIter=nIter, alpha=(50.0/n),%0A beta=beta, beta_o=beta,%0A out_dir=out_dir.format(n))%0A sampler._initialize()%0A sampler.run()%0A%0A for s in nPerplexity:%0A tw_perp, ow_perp = sampler.perplexity(index=s)%0A%0A topic_perp.set_value(s, n, tw_perp)%0A opinion_perp.set_value(s, n, ow_perp)%0A%0A logger.info('nTopics: %7B%7D, nPerplexity: %7B%7D, topic perplexity: %7B%7D, '%0A 'opinion perplexity: %7B%7D'.format(n, s, tw_perp, ow_perp))%0A%0Atopic_perp.to_csv(out_dir.format('perplexity_topic.csv'))%0Aopinion_perp.to_csv(out_dir.format('perplexity_opinion.csv'))%0A
2ed913c0add7740b9c8eb6ee8320b6924907e48f
Create q5.py
work/q5.py
work/q5.py
Python
0.00005
@@ -0,0 +1,591 @@ +import itertools%0A%0Adef max_array():%0A return %5Bx for x in range(0, 10)%5D%0Adef compute():%0A return %5B'+', '-', ''%5D%0A%0Adef sum(arr):%0A for i in itertools.product(compute(), repeat=10):%0A result = ''.join(map(str, union(max_array(), i)))%0A if result%5Blen(result) - 1%5D in compute():%0A result = result%5B:len(result) - 1%5D%0A if eval(result) == 100:%0A print(result, '=', eval(result))%0A%0Adef union(arr1, arr2):%0A result = %5B%5D%0A for i in range(1, len(arr1)):%0A result.append(arr1%5Bi%5D)%0A result.append(arr2%5Bi%5D)%0A return result%0A%0Aprint(sum(max_array()))%0A
240274ea82db24dca578692a609a262497107ccc
Prepare for interview questions
decorator_examples.py
decorator_examples.py
Python
0.000002
@@ -0,0 +1,759 @@ +def identity_decorator(fn):%0A def wrapper(*args):%0A return fn(*args)%0A return wrapper%0A%0A%0A@identity_decorator%0Adef stringify(obj):%0A return str(obj)%0A%0A%0Aprint(stringify(78))%0A%0A%0Adef uppercase(fn):%0A def wrapper(*args):%0A result = fn(*args)%0A return result.upper()%0A return wrapper%0A%0A%0A@uppercase%0Adef stringify(obj):%0A return str(obj)%0A%0A%0Aprint(stringify('Hello'))%0A%0A%0Adef cache(fn):%0A c = %7B%7D%0A def wrapper(*args):%0A if args in c:%0A return c%5Bargs%5D%0A result = fn(*args)%0A c%5Bargs%5D = result%0A return result%0A return wrapper%0A%0A%0A@cache%0Adef fibonacci(n):%0A print('Calculating fibonacci(%7B%7D)'.format(n))%0A if n == 1:%0A return 1%0A return n * fibonacci(n - 1)%0A%0A%0Aprint(fibonacci(4))%0Aprint(fibonacci(5))%0A
71a55a1252ef87629f10e48c1041416c34742ea7
Add input handling for ssh connections
modules/juliet_input.py
modules/juliet_input.py
Python
0
@@ -0,0 +1,235 @@ +from threading import Thread%0A%0Aclass Juliet_Input (Thread):%0A def __init(self):%0A Thread.__init(self)%0A %0A def run(self):%0A while True:%0A char = raw_input()%0A if char == 'q':%0A break%0A%0A
02887eb26b1c95abf6e26f30228c524d61335e40
Add download_protected_file view
downloads/views.py
downloads/views.py
Python
0.000001
@@ -0,0 +1,1040 @@ +from sendfile import sendfile%0Afrom django.conf import settings%0Afrom django.core.exceptions import PermissionDenied%0A%0A%0Adef download_protected_file(request, model_class, path_prefix, path):%0A %22%22%22%0A This view allows download of the file at the specified path, if the user%0A is allowed to. This is checked by calling the model's can_access_files%0A method.%0A %22%22%22%0A%0A # filepath is the absolute path, mediapath is relative to media folder%0A filepath = settings.SENDFILE_ROOT + path_prefix + path%0A filepath_mediapath = settings.SENDFILE_DIR + path_prefix + path%0A%0A if request.user.is_authenticated():%0A # Superusers can access all files%0A if request.user.is_superuser:%0A return sendfile(request, filepath)%0A else:%0A # We need to check can_access_files on particular instance%0A obj = model_class.get_by_filepath(filepath_mediapath)%0A%0A if obj is not None and obj.can_access_files(request.user):%0A return sendfile(request, filepath)%0A%0A raise PermissionDenied%0A
0115d088061595fe6c6f8589d0599d1b8e970813
Add dummy Keras inputs builder
scripts/lwtnn-build-dummy-inputs.py
scripts/lwtnn-build-dummy-inputs.py
Python
0.000001
@@ -0,0 +1,1502 @@ +#!/usr/bin/env python3%0A%0A%22%22%22Generate fake NN files to test the lightweight classes%22%22%22%0A%0Aimport argparse%0Aimport json%0Aimport h5py%0Aimport numpy as np%0A%0Adef _run():%0A args = _get_args()%0A _build_keras_arch(%22arch.json%22)%0A _build_keras_inputs_file(%22inputs.json%22)%0A _build_keras_weights(%22weights.h5%22, verbose=args.verbose)%0A%0Adef _get_args():%0A parser = argparse.ArgumentParser(description=__doc__)%0A parser.add_argument('-v', '--verbose', action='store_true')%0A return parser.parse_args()%0A%0Adef _build_keras_arch(name):%0A arch = %7B%0A 'layers': %5B%0A %7B'activation': 'relu', 'name': 'Dense'%7D%0A %5D%0A %7D%0A with open(name, 'w') as out_file:%0A out_file.write(json.dumps(arch, indent=2))%0A%0Adef _build_keras_inputs_file(name):%0A def build_input(num):%0A return %7B%22name%22: %22in%7B%7D%22.format(num), %22offset%22: 0.0, %22scale%22: 1.0%7D%0A top = %7B%0A %22inputs%22: %5Bbuild_input(x) for x in range(1,5)%5D,%0A %22class_labels%22: %5B%22out%7B%7D%22.format(x) for x in range(1,5)%5D%0A %7D%0A with open(name, 'w') as out_file:%0A out_file.write(json.dumps(top, indent=2))%0A%0Adef _build_keras_weights(name, verbose):%0A half_swap = np.zeros((4,4))%0A half_swap%5B0,3%5D = 1.0%0A half_swap%5B1,2%5D = 1.0%0A if verbose:%0A print(half_swap)%0A%0A bias = np.zeros(4)%0A with h5py.File(name, 'w') as h5_file:%0A layer0 = h5_file.create_group(%22layer_0%22)%0A layer0.create_dataset(%22param_0%22, data=half_swap)%0A layer0.create_dataset(%22param_1%22, data=bias)%0A%0Aif __name__ == %22__main__%22:%0A _run()%0A
ad1defca2f4d16cc5e13c579c945858b9f77c450
Rename script
snippets/clean_users_data_frames.py
snippets/clean_users_data_frames.py
Python
0.000001
@@ -0,0 +1,755 @@ +import pandas as pd%0A%0Atrain_users = pd.read_csv('../datasets/processed/processed_train_users.csv')%0Atest_users = pd.read_csv('../datasets/processed/processed_test_users.csv')%0A%0Apercentage = 0.95%0A%0Atrain_mask = train_users.isnull().sum() %3E train_users.shape%5B0%5D * percentage%0Atrain_to_remove = list(train_users.isnull().sum()%5Btrain_mask%5D.index)%0A%0Atest_mask = test_users.isnull().sum() %3E test_users.shape%5B0%5D * percentage%0Atest_to_remove = list(test_users.isnull().sum()%5Btest_mask%5D.index)%0A%0A%0Ato_remove = list(set(train_to_remove).intersection(test_to_remove))%0A%0Atrain_users.drop(to_remove, axis=1, inplace=True)%0Atest_users.drop(to_remove, axis=1, inplace=True)%0A%0Atrain_users.to_csv('clean_processed_train_users.csv')%0Atest_users.to_csv('clean_processed_test_users.csv')%0A
874323b53790ee2121b82bd57b9941d4562995d0
Add reddit downvoting script
reddit-downvoter.py
reddit-downvoter.py
Python
0.000002
@@ -0,0 +1,589 @@ +#!/usr/bin/env python%0A%0Aimport praw%0Aimport time%0A%0Asettings = %7B%0A 'username': 'username',%0A 'password': 'password',%0A 'user_agent': 'angry /r/politics robot',%0A 'subreddit': 'politics',%0A%7D%0A%0Ar = praw.Reddit(user_agent=settings%5B'user_agent'%5D)%0A%0Ar.login(settings%5B'username'%5D, settings%5B'password'%5D)%0A%0Asubmissions = r.get_subreddit(settings%5B'subreddit'%5D).get_hot(limit=100)%0A%0Afor s in submissions:%0A # Skip if post has already been downvoted%0A if not s.likes and s.likes is not None:%0A continue%0A%0A s.downvote()%0A print(%22Downvoted: '%7B%7D'%22.format(s.title%5B0:70%5D))%0A%0A time.sleep(2)%0A
d7b7056b483d52e4d94321019f8e520c166511be
Add singleton decorator.
comrade/core/decorators.py
comrade/core/decorators.py
Python
0
@@ -0,0 +1,183 @@ +def singleton(cls):%0A instances = %7B%7D%0A def getinstance():%0A if cls not in instances:%0A instances%5Bcls%5D = cls()%0A return instances%5Bcls%5D%0A return getinstance%0A
4bcc8ddb7df762155402cb1229f16849c03666c1
Check DB consistence
DB_consist.py
DB_consist.py
Python
0
@@ -0,0 +1,2487 @@ +from mysql import mysql%0Afrom env_init import create_data_type%0Aimport os%0A%0Adef create_user_data_file():%0A print(%22check user_data dir and file...%22)%0A try:%0A if not os.path.exists(%22static/user_data%22):%0A print('create dir %22static/user_data%22')%0A os.makedirs('static/user_data')%0A if not os.path.isfile(%22static/user_data/setting.txt%22):%0A print('create file %22static/user_data/setting.txt%22')%0A with open(%22static/user_data/setting.txt%22, %22w%22) as fp:%0A fp.write(%22bluetooth_enable 1%22)%0A print(%22check finish%22)%0A except Exception as e:%0A print(%22create user_data file failed%22,e)%0A%0Adef check_column_exist_or_add(db,table,column_name,data_type):%0A if len(db.query('show columns from %25s like %22%25s%22' %25 (table,column_name))) == 0:%0A print('%25s doesn%5C't in table %25s' %25(column_name,table))%0A print('add %25s %25s into table %25s' %25(column_name,data_type,table))%0A db.cmd('alter table %25s add column %25s %25s' %25 (table,column_name,data_type))%0A%0Adef check_table_exist_or_create(db,table_name,sql):%0A if len(db.query('show tables like %22%25s%22' %25 (table_name))) == 0:%0A print('Table %25s doesn%5C't exist' %25 table_name)%0A print('Create table %25s' %25 table_name)%0A db.cmd(sql)%0A%0Adef check_bluetooth_DB(db):%0A create_user_data_file()%0A check_table_exist_or_create(db,'user_prefer','create table user_prefer ( %5C%0A pref_id varchar(14) unique key, %5C%0A user_id int default 0, %5C%0A pref_data_type_01 varchar(100), %5C%0A pref_data_type_02 varchar(100), %5C%0A pref_data_type_03 varchar(100), %5C%0A pref_data_type_04 varchar(100), %5C%0A pref_data_type_05 varchar(100), %5C%0A pref_set_time datetime default now(), %5C%0A pref_is_delete bit(1) default 0)')%0A check_column_exist_or_add(db,'user','user_bluetooth_id','varchar(50)')%0A check_column_exist_or_add(db,'user','user_profession','int default 0 not null')%0A check_column_exist_or_add(db,'image_data','img_like_count','int default 0')%0A check_column_exist_or_add(db,'user','user_birthday','datetime')%0A check_column_exist_or_add(db,'text_data','text_like_count','int default 0')%0A create_data_type(%22customized_text%22)%0A%0Adef main():%0A db = mysql()%0A db.connect()%0A check_bluetooth_DB(db)%0A%0Amain()%0A
cb98b4a1580e4976de375722012483bf51ef9254
Add interactive script to get papers from Mendeley API
scripts/get_mendeley_papers.py
scripts/get_mendeley_papers.py
Python
0
@@ -0,0 +1,2221 @@ +###%0A# Copyright 2015-2020, Institute for Systems Biology%0A#%0A# Licensed under the Apache License, Version 2.0 (the %22License%22);%0A# you may not use this file except in compliance with the License.%0A# You may obtain a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS,%0A# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A# See the License for the specific language governing permissions and%0A# limitations under the License.%0A###%0A%0Afrom __future__ import print_function%0A%0Afrom mendeley import Mendeley%0A%0Adef test():%0A client_id = 9526%0A client_secret = %22AmIvWP7FRxeLHX7n%22%0A redirect_uri = %22https://isb-cgc.appspot.com/%22%0A%0A # These values should match the ones supplied when registering your application.%0A mendeley = Mendeley(client_id, client_secret=client_secret, redirect_uri=redirect_uri)%0A%0A auth = mendeley.start_implicit_grant_flow()%0A%0A # The user needs to visit this URL, and log in to Mendeley.%0A login_url = auth.get_login_url()%0A%0A print(%22Go to this link to log in: %5Cn%22 + login_url)%0A%0A # After logging in, the user will be redirected to a URL, auth_response.%0A auth_response = input(%22Copy the redirect link here: %5Cn%22)%0A auth_response = auth_response.rstrip()%0A%0A # print(%22** Response is: %22 + auth_response)%0A session = auth.authenticate(auth_response)%0A # print(session.token%5B'access_token'%5D)%0A%0A # List all groups I have access to%0A groups = session.groups.iter()%0A%0A i = 1%0A for g in groups:%0A print(%22%5B%7B%7D%5D %7B%7D%22.format(i, g.name))%0A i = i + 1%0A%0A # Let choose a group%0A selected_index = int(input('Select group to get paper from: '))%0A i = 1%0A group_id = ''%0A groups = session.groups.iter()%0A for g in groups:%0A if i == selected_index:%0A group_id = g.id%0A break%0A i = i + 1%0A%0A if group_id == '':%0A quit()%0A%0A # Get all the documents in the group%0A target_group = session.groups.get(group_id)%0A docs = target_group.documents.iter()%0A for d in docs:%0A print(d.title)%0A%0A print(%22something%22)%0A%0A%0Aif __name__ == %22__main__%22:%0A test()%0A%0A
731bc1308e94cdb341511618ba5739f6fd37b0b7
Add a base regressions package
regressions/__init__.py
regressions/__init__.py
Python
0
@@ -0,0 +1,592 @@ +# regressions%0A%0A%22%22%22A package which implements various forms of regression.%22%22%22%0A%0Aimport numpy as np%0Atry:%0A import scipy.linalg as linalg%0A linalg_source = 'scipy'%0Aexcept ImportError:%0A import numpy.linalg as linalg%0A linalg_source = 'numpy'%0A%0Aclass ParameterError(Exception):%0A %22%22%22Parameters passed to a regression routine are unacceptable%22%22%22%0A pass%0A%0A# Maximum iterations that will be attempted by iterative routines by%0A# default%0ADEFAULT_MAX_ITERATIONS = 100%0A%0A# A default epsilon value used in various places, such as to decide when%0A# iterations have converged%0ADEFAULT_EPSILON = 0.01%0A
2cdece43768e6bf9613020ae71785f9f158fd72d
Add lc0443_string_compression.py
lc0443_string_compression.py
lc0443_string_compression.py
Python
0.000005
@@ -0,0 +1,1472 @@ +%22%22%22Leetcode 443. String Compression%0AEasy%0A%0AURL: https://leetcode.com/problems/string-compression/%0A%0AGiven an array of characters, compress it in-place.%0A%0AThe length after compression must always be smaller than or equal to the%0Aoriginal array.%0A%0AEvery element of the array should be a character (not int) of length 1.%0A%0AAfter you are done modifying the input array in-place, return the new length%0Aof the array.%0A%0AFollow up:%0ACould you solve it using only O(1) extra space?%0A %0AExample 1:%0AInput:%0A%5B%22a%22,%22a%22,%22b%22,%22b%22,%22c%22,%22c%22,%22c%22%5D%0AOutput:%0AReturn 6, and the first 6 characters of the input array should be:%0A%5B%22a%22,%222%22,%22b%22,%222%22,%22c%22,%223%22%5D%0AExplanation:%0A%22aa%22 is replaced by %22a2%22. %22bb%22 is replaced by %22b2%22. %22ccc%22 is replaced by %22c3%22.%0A%0AExample 2:%0AInput:%0A%5B%22a%22%5D%0AOutput:%0AReturn 1, and the first 1 characters of the input array should be: %5B%22a%22%5D%0AExplanation:%0ANothing is replaced.%0A%0AExample 3:%0AInput:%0A%5B%22a%22,%22b%22,%22b%22,%22b%22,%22b%22,%22b%22,%22b%22,%22b%22,%22b%22,%22b%22,%22b%22,%22b%22,%22b%22%5D%0AOutput:%0AReturn 4, and the first 4 characters of the input array should be: %0A%5B%22a%22,%22b%22,%221%22,%222%22%5D.%0AExplanation:%0ASince the character %22a%22 does not repeat, it is not compressed. %22bbbbbbbbbbbb%22%0Ais replaced by %22b12%22.%0ANotice each digit has it's own entry in the array.%0A%0ANote:%0AAll characters have an ASCII value in %5B35, 126%5D.%0A1 %3C= len(chars) %3C= 1000.%0A%22%22%22%0A%0Aclass Solution(object):%0A def compress(self, chars):%0A %22%22%22%0A :type chars: List%5Bstr%5D%0A :rtype: int%0A %22%22%22%0A pass%0A%0A%0Adef main():%0A pass%0A%0A%0Aif __name__ == '__main__':%0A main()%0A
e88ef8f047fc1c6d005f78a40da864a575c1cbe7
Add tests from `index_brief`
tests/test_brief_utils.py
tests/test_brief_utils.py
Python
0
@@ -0,0 +1,1948 @@ +import mock%0Afrom app.brief_utils import index_brief%0Afrom app.models import Brief, Framework%0Afrom tests.bases import BaseApplicationTest%0A%0A%0A@mock.patch('app.brief_utils.index_object', autospec=True)%0Aclass TestIndexBriefs(BaseApplicationTest):%0A def test_live_dos_2_brief_is_indexed(self, index_object, live_dos2_framework):%0A with self.app.app_context():%0A dos2 = Framework.query.filter(Framework.slug == 'digital-outcomes-and-specialists-2').first()%0A%0A with mock.patch.object(Brief, %22serialize%22, return_value=%7B'serialized': 'object'%7D):%0A brief = Brief(status='live', framework=dos2, data=%7B'requirementsLength': '1 week'%7D)%0A index_brief(brief)%0A%0A index_object.assert_called_once_with(%0A framework='digital-outcomes-and-specialists-2',%0A object_type='briefs',%0A object_id=None,%0A serialized_object=%7B'serialized': 'object'%7D,%0A )%0A%0A def test_draft_dos_2_brief_is_not_indexed(self, index_object, live_dos2_framework):%0A with self.app.app_context():%0A dos2 = Framework.query.filter(Framework.slug == 'digital-outcomes-and-specialists-2').first()%0A%0A with mock.patch.object(Brief, %22serialize%22, return_value=%7B'serialized': 'object'%7D):%0A brief = Brief(status='draft', framework=dos2, data=%7B'requirementsLength': '1 week'%7D)%0A index_brief(brief)%0A%0A assert index_object.called is False%0A%0A def test_object_not_on_dos_not_indexed(self, index_object, live_g8_framework):%0A with self.app.app_context():%0A g8 = Framework.query.filter(Framework.slug == 'g-cloud-8').first()%0A%0A with mock.patch.object(Brief, %22serialize%22, return_value=%7B'serialized': 'object'%7D):%0A brief = Brief(status='live', framework=g8, data=%7B'requirementsLength': '1 week'%7D)%0A index_brief(brief)%0A%0A assert index_object.called is False%0A
b9593297bef14fba20a0eaa4ce384c76447aa3ce
Add tests for deepgetattr
tests/test_deepgetattr.py
tests/test_deepgetattr.py
Python
0
@@ -0,0 +1,1468 @@ +from lumbda.collection import deepgetattr%0A%0A%0Aclass MyClass(object):%0A def __init__(self, **kwargs):%0A for key, value in kwargs.iteritems():%0A setattr(self, key, value)%0A%0A%0Adef test_object_hasattr():%0A %22%22%22%0A Test that the looked for attribute is found when present%0A %22%22%22%0A my_object = MyClass(attribute=3, sub_object=MyClass(attribute=5))%0A%0A assert deepgetattr(my_object, 'attribute') == 3, 'It should return my_object.attribute'%0A assert deepgetattr(my_object, 'sub_object.attribute') == 5, 'It should return my_object.sub_object.attribute'%0A%0A%0Adef test_object_doesnt_haveattr():%0A %22%22%22%0A Test that the return value is the default one when the looked for%0A attribute is not present%0A %22%22%22%0A my_object = MyClass(attribute=3, sub_object=MyClass(attribute=5))%0A%0A assert deepgetattr(my_object, 'hello') is None, 'It should return the default value'%0A assert deepgetattr(my_object, 'hello', False) is False, 'It should return the given default value'%0A assert deepgetattr(my_object, 'hello', 'world') == 'world', 'It should return the given default value'%0A assert deepgetattr(my_object, 'hello.world') is None, 'It should return the default value'%0A assert deepgetattr(my_object, 'attribute.hello') is None, 'It should return the default value'%0A assert deepgetattr(my_object, 'sub_object.hello') is None, 'It should return the default value'%0A assert deepgetattr(my_object, '') is None, 'It should return the default value'%0A
7abd4c3893e8c1ced664315ee561ae19d3b04191
Add test_mods_import.py
tests/test_mods_import.py
tests/test_mods_import.py
Python
0.000003
@@ -0,0 +1,588 @@ +import pytest%0Aimport os%0Afrom pathlib import Path%0Afrom importlib import import_module%0A%0AHMMs = %5B%5D%0A%0Afor root, dir, files in os.walk(%22.%22):%0A if %22mods%22 in root:%0A for f in files:%0A if f.endswith(%22.py%22):%0A filepath = Path(root) / f%0A lines = %22%22.join(open(filepath).readlines())%0A if %22HiddenMarkovModel%22 in lines:%0A HMMs.append(filepath)%0A%0A@pytest.mark.parametrize((%22module_path%22), HMMs)%0Adef test_tables_L63(module_path):%0A p = str(module_path.with_suffix(%22%22)).replace(%22/%22, %22.%22)%0A import_module(p)%0A assert True%0A
c6c87e1aafa6b8a4f7929c491398574921417bd4
Add initial framerate webcam test structure
tests/webcam_framerate.py
tests/webcam_framerate.py
Python
0
@@ -0,0 +1,1667 @@ +#!/usr/bin/env python%0A%0Aimport qrtools, gi, os%0Agi.require_version('Gtk', '3.0')%0Agi.require_version('Gst', '1.0')%0Afrom gi.repository import Gtk, Gst%0Afrom avocado import Test%0Afrom utils import webcam%0A%0Aclass WebcamReadQR(Test):%0A %22%22%22%0A Uses the camera selected by v4l2src by default (/dev/video0) to get the%0A framerate by creating a pipeline with an fpsdisplaysink and initializing%0A Gtk main loop. For now is tested whether the framerate is 30 or more.%0A%0A %22%22%22%0A def setUp(self):%0A self.error = None%0A #if not os.path.exists('/dev/video0'):%0A #self.skip(%22No webcam detected: /dev/video0 cannot be found%22);%0A%0A def test(self):%0A elements = %5B'fpsdisplaysink video-sink=fakesink text-overlay=false '%0A 'signal-fps-measurements=true'%5D%0A webcam.create_video_pipeline(self, gst_elements=elements,%0A v4l2src_args=%22num-buffers=2000%22)%0A%0A bus = self.video_player.get_bus()%0A bus.connect(%22fps-measurements%22, self.on_fps_measurement)%0A%0A Gtk.main()%0A%0A if self.error != None:%0A self.fail(%22Error: %7B0%7D%22.format(self.error))%0A %0A if self.fps %3C 30:%0A self.fail(%22Measured fps is below 30, %7B0%7D%22.format(self.fps))%0A self.log.debug(%22Measured fps is 30 or more, %7B0%7D%22.format(self.fps))%0A%0A def on_fps_measurement(self, fpsdisplaysink, fps, droprate, avgfps):%0A self.fps = avgfps%0A%0A def on_message(self, bus, message):%0A t = message.type%0A%0A if t == Gst.MessageType.EOS:%0A webcam.exit(self)%0A%0A elif t == Gst.MessageType.ERROR:%0A webcam.exit(self)%0A self.error = message.parse_error()%0A
764f819d5288abcece33c75934bbaa43bf29e055
Add merge migration
corehq/apps/users/migrations/0017_merge_20200608_1401.py
corehq/apps/users/migrations/0017_merge_20200608_1401.py
Python
0.000001
@@ -0,0 +1,325 @@ +# -*- coding: utf-8 -*-%0A# Generated by Django 1.11.28 on 2020-06-08 14:01%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('users', '0016_webappspermissions'),%0A ('users', '0016_hqapikey'),%0A %5D%0A%0A operations = %5B%0A %5D%0A
db3db5819a36c6c4f3fec85a0150e5332e6fa8b1
Fix FlagEnum print issue by using build-in getattr() function
construct/lib/container.py
construct/lib/container.py
""" Various containers. """ def recursion_lock(retval, lock_name = "__recursion_lock__"): def decorator(func): def wrapper(self, *args, **kw): if getattr(self, lock_name, False): return retval setattr(self, lock_name, True) try: return func(self, *args, **kw) finally: setattr(self, lock_name, False) wrapper.__name__ = func.__name__ return wrapper return decorator class Container(dict): """ A generic container of attributes. Containers are the common way to express parsed data. """ __slots__ = ["__keys_order__"] def __init__(self, **kw): object.__setattr__(self, "__keys_order__", []) for k, v in kw.items(): self[k] = v def __getattr__(self, name): try: return self[name] except KeyError: raise AttributeError(name) def __setitem__(self, key, val): if key not in self: self.__keys_order__.append(key) dict.__setitem__(self, key, val) def __delitem__(self, key): dict.__delitem__(self, key) self.__keys_order__.remove(key) __delattr__ = __delitem__ __setattr__ = __setitem__ def clear(self): dict.clear(self) del self.__keys_order__[:] def pop(self, key, *default): val = dict.pop(self, key, *default) self.__keys_order__.remove(key) return val def popitem(self): k, v = dict.popitem(self) self.__keys_order__.remove(k) return k, v def update(self, seq, **kw): if hasattr(seq, "keys"): for k in seq.keys(): self[k] = seq[k] else: for k, v in seq: self[k] = v dict.update(self, kw) def copy(self): inst = self.__class__() inst.update(self.iteritems()) return inst __update__ = update __copy__ = copy def __iter__(self): return iter(self.__keys_order__) iterkeys = __iter__ def itervalues(self): return (self[k] for k in self.__keys_order__) def iteritems(self): return ((k, self[k]) for k in self.__keys_order__) def keys(self): return self.__keys_order__ def values(self): return list(self.itervalues()) def items(self): return list(self.iteritems()) def __repr__(self): return "%s(%s)" % (self.__class__.__name__, dict.__repr__(self)) @recursion_lock("<...>") def __pretty_str__(self, nesting = 1, indentation = " "): attrs = [] ind = indentation * nesting for k, v in self.iteritems(): if not k.startswith("_"): text = [ind, k, " = "] if hasattr(v, "__pretty_str__"): text.append(v.__pretty_str__(nesting + 1, indentation)) else: text.append(repr(v)) attrs.append("".join(text)) if not attrs: return "%s()" % (self.__class__.__name__,) attrs.insert(0, self.__class__.__name__ + ":") return "\n".join(attrs) __str__ = __pretty_str__ class FlagsContainer(Container): """ A container providing pretty-printing for flags. Only set flags are displayed. """ @recursion_lock("<...>") def __pretty_str__(self, nesting = 1, indentation = " "): attrs = [] ind = indentation * nesting for k in self.keys(): v = self.__dict__[k] if not k.startswith("_") and v: attrs.append(ind + k) if not attrs: return "%s()" % (self.__class__.__name__,) attrs.insert(0, self.__class__.__name__+ ":") return "\n".join(attrs) class ListContainer(list): """ A container for lists. """ __slots__ = ["__recursion_lock__"] def __str__(self): return self.__pretty_str__() @recursion_lock("[...]") def __pretty_str__(self, nesting = 1, indentation = " "): if not self: return "[]" ind = indentation * nesting lines = ["["] for elem in self: lines.append("\n") lines.append(ind) if hasattr(elem, "__pretty_str__"): lines.append(elem.__pretty_str__(nesting + 1, indentation)) else: lines.append(repr(elem)) lines.append("\n") lines.append(indentation * (nesting - 1)) lines.append("]") return "".join(lines) class LazyContainer(object): __slots__ = ["subcon", "stream", "pos", "context", "_value"] def __init__(self, subcon, stream, pos, context): self.subcon = subcon self.stream = stream self.pos = pos self.context = context self._value = NotImplemented def __eq__(self, other): try: return self._value == other._value except AttributeError: return False def __ne__(self, other): return not (self == other) def __str__(self): return self.__pretty_str__() def __pretty_str__(self, nesting = 1, indentation = " "): if self._value is NotImplemented: text = "<unread>" elif hasattr(self._value, "__pretty_str__"): text = self._value.__pretty_str__(nesting, indentation) else: text = str(self._value) return "%s: %s" % (self.__class__.__name__, text) def read(self): self.stream.seek(self.pos) return self.subcon._parse(self.stream, self.context) def dispose(self): self.subcon = None self.stream = None self.context = None self.pos = None def _get_value(self): if self._value is NotImplemented: self._value = self.read() return self._value value = property(_get_value) has_value = property(lambda self: self._value is not NotImplemented) if __name__ == "__main__": c = Container(x=5) c.y = 8 c.z = 9 c.w = 10 c.foo = 5 print (c)
Python
0
@@ -3551,24 +3551,24 @@ v = -self.__dict__%5Bk%5D +getattr(self, k) %0A
b522fed0a1ca2570b8652ddb64b8c847d5964d11
Add a script to generate all known codes and their decoding
list_all_codes.py
list_all_codes.py
Python
0.000002
@@ -0,0 +1,778 @@ +#!/usr/bin/env python%0A%0Aimport lsi_decode_loginfo as loginfo%0A%0Adef generate_values(data):%0A title = data%5B0%5D%0A mask = data%5B1%5D%0A sub = data%5B2%5D%0A%0A for key in sub.keys():%0A v = sub%5Bkey%5D%0A key_name = v%5B0%5D%0A key_sub = v%5B1%5D%0A key_detail = v%5B2%5D%0A if key_sub is None:%0A yield %5B(title, key, key_name, key_detail)%5D%0A else:%0A for sub_val in generate_values(key_sub):%0A yield %5B(title, key, key_name, key_detail)%5D + sub_val%0A%0Afor entry in generate_values(loginfo.types):%0A val = 0%0A for line in entry:%0A val %7C= line%5B1%5D%0A print ' %25-10s%5Ct0x%2508X' %25 ('Value', val)%0A for line in entry:%0A print ' %25-10s%5Ct0x%2508X %25s %25s' %25 (line%5B0%5D, line%5B1%5D, line%5B2%5D, line%5B3%5D)%0A print%0A print '&nbsp;'%0A print%0A
a86150c016fd88da9849c8abe58e7a3cf9233521
Add sleepytime plugin
smartbot/plugins/sleepytime.py
smartbot/plugins/sleepytime.py
Python
0
@@ -0,0 +1,800 @@ +from datetime import datetime, timedelta%0A%0Aimport smartbot.plugin%0A%0A%0Aclass Plugin(smartbot.plugin.Plugin):%0A %22%22%22Check when you should wake up.%22%22%22%0A%0A names = %5B'sleepytime', 'sleepyti.me'%5D%0A%0A @staticmethod%0A def calculate_wake_up_times(now=None, time_to_sleep=14,%0A sleep_cycle_duration=90):%0A if now is None:%0A now = datetime.now()%0A%0A now += timedelta(minutes=time_to_sleep)%0A%0A for i in range(6):%0A wake_up_time = now + timedelta(minutes=sleep_cycle_duration)%0A yield wake_up_time%0A now = wake_up_time%0A%0A def on_command(self, msg, stdin, stdout, reply):%0A times = list(self.calculate_wake_up_times())%0A msg = ' or '.join(time.strftime('%25l:%25M %25p').strip() for time in times)%0A reply(msg)%0A
86ea6884d381f9153d088c634f5353537b967403
solve 1 problem
solutions/binary-tree-paths.py
solutions/binary-tree-paths.py
Python
0.000027
@@ -0,0 +1,1590 @@ +#!/usr/bin/env python%0A# encoding: utf-8%0A%0A%22%22%22%0Abinary-tree-paths.py%0A %0ACreated by Shuailong on 2016-03-04.%0A%0Ahttps://leetcode.com/problems/binary-tree-paths/.%0A%0A%22%22%22%0A%0Afrom collections import deque%0A# Definition for a binary tree node.%0Aclass TreeNode(object):%0A def __init__(self, x):%0A self.val = x%0A self.left = None%0A self.right = None%0A%0Aclass Solution(object):%0A def binaryTreePathsList(self, root):%0A %22%22%22%0A :type root: TreeNode%0A :rtype: List%5BList%5Bint%5D%5D%0A %22%22%22%0A if root is None:%0A return %5B%5D%0A if root.left is None and root.right is None:%0A return %5B%5Broot.val%5D%5D%0A%0A lpaths = self.binaryTreePathsList(root.left)%0A rpaths = self.binaryTreePathsList(root.right)%0A%0A for path in lpaths:%0A path.insert(0, root.val)%0A for path in rpaths:%0A path.insert(0, root.val)%0A%0A return lpaths + rpaths %0A%0A%0A def binaryTreePaths(self, root):%0A %22%22%22%0A :type root: TreeNode%0A :rtype: List%5Bstr%5D%0A %22%22%22%0A res = %5B%5D%0A paths = self.binaryTreePathsList(root)%0A for path in paths:%0A s = ''%0A for i in xrange(len(path)-1):%0A s += str(path%5Bi%5D) + '-%3E'%0A s += str(path%5Blen(path)-1%5D)%0A res.append(s)%0A%0A return res%0A%0A%0Adef main():%0A solution = Solution()%0A n1 = TreeNode(1)%0A n2 = TreeNode(2)%0A n3 = TreeNode(3)%0A n4 = TreeNode(5)%0A n1.left = n2%0A n1.right = n3%0A n2.right = n4%0A%0A root = n1%0A print solution.binaryTreePaths(root)%0A %0Aif __name__ == '__main__':%0A main()%0A%0A
6ef53e8c9a3543d8e2e03816d869d02120f004c7
add __doc__ to plot_adaboost_hastie_10_2.py
examples/ensemble/plot_adaboost_hastie_10_2.py
examples/ensemble/plot_adaboost_hastie_10_2.py
"""Figure 10.2 from Elements of Statistical Learning, Ed. 2. .. author:: Peter Prettenhofer <peter.prettenhofer@gmail.com> Noel Dawe <noel.dawe@gmail.com> """ import numpy as np from sklearn import datasets from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import AdaBoostClassifier import pylab as plt n_estimators = 400 learning_rate = 1. X, y = datasets.make_hastie_10_2(n_samples=12000, random_state=1) X_test, y_test = X[2000:], y[2000:] X_train, y_train = X[:2000], y[:2000] dt_stump = DecisionTreeClassifier(max_depth=1, min_samples_leaf=1) dt_stump.fit(X_train, y_train) dt_stump_err = 1.0 - dt_stump.score(X_test, y_test) dt = DecisionTreeClassifier(max_depth=9, min_samples_leaf=1) dt.fit(X_train, y_train) dt_err = 1.0 - dt.score(X_test, y_test) ada_discrete = AdaBoostClassifier( base_estimator=dt_stump, learning_rate=learning_rate, n_estimators=n_estimators, real=False) ada_discrete.fit(X_train, y_train) ada_real = AdaBoostClassifier( base_estimator=dt_stump, learning_rate=learning_rate, n_estimators=n_estimators, real=True) ada_real.fit(X_train, y_train) fig = plt.figure(facecolor='w') ax = fig.add_subplot(111) ax.plot([1, n_estimators], [dt_stump_err] * 2, 'k-', label='Decision Stump Error') ax.plot([1, n_estimators], [dt_err] * 2, 'k--', label='Decision Tree Error') ada_discrete_err = np.zeros((n_estimators,)) for i, y_pred in enumerate(ada_discrete.staged_predict(X_test)): ada_discrete_err[i] = (y_pred != y_test).mean() ada_discrete_err_train = np.zeros((n_estimators,)) for i, y_pred in enumerate(ada_discrete.staged_predict(X_train)): ada_discrete_err_train[i] = (y_pred != y_train).mean() ada_real_err = np.zeros((n_estimators,)) for i, y_pred in enumerate(ada_real.staged_predict(X_test)): ada_real_err[i] = (y_pred != y_test).mean() ada_real_err_train = np.zeros((n_estimators,)) for i, y_pred in enumerate(ada_real.staged_predict(X_train)): ada_real_err_train[i] = (y_pred != y_train).mean() ax.plot(np.arange(n_estimators) + 1, ada_discrete_err, label='Discrete AdaBoost Test Error', color='red') ax.plot(np.arange(n_estimators) + 1, ada_discrete_err_train, label='Discrete AdaBoost Train Error', color='blue') ax.plot(np.arange(n_estimators) + 1, ada_real_err, label='Real AdaBoost Test Error', color='orange') ax.plot(np.arange(n_estimators) + 1, ada_real_err_train, label='Real AdaBoost Train Error', color='green') ax.set_ylim((0.0, 0.5)) ax.set_xlabel('n_estimators') leg = ax.legend(loc='upper right', fancybox=True) leg.get_frame().set_alpha(0.7) plt.show()
Python
0.000006
@@ -1,24 +1,482 @@ %22%22%22 -Figure 10.2 from +%0A=============================%0ADiscrete versus Real AdaBoost%0A=============================%0A%0AThis example is based on Figure 10.2 from Hastie et al 2009 %5B1%5D and illustrates%0Athe difference in performance between the discrete SAMME %5B2%5D boosting%0Aalgorithm and real SAMME.R boosting algorithm.%0A%0ADiscrete SAMME AdaBoost adapts based on errors in predicted class labels%0Awhereas real SAMME.R uses the predicted class probabilities.%0A%0A.. %5B1%5D T. Hastie, R. Tibshirani and J. Friedman, %22 Elem @@ -494,16 +494,20 @@ tistical +%0A Learnin @@ -511,29 +511,138 @@ ning -, Ed. 2 -.%0A%0A.. a +%22, Springer, 2009.%0A%0A.. %5B2%5D J. Zhu, H. Zou, S. Rosset, T. Hastie, %22Multi-class AdaBoost%22, 2009.%0A%0A%22%22%22%0Aprint __doc__%0A%0A# A uthor: -: Pet @@ -687,20 +687,19 @@ ail.com%3E -%0A +,%0A# @@ -731,19 +731,33 @@ il.com%3E%0A -%22%22%22 +#%0A# License: BSD%0A %0Aimport @@ -1745,21 +1745,8 @@ ure( -facecolor='w' )%0Aax
4f4ea5b8c76f35e70368fef0e932f1630788a64a
read json data from file and parse out the good stuff
parse_info_from_json.py
parse_info_from_json.py
Python
0.000001
@@ -0,0 +1,700 @@ +import json%0Afrom pprint import pprint%0Aimport re%0A%0Ajson_data=open('crashlacma.20140524-102001.json')%0A%0Adata = json.load(json_data)%0A%0A# TODO: handle test cases%0A# testcases:%0A# hollywood & vine, hollywood and vine%0A# order of operations: hashtag, img, address, other text.%0A# hashtag allcaps or lowercase%0A# uploaded image, link to hosted image%0A%0A# if image is uploaded via twitter%0Aimg_url = data%5B%22entities%22%5D%5B%22media%22%5D%5B0%5D%5B%22media_url%22%5D%0Ahashtag = data%5B%22entities%22%5D%5B%22hashtags%22%5D%5B0%5D%5B%22text%22%5D # won't need this parsed%0Atweet = data%5B%22text%22%5D%0Atweet_text = ' '.join(re.sub(%22(@%5BA-Za-z0-9%5D+)%7C(#%5BA-Za-z0-9%5D+)%7C(%5Cw+:%5C/%5C/%5CS+)%22,%22 %22,tweet).split())%0A%0Aprint(hashtag)%0Aprint(img_url)%0Aprint(tweet)%0Aprint(tweet_text)%0A%0A%0Ajson_data.close()
510adb95228852456e7a8074aee10d6d1dad167a
add metadata class for handling guppy geometry attributes
vector/metadata.py
vector/metadata.py
Python
0
@@ -0,0 +1,2279 @@ +%22%22%22 Metadata management %22%22%22%0A%0A# Metadata objects should%0A# - maintain internal consistency%0A# - be concatenable%0A# - be iterable%0A%0Aimport copy%0A%0Aclass GeoMetadata(object):%0A %22%22%22 Class for handling collections of metadata %22%22%22%0A%0A _dict = %7B%7D%0A _fieldtypes = %5B%5D%0A def __init__(self, data):%0A %22%22%22 Create a collection of metadata from *data*, which may be a list%0A with uniform type or a dictionary with equally-sized fields of uniform%0A type. %22%22%22%0A%0A if hasattr(data, 'keys') and hasattr(data.values, '__call__'):%0A # Dictionary of attributes%0A for k in data:%0A dtype = type(data%5Bk%5D%5B0%5D)%0A if False in (isinstance(a, dtype) for a in data%5Bk%5D):%0A raise GMetadataError(%22Data must have uniform type%22)%0A%0A n = len(data%5Bk%5D)%0A if False in (len(data%5Bk%5D) == n for k in data):%0A raise GMetadataError(%22Data must have uniform lengths%22)%0A%0A else:%0A # Single attribute%0A if not hasattr(data, '__iter__'):%0A data = %5Bdata%5D%0A dtype = type(data%5B0%5D)%0A if False in (isinstance(a, dtype) for a in data):%0A raise GMetadataError(%22Data must have uniform type%22)%0A else:%0A data = %7B'values': data%7D%0A%0A self._data = data%0A self._fieldtypes = %5Btype(data%5Bk%5D%5B0%5D) for k in data%5D%0A%0A def __add__(self, other):%0A if isinstance(other, type(self)):%0A res = copy.deepcopy(self)%0A return res.extend(other)%0A%0A def extend(self, other):%0A if isinstance(other, type(self)):%0A for i, k in enumerate(self._data):%0A if type(self._fieldtypes%5Bi%5D) == type(other._fieldtypes%5Bi%5D):%0A self._data%5Bk%5D += other._data%5Bk%5D%0A else:%0A raise GMetadataError(%22Cannot combine metadata instances %22%0A %22with different type hierarchies%22)%0A return self%0A%0A def __iter__(self):%0A return self._data.__iter__()%0A%0A def __getitem__(self, idx):%0A return tuple(%5Bself._data%5Bk%5D%5Bidx%5D for k in self._data%5D)%0A%0A%0Aclass GMetadataError(Exception):%0A def __init__(self, message=''):%0A self.message = message%0A def __str__(self):%0A return self.message%0A%0A%0A
093a029ae8607f15b9b446f54293e15f13d44c0e
Create led.py
Python/led.py
Python/led.py
Python
0
@@ -0,0 +1,404 @@ +import RPi.GPIO as GPIO%0Aimport time%0A%0A# blinking function%0Adef blink(pin):%0A GPIO.output(pin,GPIO.HIGH)%0A time.sleep(1)%0A GPIO.output(pin,GPIO.LOW)%0A time.sleep(1)%0A return%0A%0A# to use Raspberry Pi board pin numbers%0AGPIO.setmode(GPIO.BOARD)%0A%0A# set up GPIO output channel%0AGPIO.setup(21, GPIO.OUT)%0A%0A# blink GPIO21 50 times%0Afor i in range(0,50):%0A blink(11)%0A%0AGPIO.cleanup() %0A
30bc00ce84355cc40e62b1f46d32a17c6b07ac0c
Create GreenHat.py
GreenHat.py
GreenHat.py
Python
0.000001
@@ -0,0 +1,1211 @@ +# Copyright (c) 2015 Angus H. (4148)%0A# Distributed under the GNU General Public License v3.0 (GPLv3).%0A%0Afrom datetime import date, timedelta%0Afrom random import randint%0Afrom time import sleep%0Aimport sys%0Aimport subprocess%0Aimport os%0A%0A# returns a date string for the date that is N days before STARTDATE%0Adef get_date_string(n, startdate):%0A%09d = startdate - timedelta(days=n)%0A%09rtn = d.strftime(%22%25a %25b %25d %25X %25Y %25z -0400%22)%0A%09return rtn%0A%0A# main app%0Adef main(argv):%0A%09if len(argv) %3C 1 or len(argv) %3E 2:%0A%09%09print %22Error: Bad input.%22%0A%09%09sys.exit(1)%0A%09n = int(argv%5B0%5D)%0A%09if len(argv) == 1:%0A%09%09startdate = date.today()%0A%09if len(argv) == 2:%0A%09%09startdate = date(int(argv%5B1%5D%5B0:4%5D), int(argv%5B1%5D%5B5:7%5D), int(argv%5B1%5D%5B8:10%5D))%0A%09i = 0%0A%09while i %3C= n:%0A%09%09curdate = get_date_string(i, startdate)%0A%09%09num_commits = randint(1, 10)%0A%09%09for commit in range(0, num_commits):%0A%09%09%09subprocess.call(%22echo '%22 + curdate + str(randint(0, 1000000)) +%22' %3E realwork.txt; git add realwork.txt; GIT_AUTHOR_DATE='%22 + curdate + %22' GIT_COMMITTER_DATE='%22 + curdate + %22' git commit -m 'update'; git push;%22, shell=True)%0A%09%09%09sleep(.5)%0A%09%09i += 1%0A%09subprocess.call(%22git rm realwork.txt; git commit -m 'delete'; git push;%22, shell=True)%0A%0Aif __name__ == %22__main__%22:%0A%09main(sys.argv%5B1:%5D)%0A
985f23ee5e107c647d5f5e5b245c3fb7ff2d411b
Write script to convert PMF-based result to expected value
bin/to_expected.py
bin/to_expected.py
Python
0.000001
@@ -0,0 +1,1275 @@ +#!/usr/bin/env python%0A%0Aimport argparse%0A%0Aimport numpy as np%0Aimport pandas as pd%0A%0A%0Aif __name__ == '__main__':%0A parser = argparse.ArgumentParser(description='Convert result from PMF'%0A ' to expected value')%0A parser.add_argument('file', type=str,%0A help='Result DataFrame in HDF5 format')%0A parser.add_argument('outfile', type=str,%0A help='Output file')%0A parser.add_argument('--hdf-key', type=str, default='df',%0A help='Identifier in the HDF5 store')%0A args = parser.parse_args()%0A%0A df = pd.read_hdf(args.file, args.hdf_key)%0A data = np.array(%5B%5D)%0A grouped = df.groupby(level=df.columns.names%5B:4%5D, axis=1)%0A columns = %5B%5D%0A for name, _ in grouped:%0A columns.append(name)%0A pmf = df%5Bname%5D.values%0A supp = np.array(df%5Bname%5D.columns)%0A expected = np.sum(supp*pmf, axis=1)%0A data = np.concatenate((data, expected))%0A%0A index = df.index.copy()%0A columns = pd.MultiIndex.from_tuples(columns)%0A df2 = pd.DataFrame(data.reshape((len(index), len(columns))), index=index,%0A columns=columns)%0A%0A df2.to_hdf(args.outfile, args.hdf_key)%0A print(%22Stored in HDF5 format with the name '%7B%7D'%22.format(args.hdf_key))%0A
3f6ec1a3e9bcdd2dee714e74fac7215b19ae432f
Add an example of a blocking tcp server
blocking_socket.py
blocking_socket.py
Python
0.00016
@@ -0,0 +1,934 @@ +%22%22%22%0AA Simple example for testing the SimpleServer Class. A simple telnet server.%0AIt is for studying purposes only.%0A%22%22%22%0A%0Afrom server import SimpleServer%0A%0A%0A__author__ = %22Facundo Victor%22%0A__license__ = %22MIT%22%0A__email__ = %22facundovt@gmail.com%22%0A%0A%0Adef handle_message(sockets=None):%0A %22%22%22%0A Handle a simple TCP connection.%0A %22%22%22%0A if sockets is not None:%0A (readable, writable, errors) = sockets%0A try:%0A while True:%0A data = readable.recv(1024)%0A print('Received data: %25s' %25 (data))%0A if data:%0A print('Sending a custom ACK to the client')%0A writable.sendall(%22Received ;)%5Cn%22)%0A else:%0A print('Received empty data')%0A break%0A finally:%0A SS.close_connection()%0A%0A%0ASS = SimpleServer(blocking=True)%0ASS.register_handler(handle_message)%0ASS.bind_and_listeen(%22localhost%22, 7878)%0A
22fd64e88700fb8cb0c86eef10df1ae0c5fb91c9
Create parse_large_file.py
tools/parse_large_file.py
tools/parse_large_file.py
Python
0.000005
@@ -0,0 +1,2211 @@ +#!/usr/bin/evn python%0A# -*- encoding: utf-8 -*-%0A#%0A# Simple example for processing large file in multiple threads line by line%0A#%0A# Copyright 2019 Wanghong Lin%0A# %0A# Licensed under the Apache License, Version 2.0 (the %22License%22);%0A# you may not use this file except in compliance with the License.%0A# You may obtain a copy of the License at%0A# %0A# http://www.apache.org/licenses/LICENSE-2.0%0A# %0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS,%0A# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A# See the License for the specific language governing permissions and%0A# limitations under the License.%0A#%0A%0Aimport threading%0Aimport multiprocessing%0Aimport itertools%0Aimport subprocess%0A%0A%0Adef get_file_lines(f_name):%0A %22%22%22%0A Efficient way to get total line of a file%0A :param f_name: full file path%0A :return: file total length%0A %22%22%22%0A p = subprocess.Popen(%5B'wc', '-l', f_name%5D, stdout=subprocess.PIPE,%0A stderr=subprocess.PIPE)%0A result, err = p.communicate()%0A if p.returncode != 0:%0A raise IOError(err)%0A return int(result.strip().split()%5B0%5D)%0A%0A%0Adef perform_parse(*args, **kwargs):%0A start = kwargs%5B'start'%5D%0A stop = kwargs%5B'stop'%5D%0A with open(args%5B0%5D, 'r') as f:%0A for l in itertools.islice(f, start, stop):%0A l.split(',')%0A # add your other processing logic here%0A%0A%0Adef parse_large_file(file_path):%0A file_lines = get_file_lines(file_path)%0A number_of_threads = multiprocessing.cpu_count()/2%0A slice_lines = file_lines / number_of_threads%0A%0A threads = %5B%5D%0A for i in range(number_of_threads):%0A start = i * slice_lines%0A stop = max((i + 1) * slice_lines, file_lines) if i + 1 == number_of_threads else (i + 1) * slice_lines%0A t = threading.Thread(target=perform_parse, args=(file_path,), kwargs=%7B'start': start, 'stop': stop%7D,%0A name='Thread %7B%7D'.format(i))%0A print('%7B0%7D line range %7B1%7D -%3E %7B2%7D'.format(t.name, start, stop))%0A threads.append(t)%0A t.start()%0A%0A %5Bt.join() for t in threads%5D%0A%0A%0Aif __name__ == '__main__':%0A parse_large_file('path/to/large_file')%0A
3a11d1c5235fcc7f40aca4395a183d7e1316117a
Add documentation support for swagger
makiki/documentation.py
makiki/documentation.py
Python
0
@@ -0,0 +1,1818 @@ +# -*- coding: utf-8 -*-%0A%0Aimport json%0A%0A%0Aclass Documentation(object):%0A%0A HUG_TYPE_TRANSLATION = %7B%0A 'A Whole number': 'integer',%0A 'Accepts a JSON formatted data structure': 'object',%0A 'Basic text / string value': 'string',%0A 'Multiple Values': 'array',%0A %7D%0A%0A def __init__(self, hug_doc, version='1.0', title='REST API', host='localhost', schemas=None, consumes=None, produces=None):%0A self._content = %7B%0A 'swagger': '2.0',%0A 'info': %7B%0A 'version': version,%0A 'title': title,%0A %7D,%0A 'host': host,%0A 'schemes': %5B'http'%5D if schemas is None else schemas,%0A 'consumes': %5B'application/json'%5D if consumes is None else consumes,%0A 'produces': %5B'application/json'%5D if produces is None else produces,%0A 'paths': %7B%7D,%0A %7D%0A self.parse_hug_doc(hug_doc)%0A%0A def parse_hug_doc(self, hug_doc):%0A for url, spec in hug_doc.items():%0A self._content%5B'paths'%5D%5Burl%5D = %7B%7D%0A for method, detail in spec.items():%0A self._content%5B'paths'%5D%5Burl%5D%5Bmethod.lower()%5D = %7B%0A 'description': detail.get('usage', ''),%0A 'parameters': %5B%7B%0A 'name': k,%0A 'in': 'query' if method == 'GET' else 'body',%0A 'required': 'default' not in v,%0A 'type': self.HUG_TYPE_TRANSLATION.get(v.get('type', ''), 'any'),%0A %7D for k, v in detail.get('inputs', %7B%7D).items()%5D,%0A 'responses': %7B%0A '200': %7B%0A 'description': 'Success',%0A %7D%0A %7D%0A %7D%0A%0A @property%0A def content(self):%0A return json.dumps(self._content)%0A
591e9f15a3b9da59f80f81fcf0d6ddad4aeb7d6a
Add a snippet.
python/pyside/pyside6/widget_QSqlRelationalTableModel_sqlite_from_file.py
python/pyside/pyside6/widget_QSqlRelationalTableModel_sqlite_from_file.py
Python
0.000002
@@ -0,0 +1,2559 @@ +#!/usr/bin/env python3%0A# -*- coding: utf-8 -*-%0A%0A# Ref: https://doc.qt.io/qtforpython/PySide6/QtSql/QSqlRelationalTableModel.html?highlight=qsqlrelationaltablemodel%0A%0Aimport sys%0Aimport sqlite3%0Afrom PySide6 import QtCore, QtWidgets%0A%0Afrom PySide6.QtCore import Qt%0Afrom PySide6.QtWidgets import QApplication, QTableView%0Afrom PySide6.QtSql import QSqlDatabase, QSqlQuery, QSqlRelationalTableModel, QSqlRelation, QSqlRelationalDelegate%0A%0A%0A# INIT THE DATABASE #############################%0A%0Acon = sqlite3.connect(%22employee2.db%22)%0Acur = con.cursor()%0A%0Atry:%0A cur.execute(%22DROP TABLE t_employee%22)%0Aexcept:%0A pass%0A%0Atry:%0A cur.execute(%22DROP TABLE t_country%22)%0Aexcept:%0A pass%0A%0Acur.execute(%22CREATE TABLE t_country (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)%22)%0Acur.execute(%22CREATE TABLE t_employee (id INTEGER PRIMARY KEY AUTOINCREMENT, first_name TEXT, last_name TEXT, country_id TEXT, FOREIGN KEY(country_id) REFERENCES t_country(id))%22)%0A%0Aparams_list = %5B%0A (%22France%22,),%0A (%22Belgium%22,),%0A (%22Germany%22,),%0A (%22Spain%22,),%0A (%22Italy%22,),%0A%5D%0A%0Acur.executemany(%22INSERT INTO t_country (name) VALUES(?)%22, params_list)%0A%0Aparams_list = %5B%0A (%22Jean%22, %22Dupont%22, 2),%0A (%22Paul%22, %22Dupond%22, 2),%0A (%22Jeanne%22, %22Durand%22, 1),%0A (%22Anne%22, %22Dupuit%22, 1),%0A%5D%0A%0Acur.executemany(%22INSERT INTO t_employee (first_name, last_name, country_id) VALUES(?, ?, ?)%22, params_list)%0Acon.commit()%0A%0Acon.close()%0A%0A%0A# OPEN THE DATABASE #############################%0A%0Adb = QSqlDatabase.addDatabase(%22QSQLITE%22)%0Adb.setDatabaseName(%22./employee2.db%22)%0Aassert db.open()%0A%0A%0A#################################################%0A%0Aapp = QApplication(sys.argv)%0A%0Atable_view = QTableView()%0Atable_view.setSortingEnabled(True)%0A%0Amodel = QSqlRelationalTableModel()%0Amodel.setTable(%22t_employee%22)%0Amodel.setRelation(3, QSqlRelation(%22t_country%22, %22id%22, %22name%22)) # column 3 in table t_employee is a foreign key that maps with field id of table t_country, and that the view should present the country's name field to the user%0Amodel.select()%0Amodel.setHeaderData(0, Qt.Horizontal, %22ID%22)%0Amodel.setHeaderData(1, Qt.Horizontal, %22First Name%22)%0Amodel.setHeaderData(2, Qt.Horizontal, %22Last Name%22)%0Amodel.setHeaderData(3, Qt.Horizontal, %22Counrty%22)%0A%0Atable_view.setModel(model)%0Atable_view.setItemDelegate(QSqlRelationalDelegate(table_view))%0A%0A%0A#################################################%0A%0Atable_view.show()%0A%0A# The mainloop of the application. The event handling starts from this point.%0Aexit_code = app.exec()%0A%0A# The sys.exit() method ensures a clean exit.%0A# The environment will be informed, how the application ended.%0Asys.exit(exit_code)%0A
99ffed2a53c5266f312127b7a09f86254891234e
Create 4-LDR.py
Code/4-LDR.py
Code/4-LDR.py
Python
0.000005
@@ -0,0 +1,763 @@ +# Import Libraries%0Aimport time%0Aimport RPi.GPIO as GPIO%0A%0A# Set the GPIO Mode and set the pin to use for the %0AGPIO.setmode(GPIO.BCM)%0AGPIO.setwarnings(False)%0A%0A# A variable with the LDR reading pin number%0APINLDR = 27%0A %0Adef ReadLDR():%0A LDRCount = 0 # Sets the count to 0%0A GPIO.setup(PINLDR, GPIO.OUT)%0A GPIO.output(PINLDR, GPIO.LOW)%0A time.sleep(0.1) # Drains all charge from the capacitor%0A%0A GPIO.setup(PINLDR, GPIO.IN) # Sets the pin to be input%0A # While the input pin reads %E2%80%98off%E2%80%99 or Low, count%0A while (GPIO.input(PINLDR) == GPIO.LOW):%0A LDRCount += 1 # Add one to the counter%0A return LDRCount%0A %0Awhile True: %0A print ReadLDR()%0A time.sleep(1) # Wait for a second%0A
0c4095d9b370da41f653927dc92cc4233aca2beb
Add untested LedStrip driver
LedStrip.py
LedStrip.py
Python
0
@@ -0,0 +1,1103 @@ +import RPi.GPIO as GPIO, time, os%0A%0Aclass RGB:%0A r = 0xff%0A g = 0xff%0A b = 0xff%0A def __init__(self, r, g, b):%0A self.r = r%0A self.g = g%0A self.b = b%0A%0A%0Aclass LedStrip:%0A spidev = None%0A height = 10%0A%0A def __init__(self):%0A self.spidev = file(%22/dev/spidev0.0%22, %22w%22)%0A%0A def WriteStrip(self, pixels):%0A if len(pixels) != self.height:%0A return%0A start = 0%0A end = self.height%0A step = 1%0A for pixel in range(start,end,step):%0A self.spidev.write( chr((pixels%5Bpixel%5D.b %3E%3E 16) & 0xff ))%0A self.spidev.write( chr((pixels%5Bpixel%5D.b %3E%3E 8) & 0xff ))%0A self.spidev.write( chr((pixels%5Bpixel%5D.b) & 0xff ))%0A #self.spidev.write( chr(pixels%5Bpixel%5D.g %3E%3E 8) & 0xff )%0A #self.spidev.write( chr(pixels%5Bpixel%5D.r %3E%3E 0) & 0xff )%0A self.spidev.flush()%0A%0Aif __name__ == %22__main__%22:%0A strip = LedStrip()%0A startVal = 0%0A endVal = 255%0A step = 1%0A for val in range(startVal, endVal, step):%0A pixelArr = %5BRGB(val,val,val)%5D * 10%0A strip.WriteStrip(pixelArr)%0A time.sleep(0.05)%0A
35e8133dbf0f95a511c2eb219ba408af464afc2b
Create file
jupyter_notebook_config_template.py
jupyter_notebook_config_template.py
Python
0.000002
@@ -0,0 +1,270 @@ +c.NotebookApp.ip = '*'%0Ac.NotebookApp.port = 8998%0Ac.NotebookApp.open_browser = False%0Ac.NotebookApp.keyfile = u'/home/ubuntu/.certificates/jupyterkey.pem'%0Ac.NotebookApp.certfile = u'/home/ubuntu/.certificates/jupytercert.pem'%0Ac.NotebookApp.password = u'sha2:PASSWORDHASH'%0A
2d66bc24c883f135a9a22cd40a8b2682ec572373
Add count_bits
node/count_bits.py
node/count_bits.py
Python
0.000577
@@ -0,0 +1,507 @@ +from nodes import Node%0A%0Aclass CountBits(Node):%0A char = %22./%22%0A args = 2%0A results = 1%0A contents = 2000%0A %0A @Node.test_func(%5B8,2%5D, %5B%5B1, 3%5D%5D)%0A @Node.test_func(%5B12, 3%5D, %5B%5B0, 2, 1%5D%5D)%0A def count_bits(self, num: int, base: int):%0A %22%22%22Count the number of times each digit occurs in %60base%60%22%22%22%0A counts = %5B0 for i in range(base)%5D%0A %0A while num != 0:%0A num, remainder = divmod(num, base)%0A counts%5Bbase-remainder-1%5D += 1%0A return %5Bcounts%5D%0A
623115b7cb26c6402479845dd96e69c613ad4b98
Create easy_23_DashInsert.py
easy_23_DashInsert.py
easy_23_DashInsert.py
Python
0.000001
@@ -0,0 +1,398 @@ +def odd(ch):%0A return ch in '13579'%0A%0A##############################%0A# Inserts dashes between odd #%0A# digits #%0A##############################%0Adef DashInsert(num):%0A result = %5B%5D%0A prev = ' '%0A for curr in str(num):%0A if odd(prev) and odd(curr): %0A result.append('-')%0A result.append(curr)%0A prev = curr%0A return ''.join(result)%0A%0Aprint DashInsert(raw_input()) %0A
bfe073671910efdd932b92c2bb40dc24c230733a
fix migrations
apps/domain/migrations/0024_meta.py
apps/domain/migrations/0024_meta.py
Python
0.000002
@@ -0,0 +1,519 @@ +# -*- coding: utf-8 -*-%0A# Generated by Django 1.9 on 2016-11-14 12:11%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('domain', '0023_fix_label'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterModelManagers(%0A name='attribute',%0A managers=%5B%0A %5D,%0A ),%0A migrations.AlterModelManagers(%0A name='attributeentity',%0A managers=%5B%0A %5D,%0A ),%0A %5D%0A
b35dc73429d8625b298017625b4521a2f3a00eea
Add testing module
maxwellbloch/testing.py
maxwellbloch/testing.py
Python
0.000001
@@ -0,0 +1,214 @@ +# -*- coding: utf-8 -*-%0A%0Aimport nose%0A%0Adef run():%0A %22%22%22%0A Run all tests with nose.%0A %22%22%22%0A%0A # runs tests in maxwellbloch.tests module%0A nose.run(defaultTest=%22maxwellbloch.tests%22, argv=%5B'nosetests', '-v'%5D)%0A
cc04592ea5ea15944f668928d5b8e6f7d8e257a1
Update prefix-and-suffix-search.py
Python/prefix-and-suffix-search.py
Python/prefix-and-suffix-search.py
# Time: ctor: O(w * l), l is the word length on average # search: O(m + n), m is the number of prefix match, n is the number of suffix match # Space: O(w * l), w is the number of words class Trie(object): def __init__(self): _trie = lambda: collections.defaultdict(_trie) self.__trie = _trie() def insert(self, word, i): def add_word(cur, i): if "_words" not in cur: cur["_words"] = [] cur["_words"].append(i) cur = self.__trie add_word(cur, i) for c in word: cur = cur[c] add_word(cur, i) def find(self, word): cur = self.__trie for c in word: if c not in cur: return [] cur = cur[c] return cur["_words"] class WordFilter(object): def __init__(self, words): """ :type words: List[str] """ self.__prefix_trie = Trie() self.__suffix_trie = Trie() for i in reversed(xrange(len(words))): self.__prefix_trie.insert(words[i], i) self.__suffix_trie.insert(words[i][::-1], i) def f(self, prefix, suffix): """ :type prefix: str :type suffix: str :rtype: int """ prefix_match = self.__prefix_trie.find(prefix) suffix_match = self.__suffix_trie.find(suffix[::-1]) i, j = 0, 0 while i != len(prefix_match) and j != len(suffix_match): if prefix_match[i] == suffix_match[j]: return prefix_match[i] elif prefix_match[i] > suffix_match[j]: i += 1 else: j += 1 return -1 # Your WordFilter object will be instantiated and called as such: # obj = WordFilter(words) # param_1 = obj.f(prefix,suffix)
Python
0
@@ -19,16 +19,42 @@ (w * l), + w is the number of words, l is th @@ -191,34 +191,8 @@ * l) -, w is the number of words %0A%0Acl
6718e97b23d67dda6e67cda8226030edd90f7fbd
add env.py for the migrations
migrations/env.py
migrations/env.py
Python
0
@@ -0,0 +1,2158 @@ +from __future__ import with_statement%0Afrom alembic import context%0Afrom sqlalchemy import engine_from_config, pool%0Afrom logging.config import fileConfig%0A%0A# this is the Alembic Config object, which provides%0A# access to the values within the .ini file in use.%0Aconfig = context.config%0A%0A# Interpret the config file for Python logging.%0A# This line sets up loggers basically.%0AfileConfig(config.config_file_name)%0A%0A# add your model's MetaData object here%0A# for 'autogenerate' support%0A# from myapp import mymodel%0A# target_metadata = mymodel.Base.metadata%0Afrom flask import current_app%0Aconfig.set_main_option('sqlalchemy.url', current_app.config.get('SQLALCHEMY_DATABASE_URI'))%0Atarget_metadata = current_app.extensions%5B'migrate'%5D.db.metadata%0A%0A# other values from the config, defined by the needs of env.py,%0A# can be acquired:%0A# my_important_option = config.get_main_option(%22my_important_option%22)%0A# ... etc.%0A%0Adef run_migrations_offline():%0A %22%22%22Run migrations in 'offline' mode.%0A%0A This configures the context with just a URL%0A and not an Engine, though an Engine is acceptable%0A here as well. By skipping the Engine creation%0A we don't even need a DBAPI to be available.%0A%0A Calls to context.execute() here emit the given string to the%0A script output.%0A%0A %22%22%22%0A url = config.get_main_option(%22sqlalchemy.url%22)%0A context.configure(url=url)%0A%0A with context.begin_transaction():%0A context.run_migrations()%0A%0Adef run_migrations_online():%0A %22%22%22Run migrations in 'online' mode.%0A%0A In this scenario we need to create an Engine%0A and associate a connection with the context.%0A%0A %22%22%22%0A engine = engine_from_config(%0A config.get_section(config.config_ini_section),%0A prefix='sqlalchemy.',%0A poolclass=pool.NullPool)%0A%0A connection = engine.connect()%0A context.configure(%0A connection=connection,%0A target_metadata=target_metadata%0A )%0A%0A try:%0A with context.begin_transaction():%0A context.run_migrations()%0A finally:%0A connection.close()%0A%0Aif context.is_offline_mode():%0A run_migrations_offline()%0Aelse:%0A run_migrations_online()%0A%0A
0f04d1a7e641fc37b4550f4ba6d1034f2da1ea0d
Fix rebuild of iterables.
scripts/unpickle.py
scripts/unpickle.py
#!/usr/bin/env python ########################################################################## # # Copyright 2012 Jose Fonseca # All Rights Reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # ##########################################################################/ '''Sample program for apitrace pickle command. Run as: apitrace pickle foo.trace | python unpickle.py ''' import itertools import optparse import sys import time import re import cPickle as pickle class Visitor: def __init__(self): self.dispatch = {} self.dispatch[type(None)] = self.visitNone self.dispatch[bool] = self.visitBool self.dispatch[int] = self.visitInt self.dispatch[long] = self.visitInt self.dispatch[float] = self.visitFloat self.dispatch[str] = self.visitStr self.dispatch[tuple] = self.visitTuple self.dispatch[list] = self.visitList self.dispatch[dict] = self.visitDict self.dispatch[bytearray] = self.visitByteArray def visit(self, obj): method = self.dispatch.get(type(obj), self.visitObj) return method(obj) def visitObj(self, obj): raise NotImplementedError def visitAtom(self, obj): return self.visitObj(obj) def visitNone(self, obj): return self.visitAtom(obj) def visitBool(self, obj): return self.visitAtom(obj) def visitInt(self, obj): return self.visitAtom(obj) def visitFloat(self, obj): return self.visitAtom(obj) def visitStr(self, obj): return self.visitAtom(obj) def visitIterable(self, obj): return self.visitObj(obj) def visitTuple(self, obj): return self.visitIterable(obj) def visitList(self, obj): return self.visitIterable(obj) def visitDict(self, obj): raise NotImplementedError def visitByteArray(self, obj): raise NotImplementedError class Dumper(Visitor): id_re = re.compile('^[_A-Za-z][_A-Za-z0-9]*$') def visitObj(self, obj): return repr(obj) def visitStr(self, obj): if self.id_re.match(obj): return obj else: return repr(obj) def visitTuple(self, obj): return '[' + ', '.join(itertools.imap(self.visit, obj)) + ']' def visitList(self, obj): return '(' + ', '.join(itertools.imap(self.visit, obj)) + ')' def visitByteArray(self, obj): return 'blob(%u)' % len(obj) class Hasher(Visitor): '''Returns a hashable version of the objtree.''' def visitObj(self, obj): return obj def visitAtom(self, obj): return obj def visitIterable(self, obj): return tuple(itertools.imap(self.visit, obj)) def visitByteArray(self, obj): return str(obj) class Rebuilder(Visitor): '''Returns a hashable version of the objtree.''' def visitAtom(self, obj): return obj def visitIterable(self, obj): changed = False newItems = [] for oldItem in obj: newItem = self.visit(oldItem) if newItem is not oldItem: changed = True newItems.append(newItem) if changed: klass = type(obj) return klass(changed) else: return obj def visitByteArray(self, obj): return obj class Call: def __init__(self, callTuple): self.no, self.functionName, self.args, self.ret = callTuple self._hash = None def __str__(self): s = self.functionName if self.no is not None: s = str(self.no) + ' ' + s dumper = Dumper() s += '(' + ', '.join(itertools.imap(dumper.visit, self.args)) + ')' if self.ret is not None: s += ' = ' s += dumper.visit(self.ret) return s def __eq__(self, other): return \ self.functionName == other.functionName and \ self.args == other.args and \ self.ret == other.ret def __hash__(self): if self._hash is None: hasher = Hasher() hashable = hasher.visit(self.functionName), hasher.visit(self.args), hasher.visit(self.ret) self._hash = hash(hashable) return self._hash class Unpickler: callFactory = Call def __init__(self, stream): self.stream = stream def parse(self): while self.parseCall(): pass def parseCall(self): try: callTuple = pickle.load(self.stream) except EOFError: return False else: call = self.callFactory(callTuple) self.handleCall(call) return True def handleCall(self, call): pass class Counter(Unpickler): def __init__(self, stream, quiet): Unpickler.__init__(self, stream) self.quiet = quiet self.calls = 0 def handleCall(self, call): if not self.quiet: sys.stdout.write(str(call)) sys.stdout.write('\n') self.calls += 1 def main(): optparser = optparse.OptionParser( usage="\n\tapitrace pickle trace. %prog [options]") optparser.add_option( '-q', '--quiet', action="store_true", dest="quiet", default=False, help="don't dump calls to stdout") (options, args) = optparser.parse_args(sys.argv[1:]) if args: optparser.error('unexpected arguments') # Change stdin to binary mode try: import msvcrt except ImportError: pass else: import os msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY) startTime = time.time() parser = Counter(sys.stdin, options.quiet) parser.parse() stopTime = time.time() duration = stopTime - startTime sys.stderr.write('%u calls, %.03f secs, %u calls/sec\n' % (parser.calls, duration, parser.calls/duration)) if __name__ == '__main__': main()
Python
0
@@ -4266,23 +4266,24 @@ n klass( -changed +newItems )%0A
cc3b29aaa2c0ffa3cde6b901bf4bdf3ce3fb4345
Add code for pulling pitcher stats for specified date range
pybaseball/league_pitching_stats.py
pybaseball/league_pitching_stats.py
Python
0
@@ -0,0 +1,1193 @@ +import requests%0Aimport pandas as pd%0Afrom bs4 import BeautifulSoup%0A%0Adef get_soup(start_dt, end_dt):%0A%09# get most recent standings if date not specified%0A%09if((start_dt is None) or (end_dt is None)):%0A%09%09print('Error: a date range needs to be specified')%0A%09%09return None%0A%09url = %22http://www.baseball-reference.com/leagues/daily.cgi?user_team=&bust_cache=&type=p&lastndays=7&dates=fromandto&fromandto=%7B%7D.%7B%7D&level=mlb&franch=&stat=&stat_value=0%22.format(start_dt, end_dt)%0A%09s=requests.get(url).content%0A%09return BeautifulSoup(s, %22html.parser%22)%0A%0Adef get_table(soup):%0A%09table = soup.find_all('table')%5B0%5D%0A%09data = %5B%5D%0A%09headings = %5Bth.get_text() for th in table.find(%22tr%22).find_all(%22th%22)%5D%5B1:%5D%0A%09data.append(headings)%0A%09table_body = table.find('tbody')%0A%09rows = table_body.find_all('tr')%0A%09for row in rows:%0A%09 cols = row.find_all('td')%0A%09 cols = %5Bele.text.strip() for ele in cols%5D%0A%09 data.append(%5Bele for ele in cols if ele%5D)%0A%09data = pd.DataFrame(data)%0A%09data = data.rename(columns=data.iloc%5B0%5D)%0A%09data = data.reindex(data.index.drop(0))%0A%09return data%0A%0Adef pitching_stats(start_dt=None, end_dt=None):%0A%09# retrieve html from baseball reference%0A%09soup = get_soup(start_dt, end_dt)%0A%09table = get_table(soup)%0A%09return table%0A%0A%0A
bd60a99d832d839d7535a5232453afa807d6e3ee
Create __init__.py
Pi_Weather_Station/__init__.py
Pi_Weather_Station/__init__.py
Python
0.000429
@@ -0,0 +1 @@ +%0A
f60123ea933cba6b57214ad335b244b48cc65fdf
Create valid-tic-tac-toe-state.py
Python/valid-tic-tac-toe-state.py
Python/valid-tic-tac-toe-state.py
Python
0.998513
@@ -0,0 +1,2303 @@ +# Time: O(1)%0A# Space: O(1)%0A%0A# A Tic-Tac-Toe board is given as a string array board. Return True%0A# if and only if it is possible to reach this board position%0A# during the course of a valid tic-tac-toe game.%0A#%0A# The board is a 3 x 3 array, and consists of characters %22 %22, %22X%22, %0A# and %22O%22. The %22 %22 character represents an empty square.%0A#%0A# Here are the rules of Tic-Tac-Toe:%0A# - Players take turns placing characters into empty squares (%22 %22).%0A# - The first player always places %22X%22 characters, while the second player always places %22O%22 characters.%0A# - %22X%22 and %22O%22 characters are always placed into empty squares, never filled ones.%0A# - The game ends when there are 3 of the same (non-empty) character filling any row, column, or diagonal.%0A# - The game also ends if all squares are non-empty.%0A# - No more moves can be played if the game is over.%0A#%0A# Example 1:%0A# Input: board = %5B%22O %22, %22 %22, %22 %22%5D%0A# Output: false%0A# Explanation: The first player always plays %22X%22.%0A#%0A# Example 2:%0A# Input: board = %5B%22XOX%22, %22 X %22, %22 %22%5D%0A# Output: false%0A# Explanation: Players take turns making moves.%0A#%0A# Example 3:%0A# Input: board = %5B%22XXX%22, %22 %22, %22OOO%22%5D%0A# Output: false%0A#%0A# Example 4:%0A# Input: board = %5B%22XOX%22, %22O O%22, %22XOX%22%5D%0A# Output: true%0A#%0A# Note:%0A# - board is a length-3 array of strings, where each string board%5Bi%5D has length 3.%0A# - Each board%5Bi%5D%5Bj%5D is a character in the set %7B%22 %22, %22X%22, %22O%22%7D.%0A%0Aclass Solution(object):%0A def validTicTacToe(self, board):%0A %22%22%22%0A :type board: List%5Bstr%5D%0A :rtype: bool%0A %22%22%22%0A def win(board, player):%0A for i in xrange(3):%0A if all(board%5Bi%5D%5Bj%5D == player for j in xrange(3)):%0A return True%0A if all(board%5Bj%5D%5Bi%5D == player for j in xrange(3)):%0A return True%0A%0A return (player == board%5B1%5D%5B1%5D == board%5B0%5D%5B0%5D == board%5B2%5D%5B2%5D or %5C%0A player == board%5B1%5D%5B1%5D == board%5B0%5D%5B2%5D == board%5B2%5D%5B0%5D)%0A %0A FIRST, SECOND = ('X', 'O')%0A x_count = sum(row.count(FIRST) for row in board)%0A o_count = sum(row.count(SECOND) for row in board)%0A if o_count not in %7Bx_count-1, x_count%7D: return False%0A if win(board, FIRST) and x_count-1 != o_count: return False%0A if win(board, SECOND) and x_count != o_count: return False%0A%0A return True%0A
ee7a48da3ef6486c3650f9bcc1f4b59c59642adc
Add unittest-based PyDbLite test
PyDbLite/test/test_pydblite.py
PyDbLite/test/test_pydblite.py
Python
0.000001
@@ -0,0 +1,2058 @@ +# -*- coding: iso-8859-1 -*-%0D%0A%0D%0Aimport datetime%0D%0Aimport unittest%0D%0Aimport random%0D%0A%0D%0Aimport os%0D%0Aimport sys%0D%0Asys.path.insert(0,os.path.dirname(os.getcwd()))%0D%0Aimport PyDbLite%0D%0A%0D%0Adb = None%0D%0Avals1 = %5B('simon',datetime.date(1984,8,17),26)%5D%0D%0Avals2 = %5B('camille',datetime.date(1986,12,12),24),%0D%0A ('jean',datetime.date(1989,6,12),21),('florence',datetime.date(1994,1,14),17),%0D%0A ('marie-anne',datetime.date(1999,1,28),12)%5D%0D%0Avals3 = %5B('',datetime.date(2000,10,10),55)%5D%0D%0A%0D%0Aclass TestFunctions(unittest.TestCase):%0D%0A%0D%0A def test_00_init(self):%0D%0A global db%0D%0A db = PyDbLite.Base('test.pdl')%0D%0A db.create('name','birth','age',mode=%22override%22)%0D%0A%0D%0A def test_01_insert(self):%0D%0A for i,val in enumerate(vals1+vals2+vals3):%0D%0A assert db.insert(*val)==i%0D%0A assert len(db)==len(vals1+vals2+vals3)%0D%0A%0D%0A def test_10_select(self):%0D%0A for i,v in enumerate(vals1):%0D%0A rec = db%5Bi%5D%0D%0A for j,field in enumerate(db.fields):%0D%0A assert rec%5Bfield%5D==v%5Bj%5D%0D%0A%0D%0A def test_11_select(self):%0D%0A assert db(name='foo')==%5B%5D%0D%0A assert db(name='')%5B0%5D%5B'birth'%5D==datetime.date(2000,10,10)%0D%0A%0D%0A def test_12_iter(self):%0D%0A self.assertEqual(len(%5Bx for x in db%5D),len(db))%0D%0A for val in vals1+vals2+vals3:%0D%0A self.assertEqual(%5B x for x in db if x%5B'name'%5D==val %5D,db(name=val))%0D%0A self.assertEqual(%5B x for x in db if x%5B'birth'%5D==val %5D,db(birth=val))%0D%0A self.assertEqual(%5B x for x in db if x%5B'age'%5D==val %5D,db(age=val))%0D%0A%0D%0A def test_30_update(self):%0D%0A for record in db:%0D%0A db.update(record,name=record%5B'name'%5D.capitalize())%0D%0A self.assertEqual(db%5B0%5D%5B'name'%5D,%22Simon%22)%0D%0A #self.assertEqual(db%5B5%5D%5B'name'%5D%5B0%5D,%22%22)%0D%0A%0D%0A def test_40_delete(self):%0D%0A del db%5B0%5D%0D%0A self.assertEqual(db(name='Simon'),%5B%5D)%0D%0A self.assertEqual(len(db),len(vals1+vals2+vals3)-1)%0D%0A%0D%0Aif __name__==%22__main__%22:%0D%0A %0D%0A suite = unittest.TestSuite()%0D%0A suite.addTest(unittest.makeSuite(TestFunctions))%0D%0A unittest.TextTestRunner().run(suite)%0D%0A
403c724ffd9dab4ebdf3a58e02406969ed7a9fcb
Create front_back.py
Python/CodingBat/front_back.py
Python/CodingBat/front_back.py
Python
0.000013
@@ -0,0 +1,144 @@ +# http://codingbat.com/prob/p153599%0A%0Adef front_back(str):%0A if len(str) %3C= 1:%0A return str%0A %0A return str%5Blen(str)-1%5D + str%5B1:-1%5D + str%5B0%5D%0A
4a48b9998961be268cbfe64726ea78f68cedce39
Create not_string.py
Python/CodingBat/not_string.py
Python/CodingBat/not_string.py
Python
0.002302
@@ -0,0 +1,133 @@ +# http://codingbat.com/prob/p189441%0A%0Adef not_string(str):%0A if str.startswith(%22not%22):%0A return str%0A else:%0A return %22not %22 + str%0A
4d41c5cd0ff73dc288d4a840780f46c53277f9e5
Fix issue #3250 (#3253)
homeassistant/components/media_player/denon.py
homeassistant/components/media_player/denon.py
""" Support for Denon Network Receivers. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.denon/ """ import logging import telnetlib import voluptuous as vol from homeassistant.components.media_player import ( PLATFORM_SCHEMA, SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PREVIOUS_TRACK, SUPPORT_TURN_OFF, SUPPORT_TURN_ON, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, MediaPlayerDevice) from homeassistant.const import ( CONF_HOST, CONF_NAME, STATE_OFF, STATE_ON, STATE_UNKNOWN) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = 'Music station' SUPPORT_DENON = SUPPORT_PAUSE | SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE | \ SUPPORT_PREVIOUS_TRACK | SUPPORT_NEXT_TRACK | \ SUPPORT_TURN_ON | SUPPORT_TURN_OFF PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, }) def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the Denon platform.""" denon = DenonDevice(config.get(CONF_NAME), config.get(CONF_HOST)) if denon.update(): add_devices([denon]) return True else: return False class DenonDevice(MediaPlayerDevice): """Representation of a Denon device.""" # pylint: disable=too-many-public-methods, abstract-method def __init__(self, name, host): """Initialize the Denon device.""" self._name = name self._host = host self._pwstate = 'PWSTANDBY' self._volume = 0 self._muted = False self._mediasource = '' @classmethod def telnet_request(cls, telnet, command): """Execute `command` and return the response.""" telnet.write(command.encode('ASCII') + b'\r') return telnet.read_until(b'\r', timeout=0.2).decode('ASCII').strip() def telnet_command(self, command): """Establish a telnet connection and sends `command`.""" telnet = telnetlib.Telnet(self._host) telnet.write(command.encode('ASCII') + b'\r') telnet.read_very_eager() # skip response telnet.close() def update(self): """Get the latest details from the device.""" try: telnet = telnetlib.Telnet(self._host) except ConnectionRefusedError: return False self._pwstate = self.telnet_request(telnet, 'PW?') # PW? sends also SISTATUS, which is not interesting telnet.read_until(b"\r", timeout=0.2) volume_str = self.telnet_request(telnet, 'MV?')[len('MV'):] self._volume = int(volume_str) / 60 self._muted = (self.telnet_request(telnet, 'MU?') == 'MUON') self._mediasource = self.telnet_request(telnet, 'SI?')[len('SI'):] telnet.close() return True @property def name(self): """Return the name of the device.""" return self._name @property def state(self): """Return the state of the device.""" if self._pwstate == 'PWSTANDBY': return STATE_OFF if self._pwstate == 'PWON': return STATE_ON return STATE_UNKNOWN @property def volume_level(self): """Volume level of the media player (0..1).""" return self._volume @property def is_volume_muted(self): """Boolean if volume is currently muted.""" return self._muted @property def media_title(self): """Current media source.""" return self._mediasource @property def supported_media_commands(self): """Flag of media commands that are supported.""" return SUPPORT_DENON def turn_off(self): """Turn off media player.""" self.telnet_command('PWSTANDBY') def volume_up(self): """Volume up media player.""" self.telnet_command('MVUP') def volume_down(self): """Volume down media player.""" self.telnet_command('MVDOWN') def set_volume_level(self, volume): """Set volume level, range 0..1.""" # 60dB max self.telnet_command('MV' + str(round(volume * 60)).zfill(2)) def mute_volume(self, mute): """Mute (true) or unmute (false) media player.""" self.telnet_command('MU' + ('ON' if mute else 'OFF')) def media_play(self): """Play media media player.""" self.telnet_command('NS9A') def media_pause(self): """Pause media player.""" self.telnet_command('NS9B') def media_next_track(self): """Send the next track command.""" self.telnet_command('NS9D') def media_previous_track(self): """Send the previous track command.""" self.telnet_command('NS9E') def turn_on(self): """Turn the media player on.""" self.telnet_command('PWON')
Python
0
@@ -2367,16 +2367,17 @@ except +( Connecti @@ -2390,16 +2390,26 @@ sedError +, OSError) :%0A
2fc62908b2f0074a0e82a120809b80cb3e009999
add __init__.py for distro
mint/distro/__init__.py
mint/distro/__init__.py
Python
0.000016
@@ -0,0 +1,64 @@ +#%0A# Copyright (c) 2005 Specifix, Inc.%0A#%0A# All rights reserved%0A#%0A
976f7b4239a1ff21d0748f43e8224017084118b7
make neuroimaging.visualization.tests into a package
lib/visualization/tests/__init__.py
lib/visualization/tests/__init__.py
Python
0.000583
@@ -0,0 +1,116 @@ +import test_visualization%0Aimport unittest%0A%0Adef suite():%0A return unittest.TestSuite(%5Btest_visualization.suite()%5D)%0A
b58d7ae6b9887b326ba485ce885deb9c03054801
Create Factorial_of_a_number.py
Python3-5/Factorial_of_a_number.py
Python3-5/Factorial_of_a_number.py
Python
0.000016
@@ -0,0 +1,477 @@ +#Write a program which can compute the factorial of a given numbers.%0A#We will first define a function%0Adef fact(x): #Define a function named 'fact()'%0A if x == 0: #We directly return 1 if input number is 0.%0A return 1 ;%0A return x * fact(x - 1); # We return 'number * fact(number - 1)'. We are calling the same function again in its own function, This is called Recursive Function%0A%0Ax=int(input(%22Please enter a number:%22));%0Aprint fact(x);%0A
a9f6caf863b5c3156c3200d33a6cdc29f0c2ad23
Add new py-hacking package (#14027)
var/spack/repos/builtin/packages/py-hacking/package.py
var/spack/repos/builtin/packages/py-hacking/package.py
Python
0
@@ -0,0 +1,622 @@ +# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other%0A# Spack Project Developers. See the top-level COPYRIGHT file for details.%0A#%0A# SPDX-License-Identifier: (Apache-2.0 OR MIT)%0A%0Afrom spack import *%0A%0A%0Aclass PyHacking(PythonPackage):%0A %22%22%22OpenStack Hacking Guideline Enforcement.%22%22%22%0A%0A homepage = %22https://docs.openstack.org/hacking/latest/%22%0A url = %22https://pypi.io/packages/source/h/hacking/hacking-1.1.0.tar.gz%22%0A%0A import_modules = %5B'hacking'%5D%0A%0A version('1.1.0', sha256='23a306f3a1070a4469a603886ba709780f02ae7e0f1fc7061e5c6fb203828fee')%0A%0A depends_on('py-setuptools', type='build')%0A
e6641065af9078e2e50e99f657aa605d837d3976
add new package (#20112)
var/spack/repos/builtin/packages/py-vcstool/package.py
var/spack/repos/builtin/packages/py-vcstool/package.py
Python
0
@@ -0,0 +1,778 @@ +# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other%0A# Spack Project Developers. See the top-level COPYRIGHT file for details.%0A#%0A# SPDX-License-Identifier: (Apache-2.0 OR MIT)%0A%0A%0Aclass PyVcstool(PythonPackage):%0A %22%22%22vcstool enables batch commands on multiple different vcs repositories.%0A%0A Currently it supports git, hg, svn and bzr.%22%22%22%0A%0A homepage = %22https://github.com/dirk-thomas/vcstool%22%0A url = %22https://pypi.io/packages/source/v/vcstool/vcstool-0.2.15.tar.gz%22%0A%0A version('0.2.15', sha256='b1fce6fcef7b117b245a72dc8658a128635749d01dc7e9d1316490f89f9c2fde')%0A%0A depends_on('py-pyyaml', type=('build', 'run'))%0A depends_on('py-setuptools', type=('build', 'run'))%0A depends_on('py-argparse', when='%5Epython@:2.6', type=('build', 'run'))%0A
701f6a06b8405620905a67b47c5702c100a1447a
Check to make sure the input file is sorted
scripts/check_sorted.py
scripts/check_sorted.py
Python
0.000001
@@ -0,0 +1,722 @@ +import sys%0A%0Aprev_val = 0%0Aprev_val2 = 0%0Acounter = 0%0A%0Afor line in sys.stdin:%0A parts = line.split()%0A curr_val = int(parts%5B0%5D)%0A curr_val2 = int(parts%5B1%5D)%0A%0A val1 = int(parts%5B0%5D)%0A val2 = int(parts%5B1%5D)%0A%0A if val1 %3E val2:%0A print %3E%3Esys.stderr, %22Not triangular:%22, counter%0A sys.exit(1)%0A%0A if curr_val %3C prev_val:%0A print %3E%3Esys.stderr, %22Not sorted, line:%22, counter%0A sys.exit(1)%0A elif curr_val == prev_val:%0A if (curr_val2 %3C prev_val2):%0A print %3E%3Esys.stderr, %22Not sorted, line:%22, counter%0A sys.exit(1)%0A %0A prev_val = curr_val%0A prev_val2 = curr_val2%0A counter += 1%0A%0A if counter %25 1000000 == 0:%0A print %22counter:%22, counter, prev_val, curr_val%0A
0aa5466be1ba678f0428e825def010a5007059c7
Modify tests to show Unicode handling regression
scss/tests/test_misc.py
scss/tests/test_misc.py
# -*- encoding: utf-8 -*- """Tests for miscellaneous features that should maybe be broken out into their own files, maybe. """ from scss import Scss def test_super_selector(): compiler = Scss(scss_opts=dict(style='expanded')) input = """\ foo, bar { a: b; } baz { c: d; } """ expected = """\ super foo, super bar { a: b; } super baz { c: d; } """ output = compiler.compile(input, super_selector='super') assert expected == output def test_debug_info(): # nb: debug info doesn't work if the source isn't a file compiler = Scss(scss_opts=dict(style='expanded', debug_info=True)) compiler._scss_files = {} compiler._scss_files['input.css'] = """\ div { color: green; } table { color: red; } """ expected = """\ @media -sass-debug-info{filename{font-family:file\:\/\/input\.css}line{font-family:\\000031}} div { color: green; } @media -sass-debug-info{filename{font-family:file\:\/\/input\.css}line{font-family:\\000034}} table { color: red; } """ output = compiler.compile() assert expected == output def test_live_errors(): compiler = Scss(live_errors=True) output = compiler.compile("""$foo: unitless(one);""") assert "body:before" in output assert "TypeError: Expected" in output def test_extend_across_files(): compiler = Scss(scss_opts=dict(compress=0)) compiler._scss_files = {} compiler._scss_files['first.css'] = ''' @option style:legacy, short_colors:yes, reverse_colors:yes; .specialClass extends .basicClass { padding: 10px; font-size: 14px; } ''' compiler._scss_files['second.css'] = ''' @option style:legacy, short_colors:yes, reverse_colors:yes; .basicClass { padding: 20px; background-color: #FF0000; } ''' actual = compiler.compile() expected = """\ .basicClass, .specialClass { padding: 20px; background-color: #FF0000; } .specialClass { padding: 10px; font-size: 14px; } """ assert expected == actual def test_unicode_files(): compiler = Scss(scss_opts=dict(style='expanded')) unicode_input = u"""q { quotes: "“" "”" "‘" "’"; } """ output = compiler.compile(unicode_input) assert output == unicode_input
Python
0
@@ -2144,16 +2144,32 @@ %E2%80%98%22 %22%E2%80%99%22;%0A + content: %22%E2%80%A2%22;%0A %7D%0A%22%22%22%0A
b2532cfeb3541a64143ded6d86b635e2c9049080
Clean up some pylint warnings
bindings/python-examples/example.py
bindings/python-examples/example.py
#! /usr/bin/env python # -*- coding: utf8 -*- # # Link Grammar example usage # import locale from linkgrammar import Sentence, ParseOptions, Dictionary # from linkgrammar import _clinkgrammar as clg locale.setlocale(locale.LC_ALL, "en_US.UTF-8") po = ParseOptions() def desc(linkage): print linkage.diagram() print 'Postscript:' print linkage.postscript() print '---' # English is the default language sent = Sentence("This is a test.", Dictionary(), po) linkages = sent.parse() print "English: found ", sent.num_valid_linkages(), "linkages" for linkage in linkages: desc(linkage) # Russian sent = Sentence("это большой тест.", Dictionary('ru'), po) linkages = sent.parse() print "Russian: found ", sent.num_valid_linkages(), "linkages" for linkage in linkages: desc(linkage) # Turkish sent = Sentence("çok şişman adam geldi", Dictionary('tr'), po) linkages = sent.parse() print "Turkish: found ", sent.num_valid_linkages(), "linkages" for linkage in linkages: desc(linkage)
Python
0.000001
@@ -69,17 +69,16 @@ le usage - %0A#%0Aimpor @@ -274,22 +274,18 @@ f desc(l -inkage +kg ):%0A p @@ -290,22 +290,18 @@ print l -inkage +kg .diagram @@ -338,22 +338,18 @@ print l -inkage +kg .postscr
39473b1aa0d8c54b0fb43b5e97545596ed087d59
Create set-intersection-size-at-least-two.py
Python/set-intersection-size-at-least-two.py
Python/set-intersection-size-at-least-two.py
Python
0.000562
@@ -0,0 +1,1561 @@ +# Time: O(nlogn)%0A# Space: O(n)%0A%0A# An integer interval %5Ba, b%5D (for integers a %3C b) is a set of all consecutive integers from a to b,%0A# including a and b.%0A#%0A# Find the minimum size of a set S such that for every integer interval A in intervals,%0A# the intersection of S with A has size at least 2.%0A#%0A# Example 1:%0A# Input: intervals = %5B%5B1, 3%5D, %5B1, 4%5D, %5B2, 5%5D, %5B3, 5%5D%5D%0A# Output: 3%0A# Explanation:%0A# Consider the set S = %7B2, 3, 4%7D. For each interval, there are at least 2 elements from S in the interval.%0A# Also, there isn't a smaller size set that fulfills the above condition.%0A# Thus, we output the size of this set, which is 3.%0A#%0A# Example 2:%0A# Input: intervals = %5B%5B1, 2%5D, %5B2, 3%5D, %5B2, 4%5D, %5B4, 5%5D%5D%0A# Output: 5%0A# Explanation:%0A# An example of a minimum sized set is %7B1, 2, 3, 4, 5%7D.%0A#%0A# Note:%0A# intervals will have length in range %5B1, 3000%5D.%0A# intervals%5Bi%5D will have length 2, representing some integer interval.%0A# intervals%5Bi%5D%5Bj%5D will be an integer in %5B0, 10%5E8%5D.%0A%0A# greedy solution%0Aclass Solution(object):%0A def intersectionSizeTwo(self, intervals):%0A %22%22%22%0A :type intervals: List%5BList%5Bint%5D%5D%0A :rtype: int%0A %22%22%22%0A intervals.sort(key = lambda(s, e): (s, -e))%0A cnts = %5B2%5D * len(intervals)%0A result = 0%0A while intervals:%0A (start, _), cnt = intervals.pop(), cnts.pop()%0A for s in xrange(start, start+cnt):%0A for i in xrange(len(intervals)):%0A if cnts%5Bi%5D and s %3C= intervals%5Bi%5D%5B1%5D:%0A cnts%5Bi%5D -= 1%0A result += cnt%0A return result%0A
208fed6d1e162dd0fcfa10c2b79d0d35ea813478
Create intermediate-171.py
Challenge-171/Intermediate/intermediate-171.py
Challenge-171/Intermediate/intermediate-171.py
Python
0.000318
@@ -0,0 +1,1669 @@ +#Challenge 171 Intermediate%0A%0Ahexvalue = 'FF 81 BD A5 A5 BD 81 FF'.split(' ')%0Abinary = %5Bbin(int(line, 16))%5B2:%5D.zfill(8) for line in hexvalue%5D #Convert it to a list of binary lines%0Aimage = %5Bpixel.replace('1', '*').replace('0', ' ') for pixel in binary%5D #Convert it to a list of lines%0Aprint 'ORIGINAL IMAGE'%0Aprint '%5Cn'.join(image)%0A%0A%0Adef zoom(image, factor):%0A%09if factor%251==0 and factor%3E=1:%0A%09%09return '%5Cn'.join(%5B''.join(%5Bstr(pixel)*factor for pixel in line%5D) for line in image for i in range(factor)%5D)%0A%09else:%0A%09%09a = int(1/factor)%0A%09%09return '%5Cn'.join(%5Bline%5B::a%5D for line in image%5B::a%5D%5D)%0A%0Adef invert(image):%0A%09return '%5Cn'.join(%5Bline.replace('*', '#').replace(' ', '*').replace('#', ' ') for line in image%5D)%0A%0A%0Adef rotate_clockwise(image):%0A%09image = %5Blist(line) for line in image%5D #We create a pixel matrix%0A%09a = len(image)%0A%09new = %5B%5B%5B%5D for _ in range(a)%5D for _ in range(a)%5D%0A%09for x in range(a):%0A%09%09for y in range(a):%0A%09%09%09new%5By%5D%5Ba-1-x%5D = image%5Bx%5D%5By%5D%0A%09return '%5Cn'.join(%5B''.join(line) for line in new%5D)%0A%0Adef rotate_counter_clockwise(image):%0A%09image = %5Blist(line) for line in image%5D #We create a pixel matrix%0A%09a = len(image)%0A%09new = %5B%5B%5B%5D for _ in range(a)%5D for _ in range(a)%5D%0A%09for x in range(a):%0A%09%09for y in range(a):%0A%09%09%09new%5Ba-1-y%5D%5Bx%5D = image%5Bx%5D%5By%5D%0A%09return '%5Cn'.join(%5B''.join(line) for line in new%5D)%0A%0Adef prepare_for_next(image):%0A%09return image.split('%5Cn')%0A%0A#Now to the actual Challenge:%0Azoomed = zoom(image, 2)%0Aimage = prepare_for_next(zoomed)%0Arotated = rotate_clockwise(image)%0Aimage = prepare_for_next(rotated)%0Azoomed = zoom(image,2)%0Aimage = prepare_for_next(zoomed)%0Ainverted = invert(image)%0A%0Aprint inverted%0A%0A%0Aimage = prepare_for_next(inverted)%0Azoomed_out = zoom(image, 0.5)%0A%0Aprint zoomed_out%0A
752b5b43aa807e5431615219d40eafd38cacadeb
Increase length of report name on Report model
onmydesk/models.py
onmydesk/models.py
""" Required models to handle and store generated reports. """ from django.db import models from django.conf import settings from onmydesk.utils import my_import ONMYDESK_FILE_HANDLER = getattr(settings, 'ONMYDESK_FILE_HANDLER', None) def output_file_handler(filepath): """ Returns the output filepath (handled or not by an external function). This function tries to find a function handler in `settings.ONMYDESK_FILE_HANDLER`. It must receive a filepath and returns a new filepath (or url, e.g.) to be stored in the report register. It's useful to handle the report results (move to other dirs ou to cloud). :param str filepath: File path to output generated by report. :returns: File path to output (processed or not by a external handler) :rtype: str """ function_handler = ONMYDESK_FILE_HANDLER if not function_handler: return filepath handler = my_import(function_handler) return handler(filepath) class Report(models.Model): """Report model to store generated reports""" report = models.CharField(max_length=30) results = models.CharField(max_length=255, null=True, blank=True) insert_date = models.DateTimeField('Creation Date', auto_now_add=True) update_date = models.DateTimeField('Update Date', auto_now=True) created_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) def process(self, report_params=None): """Process this report. After processing the outputs will be stored at `results`. To access output results is recommended to use :func:`results_as_list`. :param dict report_params: Dictionary with params to be used for process report. """ report_class = my_import(self.report) report = report_class(params=report_params) report.process() results = [] for filepath in report.output_filepaths: results.append(output_file_handler(filepath)) self.results = ';'.join(results) @property def results_as_list(self): """Returns a list of output results stored in this model :returns: List of results :rtype: list""" if not self.results: return [] return self.results.split(';')
Python
0.000001
@@ -1091,10 +1091,11 @@ gth= -30 +255 )%0A
bdf5cfb2a7b716d897dabd62e591caad8144a029
Add election funding parsing script
utils/populate-funding.py
utils/populate-funding.py
Python
0
@@ -0,0 +1,2139 @@ +#!/usr/bin/python%0A%0Aimport os%0Aimport sys%0Aimport csv%0Afrom optparse import OptionParser%0A%0Afrom django.core.management import setup_environ%0A%0Amy_path = os.path.abspath(os.path.dirname(__file__))%0Aapp_path = os.path.normpath(my_path + '/..')%0Aapp_base = app_path + '/'%0A%0A# We need a path like '%3Capp_path%3E/utils:%3Capp_path%3E:%3Capp_path%3E/..'%0A# The first one is inserted by python itself. The order is important to%0A# guarantee that we'll import the proper app specific module in case there%0A# is also a generic (non-app-specific) module with the same name later in%0A# the path.%0Asys.path.insert(1, app_path)%0Asys.path.insert(2, os.path.normpath(app_path + '/..'))%0A%0Afrom kamu import settings%0Asetup_environ(settings)%0Afrom django.db import connection, transaction%0Afrom django import db%0A%0Afrom votes.models import Member, TermMember, Term, MemberStats%0A%0Aparser = OptionParser()%0Aparser.add_option('--input', action='store', type='string', dest='input',%0A help='input file')%0A(opts, args) = parser.parse_args()%0A%0Aif not opts.input:%0A exit(1)%0A%0AMEMBER_NAME_TRANSFORMS = %7B%0A 'Korhonen Timo': 'Korhonen Timo V.',%0A 'Ollila Heikki': 'Ollila Heikki A.',%0A 'Saarela Tanja': 'Karpela Tanja',%0A 'Kumpula Miapetra': 'Kumpula-Natri Miapetra',%0A 'Forsius-Harkimo Merikukka': 'Forsius Merikukka',%0A%7D%0A%0ATERM=%222007-2010%22%0Aterm = Term.objects.get(name=TERM)%0A%0Af = open(opts.input, 'r')%0Areader = csv.reader(f, delimiter=',', quotechar='%22')%0Afor row in reader:%0A first_name = row%5B1%5D.strip()%0A last_name = row%5B0%5D.strip()%0A budget = row%5B4%5D.strip().replace(',', '')%0A name = %22%25s %25s%22 %25 (last_name, first_name)%0A if name in MEMBER_NAME_TRANSFORMS:%0A name = MEMBER_NAME_TRANSFORMS%5Bname%5D%0A print %22%25-20s %25-20s %2510s%22 %25 (first_name, last_name, budget)%0A try:%0A member = Member.objects.get(name=name)%0A tm = TermMember.objects.get(member=member, term=term)%0A except Member.DoesNotExist:%0A continue%0A except TermMember.DoesNotExist:%0A continue%0A ms = MemberStats.objects.get(begin=term.begin, end=term.end, member=member)%0A tm.election_budget = budget%0A tm.save()%0A ms.election_budget = budget%0A ms.save()%0A%0Af.close()%0A%0A
30b53c525b2319cc664d26d083c84bba1b63ff7c
add unit test for s3 cache
mapproxy/test/unit/test_cache_s3.py
mapproxy/test/unit/test_cache_s3.py
Python
0
@@ -0,0 +1,1421 @@ +# This file is part of the MapProxy project.%0A# Copyright (C) 2011 Omniscale %3Chttp://omniscale.de%3E%0A#%0A# Licensed under the Apache License, Version 2.0 (the %22License%22);%0A# you may not use this file except in compliance with the License.%0A# You may obtain a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS,%0A# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A# See the License for the specific language governing permissions and%0A# limitations under the License.%0A%0Afrom __future__ import with_statement%0A%0Aimport os%0Aimport random%0A%0Afrom nose.plugins.skip import SkipTest%0A%0Afrom mapproxy.cache.s3 import S3Cache%0Afrom mapproxy.test.unit.test_cache_tile import TileCacheTestBase%0A%0A%0Aclass TestS3Cache(TileCacheTestBase):%0A always_loads_metadata = True%0A%0A def setup(self):%0A if not os.environ.get('MAPPROXY_TEST_S3'):%0A raise SkipTest()%0A%0A bucket_name = os.environ%5B'MAPPROXY_TEST_S3'%5D%0A dir_name = 'mapproxy/test_%25d' %25 random.randint(0, 100000)%0A%0A TileCacheTestBase.setup(self)%0A%0A self.cache = S3Cache(dir_name, file_ext='png', directory_layout='tms',%0A lock_timeout=10, bucket_name=bucket_name, profile_name=None)%0A%0A def teardown(self):%0A TileCacheTestBase.teardown(self)%0A
1d8f57ff9c6e2c9a38d1634fc14449ac401ea570
document valid restful PUT status code
pyethereum/apiserver.py
pyethereum/apiserver.py
import logging import threading import json import bottle from pyethereum.chainmanager import chain_manager from pyethereum.peermanager import peer_manager import pyethereum.dispatch as dispatch from pyethereum.blocks import block_structure import pyethereum.signals as signals from pyethereum.transactions import Transaction logger = logging.getLogger(__name__) base_url = '/api/v0alpha' app = bottle.Bottle() app.config['autojson'] = False app.install(bottle.JSONPlugin(json_dumps=lambda s: json.dumps(s, sort_keys=True))) class ApiServer(threading.Thread): def __init__(self): super(ApiServer, self).__init__() self.daemon = True self.listen_host = '127.0.0.1' self.port = 30203 def configure(self, config): self.listen_host = config.get('api', 'listen_host') self.port = config.getint('api', 'listen_port') def run(self): middleware = CorsMiddleware(app) bottle.run(middleware, server='waitress', host=self.listen_host, port=self.port) # ###### create server ###### api_server = ApiServer() @dispatch.receiver(signals.config_ready) def config_api_server(sender, config, **kwargs): api_server.configure(config) # #######cors############## class CorsMiddleware: HEADERS = [ ('Access-Control-Allow-Origin', '*'), ('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'), ('Access-Control-Allow-Headers', 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token') ] def __init__(self, app): self.app = app def __call__(self, environ, start_response): if environ["REQUEST_METHOD"] == "OPTIONS": start_response('200 OK', CorsMiddleware.HEADERS + [('Content-Length', "0")]) return "" else: def my_start_response(status, headers, exc_info=None): headers.extend(CorsMiddleware.HEADERS) return start_response(status, headers, exc_info) return self.app(environ, my_start_response) # ######### Utilities ######## def load_json_req(): json_body = bottle.request.json if not json_body: json_body = json.load(bottle.request.body) return json_body # ######## Blocks ############ def make_blocks_response(blocks): return dict(blocks = [block.to_dict() for block in blocks]) @app.get(base_url + '/blocks/') def blocks(): logger.debug('blocks/') return make_blocks_response(chain_manager.get_chain(start='', count=20)) @app.get(base_url + '/blocks/<blockhash>') def block(blockhash=None): logger.debug('blocks/%s', blockhash) blockhash = blockhash.decode('hex') if blockhash in chain_manager: return make_blocks_response([chain_manager.get(blockhash)]) else: return bottle.abort(404, 'No block with id %s' % blockhash) # ######## Transactions ############ @app.put(base_url + '/transactions/') def transactions(): # request.json FIXME / post json encoded data? i.e. the representation of # a tx hex_data = bottle.request.body.read() logger.debug('PUT transactions/ %s', hex_data) tx = Transaction.hex_deserialize(hex_data) signals.local_transaction_received.send(sender=None, transaction=tx) return '' #return bottle.redirect(base_url + '/transactions/' + tx.hex_hash()) # ######## Accounts ############ @app.get(base_url + '/accounts/') def accounts(): logger.debug('accounts') @app.get(base_url + '/accounts/<address>') def account(address=None): logger.debug('accounts/%s', address) data = chain_manager.head.account_to_dict(address) logger.debug(data) return data # ######## Peers ################### def make_peers_response(peers): objs = [dict(ip=ip, port=port, node_id=node_id.encode('hex')) for (ip, port, node_id) in peers] return dict(peers=objs) @app.get(base_url + '/peers/connected') def connected_peers(): return make_peers_response(peer_manager.get_connected_peer_addresses()) @app.get(base_url + '/peers/known') def known_peers(): return make_peers_response(peer_manager.get_known_peer_addresses())
Python
0
@@ -3355,16 +3355,789 @@ hash())%0A + %22%22%22%0A%0A HTTP status code 200 OK for a successful PUT of an update to an existing resource. No response body needed. (Per Section 9.6, 204 No Content is even more appropriate.)%0A HTTP status code 201 Created for a successful PUT of a new resource, with URIs and metadata of the new resource echoed in the response body. (RFC 2616 Section 10.2.2)%0A HTTP status code 409 Conflict for a PUT that is unsuccessful due to a 3rd-party modification, with a list of differences between the attempted update and the current resource in the response body. (RFC 2616 Section 10.4.10)%0A HTTP status code 400 Bad Request for an unsuccessful PUT, with natural-language text (such as English) in the response body that explains why the PUT failed. (RFC 2616 Section 10.4)%0A %22%22%22 %0A%0A# ####
a332a057292e701e197b5ac2250e608ef953d631
Add example config
pyfsw/config.example.py
pyfsw/config.example.py
Python
0.000001
@@ -0,0 +1,1102 @@ +# Database URI Scheme (Refer to the SQLAlchemy documentation for variations)%0ADB_URI = ''%0A%0A# Secret Key%0ASECRET_KEY = 'pyfsw'%0A%0A# Network Host%0ANET_HOST = '127.0.0.1'%0A%0A# Network Port%0ANET_PORT = 5000%0A%0A# Debug Mode%0ADEBUG = False%0A%0A# Debug Profiler%0ADEBUG_PROFILER = False%0A%0A# Date Format%0ADATE_FORMAT = '%25m/%25d/%25y %25I:%25M %25p'%0A%0A# Cache Time (Seconds)%0ACACHE_TIME = 0%0A%0A# Guild Logo Upload Path%0AUPLOAD_PATH = ''%0A%0A# Font Path (Captcha)%0AFONT_PATH = ''%0A%0A# Server Name%0ASERVER_NAME = ''%0A%0A# Town Names%0ATOWNS = %7B%0A%090: 'All',%0A%091: 'Some Town'%0A%7D%0A%0A# House Price (per SQM)%0AHOUSE_PRICE = 1000%0A%0A# Vocation Names%0AVOCATIONS = %7B%0A%090: 'No Vocation',%0A%091: 'Sorcerer',%0A%092: 'Druid',%0A%093: 'Paladin',%0A%094: 'Knight',%0A%095: 'Master Sorcerer',%0A%096: 'Elder Druid',%0A%097: 'Royal Paladin',%0A%098: 'Elite Knight'%0A%7D%0A%0A# Gender Names%0AGENDERS = %7B%0A%090: 'Female',%0A%091: 'Male'%0A%7D%0A%0ANEW_CHARACTER = %7B%0A%09'genders': %5B0, 1%5D,%0A%09'vocations': %5B5, 6, 7, 8%5D,%0A%09'towns': %5B1, 2%5D,%0A%09'outfit': %5B0, 0, 0, 0%5D%0A%7D%0A%0A# Quests List%0AQUESTS = %5B%0A%09%7B'name': 'Example Quest', 'key': 12101, 'value': 1%7D,%0A%5D%0A%0A# Achievements List%0AACHIEVEMENTS = %5B%0A%09%7B'name': 'Example Achievement', 'key': 12101, 'value': 1%7D%0A%5D%0A
9bed52b93061fea7381492ffe0ce55c6929eab78
Add tests.py to app skeleton.
lib/rapidsms/skeleton/app/tests.py
lib/rapidsms/skeleton/app/tests.py
Python
0
@@ -0,0 +1,543 @@ +from rapidsms.tests.scripted import TestScript%0Afrom app import App%0A%0Aclass TestApp (TestScript):%0A apps = (App,)%0A%0A # define your test scripts here.%0A # e.g.:%0A #%0A # testRegister = %22%22%22%0A # 8005551212 %3E register as someuser%0A # 8005551212 %3C Registered new user 'someuser' for 8005551212!%0A # 8005551212 %3E tell anotheruser what's up??%0A # 8005550000 %3C someuser said %22what's up??%22%0A # %22%22%22%0A #%0A # You can also do normal unittest.TestCase methods:%0A #%0A # def testMyModel (self):%0A # self.assertEquals(...)%0A
4c78124a434d4f953d5811ee2708eaf051bd591e
Create setup_data_libraries.py
setup_data_libraries.py
setup_data_libraries.py
Python
0.000004
@@ -0,0 +1,2800 @@ +#!/usr/bin/env python%0A%0Aimport argparse%0Aimport logging as log%0Aimport sys%0Aimport time%0A%0Aimport yaml%0Afrom bioblend import galaxy%0A%0A%0Adef setup_data_libraries(gi, data):%0A %22%22%22%0A Load files into a Galaxy data library.%0A By default all test-data tools from all installed tools%0A will be linked into a data library.%0A %22%22%22%0A%0A log.info(%22Importing data libraries.%22)%0A jc = galaxy.jobs.JobsClient(gi)%0A%0A folders = dict()%0A%0A libraries = yaml.load(data)%0A for lib in libraries%5B'libraries'%5D:%0A folders%5Blib%5B'name'%5D%5D = lib%5B'files'%5D%0A%0A if folders:%0A log.info(%22Create 'Test Data' library.%22)%0A lib = gi.libraries.create_library('Training Data', 'Data pulled from online archives.')%0A lib_id = lib%5B'id'%5D%0A%0A for fname, urls in folders.items():%0A log.info(%22Creating folder: %25s%22 %25 fname)%0A folder = gi.libraries.create_folder(lib_id, fname)%0A for url in urls:%0A gi.libraries.upload_file_from_url(%0A lib_id,%0A url%5B'url'%5D,%0A folder_id=folder%5B0%5D%5B'id'%5D,%0A file_type=url%5B'file_type'%5D%0A )%0A%0A no_break = True%0A while True:%0A no_break = False%0A for job in jc.get_jobs():%0A if job%5B'state'%5D != 'ok':%0A no_break = True%0A if not no_break:%0A break%0A time.sleep(3)%0A%0A time.sleep(20)%0A log.info(%22Finished importing test data.%22)%0A%0A%0Adef main():%0A parser = argparse.ArgumentParser(%0A description='Populate the Galaxy data library with test data.'%0A )%0A parser.add_argument(%22-v%22, %22--verbose%22, help=%22Increase output verbosity.%22,%0A action=%22store_true%22)%0A parser.add_argument('-i', '--infile', type=argparse.FileType('r'))%0A parser.add_argument(%22-g%22, %22--galaxy%22,%0A help=%22Target Galaxy instance URL/IP address.%22)%0A parser.add_argument(%22-u%22, %22--user%22,%0A help=%22Galaxy user name%22)%0A parser.add_argument(%22-p%22, %22--password%22,%0A help=%22Password for the Galaxy user%22)%0A parser.add_argument(%22-a%22, %22--api_key%22,%0A dest=%22api_key%22,%0A help=%22Galaxy admin user API key (required if not defined in the tools list file)%22)%0A%0A args = parser.parse_args()%0A%0A if args.user and args.password:%0A gi = galaxy.GalaxyInstance(url=args.galaxy, email=args.user, password=args.password)%0A elif args.api_key:%0A gi = galaxy.GalaxyInstance(url=args.galaxy, key=args.api_key)%0A else:%0A sys.exit('Please specify either a valid Galaxy username/password or an API key.')%0A%0A if args.verbose:%0A log.basicConfig(level=log.DEBUG)%0A%0A setup_data_libraries(gi, args.infile)%0A%0A%0Aif __name__ == '__main__':%0A main()%0A
d78872da09bc67435a2662cce0b253ab149b2bad
Create 03.py
02.5/03.py
02.5/03.py
Python
0
@@ -0,0 +1,2300 @@ +# By Websten from forums%0A#%0A# Given your birthday and the current date, calculate your age in days. %0A# Compensate for leap days. %0A# Assume that the birthday and current date are correct dates (and no time travel). %0A# Simply put, if you were born 1 Jan 2012 and todays date is 2 Jan 2012 %0A# you are 1 day old.%0A#%0A# Hint%0A# A whole year is 365 days, 366 if a leap year. %0A%0Adef nextDay(year, month, day):%0A %22%22%22Simple version: assume every month has 30 days%22%22%22%0A if day %3C 30:%0A return year, month, day + 1%0A else:%0A if month == 12:%0A return year + 1, 1, 1%0A else:%0A return year, month + 1, 1%0A %0Adef dateIsAfter(year1, month1, day1, year2, month2, day2):%0A %22%22%22Returns True if year1-month1-day1 is after year2-month2-day2. Otherwise, returns False.%22%22%22%0A if year1 %3E year2:%0A return True%0A if year1 == year2:%0A if month1 %3E month2:%0A return True%0A if month1 == month2:%0A return day1 %3E day2%0A return False %0A%0Adef daysBetweenDates(year1, month1, day1, year2, month2, day2):%0A %22%22%22Returns the number of days between year1/month1/day1%0A and year2/month2/day2. Assumes inputs are valid dates%0A in Gregorian calendar.%22%22%22%0A # program defensively! Add an assertion if the input is not valid!%0A assert(not dateIsAfter(year1, month1, day1, year2, month2, day2))%0A days = 0%0A while dateIsAfter(year2, month2, day2, year1, month1, day1):%0A days += 1%0A (year1, month1, day1) = nextDay(year1, month1, day1)%0A return days%0A%0Adef test():%0A test_cases = %5B((2012,9,30,2012,10,30),30), %0A ((2012,1,1,2013,1,1),360),%0A ((2012,9,1,2012,9,4),3),%0A ((2013,1,1,1999,12,31), %22AssertionError%22)%5D%0A %0A for (args, answer) in test_cases:%0A try:%0A result = daysBetweenDates(*args)%0A if result != answer:%0A print %22Test with data:%22, args, %22failed%22%0A else:%0A print %22Test case passed!%22%0A except AssertionError:%0A if answer == %22AssertionError%22:%0A print %22Nice job! Test case %7B0%7D correctly raises AssertionError!%5Cn%22.format(args)%0A else:%0A print %22Check your work! Test case %7B0%7D should not raise AssertionError!%5Cn%22.format(args) %0Atest()%0A
d2b3996edc1af3f7f491354a762b8bd34c8345a1
Create remove_string_spaces.py
remove_string_spaces.py
remove_string_spaces.py
Python
0.00025
@@ -0,0 +1,142 @@ +#Kunal Gautam%0A#Codewars : @Kunalpod%0A#Problem name: Remove String Spaces%0A#Problem level: 8 kyu%0A%0Adef no_space(x):%0A return ''.join(x.split())%0A
8ea44bc5daa099ccc2e48c606f38a424235b9f3d
Create a.py
abc001/a.py
abc001/a.py
Python
0.000489
@@ -0,0 +1,52 @@ +h1 = int(input())%0Ah2 = int(input())%0A%0Aprint(h1 - h2)%0A
730b11a45696b4d4b8b0e56c0028ec6eeca7da4f
Create a.py
agc017/a.py
agc017/a.py
Python
0.000489
@@ -0,0 +1,745 @@ +import math%0A %0A %0Adef comb(n, r):%0A return math.factorial(n) / math.factorial(r) / math.factorial(n - r)%0A %0A %0Adef main():%0A n, p = map(int, input().split())%0A a = tuple(map(lambda x: int(x) %25 2, input().split()))%0A %0A if n == 1 and a%5B0%5D %25 2 != p:%0A print(0)%0A return 0%0A %0A t = len(tuple(filter(lambda x: x == 1, a)))%0A f = n - t%0A %0A f_comb = 0%0A for j in range(f + 1):%0A f_comb += comb(f, j)%0A %0A t_comb = 0%0A if p == 0:%0A for i in range(t + 1):%0A if i %25 2 == 0:%0A t_comb += comb(t, i)%0A else:%0A for i in range(t + 1):%0A if i %25 2 == 1:%0A t_comb += comb(t, i)%0A %0A print(int(t_comb * f_comb))%0A %0A return 0%0A %0A %0Aif __name__ == '__main__':%0A main()%0A
15b1779475c7744a85e948c419de34be038fba94
Add lc0314_binary_tree_vertical_order_traversal.py
lc0314_binary_tree_vertical_order_traversal.py
lc0314_binary_tree_vertical_order_traversal.py
Python
0.000098
@@ -0,0 +1,1259 @@ +%22%22%22Leetcode 314. Binary Tree Vertical Order Traversal%0AMedium%0A%0AURL: https://leetcode.com/problems/binary-tree-vertical-order-traversal/%0A%0AGiven a binary tree, return the vertical order traversal of its nodes' values.%0A(ie, from top to bottom, column by column).%0A%0AIf two nodes are in the same row and column, the order should be from left to%0Aright.%0A%0AExamples 1:%0AInput: %5B3,9,20,null,null,15,7%5D%0A 3%0A /%5C%0A / %5C%0A 9 20%0A /%5C%0A / %5C%0A 15 7%0AOutput:%0A%5B%0A %5B9%5D,%0A %5B3,15%5D,%0A %5B20%5D,%0A %5B7%5D%0A%5D%0A%0AExamples 2:%0AInput: %5B3,9,8,4,0,1,7%5D%0A%0A 3%0A /%5C%0A / %5C%0A 9 8%0A /%5C /%5C%0A / %5C/ %5C%0A 4 01 7%0AOutput:%0A%5B%0A %5B4%5D,%0A %5B9%5D,%0A %5B3,0,1%5D,%0A %5B8%5D,%0A %5B7%5D%0A%5D%0A%0AExamples 3:%0AInput: %5B3,9,8,4,0,1,7,null,null,null,2,5%5D (0's right child is 2 and 1's left%0Achild is 5)%0A 3%0A /%5C%0A / %5C%0A 9 8%0A /%5C /%5C%0A / %5C/ %5C%0A 4 01 7%0A /%5C%0A / %5C%0A 5 2%0AOutput:%0A%5B%0A %5B4%5D,%0A %5B9,5%5D,%0A %5B3,0,1%5D,%0A %5B8,2%5D,%0A %5B7%5D%0A%5D%0A%22%22%22%0A%0A# Definition for a binary tree node.%0Aclass TreeNode(object):%0A def __init__(self, val):%0A self.val = val%0A self.left = None%0A self.right = None%0A%0A%0Aclass Solution(object):%0A def verticalOrder(self, root):%0A %22%22%22%0A :type root: TreeNode%0A :rtype: List%5BList%5Bint%5D%5D%0A %22%22%22%0A pass%0A%0A%0Adef main():%0A pass%0A%0A%0Aif __name__ == '__main__':%0A main()%0A
934e907180645e3dc618ff5c75a4982656310673
Add the arrayfns compatibility library -- not finished.
numpy/oldnumeric/arrayfns.py
numpy/oldnumeric/arrayfns.py
Python
0
@@ -0,0 +1,2055 @@ +%22%22%22Backward compatible with arrayfns from Numeric%0A%22%22%22%0A%0A__all__ = %5B'array_set', 'construct3', 'digitize', 'error', 'find_mask', 'histogram', 'index_sort',%0A 'interp', 'nz', 'reverse', 'span', 'to_corners', 'zmin_zmax'%5D%0A%0Aimport numpy as nx%0Afrom numpy import asarray%0A%0Aclass error(Exception):%0A pass%0A%0Adef array_set(vals1, indices, vals2):%0A indices = asarray(indices)%0A if indices.ndim != 1:%0A raise ValueError, %22index array must be 1-d%22%0A if not isinstance(vals1, ndarray):%0A raise TypeError, %22vals1 must be an ndarray%22%0A vals1 = asarray(vals1)%0A vals2 = asarray(vals2)%0A if vals1.ndim != vals2.ndim or vals1.ndim %3C 1:%0A raise error, %22vals1 and vals2 must have same number of dimensions (%3E=1)%22%0A vals1%5Bindices%5D = vals2%0A%0Adef construct3(mask, itype):%0A raise NotImplementedError%0A%0Afrom numpy import digitize%0A%0Adef find_mask(fs, node_edges):%0A raise NotImplementedError%0A%0Adef histogram(lst, weight=None):%0A raise NotImplementedError%0A%0Adef index_sort(arr):%0A return asarray(arr).argsort(kind='heap')%0A%0Adef interp(y, x, z, typ=None):%0A %22%22%22y(z) interpolated by treating y(x) as piecewise function%0A %22%22%22%0A res = numpy.interp(z, x, y)%0A if typ is None or typ == 'd':%0A return res%0A if typ == 'f':%0A return res.astype('f')%0A%0A raise error, %22incompatible typecode%22%0A%0Adef nz(x):%0A x = asarray(x,dtype=nx.ubyte)%0A if x.ndim != 1:%0A raise TypeError, %22intput must have 1 dimension.%22%0A indxs = nx.flatnonzero(x != 0)%0A return indxs%5B-1%5D.item()+1%0A%0Adef reverse(x, n):%0A x = asarray(x,dtype='d')%0A if x.ndim != 2:%0A raise ValueError, %22input must be 2-d%22%0A y = nx.empty_like(x)%0A if n == 0:%0A y%5B...%5D = x%5B::-1,:%5D%0A elif n == 1:%0A y%5B...%5D = x%5B:,::-1%5D%0A return y%0A%0Adef span(lo, hi, num, d2=0):%0A x = linspace(lo, hi, num)%0A if d2 %3C= 0%0A return x%0A else:%0A ret = empty((d2,num),x.dtype)%0A ret%5B...%5D = x%0A return ret%0A%0Adef to_corners(arr, nv, nvsum):%0A raise NotImplementedError%0A%0Adef zmin_zmax(z, ireg):%0A raise NotImplementedError%0A %0A
d5daa2376fadae0d6715b606a0c355b572efdd0c
Add Python benchmark
lib/node_modules/@stdlib/math/base/dist/beta/kurtosis/benchmark/python/benchmark.scipy.py
lib/node_modules/@stdlib/math/base/dist/beta/kurtosis/benchmark/python/benchmark.scipy.py
Python
0.000138
@@ -0,0 +1,1590 @@ +#!/usr/bin/env python%0A%22%22%22Benchmark scipy.stats.beta.stats.%22%22%22%0A%0Aimport timeit%0A%0Aname = %22beta:kurtosis%22%0Arepeats = 3%0Aiterations = 1000%0A%0A%0Adef print_version():%0A %22%22%22Print the TAP version.%22%22%22%0A%0A print(%22TAP version 13%22)%0A%0A%0Adef print_summary(total, passing):%0A %22%22%22Print the benchmark summary.%0A%0A # Arguments%0A%0A * %60total%60: total number of tests%0A * %60passing%60: number of passing tests%0A%0A %22%22%22%0A%0A print(%22#%22)%0A print(%221..%22 + str(total)) # TAP plan%0A print(%22# total %22 + str(total))%0A print(%22# pass %22 + str(passing))%0A print(%22#%22)%0A print(%22# ok%22)%0A%0A%0Adef print_results(elapsed):%0A %22%22%22Print benchmark results.%0A%0A # Arguments%0A%0A * %60elapsed%60: elapsed time (in seconds)%0A%0A # Examples%0A%0A %60%60%60 python%0A python%3E print_results(0.131009101868)%0A %60%60%60%0A %22%22%22%0A%0A rate = iterations / elapsed%0A%0A print(%22 ---%22)%0A print(%22 iterations: %22 + str(iterations))%0A print(%22 elapsed: %22 + str(elapsed))%0A print(%22 rate: %22 + str(rate))%0A print(%22 ...%22)%0A%0A%0Adef benchmark():%0A %22%22%22Run the benchmark and print benchmark results.%22%22%22%0A%0A setup = %22from scipy.stats import beta; from random import random;%22%0A stmt = %22y = beta.stats(random()*10.0 + 1.0, random()*10.0 + 1.0, moments='k')%22%0A%0A t = timeit.Timer(stmt, setup=setup)%0A%0A print_version()%0A%0A for i in xrange(repeats):%0A print(%22# python::%22 + name)%0A elapsed = t.timeit(number=iterations)%0A print_results(elapsed)%0A print(%22ok %22 + str(i+1) + %22 benchmark finished%22)%0A%0A print_summary(repeats, repeats)%0A%0A%0Adef main():%0A %22%22%22Run the benchmark.%22%22%22%0A benchmark()%0A%0A%0Aif __name__ == %22__main__%22:%0A main()%0A
7e7879eb5c0d547a56a082a9b3a444fea59e9156
Create revEncry.py
Codingame/Python/Clash/revEncry.py
Codingame/Python/Clash/revEncry.py
Python
0.000001
@@ -0,0 +1,223 @@ +import sys%0Aimport math%0A%0A# Auto-generated code below aims at helping you parse%0A# the standard input according to the problem statement.%0A%0Aword = input()%0Afor x in word:%0A o = ord(x)%0A k = 122-o%0A print(chr(97+k),end='')%0A
625548dfc54a7f0620a83f62435c6e246dc58d12
Solve 18.
018/solution.py
018/solution.py
Python
0.999773
@@ -0,0 +1,1096 @@ +%22%22%22 Project Euler problem #18. %22%22%22%0A%0A%0Adef problem():%0A %22%22%22 Solve the problem.%0A%0A Find the maximum total from top to bottom of the triangle below.%0A%0A Answer:%0A%0A %22%22%22%0A triangle = %22%22%22%0A 75%0A 95 64%0A 17 47 82%0A 18 35 87 10%0A 20 04 82 47 65%0A 19 01 23 75 03 34%0A 88 02 77 73 07 63 67%0A 99 65 04 28 06 16 70 92%0A 41 41 26 56 83 40 80 70 33%0A 41 48 72 33 47 32 37 16 94 29%0A 53 71 44 65 25 43 91 52 97 51 14%0A 70 11 33 28 77 73 17 78 39 68 17 57%0A 91 71 52 38 17 14 91 43 58 50 27 29 48%0A 63 66 04 68 89 53 67 30 73 16 69 87 40 31%0A 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23%0A %22%22%22%0A triangle = %5B%0A map(int, l.strip().split()) for l in triangle.split('%5Cn') if l.strip()%5D%0A%0A gen = iter(reversed(triangle))%0A sums = next(gen)%0A%0A def grouper(nodes):%0A for n in range(len(nodes) - 1):%0A yield nodes%5Bn%5D, nodes%5Bn+1%5D%0A%0A for nodes in gen:%0A sums = %5Bs + max(nn) for s, nn in zip(nodes, grouper(sums))%5D%0A%0A return sums%5B0%5D%0A%0A%0Aif __name__ == '__main__':%0A print problem()%0A
b647416b719c9f0b2534c13a67d3396fefaada47
Add problem 1 sum muliples of 3 or 5 python solution
p001_multiples_of_3_and_5.py
p001_multiples_of_3_and_5.py
Python
0.999989
@@ -0,0 +1,1343 @@ +#%0A'''%0AProject Euler - Problem 1 - Multiples of 3 and 5%0Ahttps://projecteuler.net/problem=1%0A%0AIf we list all the natural numbers below 10 that are multiples of 3 or 5, we%0Aget 3, 5, 6 and 9. The sum of these multiples is 23.%0A%0AFind the sum of all the multiples of 3 or 5 below 1000.%0A'''%0A%0Aimport sys%0A%0A%0Adef main():%0A '''Sum the numbers from 1 through 999 that are multiples of either 3 or 5.%0A '''%0A # get list of numbers using list comprehension%0A numbers = %5Bx for x in range(1, 1000) if x %25 3 == 0 or x %25 5 == 0%5D%0A count = len(numbers)%0A total = sum(numbers)%0A # display length of list and the sum of its elements%0A print(%22There are %7B0%7D numbers from 1 through 999 that are multiples of either%22%0A %223 or 5. Their sum is: %7B1%7D%22.format(count, total))%0A%0A # One line alternative solution%0A # sum the output of a generator whose elements are from 1 to 999 and provided%0A # they are a multiple of 3 or 5 using modulo arithmetic. No intermediate list%0A # is constructed.%0A total = sum(x for x in range(1, 1000) if x %25 3 == 0 or x %25 5 == 0)%0A print(%22Alternative: Sum of numbers 1 through 999 that are multiples of either%22%0A %22 3 or 5: %7B0%7D%22.format(total))%0A%0Aif __name__ == '__main__':%0A # interactive run main, capture keyboard interrupts%0A try:%0A sys.exit(main())%0A except KeyboardInterrupt:%0A pass%0A
6c806f12129d132db17cf601335f638b82a814d6
Create form.py
AutoMap/form.py
AutoMap/form.py
Python
0
@@ -0,0 +1,1981 @@ +import turtle%0Aimport Tkinter as tk%0A%0Adef desenha(distancia, angulo, lousa):%0A lousa.penup()%0A lousa.home()%0A lousa.left(angulo)%0A lousa.pendown()%0A lousa.forward(distancia)%0A %0Adef main():%0A app = tk.Tk()%0A app.title(%22Mapeamento 2D de ambiente %22)%0A app.fontePadrao = (%22Arial%22, %2210%22, %22bold%22)%0A %0A app.primeiroContainer = tk.Frame(app)%0A app.primeiroContainer%5B%22padx%22%5D = 20%0A app.primeiroContainer.pack()%0A%0A app.segundoContainer = tk.Frame(app)%0A app.segundoContainer%5B%22padx%22%5D = 20%0A app.segundoContainer.pack()%0A%0A app.lblControle = tk.Label(app.primeiroContainer, text=%22Controle de movimento%22, font=app.fontePadrao)%0A app.lblControle.pack(side=tk.TOP)%0A%0A app.frente = tk.Button(app.primeiroContainer)%0A app.frente%5B%22text%22%5D = %22Frente%22%0A app.frente%5B%22font%22%5D = (%22Calibri%22, %228%22)%0A app.frente%5B%22width%22%5D = 12%0A #app.frente%5B%22command%22%5D = self.verificaSenha%0A app.frente.pack()%0A %0A app.direita = tk.Button(app.primeiroContainer)%0A app.direita%5B%22text%22%5D = %22Direita%22%0A app.direita%5B%22font%22%5D = (%22Calibri%22, %228%22)%0A app.direita%5B%22width%22%5D = 12%0A #app.direita%5B%22command%22%5D = self.verificaSenha%0A app.direita.pack(side=tk.LEFT)%0A%0A app.esquerda = tk.Button(app.primeiroContainer)%0A app.esquerda%5B%22text%22%5D = %22Esquerda%22%0A app.esquerda%5B%22font%22%5D = (%22Calibri%22, %228%22)%0A app.esquerda%5B%22width%22%5D = 12%0A #app.esquerda%5B%22command%22%5D = self.verificaSenha%0A app.esquerda.pack(side=tk.RIGHT)%0A%0A app.re = tk.Button(app.primeiroContainer)%0A app.re%5B%22text%22%5D = %22Re%22%0A app.re%5B%22font%22%5D = (%22Calibri%22, %228%22)%0A app.re%5B%22width%22%5D = 12%0A #app.re%5B%22command%22%5D = self.verificaSenha%0A app.re.pack(side=tk.BOTTOM)%0A %0A app.lblCanvas = tk.Label(app.segundoContainer, text=%22Visualizacao do mapa%22, font=app.fontePadrao)%0A app.lblCanvas.pack(side=tk.TOP)%0A %0A canvas = tk.Canvas(app.segundoContainer,width=500,height=500)%0A canvas.pack()%0A %0A mapa = turtle.RawTurtle(canvas)%0A for i in range(360):%0A desenha(180, i,mapa)%0A%0A app.mainloop()%0A%0Amain()%0A
0c2f07fabb94698b8cf1b42a4f671ad0cd5e365f
Add migration for comment notification type
src/ggrc/migrations/versions/20160321011353_3914dbf78dc1_add_comment_notification_type.py
src/ggrc/migrations/versions/20160321011353_3914dbf78dc1_add_comment_notification_type.py
Python
0
@@ -0,0 +1,1748 @@ +# Copyright (C) 2016 Google Inc., authors, and contributors %3Csee AUTHORS file%3E%0A# Licensed under http://www.apache.org/licenses/LICENSE-2.0 %3Csee LICENSE file%3E%0A# Created By: miha@reciprocitylabs.com%0A# Maintained By: miha@reciprocitylabs.com%0A%0A%22%22%22%0AAdd comment notification type%0A%0ACreate Date: 2016-03-21 01:13:53.293580%0A%22%22%22%0A# disable Invalid constant name pylint warning for mandatory Alembic variables.%0A# pylint: disable=invalid-name%0A%0Aimport sqlalchemy as sa%0Afrom sqlalchemy.sql import column%0Afrom sqlalchemy.sql import table%0Afrom alembic import op%0A%0A%0A# revision identifiers, used by Alembic.%0Arevision = '3914dbf78dc1'%0Adown_revision = '50c374901d42'%0A%0A%0ANOTIFICATION_TYPES = table(%0A 'notification_types',%0A column('id', sa.Integer),%0A column('name', sa.String),%0A column('description', sa.Text),%0A column('template', sa.String),%0A column('instant', sa.Boolean),%0A column('advance_notice', sa.Integer),%0A column('advance_notice_end', sa.Integer),%0A column('created_at', sa.DateTime),%0A column('modified_by_id', sa.Integer),%0A column('updated_at', sa.DateTime),%0A column('context_id', sa.Integer),%0A)%0A%0ANOTIFICATIONS = %5B%7B%0A %22name%22: %22comment_created%22,%0A %22description%22: %22Notify selected users that a comment has been created%22,%0A %22template%22: %22comment_created%22,%0A %22advance_notice%22: 0,%0A %22instant%22: False,%0A%7D%5D%0A%0A%0Adef upgrade():%0A %22%22%22Add notification type entries for requests and assessments.%22%22%22%0A op.bulk_insert(NOTIFICATION_TYPES, NOTIFICATIONS)%0A%0A%0Adef downgrade():%0A %22%22%22Remove notification type entries for requests and assessments.%22%22%22%0A notification_names = %5Bnotif%5B%22name%22%5D for notif in NOTIFICATIONS%5D%0A op.execute(%0A NOTIFICATION_TYPES.delete().where(%0A NOTIFICATION_TYPES.c.name.in_(notification_names)%0A )%0A )%0A
2a6f3eca3187f8e4ca078cb592bb324a735cc246
Create solution.py
hackerrank/algorithms/sorting/easy/find_the_median/py/solution.py
hackerrank/algorithms/sorting/easy/find_the_median/py/solution.py
Python
0.000018
@@ -0,0 +1,696 @@ +#!/bin/python%0A%0Adef partition(L, lo, hi):%0A # Lomuto partitioning.%0A #%0A i = j = lo%0A v = hi - 1%0A while i %3C hi:%0A if L%5Bi%5D %3C L%5Bv%5D:%0A L%5Bi%5D, L%5Bj%5D = L%5Bj%5D, L%5Bi%5D%0A j += 1%0A i += 1%0A L%5Bv%5D, L%5Bj%5D = L%5Bj%5D, L%5Bv%5D%0A return j%0A%0Adef median(L):%0A # Hoare's quick select.%0A #%0A if len(L) == 0:%0A raise ValueError(%22Empty sequence.%22)%0A lo = 0%0A hi = len(L)%0A while lo %3C hi:%0A v = partition(L, lo, hi)%0A if v %3C len(L) // 2:%0A lo = v + 1%0A elif v %3E len(L) // 2:%0A hi = v%0A else: %0A break%0A return L%5Bv%5D%0A%0Asize = int(raw_input())%0AL = %5Bint(value) for value in raw_input().split()%5D%0Am = median(L)%0Aprint m%0A
6f7ed6f3b082c7f6399ab456a6f6b291219c910f
ADD migration scripts for uom prices
product_uom_prices/migrations/8.0.0.5.0/pre-migration.py
product_uom_prices/migrations/8.0.0.5.0/pre-migration.py
Python
0
@@ -0,0 +1,962 @@ +# -*- encoding: utf-8 -*-%0Afrom openerp import SUPERUSER_ID%0Afrom openerp.modules.registry import RegistryManager%0A%0A%0Adef set_value(cr, model, table, field, value, condition):%0A print 'Set value %25s on field %25s on table %25s' %25 (%0A value, field, table)%0A cr.execute('SELECT id '%0A 'FROM %25(table)s '%0A '%25(condition)s' %25 %7B%0A 'table': table,%0A 'condition': condition,%0A %7D)%0A for row in cr.fetchall():%0A model.write(cr, SUPERUSER_ID, row%5B0%5D, %7Bfield: value%7D)%0A%0A%0Adef migrate(cr, version):%0A print 'Migrating product_uom_prices'%0A if not version:%0A return%0A registry = RegistryManager.get(cr.dbname)%0A model = 'product.template'%0A table = 'product_template'%0A field = %22list_price_type%22%0A value = %22by_uom%22%0A condition = %22WHERE use_uom_prices%22%0A set_value(%0A cr,%0A registry%5Bmodel%5D,%0A table,%0A field,%0A value,%0A condition,%0A )%0A
9b6f86cb2f4763625127a3d9d236238a4dd998ba
Create fileExamples.py
Bits/fileExamples.py
Bits/fileExamples.py
Python
0
@@ -0,0 +1,578 @@ +#!/usr/bin/env python%0A%0A# CREATING A NEW FILE%0Afile = open(%22newfile.txt%22, %22w%22)%0Afile.write(%22hello world in the new file%5Cn%22)%0Afile.write(%22and another line%5Cn%22)%0Afile.close()%0A%0A%0A# READING A FILE%0Afile = open('newfile.txt', 'r')%0Aprint file.read() #Put n for the first n chars%0A%0A%0A# LOOPING OVER FILE%0A%0Afile = open('newfile.txt', 'r')%0A%0Afor line in file:%0A print line%0A%0A%0A# WRITING IN A FILE%0A%0Afile = open(%22newfile.txt%22, %22w%22)%0Afile.write(%22This is a test%5Cn%22)%0Afile.write(%22And here is another line%5Cn%22)%0Afile.close()%0A%0A%0A# EXAMPLES%0A%0Awith open(%22newfile.txt%22) as f:%0A for line in f:%0A print line,%0A