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
22e8cc6200cafd5cec386c35142cd742d4a2a735
add problem 34
problem_034.py
problem_034.py
Python
0.00477
@@ -0,0 +1,595 @@ +#!/usr/bin/env python%0A#-*-coding:utf-8-*-%0A%0A'''%0A145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.%0A%0AFind the sum of all numbers which are equal to%0Athe sum of the factorial of their digits.%0A%0ANote: as 1! = 1 and 2! = 2 are not sums they are not included.%0A'''%0A%0Aimport math%0Aimport timeit%0A%0Adef calc():%0A eqs = %5B%5D%0A for i in range(3, 2177280):%0A if i == sum(map(lambda j: math.factorial(j), map(int, list(str(i))))):%0A eqs.append(i)%0A return eqs%0A%0Aif __name__ == '__main__':%0A print calc()%0A print timeit.Timer('problem_034.calc()', 'import problem_034').timeit(1)%0A
f64068b7b6e50f9280b51831715df8cb4c586daa
Update merge person tool
project/apps/api/management/commands/merge_persons.py
project/apps/api/management/commands/merge_persons.py
Python
0.000001
@@ -0,0 +1,2331 @@ +from optparse import make_option%0A%0Afrom django.core.management.base import (%0A BaseCommand,%0A CommandError,%0A)%0A%0Afrom apps.api.models import (%0A Person,%0A Singer,%0A Director,%0A Arranger,%0A)%0A%0A%0Aclass Command(BaseCommand):%0A help = %22Merge selected singers by name%22%0A option_list = BaseCommand.option_list + (%0A make_option(%0A %22-o%22,%0A %22--old%22,%0A dest=%22old%22,%0A help=%22specify old name%22,%0A ),%0A )%0A option_list = option_list + (%0A make_option(%0A %22-n%22,%0A %22--new%22,%0A dest=%22new%22,%0A help=%22specify new name%22,%0A ),%0A )%0A%0A def handle(self, *args, **options):%0A # make sure file option is present%0A if options%5B'old'%5D is None:%0A raise CommandError(%22Option %60--old=...%60 must be specified.%22)%0A%0A if options%5B'new'%5D is None:%0A raise CommandError(%22Option %60--new=...%60 must be specified.%22)%0A%0A # make sure both singers exist%0A try:%0A new_person = Person.objects.get(%0A name__iexact=options%5B'new'%5D,%0A )%0A except Person.DoesNotExist:%0A raise CommandError(%22New person does not exist.%22)%0A try:%0A old_person = Person.objects.get(%0A name__iexact=options%5B'old'%5D,%0A )%0A except Singer.DoesNotExist:%0A raise CommandError(%22Old person does not exist.%22)%0A%0A # Move related records%0A for director in old_person.choruses.all():%0A Director.objects.create(%0A person=new_person,%0A contestant=director.contestant,%0A part=director.part,%0A )%0A for singer in old_person.quartets.all():%0A Singer.objects.create(%0A person=new_person,%0A contestant=singer.contestant,%0A part=singer.part,%0A )%0A%0A for arranger in old_person.arrangements.all():%0A Arranger.objects.create(%0A person=new_person,%0A chart=arranger.chart,%0A part=arranger.part,%0A )%0A%0A # remove redundant singer%0A try:%0A old_person.delete()%0A except Exception as e:%0A raise CommandError(%22Error deleted old singer: %7B0%7D%22.format(e))%0A%0A return %22Merged %7B0%7D into %7B1%7D%22.format(old_person, new_person)%0A
12bca37026ef4db41bd452dcb8cdc9022cdcf8c9
Create pythonhelloworld.py
pythonhelloworld.py
pythonhelloworld.py
Python
0.999993
@@ -0,0 +1,19 @@ +print %22hello word%22%0A
8e4240cd9bc2c06264ef23fddfc93ccf76e5ff9b
Create progressbar.py
progressbar.py
progressbar.py
Python
0.000001
@@ -0,0 +1,3968 @@ +################################################################################%0A# Example usage:%0A# $ python%0A# %3E%3E%3E import Progress%0A# %3E%3E%3E total = 100%0A# %3E%3E%3E message = 'Doing this task '%0A# %3E%3E%3E with Progress.Bar(total, message) as bar:%0A# ... for n in range(total):%0A# ... time.sleep(0.1)%0A# ... bar.update()%0A# ...%0A# Doing this task %5B------------------------------------------------------------%5D%0A################################################################################%0Aimport sys%0A################################################################################%0Aclass Bar:%0A%0A # A progress bar is draw using 4 elements:%0A # 1. A message%0A # 2. The left (start) boundary%0A # 3. The body of the progress bar%0A # 4. The right (end) boundary%0A template = '%7Bmsg%7D%7Bstart%7D%7Bbody%7D%7Bend%7D'%0A%0A##################################################%0A%0A def __init__(self, total, message='', max_width=80,%0A marker='#', placeholders='-',%0A start='%5B', end='%5D'):%0A%0A # Assume zero width so that self.from_template() works%0A self.width = 0%0A%0A # A bar measures progress towards a total%0A self.total = total%0A%0A # A progress bar may have a message before it%0A self.message = message%0A%0A # A Progress.Bar is a series of markers%0A self.marker = marker%0A%0A # drawn over the top of placeholders%0A self.placeholders = placeholders%0A%0A # and delimited by start and end characters%0A self.start=start%0A self.end=end%0A%0A # calculate how much of the max_width will be consumed by the message%0A # and the start/end delimiters.%0A padding_width = len(self.from_template())%0A%0A # Calculate the width of the body of the bar%0A self.width = max_width - padding_width%0A%0A # How many parts of the total go per marker in the body of the bar%0A self.granularity = total / self.width%0A%0A##############################%0A%0A def from_template(self):%0A ''' Returns a string representation of the Progress.Bar, including the%0A message, the start and end markers and a series of placeholders.%0A '''%0A return self.template.format(msg = self.message,%0A start = self.start,%0A end = self.end,%0A body = self.placeholders * self.width)%0A%0A##################################################%0A%0A def __enter__(self):%0A # How much of the total has passed%0A self.progress = 0%0A%0A # How much of the width has been drawn%0A self.rendered = 0%0A%0A # Write out the Progress.Bar with placeholders%0A sys.stdout.write(self.from_template())%0A%0A # Write out backspaces until the cursor is at the start marker%0A sys.stdout.write('%5Cb' * (self.width + len(self.end)))%0A sys.stdout.flush()%0A%0A # act as a proper generator%0A return self%0A%0A##############################%0A%0A def __exit__(self, type, value, traceback):%0A # always render a completed Progress.Bar%0A while not self.is_fully_rendered():%0A self.render()%0A%0A # then finish on the next line%0A print('')%0A%0A##################################################%0A%0A def render(self):%0A ''' Outputs one marker over the top of a placeholder if the progress%0A bar is still not fully rendered.%0A '''%0A self.rendered += 1%0A if not self.is_fully_rendered():%0A sys.stdout.write(self.marker)%0A sys.stdout.flush()%0A%0A##############################%0A%0A def is_fully_rendered(self):%0A return self.rendered %3E self.width%0A%0A##################################################%0A%0A def update(self, n=1):%0A ''' Update the Progress.Bar n counts towards the total.%0A '''%0A if n %3E 0:%0A self.progress += 1%0A while self.progress / self.granularity %3E self.rendered:%0A self.render()%0A self.update(n-1)%0A
465c2c92da5db91bcc1f9149fbfa5722d30e10f9
add some tests for the Basic Auth filter
test/test_basic_auth.py
test/test_basic_auth.py
Python
0
@@ -0,0 +1,1182 @@ +import unittest%0A%0Afrom libsaas import http%0Afrom libsaas.filters import auth%0A%0A%0Aclass BasicAuthTestCase(unittest.TestCase):%0A%0A def test_simple(self):%0A auth_filter = auth.BasicAuth('user', 'pass')%0A req = http.Request('GET', 'http://example.net/')%0A auth_filter(req)%0A%0A self.assertEqual(req.headers%5B'Authorization'%5D, 'Basic dXNlcjpwYXNz')%0A%0A def test_unicode(self):%0A # try both a unicode and a bytes parameter%0A _lambda = b'%5Cxce%5Cxbb'%0A _ulambda = _lambda.decode('utf-8')%0A%0A auth_bytes = auth.BasicAuth('user', _lambda)%0A auth_unicode = auth.BasicAuth('user', _ulambda)%0A auth_mixed = auth.BasicAuth(_lambda, _ulambda)%0A%0A expected_bytes = 'Basic dXNlcjrOuw=='%0A expected_unicode = expected_bytes%0A expected_mixed = 'Basic zrs6zrs='%0A%0A for auth_filter, expected in ((auth_bytes, expected_bytes),%0A (auth_unicode, expected_unicode),%0A (auth_mixed, expected_mixed)):%0A%0A req = http.Request('GET', 'http://example.net/')%0A auth_filter(req)%0A%0A self.assertEqual(req.headers%5B'Authorization'%5D, expected)%0A
f6ea68d6a900eb33c2004aa65805b157b99c9ff8
Remove beta. from hostname.
fabfile.py
fabfile.py
from fabric.api import * from fabric.contrib.files import * from fabric.colors import red def deploy(branch='master'): "Deploy the specified branch to the remote host." root_dir = '/home/www-data' code_dir = '%s/django_app' % root_dir virtualenv_name = 'django_venv' virtualenv_dir = '%s/%s' % (root_dir, virtualenv_name) host = 'beta.censusreporter.org' sudo('mkdir -p %s' % root_dir) sudo('chown www-data:www-data %s' % root_dir) # Install required packages sudo('apt-get update') sudo('apt-get install -y git') # Install and set up apache and mod_wsgi sudo('apt-get install -y apache2 libapache2-mod-wsgi') sudo('a2enmod wsgi') sudo('rm -f /etc/apache2/sites-enabled/000-default') sudo('rm -f /etc/apache2/sites-enabled/%s' % host) sudo('rm -f /etc/apache2/sites-available/%s' % host) upload_template('./server/apache2/site', '/etc/apache2/sites-available/%s' % host, use_sudo=True, context={ 'domainname': host, 'django_project_path': '%s/censusreporter' % code_dir, 'django_static_path': '%s/censusreporter/apps/census/static' % code_dir, 'django_venv_path': '%s/lib/python2.7/site-packages' % virtualenv_dir }) sudo('a2ensite %s' % host) # Install up to virtualenv sudo('apt-get install -y python-setuptools') sudo('easy_install pip') sudo('pip install virtualenv') # Create virtualenv and add our django app to its PYTHONPATH sudo('virtualenv --no-site-packages %s' % virtualenv_dir) sudo('rm -f %s/lib/python2.7/site-packages/censusreporter.pth' % virtualenv_dir) append('%s/lib/python2.7/site-packages/censusreporter.pth' % virtualenv_dir, '%s/censusreporter' % code_dir, use_sudo=True) append('%s/lib/python2.7/site-packages/censusreporter.pth' % virtualenv_dir, '%s/censusreporter/apps' % code_dir, use_sudo=True) append('%s/bin/activate' % virtualenv_dir, 'export DJANGO_SETTINGS_MODULE="config.prod.settings"', use_sudo=True) with settings(warn_only=True): if sudo('test -d %s' % code_dir).failed: sudo('git clone git://github.com/censusreporter/censusreporter.git %s' % code_dir) with cd(code_dir): sudo('git pull origin %s' % branch) # Install pip requirements sudo('source %s/bin/activate && pip install -r requirements.txt' % virtualenv_dir) # Make sure everything is correctly owned sudo('chown www-data:www-data -R %s %s' % (code_dir, virtualenv_dir)) # Restart apache sudo('service apache2 restart')
Python
0.000007
@@ -354,12 +354,11 @@ = ' -beta +www .cen
4cac86aeb2d24a916fc5ae9ca98e3898f4729e1c
add protocol.py module
plumbca/protocol.py
plumbca/protocol.py
Python
0.000001
@@ -0,0 +1,1060 @@ +# -*- coding: utf-8 -*-%0A%22%22%22%0A plumbca.protocol%0A ~~~~~~~~~~~~~~~~%0A%0A Implements the protocol support for Plumbca.%0A%0A :copyright: (c) 2015 by Jason Lai.%0A :license: BSD, see LICENSE for more details.%0A%22%22%22%0A%0Aimport logging%0Aimport asyncio%0A%0Afrom .message import Request%0Afrom .worker import Worker%0A%0A%0Aactlog = logging.getLogger('activity')%0Aerrlog = logging.getLogger('errors')%0A%0A%0Aclass PlumbcaCmdProtocol:%0A%0A def __init__(self):%0A self.handler = Worker()%0A%0A async def plumbca_cmd_handle(self, reader, writer):%0A %22%22%22Simple plumbca command protocol implementation.%0A%0A plumbca_cmd_handle handles incoming command request.%0A %22%22%22%0A data = await reader.read()%0A req = Request(data)%0A addr = writer.get_extra_info('peername')%0A actlog.info(%22%3CServer%3E Received %25r from %25r%22, req.command, addr)%0A%0A # drive the command process%0A resp = self.handler.run_command(req)%0A%0A writer.write(req.args)%0A await writer.drain()%0A%0A actlog.info(%22Close the client %25r socket%22, addr)%0A writer.close()%0A
545af0493cf08cb15d262f3a5333df6d1fce6848
Add util convenience functions for accessing data without decorators
brake/utils.py
brake/utils.py
Python
0
@@ -0,0 +1,555 @@ +from decorators import _backend%0A%0A%22%22%22Access limits and increment counts without using a decorator.%22%22%22%0A%0Adef get_limits(request, label, field, periods):%0A limits = %5B%5D%0A count = 10%0A for period in periods:%0A limits.extend(_backend.limit(%0A label,%0A request,%0A field=field,%0A count=count,%0A period=period%0A ))%0A count += 10%0A%0A return limits%0A%0Adef inc_counts(request, label, field, periods):%0A for period in periods:%0A _backend.count(label, request, field=field, period=period)%0A
e0c3a46d1c3c13b5c956bf3cc6f30ad495f87ccd
put the logger config in a separate file for cleanliness
voglogger.py
voglogger.py
Python
0
@@ -0,0 +1,603 @@ +#!/usr/bin/python%0A%0A%22%22%22%0A%0A%09logger management for VOGLbot%0A%0A%09writes out to both the console and a file 'voglbot.log'%0A%0A%22%22%22%0A%0Aimport sys%0Aimport logging%0Aimport time%0A%0Alogging.basicConfig(%0A%09filename = 'voglbot.log',%0A%09filemode = 'w',%0A%09level=logging.DEBUG,%0A%09format='%25(asctime)s: %25(message)s',%0A%09datefmt = '%25d-%25m %25H:%25M:%25S',%0A%09stream = sys.stdout,%0A)%0A# for console logging%0Aconsole = logging.StreamHandler()%0Aconsole.setLevel(logging.INFO)%0Aformatter = logging.Formatter('%25(asctime)-12s : %25(levelname)-8s %25(message)s')%0Aconsole.setFormatter(formatter)%0A%0Alogger = logging.getLogger()%0Alogging.getLogger('').addHandler(console)%0A
a984120bdb6c67a3dc2ca89ce9ae5498230015ea
Add initial runner
hug/run.py
hug/run.py
Python
0.000003
@@ -0,0 +1,729 @@ +%22%22%22hug/run.py%0A%0AContains logic to enable execution of hug APIS from the command line%0A%22%22%22%0Afrom wsgiref.simple_server import make_server%0A%0Aimport falcon%0Aimport sys%0Aimport importlib%0A%0A%0Adef server(module):%0A api = falcon.API()%0A for url, method_handlers in module.HUG_API_CALLS:%0A api.add_route(url, namedtuple('Router', method_handlers.keys())(**method_handlers))%0A return api%0A%0A%0Adef terminal():%0A if len(sys.argv) %3C 2:%0A print(%22Please specify a hug API file to start the server with%22, file=sys.stderr)%0A%0A api = server(importlib.machinery.SourceFileLoader(sys.argv%5B1%5D.split(%22.%22)%5B0%5D, sys.argv%5B1%5D).load_module())%0A httpd = make_server('', 8000, api)%0A print(%22Serving on port 8000...%22)%0A httpd.serve_forever()%0A
1578e1a129d91605148cf48f8793ac098ad0de7e
add command group
ibu/cli.py
ibu/cli.py
Python
0.000004
@@ -0,0 +1,258 @@ +# -*- coding: utf-8 -*-%0Afrom __future__ import print_function%0A%0Aimport click%0A%0A%0ACONTEXT_SETTINGS = dict(help_option_names=%5B'-h', '--help'%5D)%0A%0A%[email protected]()%0Adef ibu():%0A pass%0A%0A%[email protected](context_settings=CONTEXT_SETTINGS)%0Adef test():%0A print(%22hello%22)%0A
33dc091a43d3868324631fdb420721ab35d1f6ce
Create dis_q.py
dis_q.py
dis_q.py
Python
0.000139
@@ -0,0 +1,2226 @@ +#!/usr/bin/python%0A%0Aimport pymqi%0A%0Aqueue_manager = %22MQSD.TEST%22%0Achannel = %22SYSTEM.DEF.SVRCONN%22%0Ahost = %2210.21.218.15%22%0Aport = %2214123%22%0Aconn_info = %22%25s(%25s)%22 %25 (host, port)%0A%0Aprefix = %22*%22%0Aqueue_type = pymqi.CMQC.MQQT_ALL%0A# queue_type = pymqi.CMQC.MQQT_LOCAL%0Aexcluded_prefix = %5B'SYSTEM', 'MSB', 'AMQ' , 'MQAI'%5D%0A# excluded_prefix = %5B %5D%0A%0Aargs = %7Bpymqi.CMQC.MQCA_Q_NAME: prefix,%0A pymqi.CMQC.MQIA_Q_TYPE: queue_type%7D%0A%0Aqmgr = pymqi.connect(queue_manager, channel, conn_info)%0Apcf = pymqi.PCFExecute(qmgr)%0A%0Atry:%0A response = pcf.MQCMD_INQUIRE_Q(args)%0Aexcept pymqi.MQMIError, e:%0A if e.comp == pymqi.CMQC.MQCC_FAILED and e.reason == pymqi.CMQC.MQRC_UNKNOWN_OBJECT_NAME:%0A print %22No queues matched given arguments.%22%0A else:%0A raise%0Aelse:%0A for queue_info in response:%0A# Queue Name QueueDepth MaxDepth XMITQ Type%0A# https://www-01.ibm.com/support/knowledgecenter/SSFKSJ_7.1.0/com.ibm.mq.javadoc.doc/WMQJavaClasses/com/ibm/mq/pcf/CMQC.html%0A queue_name = queue_info%5Bpymqi.CMQC.MQCA_Q_NAME%5D%0A if not any(queue_name.startswith(prefix) for prefix in excluded_prefix):%0A queue_type = queue_info%5Bpymqi.CMQC.MQIA_Q_TYPE%5D%0A if queue_type == 1: #LOCAL%0A queue_type = %22LOCAL%22%0A queue_depth = queue_info%5Bpymqi.CMQC.MQIA_CURRENT_Q_DEPTH%5D%0A queue_mdepth = queue_info%5Bpymqi.CMQC.MQIA_MAX_Q_DEPTH%5D%0A print %22%25s %5Ct %25s %5Ct %25s %5Ct %25s%22 %25 (queue_name, queue_depth, queue_mdepth, queue_type)%0A # elif queue_type == 2: #MODEL%0A elif queue_type == 3: #ALIAS%0A queue_type = %22ALIAS%22%0A queue_depth = %22-%22%0A queue_mdepth = %22------%22%0A print %22%25s %5Ct %25s %5Ct %25s %5Ct %25s%22 %25 (queue_name, queue_depth, queue_mdepth, queue_type)%0A elif queue_type == 6: #REMOTE%0A queue_type = %22REMOTE%22%0A queue_depth = %22-%22%0A queue_mdepth = %22------%22%0A print %22%25s %5Ct %25s %5Ct %25s %5Ct %25s%22 %25 (queue_name, queue_depth, queue_mdepth, queue_type)%0A # print %22%25s %5Ct %25s%22 %25 (queue_name, queue_type)%0A else:%0A print %22%25s %5Ct %25s%22 %25 (queue_name, queue_type)%0A # print %22%25s %5Ct %25s%22 %25 (queue_name, queue_type)%0A%0Aqmgr.disconnect()%0A%0A%0A%0A
b7541c063b6fc10fdd622cbd680ea4418c679f6b
Add NodeList iterator
d1_libclient_python/src/d1_client/iter/node.py
d1_libclient_python/src/d1_client/iter/node.py
Python
0.000001
@@ -0,0 +1,1937 @@ +# -*- coding: utf-8 -*-%0A%0A# This work was created by participants in the DataONE project, and is%0A# jointly copyrighted by participating institutions in DataONE. For%0A# more information on DataONE, see our web site at http://dataone.org.%0A#%0A# Copyright 2009-2016 DataONE%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%22%22%22Iterate over the nodes that are registered in a DataONE environment%0A%0AFor each Node in the environment, returns a PyXB representation of a DataONE%0ANode document.%0A%0Ahttps://releases.dataone.org/online/api-documentation-v2.0/apis/Types.html#Types.Node%0A%22%22%22%0Aimport d1_client.mnclient_1_1%0Aimport d1_client.mnclient_2_0%0Aimport d1_common.types.dataoneTypes_v1_1 as v1%0Aimport d1_common.types.dataoneTypes_v2_0 as v2%0A%0AMAJOR_VERSION = 2%0A%0A%0Aclass NodeListIterator(object):%0A def __init__(%0A self,%0A base_url,%0A major_version=MAJOR_VERSION,%0A client_dict=None,%0A listNodes_dict=None,%0A ):%0A self._base_url = base_url%0A self._major_version = major_version%0A self._client_dict = client_dict or %7B%7D%0A self._listNodes_dict = listNodes_dict%0A%0A def __iter__(self):%0A client = d1_client.mnclient_2_0.MemberNodeClient_2_0(%0A self._base_url, **self._client_dict%0A )%0A node_list_pyxb = client.listNodes()%0A logging.debug(%0A 'Retrieved %7B%7D Node documents'.format(len(node_list_pyxb.node))%0A )%0A for node_pyxb in sorted(%0A node_list_pyxb.node, key=lambda x: x.identifier.value()%0A ):%0A yield node_pyxb%0A
2c900f8bddc9efb40d900bf28f8c6b3188add71e
Disable trix parser tests with Jython
test/test_trix_parse.py
test/test_trix_parse.py
#!/usr/bin/env python from rdflib.graph import ConjunctiveGraph import unittest class TestTrixParse(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testAperture(self): g=ConjunctiveGraph() g.parse("test/trix/aperture.trix",format="trix") c=list(g.contexts()) #print list(g.contexts()) t=sum(map(len, g.contexts())) self.assertEquals(t,24) self.assertEquals(len(c),4) #print "Parsed %d triples"%t def testSpec(self): g=ConjunctiveGraph() g.parse("test/trix/nokia_example.trix",format="trix") #print "Parsed %d triples"%len(g) if __name__=='__main__': unittest.main()
Python
0
@@ -711,17 +711,367 @@ %0A -%0A + def testNG4j(self): %0A%0A g=ConjunctiveGraph()%0A %0A g.parse(%22test/trix/ng4jtest.trix%22,format=%22trix%22)%0A %0A #print %22Parsed %25d triples%22%25len(g)%0A%0Aimport platform%0Aif platform.system() == 'Java':%0A from nose import SkipTest%0A raise SkipTest('Jython issues - %22JavaSAXParser%22 object has no attribute %22start_namespace_decl%22') %0A%0Aif __n
0cb6474b8c02f2cb7af54f8321f82a53175e8345
check for globals in the lib that are not prefixed with toku. addresses #74
src/tokuglobals.py
src/tokuglobals.py
Python
0.00001
@@ -0,0 +1,1252 @@ +#!/usr/bin/python%0A%0Aimport sys%0Aimport os%0Aimport re%0A%0Adef checkglobals(libname, exceptsymbols, verbose):%0A badglobals = 0%0A nmcmd = %22nm -g %22 + libname%0A f = os.popen(nmcmd)%0A b = f.readline()%0A while b != %22%22:%0A match = re.match(%22%5E(%5B0-9a-f%5D+)%5Cs(.?)%5Cs(.*)$%22, b)%0A if match == None:%0A match = re.match(%22%5E%5Cs+(.*)$%22, b)%0A if match == None:%0A print %22unknown%22, b%0A badglobals = 1%0A else:%0A type = match.group(2)%0A symbol = match.group(3)%0A if verbose: print type, symbol%0A match = re.match(%22%5Etoku_%22, symbol)%0A if match == None and not exceptsymbols.has_key(symbol):%0A print %22non toku symbol=%22, symbol%0A badglobals = 1%0A b = f.readline()%0A f.close()%0A return badglobals%0A%0Adef main():%0A verbose = 0%0A for arg in sys.argv%5B1:%5D:%0A if arg == %22-v%22:%0A verbose += 1%0A exceptsymbols = %7B%7D%0A for n in %5B %22_init%22, %22_fini%22, %22_end%22, %22_edata%22, %22__bss_start%22 %5D:%0A exceptsymbols%5Bn%5D = 1%0A for n in %5B %22db_env_create%22, %22db_create%22, %22db_strerror%22, %22db_version%22, %22log_compare%22 %5D:%0A exceptsymbols%5Bn%5D = 1%0A return checkglobals(%22libdb.so%22, exceptsymbols, verbose)%0A %0Asys.exit(main())%0A
24b8437003269ebd10c46d0fbdaa3e432d7535d6
Add VCF -> non-reference likelihood table script.
genotype-likelihoods.py
genotype-likelihoods.py
Python
0
@@ -0,0 +1,1052 @@ +from __future__ import print_function%0Aimport sys%0Aimport cyvcf%0Afrom argparse import ArgumentParser, FileType%0Aimport toolz as tz%0A%0Adescription = (%22Create a table of probability of a non reference call for each %22%0A %22genotype for each sample. This is PL%5B0%5D. -1 is output for samples %22%0A %22with a missing PL call at a position.%22)%0Aparser = ArgumentParser(description=description)%0Aparser.add_argument(%22vcf%22, type=FileType('r'),%0A help=%22VCF file to convert, use '-' to read from stdin%22)%0Aargs = parser.parse_args()%0A%0Avcf_reader = cyvcf.Reader(args.vcf)%0Arecords = tz.take(10, vcf_reader)%0A%0Asamples = vcf_reader.samples%5B1:5%5D%0A%0Aheader = %22%5Ct%22.join(%5Bstr(x) for x in %5B%22CHROM%22, %22POS%22, %22ID%22, %22REF%22, %22ALT%22%5D + samples%5D)%0A%0Aprint(header, file=sys.stdout)%0Afor record in records:%0A line = %5Brecord.CHROM, record.POS, record.ID, record.REF, record.alleles%5B1%5D%5D%0A pls = %5Bx.data.get(%22PL%22, None) for x in record.samples%5B1:5%5D%5D%0A pls = %5Bx%5B0%5D if x else %22-1%22 for x in pls%5D%0A print(%22%5Ct%22.join(%5Bstr(x) for x in line + pls%5D), file=sys.stdout)%0A
6a9ddbf5d775df14c994c9af9e89195ca05a58f9
Add pyjokes CLI test
tests/test_cli_error.py
tests/test_cli_error.py
Python
0
@@ -0,0 +1,451 @@ +%0A%0Aimport pytest%0Aimport subprocess%0Afrom subprocess import Popen, PIPE%0A%0Adef test_pyjokes_call_exception():%0A pytest.raises(subprocess.CalledProcessError, %22subprocess.check_call('pyjokes')%22)%0A%0A%0Adef test_pyjokes_call_output():%0A try:%0A p = subprocess.Popen('pyjokes', stdin=PIPE, stdout=PIPE, stderr=PIPE)%0A except:%0A out, err = p.communicate()%0A assert out == b'Did you mean pyjoke?'%0A assert p.returncode == 1%0A pass
83a4c9bfa64543ecda65ed4c916fad8ad0a9233d
Create markov.py
markov.py
markov.py
Python
0.000001
@@ -0,0 +1,1437 @@ +# -*- coding: utf-8 -*-%0Aimport random%0A%0Angram = lambda text, n: %5Btext%5Bi:i+n%5D for i in xrange(len(text) - n + 1)%5D%0A%0Aflatten2D = lambda data: %5Bflattened for inner in data for flattened in inner%5D%0A%0Arandelement = lambda x: x%5Brandom.randint(0, len(x) - 1)%5D%0A%0Aclass Markov:%0A def __init__(self, data, n):%0A self.data = data%0A self.n = n%0A %0A def markov(self, limit, firstword, lastword, getlength, lengthlimit=None, result=None): %0A if limit == 0:%0A return %5Bk for k in %5Bi%5B0%5D for i in result%5B:-1%5D%5D + result%5B-1%5D%5D%0A %0A candidatelist = %5B%5D%0A if result != None:%0A candidatelist = %5Bcandidate for candidate in self.data if result%5B-1%5D%5B1:self.n%5D == candidate%5B0:self.n - 1%5D%5D%0A else:%0A result = %5B%5D%0A candidatelist = %5Bcandidate for candidate in self.data if candidate%5B0%5D == firstword%5D%0A %0A if candidatelist == %5B%5D:%0A result.append(randelement(self.data))%0A else:%0A result.append(randelement(candidatelist))%0A %0A wordcount = getlength(%5Bk for k in %5Bi%5B0%5D for i in result%5B:-1%5D%5D + result%5B-1%5D%5D)%0A charlimitflag = lengthlimit == None or wordcount %3C lengthlimit%0A if not charlimitflag:%0A result = result%5B:-1%5D%0A %0A mrkv = lambda li: self.markov(li, firstword, lastword, getlength, lengthlimit, result)%0A return mrkv(limit - 1) if charlimitflag and result%5B-1%5D%5B-1%5D != lastword else mrkv(0)%0A %0A
0970115f9bc1bab019c23ab46e64b26d5e754313
Implement function for displaying tuning guidance on a DIY 8-segment LEDs display
led_display.py
led_display.py
Python
0
@@ -0,0 +1,968 @@ +import math%0Afrom gpiozero import LED%0Afrom time import sleep%0A%0A%0Ag0 = LED(12)%0Af0 = LED(16)%0Aa0 = LED(20)%0Ab0 = LED(21)%0Ae0 = LED(17)%0Ad0 = LED(27)%0Ac0 = LED(22)%0A%0Ag1 = LED(25)%0Af1 = LED(24)%0Aa1 = LED(23)%0Ab1 = LED(18)%0Ae1 = LED(5)%0Ad1 = LED(6)%0Ac1 = LED(13)%0A%0APITCHES = %7B%0A 'E2': ((a0, d0, e0, f0, g0), (b0, c0)),%0A 'A2': ((a0, b0, c0, e0, f0, g0), (d0, )),%0A 'D3': ((b0, c0, d0, e0, g0), (a0, f0,)),%0A 'G3': ((a0, b0, c0, d0, f0, g0), (e0, )),%0A 'B3': ((c0, d0, e0, f0, g0), (a0, b0,)),%0A 'E4': ((a0, d0, e0, f0, g0), (b0, c0)),%0A%7D%0A%0ADIRECTIONS = %7B%0A -1: ((a1, b1, f1, g1), (c1, d1, e1,)),%0A 0: ((g1, ), (a1, b1, c1, d1, e1, f1, )),%0A 1: ((c1, d1, e1, g1), (a1, b1, f1)),%0A%7D%0A%0Adef display_tuning_guidance(pitch, direction):%0A leds_on = PITCHES%5Bpitch%5D%5B0%5D + DIRECTIONS%5Bdirection%5D%5B0%5D%0A leds_off = PITCHES%5Bpitch%5D%5B1%5D + DIRECTIONS%5Bdirection%5D%5B1%5D%0A # Turn the appropriate leds on or off%0A for led in leds_on:%0A led.off()%0A for led in leds_off:%0A led.on()%0A
550d8bcd49e5ec591286f3f42de7dd54ef853bb8
Add a utility script to print duplicates
find_dupes.py
find_dupes.py
Python
0.000003
@@ -0,0 +1,719 @@ +#!/usr/bin/env python3%0A%0Aimport json%0Aimport os%0Aimport random%0A%0Ascriptpath = os.path.dirname(__file__)%0Adata_dir = os.path.join(scriptpath, 'data')%0Aall_json = %5Bf for f in os.listdir(data_dir) if os.path.isfile(os.path.join(data_dir, f))%5D%0Aquotes = %5B%5D%0Afor f in all_json:%0A%09filename = os.path.join(data_dir, f)%0A%09with open(filename) as json_data:%0A%09%09quotes += json.load(json_data)%5B'data'%5D%0A%09%09%0Auniq_authors = %7B quote%5B'author'%5D for quote in quotes%7D%0Auniq_quotes = %7B quote%5B'quote'%5D for quote in quotes%7D%0A%0Aprint('Unique quotes: %7B%7D, authors: %7B%7D'.format(len(uniq_quotes), len(uniq_authors))) %0A%0Aseen = set()%0Adupes = sorted(%5Bx for x in quotes if x%5B'quote'%5D in seen or seen.add(x%5B'quote'%5D)%5D, key=lambda x:x%5B'quote'%5D)%0A%0Aprint(*dupes, sep='%5Cn')
a02b2866a3bf6067a2ee7f6d194c52c0a4d4500e
Create welcome_email_daemon.py
welcome_email_daemon.py
welcome_email_daemon.py
Python
0.000122
@@ -0,0 +1,1839 @@ +#send new members a welcome email%0Afrom smtplib import SMTP as smtp%0Afrom time import sleep%0A%0A%0Adef welcome_bot():%0A fp = open('busters','r')%0A np = open('welcomed','a')%0A for eachline in fp:%0A if not is_in(eachline.strip()):%0A send_welcome(eachline.strip())%0A np.write(eachline.strip()+'%5Cn')%0A fp.close()%0A np.close()%0A%0Adef is_in(email):%0A is_in_welcomed = False%0A mp = open('welcomed','r')%0A for eachline in mp:%0A if eachline.strip() == email: is_in_welcomed = True%0A return is_in_welcomed%0A mp.close()%0A%0Adef send_welcome(email):%0A FROM = 'customer_services@my_domain.com'%0A TO = email%0A BODY_success = %22%5Cr%5CnThankyou for joining the Food Coop! To make an order go to www.my_website.com%5Cr%5Cn%5C%0APick the items you want and copy-paste the code to customer_services@my_domain.com with the %5C%0Asubject line of the email set to 'food' (all lower-case letters and without the quotation marks)%5Cr%5Cn%5Cr%5Cn%5C%0AIf your order is successful you'll receive a confirmation email from the Food Coop within 5 minutes %5C%0Aof you sending in your order%5Cr%5Cn%5Cr%5Cn%5C%0APickup is on Wednesday on Mars (on the first floor of the Food Department. We will put signs up %5C%0Aon the day) from 12 to 3pm. See you there!%5Cr%5Cn%5Cr%5CnThe Food Coop Team%5Cr%5Cn(automated email. %5C%0Awrite to customer_services@my_domain.com if you're having trouble)%5Cr%5Cn%22%0A SUBJECT_success = %22Food Coop membership%22%0A message = 'From: ' + FROM + '%5Cr%5CnTo: ' + TO + '%5Cr%5CnSubject: ' + SUBJECT_success + '%5Cr%5Cn%5Cr%5Cn' + BODY_success%0A SMTPSERVER = 'localhost'%0A%0A sendserver = smtp(SMTPSERVER)%0A errors = sendserver.sendmail(FROM, TO, message)%0A sendserver.quit()%0A%0A if len(errors) != 0:%0A lp = open('welcome_errors', 'a')%0A for eachline in errors:%0A lp.write(eachline+'%5Cn')%0A lp.write('%5Cn%5Cn')%0A lp.close()%0A%0Awhile True:%0A sleep(10)%0A welcome_bot()%0A
a892a389cfc94ebf72579ed6888c02463cdf7e6d
add moviepy - text_erscheinen_lassen_rechts2links.py
moviepy/text_erscheinen_lassen_rechts2links.py
moviepy/text_erscheinen_lassen_rechts2links.py
Python
0.000006
@@ -0,0 +1,1871 @@ +#!/usr/bin/env python%0A%0A# Video mit Text erzeugen, Text von rechts nach links erscheinen lassen%0A%0A# Einstellungen%0Atext = 'Text' # Text%0Atextgroesse = 150 # Textgroesse in Pixel%0Atextfarbe_r = 0 # Textfarbe R%0Atextfarbe_g = 0 # Textfarbe G%0Atextfarbe_b = 0 # Textfarbe B%0Aschrift = 'FreeSans' # Schriftart%0Awinkel = 0 # Winkel%0Ahgfarbe_r = 1 # Hintergrundfarbe R%0Ahgfarbe_g = 1 # Hintergrundfarbe G%0Ahgfarbe_b = 1 # Hintergrundfarbe B%0Avideobreite = 1280 # in Pixel%0Avideohoehe = 720 # in Pixel%0Avideolaenge = 5 # in Sekunden %0Avideodatei = 'text.ogv' # Videodatei%0Aframes = 25 # Frames pro Sekunde%0A%0A# Modul moviepy importieren%0Afrom moviepy.editor import *%0A# Modul gizeh importieren%0Aimport gizeh%0A%0A# Funktion um Frames zu erzeugen, t ist die Zeit beim jeweiligen Frame%0Adef create_frame(t):%0A img = gizeh.Surface(videobreite,videohoehe,bg_color=(hgfarbe_r,hgfarbe_g,hgfarbe_b))%0A text_img = gizeh.text(text, fontfamily=schrift, fontsize=textgroesse,%0A fill=(textfarbe_r,textfarbe_g,textfarbe_b),%0A xy=(videobreite/2,videohoehe/2), angle=winkel)%0A rect_img = gizeh.rectangle(lx=videobreite, ly=videohoehe, xy=(videobreite/2-t*videobreite/videolaenge,videohoehe/2), fill=(hgfarbe_r,hgfarbe_g,hgfarbe_b), angle=winkel)%0A text_img.draw(img)%0A rect_img.draw(img)%0A return img.get_npimage()%0A%0A# Video erzeugen%0Avideo = VideoClip(create_frame, duration=videolaenge) %0A%0A# Video schreiben%0Avideo.write_videofile(videodatei, fps=frames)%0A%0A%0A# Hilfe fuer moviepy: https://zulko.github.io/moviepy/index.html%0A# Hilfe fuer gizeh: https://github.com/Zulko/gizeh%0A%0A# text_erscheinen_lassen_rechts2links.py%0A# Lizenz: http://creativecommons.org/publicdomain/zero/1.0/%0A# Author: openscreencast.de%0A%0A
5db0ef459f4b0f0d3903578ae89bef7d0de7bf98
add terminal test file
termtest.py
termtest.py
Python
0.000001
@@ -0,0 +1,391 @@ +#!/usr/bin/python3%0A%0Aimport termbox%0A%0At = termbox.Termbox()%0A%0At.clear()%0A%0Awidth = t.width()%0Aheight = t.height()%0Acell_count = width * height%0Achar = ord('a')%0Afor c in range(1):%0A for i in range(26):%0A for y in range(height):%0A for x in range(width):%0A t.change_cell(x, y, char, termbox.WHITE, termbox.BLACK)%0A t.present()%0A char += 1%0A%0At.close()%0A
3d8667d2bfd75fe076b15b171e5c942a2a358508
add basic is_unitary tests
test_gate.py
test_gate.py
Python
0.000017
@@ -0,0 +1,394 @@ +import numpy as np%0Aimport unittest%0Aimport gate%0A%0Aclass TestGate(unittest.TestCase):%0A%09def test_is_unitary(self):%0A%09%09qg = gate.QuantumGate(np.matrix('0 1; 1 0', np.complex_))%0A%09%09self.assertTrue(qg.is_unitary())%0A%0A%09def test_is_not_unitary(self):%0A%09%09matrix = np.matrix('1 1; 1 0', np.complex_)%0A%09%09self.failUnlessRaises(Exception, gate.QuantumGate, matrix)%0A%0Aif __name__ == '__main__':%0A unittest.main()%0A
bf0a4ee5023cddd4072330e9a3e5a530aeea956e
test unit added
test_unit.py
test_unit.py
Python
0
@@ -0,0 +1,163 @@ +class test_output:%0A def run(self, queue):%0A while True:%0A item = queue.get()%0A print(item)%0A%0A%0Adef mod_init():%0A return test_output()%0A
6764d0286f2386bef8ab5f627d061f45047956e9
add logger
logger.py
logger.py
Python
0.000026
@@ -0,0 +1,1011 @@ +#!/usr/bin/env python%0A%0Aimport logging%0Aimport os%0Afrom termcolor import colored%0A %0A %0Aclass ColorLog(object):%0A %0A colormap = dict(%0A debug=dict(color='grey', attrs=%5B'bold'%5D),%0A info=dict(color='green'),%0A warn=dict(color='yellow', attrs=%5B'bold'%5D),%0A warning=dict(color='yellow', attrs=%5B'bold'%5D),%0A error=dict(color='red'),%0A critical=dict(color='red', attrs=%5B'bold'%5D),%0A )%0A %0A def __init__(self, logger):%0A self._log = logger%0A %0A def __getattr__(self, name):%0A if name in %5B'debug', 'info', 'warn', 'warning', 'error', 'critical'%5D:%0A return lambda s, *args: getattr(self._log, name)(%0A colored(s, **self.colormap%5Bname%5D), *args)%0A %0A return getattr(self._log, name)%0A%0A# Initialize logger%0Alogging.basicConfig(format=%22%25(levelname)s: %25(name)s - %25(message)s%22, level=logging.INFO)%0Afh = logging.FileHandler(%22timDIMM.log%22)%0Afh.setLevel(logging.DEBUG)%0Afh.setFormatter(logging.Formatter(%22%25(asctime)s: %25(levelname)s - %25(name)s - %25(message)s%22))%0A
9cd3e1183b78f561751a638cf4e863703ec080d6
add load ini file config
load_config.py
load_config.py
Python
0.000001
@@ -0,0 +1,735 @@ +#!/usr/bin/env python%0A%22%22%22%0Aconf file example%0A%0A%5Belk-server%5D%0Aip = elk.server.ip%0Akibana = check_http%0Aelasticsearch = check_http!-p 9200%0Alogstash-3333 = check_tcp!3333%0Alogstash-3334 = check_tcp!3334%0Aload = check_nrpe!check_load%0A%22%22%22%0A%0Aimport os, sys%0Atry:%0A from ConfigParser import ConfigParser%0Aexcept ImportError:%0A from configparser import ConfigParser%0A%0Aparser = ConfigParser()%0Aparser.read(sys.argv%5B1%5D)%0Aparser.sections()%0Afor section in parser.sections():%0A os.system('./add_host.sh %7B%7D %7B%7D'.format(section, parser.get(section, 'ip')))%0A parser.remove_option(section, 'ip')%0A for service, command in parser.items(section):%0A os.system('./add_service_to_host.sh %7B%7D %7B%7D %7B%7D'.format(section, service, command.replace('/', r'%5C/')))%0A%0A
e559a0458d1e4b0ec578eb9bcfdcc992d439a35d
Add test cases for the backwards compatibility in #24
tests/test_backwards.py
tests/test_backwards.py
Python
0
@@ -0,0 +1,1771 @@ +%22%22%22 Test backwards-compatible behavior %22%22%22%0Aimport json%0A%0Afrom flywheel import Field, Model%0Afrom flywheel.fields.types import TypeDefinition, DictType, STRING%0Afrom flywheel.tests import DynamoSystemTest%0A%0A%0Aclass JsonType(TypeDefinition):%0A%0A %22%22%22 Simple type that serializes to JSON %22%22%22%0A%0A data_type = json%0A ddb_data_type = STRING%0A%0A def coerce(self, value, force):%0A return value%0A%0A def ddb_dump(self, value):%0A return json.dumps(value)%0A%0A def ddb_load(self, value):%0A return json.loads(value)%0A%0A%0Aclass OldDict(Model):%0A%0A %22%22%22 Model that uses an old-style json field as a dict store %22%22%22%0A%0A __metadata__ = %7B%0A '_name': 'dict-test',%0A %7D%0A%0A id = Field(hash_key=True)%0A data = Field(data_type=JsonType())%0A%0A%0Aclass TestOldJsonTypes(DynamoSystemTest):%0A%0A %22%22%22 Test the graceful handling of old json-serialized data %22%22%22%0A%0A models = %5BOldDict%5D%0A%0A def setUp(self):%0A super(TestOldJsonTypes, self).setUp()%0A OldDict.meta_.fields%5B'data'%5D.data_type = JsonType()%0A%0A def test_migrate_data(self):%0A %22%22%22 Test graceful load of old json-serialized data %22%22%22%0A old = OldDict('a', data=%7B'a': 1%7D)%0A self.engine.save(old)%0A OldDict.meta_.fields%5B'data'%5D.data_type = DictType()%0A new = self.engine.scan(OldDict).one()%0A self.assertEqual(new.data, old.data)%0A%0A def test_resave_old_data(self):%0A %22%22%22 Test the resaving of data that used to be json %22%22%22%0A old = OldDict('a', data=%7B'a': 1%7D)%0A self.engine.save(old)%0A OldDict.meta_.fields%5B'data'%5D.data_type = DictType()%0A new = self.engine.scan(OldDict).one()%0A new.data%5B'b'%5D = 2%0A new.sync(raise_on_conflict=False)%0A ret = self.engine.scan(OldDict).one()%0A self.assertEqual(ret.data, %7B'a': 1, 'b': 2%7D)%0A
501c38ac9e8b9fbb35b64321e103a0dfe064e718
Add a sequence module for optimizing gating
QGL/BasicSequences/BlankingSweeps.py
QGL/BasicSequences/BlankingSweeps.py
Python
0
@@ -0,0 +1,1016 @@ +%22%22%22%0ASequences for optimizing gating timing.%0A%22%22%22%0Afrom ..PulsePrimitives import *%0Afrom ..Compiler import compile_to_hardware%0A%0Adef sweep_gateDelay(qubit, sweepPts):%0A %22%22%22%0A Sweep the gate delay associated with a qubit channel using a simple Id, Id, X90, X90%0A seqeuence.%0A %0A Parameters%0A ---------%0A qubit : logical qubit to create sequences for%0A sweepPts : iterable to sweep the gate delay over.%0A %22%22%22%0A %0A %0A generator = qubit.physChan.generator%0A oldDelay = generator.gateDelay%0A %0A for ct, delay in enumerate(sweepPts):%0A seqs = %5B%5BId(qubit, length=120e-9), Id(qubit), MEAS(qubit)%5D,%0A %5BId(qubit, length=120e-9), MEAS(qubit)%5D,%0A %5BId(qubit, length=120e-9), X90(qubit), MEAS(qubit)%5D,%0A %5BId(qubit, length=120e-9), X90(qubit), MEAS(qubit)%5D%5D%0A %0A generator.gateDelay = delay%0A %0A compile_to_hardware(seqs, 'BlankingSweeps/GateDelay', suffix='_%7B%7D'.format(ct+1))%0A%0A generator.gateDelay = oldDelay %0A
213d1e65ebd6d2f9249d26c7ac3690d6bc6cde24
fix encoding
manage.py
manage.py
Python
0.274682
@@ -0,0 +1,258 @@ +#!/usr/bin/env python%0Aimport os%0Aimport sys%0A%0Aif __name__ == %22__main__%22:%0A os.environ.setdefault(%22DJANGO_SETTINGS_MODULE%22, %22geode_geocoding.settings%22)%0A%0A from django.core.management import execute_from_command_line%0A%0A execute_from_command_line(sys.argv)%0A
6e6c1428d61137b2a86f26e72aa97c510debd9eb
Update visualize.py
script/visualize.py
script/visualize.py
#!/usr/bin/python # -*- coding:utf-8 -*- import sys import os import matplotlib import matplotlib.pyplot as plt from matplotlib.colors import BoundaryNorm from matplotlib.ticker import MaxNLocator #plt.style.use('ggplot') import numpy as np from decimal import Decimal from timeit import default_timer as timer import argparse from rio import read_quantity, read_converter sys.path.insert(1, os.path.join(sys.path[0], '..')) import config sys.path.insert(1, os.path.join(sys.path[0], 'sod_shocktube')) from sod import solve parser = argparse.ArgumentParser(description="Visualize reference results from simulation", prefix_chars='-') parser.add_argument("project_name", type = str, help = "Name of scheme") parser.add_argument("--case", type = str, help = "Case to visualize", required=True) args = parser.parse_args() # Check if refence results exist. case_path = os.path.join(config.cases_dir, args.project_name, args.case, 'ref', 'final') #case_path = os.path.join(config.cases_dir, 'hydro4x1', 'n2dsod512x512', 'ref', 'final') print("Looking for results in %s ..." % case_path) if not os.path.isdir(case_path): print("Can't file reference result directory.") sys.exit(1) if not os.path.isfile(os.path.join(case_path, 'rho.dat')): print("Can't file reference result file.") sys.exit(1) # Load quantities. quantityListName = ["rho", "rhou_x", "rhou_y", "rhoe"] data = dict() uid_to_coords = dict() Nx, Ny, dx, dy = read_converter(case_path, uid_to_coords) for q in quantityListName: data[q] = np.zeros((Nx, Ny)) start = timer() read_quantity(data[q], case_path, uid_to_coords, q) end = timer() print("Time to load quantity", q, "%s second(s)" % int((end - start))) x = np.linspace(0., Nx * float(dx), Nx) y = np.linspace(0., Ny * float(dy), Ny) Ux = np.zeros((Nx, Ny)) Uy = np.zeros((Nx, Ny)) Ek = np.zeros((Nx, Ny)) Ei = np.zeros((Nx, Ny)) rho_1D = np.zeros(Nx) for i in range(Nx): rho_1D[i] = data['rho'][i][0] for j in range(Ny): if data['rho'][i][j] == 0.: continue Ux[i][j] = data['rhou_x'][i][j] / data['rho'][i][j] Uy[i][j] = data['rhou_y'][i][j] / data['rho'][i][j] Ek[i][j] = np.sqrt(Ux[i][j]*Ux[i][j] + Uy[i][j]*Uy[i][j]) Ei[i][j] = data['rhoe'][i][j] / data['rho'][i][j] gamma = 1.4 npts = 500 positions, regions, values = solve(left_state=(1, 1, 0), right_state=(0.1, 0.125, 0.), geometry=(0., 1., 0.5), t=0.2, gamma=gamma, npts=npts) # Now show them. ########## rho ################ fig = plt.figure(0, figsize=(9, 6)) ax0 = fig.add_subplot(221) cf = ax0.contourf(data['rho'].transpose()) fig.colorbar(cf, ax=ax0) ax0.set_title('rho contourf with levels') ax0.axis('tight') ########## rho 1D border ################ ax1 = fig.add_subplot(223) ax1.plot(x, rho_1D, 'b+-', linewidth=2, markersize=3, label="simul.") plt.plot(values['x'], values['rho'], linewidth=1.5, color='r', linestyle='dashed', label="exact") ax1.set(xlabel='x', ylabel='density', title='Rho value on y = 0') ax1.grid() ax1.axis([0, 1, 0, 1.1]) #ax1.axis('tight') ########## internal energy ################ ax2 = fig.add_subplot(222) cm = ax2.pcolormesh(Ei.transpose()) fig.colorbar(cm, ax=ax2) ax2.set_title('rho pcolormesh with levels') ax2.axis('tight') ########## velocity field ################ ax3 = fig.add_subplot(224) #lw = 3 * Ek.transpose() / Ek.max() #strm = ax3.streamplot(x, y, Ux.transpose(), Uy.transpose(), color=Ek.transpose(), cmap='autumn', linewidth=lw) strm = ax3.streamplot(x, y, Ux.transpose(), Uy.transpose(),color=Ek.transpose()) #strm = ax3.streamplot(x, y, Ux.transpose(), Uy.transpose()) #fig.colorbar(strm.lines) #strm = ax3.contourf(Ux.transpose()) #fig.colorbar(strm, ax=ax3) ax3.set_title('u field') ax3.axis('tight') # adjust spacing between subplots so `ax1` title and `ax0` tick labels don't overlap fig.tight_layout() plt.legend() plt.show()
Python
0
@@ -10,16 +10,17 @@ n/python +3 %0A# -*- c @@ -36,16 +36,34 @@ -8 -*-%0A%0A +import __future__%0A import s @@ -2531,40 +2531,8 @@ em.%0A -########## rho ################%0A fig @@ -2562,16 +2562,49 @@ =(9, 6)) +%0A%0A########## rho ################ %0Aax0 = f @@ -2989,17 +2989,16 @@ exact%22)%0A -%0A ax1.set(
6107d7fe1db571367a20143fa38fc6bec3056d36
Fix port for activity script
scripts/activity.py
scripts/activity.py
#!/usr/bin/env python import argparse import collections import itertools import os import random import sys import time from contextlib import contextmanager import logbook sys.path.insert(0, os.path.join(os.path.abspath(os.path.dirname(__file__)), "..")) from flask_app import app from flask_app.smtp import smtpd_context from mailboxer import Mailboxer parser = argparse.ArgumentParser(usage="%(prog)s [options] args...") parser.add_argument("--smtp-port", default=None, type=int) parser.add_argument("--port", default=8080) class Application(object): def __init__(self, args): self._args = args def main(self): client = Mailboxer("http://127.0.0.1:{0}".format(self._args.port)) mailboxes = collections.deque(maxlen=5) with self._get_smtpd_context() as smtp: for iteration in itertools.count(): if iteration % 3 == 0: logbook.info("Creating mailbox (#{})", iteration) mailboxes.append("mailbox{0}@demo.com".format(time.time())) client.create_mailbox(mailboxes[-1]) logbook.info("Sending email... (#{})", iteration) smtp.sendmail("[email protected]", [random.choice(mailboxes)], "This is message no. {0}".format(iteration)) time.sleep(5) return 0 @contextmanager def _get_smtpd_context(self): if self._args.smtp_port is None: with smtpd_context() as result: yield result else: yield SMTP("127.0.0.1", self._args.smtp_port) #### For use with entry_points/console_scripts def main_entry_point(): args = parser.parse_args() app = Application(args) sys.exit(app.main()) if __name__ == "__main__": main_entry_point()
Python
0
@@ -521,17 +521,17 @@ fault=80 -8 +0 0)%0A%0A%0Acla
6c94617d8ea2b66bba6c33fdc9aa81c5161a53f8
add yaml
marcov.py
marcov.py
Python
0.000067
@@ -0,0 +1,2004 @@ +#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A#twitterBot.py%0Aimport sys%0Areload(sys)%0Asys.setdefaultencoding('utf-8')%0A#use python-twitter%0Aimport twitter%0Aimport MeCab%0Aimport random%0Aimport re%0Aimport yaml%0A%0A_var = open(%22../API.yaml%22).read()%0A_yaml = yaml.load(_var)%0Aapi = twitter.Api(%0A consumer_key = _yaml%5B%22consumer_key0%22%5D,%0A consumer_secret = _yaml%5B%22consumer_secret0%22%5D,%0A access_token_key = _yaml%5B%22access_token0%22%5D,%0A access_token_secret = _yaml%5B%22access_token_secret0%22%5D%0A )%0A%0Adef wakati(text):%0A t = MeCab.Tagger(%22-Owakati%22)%0A m = t.parse(text)%0A result = m.rstrip(%22 %5Cn%22).split(%22 %22)%0A return result%0A%0Adef markov(src):%0A wordlist = wakati(src)%0A markov = %7B%7D%0A w1=''%0A for word in wordlist:%0A if w1:%0A if(w1)not in markov:%0A markov%5B(w1)%5D = %5B%5D%0A markov%5B(w1)%5D.append(word)%0A w1=word%0A count = 0%0A sentence=''%0A w1=random.choice(markov.keys())%0A #%E3%82%AB%E3%82%A6%E3%83%B3%E3%83%88%E6%95%B0%E3%81%AF%E3%81%8A%E3%81%93%E3%81%AE%E3%81%BF%E3%81%A7%0A while count %3C 50:%0A if markov.has_key((w1))==True:%0A tmp = random.choice(markov%5B(w1)%5D)%0A sentence += tmp%0A w1=tmp%0A count += 1%0A return sentence%0A%0Adef tweet_friends():%0A i=0%0A j=0%0A friends = api.GetFriends()%0A tweets = ''%0A for i in range(len(friends)):%0A friend_timeline = api.GetUserTimeline(screen_name=friends%5Bi%5D.screen_name)%0A for j in range(len(friend_timeline)):%0A #%E4%BB%96%E3%81%AE%E4%BA%BA%E3%81%B8%E3%81%AE%E3%83%84%E3%82%A4%E3%83%BC%E3%83%88%E3%81%AF%E9%99%A4%E5%A4%96%0A if %22@%22 not in friend_timeline%5Bj%5D.text:%0A tweets+=friend_timeline%5Bj%5D.text%0A tweets=str(tweets)%0A tweets=re.sub('https?://%5B%5Cw/:%25#%5C$&%5C?%5C(%5C)~%5C.=%5C+%5C-%5D+',%22%22,tweets)%0A FriendsTweet = marcov(tweets)%0A return FriendsTweet%0A%0Adef tweet_own():%0A i=0%0A own = api.GetUserTimeline(screen_name='geo_ebi',count=100)%0A tweets=''%0A for i in range(len(own)):%0A if %22@%22 not in own%5Bi%5D.text:%0A tweets+=own%5Bi%5D.text%0A tweets=str(tweets)%0A tweets=re.sub('https?://%5B%5Cw/:%25#%5C$&%5C?%5C(%5C)~%5C.=%5C+%5C-%5D+',%22%22,tweets)%0A OwnTweet = markov(tweets)%0A return OwnTweet%0A%0Aif random.random()%3C0.5:%0A Bot = tweet_own()%0A print(Bot)%0A status = api.PostUpdate(Bot)%0Aelse:%0A Bot = tweet_friends()%0A print(Bot)%0A status = api.PostUpdate(Bot)%0A%0A
9dcc635d0d5239928415ecab7a5ddb5387f98dea
add mail.py
globe/mail.py
globe/mail.py
Python
0.000002
@@ -0,0 +1,264 @@ +from flask_mail import Message%0Afrom globe import app, mail%0A%0Adef send_email(subject, sender, recipients, text_body, html_body):%0A msg = Message(subject, sender=sender%5B0%5D, recipients=recipients)%0A msg.body = text_body%0A msg.html = html_body%0A mail.send(msg)%0A
56ad587d21abe5251be5ce5fced8e42f1d89c2f4
Create tutorial1.py
tutorial1.py
tutorial1.py
Python
0
@@ -0,0 +1,48 @@ +from ggame import App%0Amyapp = App()%0Amyapp.run()%0A
ef8ad297634d2153d5a1675d7bb60b963f8c6abd
Add wrapper
cfn_wrapper.py
cfn_wrapper.py
Python
0.000004
@@ -0,0 +1,2982 @@ +# MIT Licensed, Copyright (c) 2015 Ryan Scott Brown %[email protected]%3E%0A%0Aimport json%0Aimport logging%0Aimport urllib2%0A%0Alogger = logging.getLogger()%0Alogger.setLevel(logging.INFO)%0A%0A%22%22%22%0AEvent example%0A%7B%0A %22Status%22: SUCCESS %7C FAILED,%0A %22Reason: mandatory on failure%0A %22PhysicalResourceId%22: string,%0A %22StackId%22: event%5B%22StackId%22%5D,%0A %22RequestId%22: event%5B%22RequestId%22%5D,%0A %22LogicalResourceId%22: event%5B%22LogicalResourceId%22%5D,%0A %22Data%22: %7B%7D%0A%7D%0A%22%22%22%0A%0Adef wrap_user_handler(func, base_response=None):%0A def wrapper_func(event, context):%0A response = %7B%0A %22StackId%22: event%5B%22StackId%22%5D,%0A %22RequestId%22: event%5B%22RequestId%22%5D,%0A %22LogicalResourceId%22: event%5B%22LogicalResourceId%22%5D,%0A %22Status%22: %22SUCCESS%22,%0A %7D%0A if base_response is not None:%0A response.update(base_response)%0A%0A logger.debug(%22Received %25s request with event: %25s%22 %25 (event%5B'RequestType'%5D, json.dumps(event)))%0A%0A try:%0A response.update(func(event, context))%0A except:%0A logger.exception(%22Failed to execute resource function%22)%0A response.update(%7B%0A %22Status%22: %22FAILED%22,%0A %22Reason%22: %22Exception was raised while handling custom resource%22%0A %7D)%0A%0A serialized = json.dumps(response)%0A logger.info(%22Responding to '%25s' request with: %25s%22 %25 (%0A event%5B'RequestType'%5D, serialized))%0A%0A req = urllib2.Request(%0A event%5B'ResponseURL'%5D, data=serialized,%0A headers=%7B'Content-Length': len(serialized),%0A 'Content-Type': ''%7D%0A )%0A req.get_method = lambda: 'PUT'%0A%0A try:%0A urllib2.urlopen(req)%0A logger.debug(%22Request to CFN API succeeded, nothing to do here%22)%0A except urllib2.HTTPError as e:%0A logger.error(%22Callback to CFN API failed with status %25d%22 %25 e.code)%0A logger.error(%22Response: %25s%22 %25 e.reason)%0A except urllib2.URLError as e:%0A logger.error(%22Failed to reach the server - %25s%22 %25 e.reason)%0A%0A return wrapper_func%0A%0Aclass Resource(object):%0A _dispatch = None%0A%0A def __init__(self):%0A self._dispatch = %7B%7D%0A%0A def __call__(self, event, context):%0A request = event%5B'RequestType'%5D%0A logger.debug(%22Received %7B%7D type event. Full parameters: %7B%7D%22.format(request, json.dumps(event)))%0A return self._dispatch.get(request, self._succeed)(event, context)%0A%0A def _succeed(self, event, context):%0A return %7B%0A 'Status': 'SUCCESS',%0A 'PhysicalResourceId': event.get('PhysicalResourceId', 'mock-resource-id'),%0A 'Reason': 'Life is good, man',%0A 'Data': %7B%7D,%0A %7D%0A%0A def create(self, wraps):%0A self._dispatch%5B'Create'%5D = wrap_user_handler(wraps)%0A return wraps%0A%0A def update(self, wraps):%0A self._dispatch%5B'Update'%5D = wrap_user_handler(wraps)%0A return wraps%0A%0A def delete(self, wraps):%0A self._dispatch%5B'Delete'%5D = wrap_user_handler(wraps)%0A return wraps%0A
e62a705d464df21098123ada89d38c3e3fe8ca73
Define a channel interface
zerorpc/channel_base.py
zerorpc/channel_base.py
Python
0.015718
@@ -0,0 +1,1967 @@ +# -*- coding: utf-8 -*-%0A# Open Source Initiative OSI - The MIT License (MIT):Licensing%0A#%0A# The MIT License (MIT)%0A# Copyright (c) 2014 Fran%C3%A7ois-Xavier Bourlet ([email protected])%0A#%0A# Permission is hereby granted, free of charge, to any person obtaining a copy of%0A# this software and associated documentation files (the %22Software%22), to deal in%0A# the Software without restriction, including without limitation the rights to%0A# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies%0A# of the Software, and to permit persons to whom the Software is furnished to do%0A# so, subject to the following conditions:%0A#%0A# The above copyright notice and this permission notice shall be included in all%0A# copies or substantial portions of the Software.%0A#%0A# THE SOFTWARE IS PROVIDED %22AS IS%22, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR%0A# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,%0A# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE%0A# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER%0A# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,%0A# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE%0A# SOFTWARE.%0A%0A%0Aclass ChannelBase(object):%0A%0A @property%0A def context(self):%0A raise NotImplementedError()%0A%0A @property%0A def recv_is_supported(self):%0A raise NotImplementedError()%0A%0A @property%0A def emit_is_supported(self):%0A raise NotImplementedError()%0A%0A def close(self):%0A raise NotImplementedError()%0A%0A def new_event(self, name, args, xheader=None):%0A raise NotImplementedError()%0A%0A def emit_event(self, event, timeout=None):%0A raise NotImplementedError()%0A%0A def emit(self, name, args, xheader=None, timeout=None):%0A event = self.new_event(name, args, xheader)%0A return self.emit_event(event, timeout)%0A%0A def recv(self, timeout=None):%0A raise NotImplementedError()%0A
c19120e0123b76236d11f3523e2ebd64c00b9feb
Check import
homeassistant/components/thermostat/radiotherm.py
homeassistant/components/thermostat/radiotherm.py
""" homeassistant.components.thermostat.radiotherm ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Adds support for Radio Thermostat wifi-enabled home thermostats. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/thermostat.radiotherm.html """ import logging import datetime from urllib.error import URLError from homeassistant.components.thermostat import (ThermostatDevice, STATE_COOL, STATE_IDLE, STATE_HEAT) from homeassistant.const import (CONF_HOST, TEMP_FAHRENHEIT) REQUIREMENTS = ['radiotherm==1.2'] HOLD_TEMP = 'hold_temp' _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_devices, discovery_info=None): """ Sets up the Radio Thermostat. """ import radiotherm hosts = [] if CONF_HOST in config: hosts = config[CONF_HOST] else: hosts.append(radiotherm.discover.discover_address()) if hosts is None: _LOGGER.error("No radiotherm thermostats detected") return hold_temp = config.get(HOLD_TEMP, False) tstats = [] for host in hosts: try: tstat = radiotherm.get_thermostat(host) tstats.append(RadioThermostat(tstat, hold_temp)) except (URLError, OSError): _LOGGER.exception("Unable to connect to Radio Thermostat: %s", host) add_devices(tstats) class RadioThermostat(ThermostatDevice): """ Represent a Radio Thermostat. """ def __init__(self, device, hold_temp): self.device = device self.set_time() self._target_temperature = None self._current_temperature = None self._operation = STATE_IDLE self._name = None self.hold_temp = hold_temp self.update() @property def name(self): """ Returns the name of the Radio Thermostat. """ return self._name @property def unit_of_measurement(self): """ Unit of measurement this thermostat expresses itself in. """ return TEMP_FAHRENHEIT @property def device_state_attributes(self): """ Returns device specific state attributes. """ return { "fan": self.device.fmode['human'], "mode": self.device.tmode['human'] } @property def current_temperature(self): """ Returns the current temperature. """ return round(self._current_temperature, 1) @property def operation(self): """ Returns current operation. head, cool idle """ return self._operation @property def target_temperature(self): """ Returns the temperature we try to reach. """ return round(self._target_temperature, 1) def update(self): self._current_temperature = self.device.temp['raw'] self._name = self.device.name['raw'] if self.device.tmode['human'] == 'Cool': self._target_temperature = self.device.t_cool['raw'] self._operation = STATE_COOL elif self.device.tmode['human'] == 'Heat': self._target_temperature = self.device.t_heat['raw'] self._operation = STATE_HEAT else: self._operation = STATE_IDLE def set_temperature(self, temperature): """ Set new target temperature """ if self._operation == STATE_COOL: self.device.t_cool = temperature elif self._operation == STATE_HEAT: self.device.t_heat = temperature if self.hold_temp: self.device.hold = 1 else: self.device.hold = 0 def set_time(self): """ Set device time """ now = datetime.datetime.now() self.device.time = {'day': now.weekday(), 'hour': now.hour, 'minute': now.minute}
Python
0
@@ -785,24 +785,37 @@ mostat. %22%22%22%0A + try:%0A import r @@ -823,16 +823,199 @@ diotherm +%0A except ImportError:%0A _LOGGER.exception(%0A %22Unable to import radiotherm. %22%0A %22Did you maybe not install the 'radiotherm' package?%22)%0A return False %0A%0A ho
10f7e5c8c1a2cdc84f706ccad041755b83c4953b
Create htmlsearch.py
htmlsearch.py
htmlsearch.py
Python
0.00002
@@ -0,0 +1,317 @@ +import glob%0Aprint glob.glob(%22*.html%22)%0Aarr = glob.glob(%22*.html%22)%0Ai=0%0Ak=%5B%5D%0Aray =%5B%5D%0Awhile i %3C len(arr):%0A file = open(arr%5Bi%5D, %22r%22)%0A #print file.read()%0A k.append(file.read())%0A i = i+1%0Aprint k%0A'''%0AOutputs:%0Aprint print glob.glob(%22*.html%22)%0A%5B'source.html', 'so.html'%5D %0Aprint k%0A%5B'google.com', 'socorop.com'%5D %0A'''%0A
46eb1c2d10316eae4d85b3d689307e32ed763d07
add 6-17.py
chapter6/6-17.py
chapter6/6-17.py
Python
0.998825
@@ -0,0 +1,620 @@ +#!/usr/bin/env python%0A%0Adef myPop(myList):%0A if len(myList) == 0:%0A print %22no more element to pop%22%0A exit(1)%0A else:%0A result = myList%5Blen(myList)-1%5D%0A myList.remove(result)%0A return result%0A%0Adef myPush(myList,element):%0A myList.append(element)%0A%0Adef main():%0A myList = %5B%5D%0A for i in range(800,810,3):%0A myPush(myList,i)%0A print %22myList push %25s%22 %25 i%0A print %22myList = %25s%22 %25 myList%0A print %22myList = %25s%22 %25 myList%0A for i in range(4):%0A print %22myList pop %25s %22 %25 myPop(myList)%0A print %22myList = %25s%22 %25 myList%0A%0Aif __name__ == '__main__':%0A main()%0A
a3fc49840ca098cea4e874353272f69baf6e229f
fix bugs
tornadocnauth/Douban.py
tornadocnauth/Douban.py
# -*- coding: utf-8 -*- from tornado import gen from tornado import httpclient from tornado import escape from tornado.httputil import url_concat from tornado.concurrent import Future from tornado.auth import OAuth2Mixin, _auth_return_future, AuthError try: import urlparse except ImportError: import urllib.parse as urlparse try: import urllib.parse as urllib_parse except ImportError: import urllib as urllib_parse class DoubanMixin(OAuth2Mixin): _OAUTH_ACCESS_TOKEN_URL = 'https://www.douban.com/service/auth2/token' _OAUTH_AUTHORIZE_URL = 'https://www.douban.com/service/auth2/auth?' def authorize_redirect(self, redirect_uri=None, client_id=None, response_type='code', extra_params=None): args = { 'redirect_uri': redirect_uri, 'client_id': client_id, 'response_type': response_type, } if extra_params: args.update(extra_params) self.redirect(url_concat(self._OAUTH_AUTHORIZE_URL, args)) @_auth_return_future def get_authenticated_user(self, redirect_uri, client_id, client_secret, code, callback, grant_type='authorization_code', extra_fields=None): http = self.get_auth_http_client() args = { 'redirect_uri': redirect_uri, 'code': code, 'client_id': client_id, 'client_secret': client_secret, 'grant_type': grant_type, } fields = set(['id', 'uid', 'name', 'avatar']) if extra_fields: fields.update(extra_fields) http.fetch(self._OAUTH_ACCESS_TOKEN_URL, method="POST", body=urllib_parse.urlencode(args), callback=self.async_callback(self._on_access_token, redirect_uri, client_id, client_secret, callback, fields)) def _oauth_requeset_token_url(self, rediret_uri=None, client_id=None, client_secret=None, code=None, grant_type=None, extra_params=None): pass def _on_access_token(self, redirect_uri, client_id, client_secret, future, fields, response): if response.error: future.set_exception(AuthError('Douban auth error %s' % str(response))) return args = escape.json_decode(escape.native_str(response.body)) session = { 'access_token': args['access_token'], 'expires': args['expires_in'], 'refresh_token': args['refresh_token'], 'douban_user_id': args['douban_user_id'], } self.douban_request( path='/user/~me', callback=self.async_callback( self._on_get_user_info, future, session, fields), access_token=session['access_token'], ) def _on_get_user_info(self, future, session, fields, user): if user is None: future.set_result(None) return fieldmap = {} for field in fields: fieldmap[field] = user.get(field) fieldmap.update({'access_token': session['access_token'], 'session_expires': session['expires']) future.set_result(fieldmap) @_auth_return_future def douban_request(self, path, callback, access_token=None, post_args=None, **args): url = "https://api.douban.com/v2" + path all_args = {} if args: all_args.update(args) callback = self.async_callback(self._on_douban_request, callback) http = self.get_auth_http_client() if post_args is not None: request = httpclient.HTTPRequest(url, method="POST", headers=dict(access_token=access_token), body=urllib_parse.urlencode(post_args)) elif all_args: url += "?" + urllib_parse.urlencode(all_args) request = httpclient.HTTPRequest(url, headers=dict(access_token=access_token)) else: request = httpclient.HTTPRequest(url, headers=dict(access_token=access_token)) http.fetch(request, callback=callback) def _on_douban_request(self, future, response): if response.error: future.set_exception(AuthError('Error response % fetching %s', response.error, response.request.url)) return future.set_result(escape.json_decode(response.body)) def get_auth_http_client(self): return httpclient.AsyncHTTPClient()
Python
0.000001
@@ -3283,16 +3283,17 @@ xpires'%5D +%7D )%0A%0A
19d4d2b8322ee34d07f711c4f2928c76f3366243
Fix for Pagination
flaskext/mongoengine/__init__.py
flaskext/mongoengine/__init__.py
# -*- coding: utf-8 -*- from __future__ import absolute_import import math import mongoengine from mongoengine.queryset import MultipleObjectsReturned, DoesNotExist from mongoengine.queryset import QuerySet as BaseQuerySet from mongoengine import ValidationError from flask import abort def _include_mongoengine(obj): for module in mongoengine, mongoengine.fields: for key in module.__all__: if not hasattr(obj, key): setattr(obj, key, getattr(module, key)) class MongoEngine(object): def __init__(self, app=None): _include_mongoengine(self) self.QuerySet = QuerySet self.BaseQuerySet = BaseQuerySet if app is not None: self.init_app(app) def init_app(self, app): db = app.config['MONGODB_DB'] username = app.config.get('MONGODB_USERNAME', None) password = app.config.get('MONGODB_PASSWORD', None) # more settings e.g. port etc needed self.connection = mongoengine.connect( db=db, username=username, password=password) class QuerySet(BaseQuerySet): def get_or_404(self, *args, **kwargs): try: return self.get(*args, **kwargs) except (MultipleObjectsReturned, DoesNotExist, ValidationError): abort(404) def first_or_404(self): obj = self.first() if obj is None: abort(404) return obj def paginate(self, page, per_page, error_out=True): if error_out and page < 1: abort(404) offset = (page - 1) * per_page items = self[offset:per_page] if not items and page != 1 and error_out: abort(404) return Pagination(self, page, per_page, self.count(), items) class Pagination(object): def __init__(self, queryset, page, per_page, total, items): self.queryset = queryset self.page = page self.total = total self.items = items @property def pages(self): """The total number of pages""" return int(math.ceil(self.total / float(self.per_page))) def prev(self, error_out=False): """Returns a :class:`Pagination` object for the previous page.""" assert self.queryset is not None, 'a query object is required ' \ 'for this method to work' return self.queryset.paginate(self.page - 1, self.per_page, error_out) @property def prev_num(self): """Number of the previous page.""" return self.page - 1 @property def has_prev(self): """True if a previous page exists""" return self.page > 1 def next(self, error_out=False): """Returns a :class:`Pagination` object for the next page.""" assert self.queryset is not None, 'a query object is required ' \ 'for this method to work' return self.queryset.paginate(self.page + 1, self.per_page, error_out) @property def has_next(self): """True if a next page exists.""" return self.page < self.pages @property def next_num(self): """Number of the next page""" return self.page + 1 def iter_pages(self, left_edge=2, left_current=2, right_current=5, right_edge=2): """Iterates over the page numbers in the pagination. The four parameters control the thresholds how many numbers should be produced from the sides. Skipped page numbers are represented as `None`. This is how you could render such a pagination in the templates: .. sourcecode:: html+jinja {% macro render_pagination(pagination, endpoint) %} <div class=pagination> {%- for page in pagination.iter_pages() %} {% if page %} {% if page != pagination.page %} <a href="{{ url_for(endpoint, page=page) }}">{{ page }}</a> {% else %} <strong>{{ page }}</strong> {% endif %} {% else %} <span class=ellipsis>…</span> {% endif %} {%- endfor %} </div> {% endmacro %} """ last = 0 for num in xrange(1, self.pages + 1): if num <= left_edge or \ (num > self.page - left_current - 1 and num < self.page + right_current) or \ num > self.pages - right_edge: if last + 1 != num: yield None yield num last = num
Python
0.000001
@@ -1912,24 +1912,57 @@ page = page%0A + self.per_page = per_page%0A self
7faff0ae9ea4b8d72b42d1af992bb4c72cc745ff
test program to immediately connect and disconnect
test/client_immediate_disconnect.py
test/client_immediate_disconnect.py
Python
0
@@ -0,0 +1,223 @@ +#!/usr/bin/env python%0A%0Aimport socket%0A%0A%0Ahost = socket.gethostname() # Get local machine name%0Aport = 55555 # Reserve a port for your service.%0A%0A%0A%0As = socket.socket()%0As.connect((host, port))%0As.send(%22x%22)%0As.close%0A%0A
5b6667de8b91232facec27bc11305513bb2ec3b3
add demo tests for parameterization
test_parameters.py
test_parameters.py
Python
0
@@ -0,0 +1,1477 @@ +#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0Aimport pytest%0Aimport time%0A%0Afrom selenium import webdriver%0A%0A%0Abrowser = webdriver.Firefox()%0Aemail_addresses = %5B%22invalid_email%22, %22another_invalid_email@%22, %22not_another_invalid_email@blah%22%5D%0Apasswords = %5B%22weak_password%22, %22generic_password%22, %22shitty_password%22%5D%0A%0A%[email protected](%22email%22, email_addresses)%[email protected](%22password%22, passwords)%0Adef test_assert_login_button_enabled(email, password):%0A browser.get(%22https://start.engagespark.com/sign-in/%22)%0A time.sleep(3)%0A browser.find_element_by_name(%22login%22).click()%0A browser.find_element_by_name(%22login%22).send_keys(email)%0A browser.find_element_by_name(%22password%22).click()%0A browser.find_element_by_name(%22password%22).send_keys(password)%0A%0A%[email protected](%22field_name, maxlength%22, %5B%0A (%22login%22, %2275%22),%0A (%22password%22, %22128%22),%0A%5D)%0Adef test_assert_field_maxlength(field_name, maxlength):%0A browser.get(%22https://start.engagespark.com/sign-in/%22)%0A time.sleep(3)%0A browser.find_element_by_name(field_name).get_attribute(%22maxlength%22) == maxlength%0A%0A%[email protected](%22email%22, %5B%0A %[email protected]%22,%0A pytest.mark.xfail(%22blah%22),%0A%5D)%0Adef test_assert_valid_email_entry(email):%0A browser.get(%22https://start.engagespark.com/sign-in/%22)%0A time.sleep(3)%0A browser.find_element_by_name(%22login%22).click()%0A browser.find_element_by_name(%22login%22).send_keys(email)%0A assert %22@%22 in browser.find_element_by_name(%22login%22).get_attribute(%22value%22)%0A
30708957d3a75bd84aa5d26e309d6bae4121c10b
Add --clear-backlog option
flexget/plugins/input/backlog.py
flexget/plugins/input/backlog.py
from __future__ import unicode_literals, division, absolute_import import logging import pickle from datetime import datetime from sqlalchemy import Column, Integer, String, DateTime, PickleType, Index from flexget import db_schema from flexget.entry import Entry from flexget.manager import Session from flexget.plugin import register_plugin, priority from flexget.utils.database import safe_pickle_synonym from flexget.utils.sqlalchemy_utils import table_schema from flexget.utils.tools import parse_timedelta log = logging.getLogger('backlog') Base = db_schema.versioned_base('backlog', 1) @db_schema.upgrade('backlog') def upgrade(ver, session): if ver is None: # Make sure there is no data we can't load in the backlog table backlog_table = table_schema('backlog', session) try: for item in session.query('entry').select_from(backlog_table).all(): pickle.loads(item.entry) except (ImportError, TypeError): # If there were problems, we can drop the data. log.info('Backlog table contains unloadable data, clearing old data.') session.execute(backlog_table.delete()) ver = 0 if ver == 0: backlog_table = table_schema('backlog', session) log.info('Creating index on backlog table.') Index('ix_backlog_feed_expire', backlog_table.c.feed, backlog_table.c.expire).create(bind=session.bind) ver = 1 return ver class BacklogEntry(Base): __tablename__ = 'backlog' id = Column(Integer, primary_key=True) task = Column('feed', String) title = Column(String) expire = Column(DateTime) _entry = Column('entry', PickleType) entry = safe_pickle_synonym('_entry') def __repr__(self): return '<BacklogEntry(title=%s)>' % (self.title) Index('ix_backlog_feed_expire', BacklogEntry.task, BacklogEntry.expire) class InputBacklog(object): """ Keeps task history for given amount of time. Example:: backlog: 4 days Rarely useful for end users, mainly used by other plugins. """ def validator(self): from flexget import validator return validator.factory('interval') @priority(-255) def on_task_input(self, task, config): # Get a list of entries to inject injections = self.get_injections(task) # Take a snapshot of the entries' states after the input event in case we have to store them to backlog for entry in task.entries + injections: entry.take_snapshot('after_input') if config: # If backlog is manually enabled for this task, learn the entries. self.learn_backlog(task, config) # Return the entries from backlog that are not already in the task return injections def on_task_abort(self, task, config): """Remember all entries until next execution when task gets aborted.""" if task.entries: log.debug('Remembering all entries to backlog because of task abort.') self.learn_backlog(task) def add_backlog(self, task, entry, amount=''): """Add single entry to task backlog If :amount: is not specified, entry will only be injected on next execution.""" snapshot = entry.snapshots.get('after_input') if not snapshot: if task.current_phase != 'input': # Not having a snapshot is normal during input phase, don't display a warning log.warning('No input snapshot available for `%s`, using current state' % entry['title']) snapshot = entry session = Session() expire_time = datetime.now() + parse_timedelta(amount) backlog_entry = session.query(BacklogEntry).filter(BacklogEntry.title == entry['title']).\ filter(BacklogEntry.task == task.name).first() if backlog_entry: # If there is already a backlog entry for this, update the expiry time if necessary. if backlog_entry.expire < expire_time: log.debug('Updating expiry time for %s' % entry['title']) backlog_entry.expire = expire_time else: log.debug('Saving %s' % entry['title']) backlog_entry = BacklogEntry() backlog_entry.title = entry['title'] backlog_entry.entry = snapshot backlog_entry.task = task.name backlog_entry.expire = expire_time session.add(backlog_entry) session.commit() def learn_backlog(self, task, amount=''): """Learn current entries into backlog. All task inputs must have been executed.""" for entry in task.entries: self.add_backlog(task, entry, amount) def get_injections(self, task): """Insert missing entries from backlog.""" entries = [] task_backlog = task.session.query(BacklogEntry).filter(BacklogEntry.task == task.name) for backlog_entry in task_backlog.all(): entry = Entry(backlog_entry.entry) # this is already in the task if task.find_entry(title=entry['title'], url=entry['url']): continue log.debug('Restoring %s' % entry['title']) entries.append(entry) if entries: log.verbose('Added %s entries from backlog' % len(entries)) # purge expired for backlog_entry in task_backlog.filter(datetime.now() > BacklogEntry.expire).all(): log.debug('Purging %s' % backlog_entry.title) task.session.delete(backlog_entry) return entries register_plugin(InputBacklog, 'backlog', builtin=True, api_ver=2)
Python
0.000007
@@ -259,16 +259,48 @@ t Entry%0A +from flexget.event import event%0A from fle @@ -370,16 +370,40 @@ _plugin, + register_parser_option, priorit @@ -562,16 +562,25 @@ imedelta +, console %0A%0Alog = @@ -5669,70 +5669,479 @@ es%0A%0A -register_plugin(InputBacklog, 'backlog', builtin=True, api_ver=2 +%0A@event('manager.startup')%0Adef clear_backlog(manager):%0A if not manager.options.clear_backlog:%0A return%0A manager.disable_tasks()%0A session = Session()%0A num = session.query(BacklogEntry).delete()%0A session.close()%0A console('%25s entries cleared from backlog.' %25 num)%0A%0A%0A%0Aregister_plugin(InputBacklog, 'backlog', builtin=True, api_ver=2)%0Aregister_parser_option('--clear-backlog', action='store_true', default=False, help='Remove all items from the backlog.' )%0A
4aecc9be1e2e8074a20606e65db3f9e6283eb8d3
add utils
uhura/exchange/utils.py
uhura/exchange/utils.py
Python
0.000004
@@ -0,0 +1,183 @@ +%22%22%22%0AUtilities and helper functions%0A%22%22%22%0A%0Adef get_object_or_none(model, **kwargs):%0A try:%0A return model.objects.get(**kwargs)%0A except model.DoesNotExist:%0A return None
071aa9f5465847fdda517d1a78c37f1dbfe69f9f
test mock
tests/mock_bank.py
tests/mock_bank.py
Python
0.000002
@@ -0,0 +1,203 @@ +#!/usr/bin/python%0A# -*- encoding: utf-8 -*-%0A%0Aimport sys%0Aimport os.path%0Asys.path.append(os.path.join(os.path.dirname(__file__),'..'))%0Afrom src.bank import Bank%0Afrom mock import MagicMock%0A%0A%0Athing = Bank()%0A
f3182c9651509d2e1009040601c23a78ed3e9b7c
Create laynger.py
laynger.py
laynger.py
Python
0.000001
@@ -0,0 +1,488 @@ +#import sublime%0Aimport sublime_plugin%0A%0A%0Aclass laynger(sublime_plugin.TextCommand):%0A def run(self, edit, opt='center'):%0A window = self.view.window()%0A%0A layout = window.get_layout()%0A%0A if len(layout%5B'cols'%5D) %3E 3:%0A return%0A%0A if opt == u'center':%0A layout%5B'cols'%5D%5B1%5D = 0.5%0A elif opt == u'right':%0A layout%5B'cols'%5D%5B1%5D += 0.01%0A else:%0A layout%5B'cols'%5D%5B1%5D -= 0.01%0A%0A window.run_command('set_layout', layout)%0A
7a64fb0c3093fd23eeed84799c1590a72f59a96c
Create boafiSettings.py
webGUI/boafiSettings.py
webGUI/boafiSettings.py
Python
0.000001
@@ -0,0 +1,1774 @@ +#!/usr/bin/python%0A%0Aimport os,time,argparse%0A%0A%0A%0Aparser = argparse.ArgumentParser()%0A%0A%0Aparser.add_argument('-intf', action='store', dest='intf',default=%22none%22,%0A help='Select interface')%0A%0Aparser.add_argument('-ip', action='store', dest='ip',default=%22none%22,%0A help='Use given ip address')%0A%0Aparser.add_argument('-reboot', action='store', dest='reboot',default=False,%0A help='Reboot the machine')%0A%0Aparser.add_argument('-down', action='store', dest='down',default=%22none%22,%0A help='Shut given interface')%0A%0Aparser.add_argument('-up', action='store', dest='up',default=%22none%22,%0A help='Turn on given interface')%0A%0Aparser.add_argument('-restart', action='store', dest='restart',default=%22none%22,%0A help='Restart given service')%0A%0Aparser.add_argument('-ifstat', action='store', dest='ifstat',default=%22none%22,%0A help='Return bandwith values of given seconds')%0A%0A%0A%0A%0Aresults = parser.parse_args()%0Aip=results.ip%0Aintf=results.intf%0Areboot=results.reboot%0Adown=results.down%0Aup=results.up%0Arestart=results.restart%0Aifstat=results.ifstat%0A%0A%0Aif not(intf==%22none%22):%0A if(ip!=%22none%22):%0A os.popen(%22sudo ifconfig %22+intf+%22 %22+ip)%0A else:%0A print %22no ip!%22%0A%0Aif(reboot):%0A os.popen(%22sudo reboot%22)%0A%0Aif not(up==%22none%22):%0A os.popen(%22sudo ifconfig %22+up+%22 up%22)%0A print %22Up interface%22+up%0A%0Aif not(down==%22none%22):%0A os.popen(%22sudo ifconfig %22+down+%22 down%22)%0A print %22Up interface%22+down%0A%0A%0Aif not(restart==%22none%22):%0A os.popen(%22sudo service %22+restart+%22 restart%22)%0A print %22Restarted %22+restart%0A%0Aif not(ifstat==%22none%22):%0A secs=ifstat%0A stats=os.popen(%22timeout %22+secs+%22s ifstat -t -q 0.5%22).read()%0A print stats%0A
fdd2a50445d2f2cb92480f8f42c463b312411361
Add a simple command to print all areas in all generations
mapit/management/commands/mapit_print_areas.py
mapit/management/commands/mapit_print_areas.py
Python
0.000003
@@ -0,0 +1,763 @@ +# For each generation, show every area, grouped by type%0A%0Afrom django.core.management.base import NoArgsCommand%0Afrom mapit.models import Area, Generation, Type, NameType, Country, CodeType%0A%0Aclass Command(NoArgsCommand):%0A help = 'Show all areas by generation and area type'%0A def handle_noargs(self, **options):%0A for g in Generation.objects.all().order_by('id'):%0A print g%0A for t in Type.objects.all().order_by('code'):%0A qs = Area.objects.filter(type=t,%0A generation_high__gte=g,%0A generation_low__lte=g)%0A print %22 %25s (number of areas: %25d)%22 %25 (t, qs.count())%0A for a in qs:%0A print %22 %22, a%0A
9dee7d8d253847758d3252401c01215f972a22b1
Add synthtool scripts (#3765)
google-cloud-monitoring/synth.py
google-cloud-monitoring/synth.py
Python
0.000001
@@ -0,0 +1,1234 @@ +# Copyright 2018 Google LLC%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%22%22%22This script is used to synthesize generated parts of this library.%22%22%22%0A%0Aimport synthtool as s%0Aimport synthtool.gcp as gcp%0A%0Agapic = gcp.GAPICGenerator()%0Acommon_templates = gcp.CommonTemplates()%0A%0Alibrary = gapic.java_library(%0A service='monitoring',%0A version='v3',%0A config_path='/google/monitoring/artman_monitoring.yaml',%0A artman_output_name='')%0A%0As.copy(library / 'gapic-google-cloud-monitoring-v3/src', 'src')%0As.copy(library / 'grpc-google-cloud-monitoring-v3/src', '../../google-api-grpc/grpc-google-cloud-monitoring-v3/src')%0As.copy(library / 'proto-google-cloud-monitoring-v3/src', '../../google-api-grpc/proto-google-cloud-monitoring-v3/src')%0A
92ccb08f72828ba6454bbc3ff162ec73534ceea2
Interview question: find exact sum of two numbers
python/interviewquestions/find_exact_sum.py
python/interviewquestions/find_exact_sum.py
Python
0.99999
@@ -0,0 +1,2497 @@ +%22%22%22%0AYou've built an in-flight entertainment system with on-demand movie streaming.%0AUsers on longer flights like to start a second movie right when their first one%0Aends, but they complain that the plane usually lands before they can see the%0Aending. So you're building a feature for choosing two movies whose total%0Aruntimes will equal the exact flight length.%0A%0AWrite a function that takes an integer flight_length (in minutes) and a list%0Aof integers movie_lengths (in minutes) and returns a boolean indicating%0Awhether there are two numbers in movie_lengths whose sum equals flight_length.%0A%0AWhen building your function:%0A%0A Assume your users will watch exactly two movies%0A Don't make your users watch the same movie twice%0A Optimize for runtime over memory%0A%22%22%22%0A%0A%22%22%22%0AWe can reword this problem as finding the two numbers in the given list whose%0Asum is exactly flight_length.%0A%22%22%22%0A%0Aimport unittest%0A%0A%0Adef has_valid_movies_combo(l, flight_length):%0A # we want to know if there are two items a, b in l such as:%0A # a + b = flight_length%0A # Given that:%0A # b = flight_length - a%0A # We prebuild a new list of (flight_length - a) items so all we have to do%0A # is iterate again over the list and test that it contains b.%0A # (We need a dict that also stores the idx of the item so that we can make%0A # sure that the user won't see the same movie twice. Currently we assume%0A # that the length of the movies is unique, as not assuming that would%0A # introduce unnecessary complications (the dict must be a dict of lists)).%0A sub = dict(%5B(flight_length - item, idx) for idx, item in enumerate(l)%5D)%0A for idx, item in enumerate(l):%0A if item in sub and sub%5Bitem%5D != idx:%0A return True%0A return False%0A%0A%0Aclass TestZeroSum(unittest.TestCase):%0A def test_true(self):%0A l = %5B30, 40, 50, 60, 70%5D%0A self.assertTrue(has_valid_movies_combo(l, 80))%0A self.assertTrue(has_valid_movies_combo(l, 100))%0A self.assertTrue(has_valid_movies_combo(l, 130))%0A self.assertTrue(has_valid_movies_combo(l, 90))%0A%0A def test_false(self):%0A l = %5B30, 40, 50, 60, 70%5D%0A self.assertFalse(has_valid_movies_combo(l, 10))%0A self.assertFalse(has_valid_movies_combo(l, 30))%0A self.assertFalse(has_valid_movies_combo(l, 40))%0A self.assertFalse(has_valid_movies_combo(l, 14))%0A%0A def test_same_movie(self):%0A l = %5B30, 40%5D%0A self.assertFalse(has_valid_movies_combo(l, 60))%0A%0A%0Aif __name__ == %22__main__%22:%0A unittest.main()%0A
92f799d0584b598f368df44201446531dffd7d13
Copy paste artist from filename1 to filename2
python/utilities/transform_mp3_filenames.py
python/utilities/transform_mp3_filenames.py
Python
0
@@ -0,0 +1,1581 @@ +# Extract the artist name from songs with filenames in this format:%0D%0A# (number) - (artist) - (title).mp3%0D%0A# and add the artists name to songs with filenames in this format:%0D%0A# (number)..(title).mp3%0D%0A# to make filenames in this format:%0D%0A# (number)..(artist)..(title).mp3%0D%0A#%0D%0A# eg.: 14 - 13th Floor Elevators - You're Gonna Miss Me.mp3%0D%0A# + 14..You're Gonna Miss Me.mp3%0D%0A# =%3E 14..13th Floor Elevators..You're Gonna Miss Me.mp3%0D%0A#%0D%0A# Copyright 2017 Dave Cuthbert%0D%0A# MIT License%0D%0A%0D%0Afrom __future__ import print_function #Not needed with python3%0D%0A%0D%0Aimport os as os%0D%0Aimport re as re%0D%0A%0D%0ATARGET_DIR = r%22/insert/target/path%22%0D%0A%0D%0Adef extract_artist(title):%0D%0A artist_regex = re.compile(' - (.*?) - ') %0D%0A artist = artist_regex.search(title)%0D%0A return artist.group(1)%0D%0A %0D%0Adef get_song_list():%0D%0A song_list = os.listdir(os.getcwd())%0D%0A return song_list%0D%0A%0D%0Adef get_artists():%0D%0A song_list = get_song_list()%0D%0A artists = %5B%5D%0D%0A for song in song_list:%0D%0A artists.append(extract_artist(song))%0D%0A return artists%0D%0A %0D%0Adef insert_artist_name():%0D%0A artist_names = get_artists()%0D%0A old_filenames = os.listdir(TARGET_DIR)%0D%0A new_filenames = %5B%5D%0D%0A for (old_filename, artist) in zip(old_filenames, artist_names):%0D%0A new_filename = re.sub('%5C.%5C.', '..' + artist + '..', old_filename)%0D%0A os.rename(os.path.join(TARGET_DIR, old_filename), %0D%0A os.path.join(TARGET_DIR, new_filename)) %0D%0A %0D%0A %0D%0A %0D%0Aif %22__main__%22 == __name__:%0D%0A #print(*get_artists(), sep='%5Cn') #DEBUG%0D%0A insert_artist_name()
ec0ee6ffc7b72ba50846bac60ec63e1188bf0481
test parser
parser.py
parser.py
Python
0.000028
@@ -0,0 +1,870 @@ +#!/usr/bin/python3%0Aimport requests%0Aimport sys%0Afrom bs4 import BeautifulSoup%0A%0A#filters through text from soup and strips text of whitespace%0Adef filterText(text):%0A if text.parent.name in %5B'style', 'script', '%5Bdocument%5D', 'head', 'title'%5D:%0A return False%0A if text in %5B'%5Cn', ' ', '%5Cr', '%5Ct'%5D:%0A return False%0A return True%0A%0A#prints out url with all text from url on one line%0Adef textParser(url):%0A print (url, end='')%0A webPage = requests.get(url)%0A #format html and only print text from webpage:%0A soup = BeautifulSoup(webPage.content, %22lxml%22)%0A allText = soup.findAll(text=True)%0A #print (allText%5B432%5D)%0A for i in allText:%0A if filterText(i):%0A print (i.replace('%5Cn',' '), end='')%0A%0Adef main():%0A defaultURLS = %22http://en.wikipedia.org/wiki/Web_crawler%22%0A textParser(defaultURLS)%0A%0Aif __name__ == %22__main__%22:%0A main()%0A%0A
58e0ea4b555cf89ace4f5d97c579dbba905e7eeb
Add script to list objects
jsk_arc2017_common/scripts/list_objects.py
jsk_arc2017_common/scripts/list_objects.py
Python
0.000001
@@ -0,0 +1,376 @@ +#!/usr/bin/env python%0A%0Aimport os.path as osp%0A%0Aimport rospkg%0A%0A%0APKG_PATH = rospkg.RosPack().get_path('jsk_arc2017_common')%0A%0Aobject_names = %5B'__background__'%5D%0Awith open(osp.join(PKG_PATH, 'data/names/objects.txt')) as f:%0A object_names += %5Bx.strip() for x in f%5D%0Aobject_names.append('__shelf__')%0A%0Afor obj_id, obj in enumerate(object_names):%0A print('%252d: %25s' %25 (obj_id, obj))%0A
04feafc2b3a13b394d5b510e9bc48e542d4880c5
Create pfkill.py
pfkill.py
pfkill.py
Python
0.000001
@@ -0,0 +1,609 @@ +%22%22%22%0Ahow to it use:%0A$ python pfkill %3Cport number%3E%0A%0Awhat doing:%0A1. read %3Cport number%3E.pid file%0A2. send signal to running app%0A3. delete %3Cport number%3E.rule%0A4. delete %3Cport number%3E.pid%0A%22%22%22%0A%0Aimport os%0Aimport sys%0Aimport signal%0A# import logging%0A%0Aport = sys.argv%5B1%5D%0A%0A# read %3Cport%3E.pid%0Apid = int(open(%22%25s.pid%22 %25 port, 'r').read().split('%5Cn')%5B0%5D)%0A%0A# print pid%0A%0A# kill app by pid%0A# signal.SIGQUIT or signal.SIGKILL%0Atry:%0A os.kill(pid, signal.SIGQUIT)%0Aexcept OSError, e:%0A print e%0A # logging.INFO(%22ee%22)%0A%0A# delete %3Cport%3E.rule%0Aos.unlink(%22%25s.rule%22 %25 port)%0A%0A# delete %3Cport%3E.pid%0Aos.unlink(%22%25s.pid%22 %25 port)%0A%0A# todo: exit%0A
e988a10ea18b644b9bc319286d75cb2a15079c59
add case owners endpoint
corehq/apps/reports/v2/endpoints/case_owner.py
corehq/apps/reports/v2/endpoints/case_owner.py
Python
0
@@ -0,0 +1,824 @@ +from __future__ import absolute_import%0Afrom __future__ import unicode_literals%0A%0Afrom corehq.apps.reports.filters.controllers import (%0A CaseListFilterOptionsController,%0A)%0Afrom corehq.apps.reports.v2.models import BaseOptionsEndpoint%0A%0A%0Aclass CaseOwnerEndpoint(BaseOptionsEndpoint):%0A slug = %22case_owner%22%0A%0A @property%0A def search(self):%0A return self.data.get('search', '')%0A%0A @property%0A def page(self):%0A return self.data.get('page', 1)%0A%0A def get_response(self):%0A options_controller = CaseListFilterOptionsController(%0A self.request, self.domain, self.search%0A )%0A has_more, results = options_controller.get_options(show_more=True)%0A return %7B%0A 'results': results,%0A 'pagination': %7B%0A 'more': has_more,%0A %7D%0A %7D%0A
458091fe923038fe8537bf3b9efbff6157a7e57a
add tests for riakcached.clients.ThreadedRiakClient
riakcached/tests/test_threadedriakclient.py
riakcached/tests/test_threadedriakclient.py
Python
0
@@ -0,0 +1,2503 @@ +import mock%0Aimport unittest2%0A%0Afrom riakcached.clients import ThreadedRiakClient%0Aimport riakcached.pools%0A%0A%0Aclass TestThreadedRiakClient(unittest2.TestCase):%0A def test_get_many(self):%0A pool = mock.Mock(spec=riakcached.pools.Pool)%0A pool.request.return_value = 200, %22result%22, %7B%22content-type%22: %22text/plain%22%7D%0A pool.url = %22http://127.0.0.1:8098%22%0A%0A client = ThreadedRiakClient(%22test_bucket%22, pool=pool)%0A results = client.get_many(%5B%22test1%22, %22test2%22%5D)%0A self.assertEqual(results, %7B%0A %22test1%22: %22result%22,%0A %22test2%22: %22result%22,%0A %7D)%0A self.assertEqual(2, pool.request.call_count)%0A pool.request.assert_any_call(%0A method=%22GET%22,%0A url=%22http://127.0.0.1:8098/buckets/test_bucket/keys/test1%22,%0A )%0A pool.request.assert_any_call(%0A method=%22GET%22,%0A url=%22http://127.0.0.1:8098/buckets/test_bucket/keys/test2%22,%0A )%0A%0A def test_set_many(self):%0A pool = mock.Mock(spec=riakcached.pools.Pool)%0A pool.request.return_value = 200, %22%22, %7B%22content-type%22: %22text/plain%22%7D%0A pool.url = %22http://127.0.0.1:8098%22%0A%0A client = ThreadedRiakClient(%22test_bucket%22, pool=pool)%0A client.set_many(%7B%0A %22test1%22: %22value1%22,%0A %22test2%22: %22value2%22,%0A %7D)%0A self.assertEqual(2, pool.request.call_count)%0A pool.request.assert_any_call(%0A method=%22POST%22,%0A url=%22http://127.0.0.1:8098/buckets/test_bucket/keys/test1%22,%0A body=%22value1%22,%0A headers=%7B%0A %22Content-Type%22: %22text/plain%22,%0A %7D,%0A )%0A pool.request.assert_any_call(%0A method=%22POST%22,%0A url=%22http://127.0.0.1:8098/buckets/test_bucket/keys/test2%22,%0A body=%22value2%22,%0A headers=%7B%0A %22Content-Type%22: %22text/plain%22,%0A %7D,%0A )%0A%0A def test_delete_many(self):%0A pool = mock.Mock(spec=riakcached.pools.Pool)%0A pool.request.return_value = 204, %22%22, %7B%7D%0A pool.url = %22http://127.0.0.1:8098%22%0A%0A client = ThreadedRiakClient(%22test_bucket%22, pool=pool)%0A client.delete_many(%5B%22test1%22, %22test2%22%5D)%0A self.assertEqual(2, pool.request.call_count)%0A pool.request.assert_any_call(%0A method=%22DELETE%22,%0A url=%22http://127.0.0.1:8098/buckets/test_bucket/keys/test1%22,%0A )%0A pool.request.assert_any_call(%0A method=%22DELETE%22,%0A url=%22http://127.0.0.1:8098/buckets/test_bucket/keys/test2%22,%0A )%0A
a91a942c45921b64fe0d740d81604dba921c214e
Create folder for QC and CNV cutoff codes
bin/cutoffs/__init__.py
bin/cutoffs/__init__.py
Python
0
@@ -0,0 +1 @@ +%0A
e40b92966762dfadff53355e9e38636a4769543f
Add intermediate tower 2
pythonwarrior/towers/intermediate/level_002.py
pythonwarrior/towers/intermediate/level_002.py
Python
0.999719
@@ -0,0 +1,939 @@ +# ----%0A# %7C@s %7C%0A# %7C sS%3E%7C%0A# ----%0A%0Alevel.description(%22Another large room, but with several enemies %22%0A %22blocking your way to the stairs.%22)%0Alevel.tip(%22Just like walking, you can attack_ and feel in multiple %22%0A %22directions ('forward', 'left', 'right', 'backward').%22)%0Alevel.clue(%22Call warrior.feel(direction).is_enemy() in each direction %22%0A %22to make sure there isn't an enemy beside you %22%0A %22(attack if there is). %22%0A %22Call warrior.rest_ if you're low and health when there %22%0A %22are no enemies around.%22)%0Alevel.time_bonus(40)%0Alevel.ace_score(84)%0Alevel.size(4, 2)%0Alevel.stairs(3, 1)%0A%0Adef add_abilities(warrior):%0A warrior.add_abilities('attack_')%0A warrior.add_abilities('health')%0A warrior.add_abilities('rest_')%0A%0Alevel.warrior(0, 0, 'east', func=add_abilities)%0A%0Alevel.unit('sludge', 1, 0, 'west')%0Alevel.unit('thick_sludge', 2, 1, 'west')%0Alevel.unit('sludge', 1, 1, 'north')%0A
71d66fb3bdbcb38d29accb6bdfbf4ac8b2996e89
Add intermediate tower 3
pythonwarrior/towers/intermediate/level_003.py
pythonwarrior/towers/intermediate/level_003.py
Python
0.999787
@@ -0,0 +1,721 @@ +# ---%0A# %7C%3Es %7C%0A# %7Cs@s%7C%0A# %7C C %7C%0A# ---%0A%0Alevel.description(%22You feel slime on all sides, you're surrounded!%22)%0Alevel.tip(%22Call warrior.bind_(direction) to bind an enemy to keep him %22%0A %22from attacking. Bound enemies look like captives.%22)%0Alevel.clue(%22Count the number of enemies around you. Bind an enemy if %22%0A %22there are two or more.%22)%0Alevel.time_bonus(50)%0Alevel.ace_score(101)%0Alevel.size(3, 3)%0Alevel.stairs(0, 0)%0A%0Adef add_abilities(warrior):%0A warrior.add_abilities('bind_')%0A warrior.add_abilities('rescue_')%0A%0Alevel.warrior(1, 1, 'east', func=add_abilities)%0A%0Alevel.unit('sludge', 1, 0, 'west')%0Alevel.unit('captive', 1, 2, 'west')%0Alevel.unit('sludge', 0, 1, 'west')%0Alevel.unit('sludge', 2, 1, 'west')%0A
260cb76132bfe618b58cf34ad8dd61f59e847f90
create table
zaifbot/models/nonce.py
zaifbot/models/nonce.py
Python
0.00008
@@ -0,0 +1,493 @@ +from sqlalchemy import Column, Integer, String, DateTime%0Afrom datetime import datetime%0Afrom zaifbot.models import Base%0A%0A%0Aclass Nonce(Base):%0A __tablename__ = 'nonces'%0A id = Column(Integer, primary_key=True)%0A key = Column(String, nullable=False)%0A secret = Column(String, nullable=False)%0A nonce = Column(Integer, default=0, nullable=False)%0A created_at = Column(DateTime, default=datetime.now())%0A updated_at = Column(DateTime, default=datetime.now(), onupdate=datetime.now())%0A
a72567202e9b4024758706c00f016153ec04a53d
Create render.py
render.py
render.py
Python
0.000001
@@ -0,0 +1,566 @@ +#! /usr/bin/python3%0Afrom random import random%0A %0Aimport pyglet%0Afrom pyglet.window import key, Window%0Afrom pyglet.gl import *%0Afrom pyglet.gl.glu import *%0A%0A%0Awindow = Window()%0A%0A%[email protected]%0Adef on_draw():%0A pass # TODO: implement!%0A%[email protected]%0Adef on_resize(width, height):%0A pass # TODO: implement!%0A%[email protected]%0Adef on_key_press(symbol, modifiers):%0A if symbol == key.LEFT:%0A update_frame(-1)%0A elif symbol == key.RIGHT:%0A update_frame(1)%0A %0A%0Aif __name__==%22__main__%22:%0A pyglet.clock.schedule_interval(update_frame, 0.02)%0A pyglet.app.run()%0A
77dca533f2d2fe94b233bd48561e1ed887928265
add sample.py
sample.py
sample.py
Python
0.000001
@@ -0,0 +1,477 @@ +#-*- coding: UTF-8 -*-%0A# https://github.com/carpedm20/LINE%0A%0Afrom line import LineClient, LineGroup, LineContact%0A%0Af = open(%22credentials%22)%0AID = f.readline().strip()%0APASSWD = f.readline().strip()%0Af.close()%0A%0Aclient = LineClient(ID, PASSWD, com_name=%22line_api_demo%22)%0Afriends = client.contacts%0A%0A%0Afor i, friend in enumerate(friends):%0A%09print i, friend%0A%0A#for i, group in enumerate(groups):%0A#%09print i, group%0A%0Afriend = client.contacts%5B429%5D%0Afriend.sendMessage(%22hello world! %E6%9C%AC%E8%A8%8A%E6%81%AF%E7%94%B1%E6%A9%9F%E5%99%A8%E4%BA%BA%E5%AF%84%E9%80%81 XD%22)%0A
cf3ed974c97d6eaa7983b249a65b4e6df4309c28
Rename owners to instances
nycodex/db.py
nycodex/db.py
from enum import Enum import os import typing import sqlalchemy from sqlalchemy.dialects import postgresql from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() engine = sqlalchemy.create_engine(os.environ["DATABASE_URI"]) Session = sqlalchemy.orm.sessionmaker(bind=engine) class DomainCategory(Enum): BIGAPPS = "NYC BigApps" BUSINESS = "Business" CITY_GOVERNMENT = "City Government" EDUCATION = "Education" ENVIRONMENT = "Environment" HEALTH = "Health" HOUSING_DEVELOPMENT = "Housing & Development" PUBLIC_SAFETY = "Public Safety" RECREATION = "Recreation" SOCIAL_SERVICES = "Social Services" TRANSPORTATION = "Transportation" class DbMixin(): @classmethod def upsert(cls, conn: sqlalchemy.engine.base.Connection, owners: typing.Iterable["Owner"]) -> None: keys = cls.__table__.c.keys() for owner in owners: data = {key: getattr(owner, key) for key in keys} insert = (postgresql.insert(cls.__table__).values(**data) .on_conflict_do_update( index_elements=[cls.__table__.c.id], set_={k: data[k] for k in data if k != 'id'})) conn.execute(insert) def __eq__(self, other): keys = self.__table__.c.keys() return ({key: getattr(self, key) for key in keys} == { key: getattr(other, key) for key in keys }) class Dataset(Base, DbMixin): __tablename__ = "dataset" id = sqlalchemy.Column(sqlalchemy.CHAR(9), primary_key=True) name = sqlalchemy.Column(sqlalchemy.VARCHAR, nullable=False) description = sqlalchemy.Column(sqlalchemy.TEXT, nullable=False) owner_id = sqlalchemy.Column( sqlalchemy.CHAR(9), sqlalchemy.ForeignKey("owner.id")) domain_category = sqlalchemy.Column( postgresql.ENUM( * [v.value for v in DomainCategory.__members__.values()], name="DomainCategory"), nullable=True) class Owner(Base, DbMixin): __tablename__ = "owner" id = sqlalchemy.Column(sqlalchemy.CHAR(9), primary_key=True) name = sqlalchemy.Column(sqlalchemy.TEXT, nullable=False)
Python
0.000082
@@ -183,16 +183,37 @@ e_base() + # type: typing.Any %0A%0Aengine @@ -738,16 +738,49 @@ ixin():%0A + __table__: sqlalchemy.Table%0A%0A @cla @@ -864,21 +864,24 @@ -owner +instance s: typin @@ -892,21 +892,23 @@ erable%5B%22 -Owner +DbMixin %22%5D) -%3E N @@ -966,22 +966,28 @@ for -owner in owner +instance in instance s:%0A @@ -1018,21 +1018,24 @@ getattr( -owner +instance , key) f
db195957288ef7b6c5c9de6551689d4d06db28c1
Create add_digits.py
lintcode/naive/add_digits/py/add_digits.py
lintcode/naive/add_digits/py/add_digits.py
Python
0.000094
@@ -0,0 +1,238 @@ +class Solution:%0A # @param %7Bint%7D num a non-negative integer%0A # @return %7Bint%7D one digit%0A def addDigits(self, num):%0A %0A while len(str(num)) %3E 1:%0A num = sum(map(int, str(num)))%0A %0A return num%0A
836845abde53ee55bca93f098ece78880ab6b5c6
Use same variable names as testing environment
examples/events/create_massive_dummy_events.py
examples/events/create_massive_dummy_events.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from pymisp import PyMISP from keys import misp_url, misp_key, misp_verifycert import argparse import tools def init(url, key): return PyMISP(url, key, misp_verifycert, 'json') if __name__ == '__main__': parser = argparse.ArgumentParser(description='Create a given number of event containing a given number of attributes eachh.') parser.add_argument("-l", "--limit", type=int, help="Number of events to create (default 1)") parser.add_argument("-a", "--attribute", type=int, help="Number of attributes per event (default 3000)") args = parser.parse_args() misp = init(misp_url, misp_key) if args.limit is None: args.limit = 1 if args.attribute is None: args.attribute = 3000 for i in range(args.limit): tools.create_massive_dummy_events(misp, args.attribute)
Python
0.000016
@@ -87,146 +87,46 @@ ort -misp_url, misp_key, misp_verifycert%0Aimport argparse%0Aimport tools%0A%0Adef init(url, key):%0A return PyMISP(url, key, misp_verifycert, 'json') +url, key%0Aimport argparse%0Aimport tools%0A %0A%0Aif @@ -534,31 +534,37 @@ p = -init(misp_url, misp_key +PyMISP(url, key, True, 'json' )%0A%0A
2d12c640e42e83580ee27933f0ad9bed2ebcc169
add allauth and make owner of audio required
satsound/migrations/0007_auto_20170115_0331.py
satsound/migrations/0007_auto_20170115_0331.py
Python
0
@@ -0,0 +1,583 @@ +# -*- coding: utf-8 -*-%0A# Generated by Django 1.10.4 on 2017-01-15 03:31%0Afrom __future__ import unicode_literals%0A%0Aimport django.db.models.deletion%0Afrom django.conf import settings%0Afrom django.db import migrations, models%0A%0A%0Aclass Migration(migrations.Migration):%0A dependencies = %5B%0A ('satsound', '0006_auto_20161230_0403'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterField(%0A model_name='satelliteaudio',%0A name='user',%0A field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),%0A ),%0A %5D%0A
a635a8d58e46cf4ef1bc225f8824d73984971fee
Add the answer to the sixth question of Assignment 3
countVowels.py
countVowels.py
Python
0.999999
@@ -0,0 +1,1443 @@ +%22%22%22 Q6- Write a program that counts up the number of vowels contained in the string s. Valid vowels are: 'a', 'e', 'i',%0A'o', and 'u'. For example, if s = 'azcbobobegghakl', your program should print: Number of vowels: 5%0A%22%22%22%0A%0A# Using the isVowel function from isVowel.py module (Answer of fifth question of Assignment 3)%0Adef isVowel( char ):%0A%0A%09# Converting the letter to lowercase for our convenience and hence, we do not need to check character's case and hence, simplifies the problem%0A%09# str.lower( char ) %0A%09# The above function has been commented out since this is not required in this problem.. But, the above built-in function might be useful in normal cases.%0A%0A%09# Splitting the condition: 'a' or 'e' or 'i' or 'o' or 'u' to make it more readable and easier to understand. %0A%09%0A%09is_char_a = char == 'a'%0A%09is_char_e = char == 'e'%0A%09is_char_i = char == 'i'%0A%09is_char_o = char == 'o'%0A%09is_char_u = char == 'u'%0A%0A%09is_char_vowel = is_char_a or is_char_e or is_char_i or is_char_o or is_char_u %0A%09%0A%09return is_char_vowel%0A%0A%0Adef countVowels( string ):%0A%0A%09if str.islower( string ):%0A%0A%09%09count = 0 # Counts the number of vowels%0A%09%09for letter in string:%0A%0A%09%09%09if isVowel( letter ):%0A%09%09%09%09count += 1%0A%09%09%0A%09%09print( %22Number of vowels: %22 + str( count ) )%0A%09else:%0A%0A%09%09if len( string ):%0A%09%09%09print( %22Error: All the characters in the string should be in LOWERCASE.%22 )%0A%09%09else:%0A%09%09%09print( %22Error: The string is EMPTY.%22 )%0A%0Astring = input( %22Enter the string: %22 )%0AcountVowels( string )
58fabd7929a4c712f5e87a39aaf8c34bae8759b8
Add photos to the admin
quickphotos/admin.py
quickphotos/admin.py
Python
0
@@ -0,0 +1,512 @@ +from django.contrib import admin%0A%0Afrom .models import Photo%0A%0A%[email protected](Photo)%0Aclass PhotoAdmin(admin.ModelAdmin):%0A list_display = ('user', 'caption', 'created')%0A list_filter = ('created',)%0A date_hierarchy = 'created'%0A readonly_fields = (%0A 'photo_id', 'user', 'image', 'created', 'caption', 'link', 'like_count', 'comment_count')%0A fieldsets = (%0A (None, %7B%0A 'fields': readonly_fields,%0A %7D),%0A )%0A%0A def has_add_permission(self, request):%0A return False%0A
f7035a6c328bb237dd3c9be5d9da805606e059ae
Create adjust_xml_impath.py
object_detection/adjust_xml_impath.py
object_detection/adjust_xml_impath.py
Python
0.000004
@@ -0,0 +1,990 @@ +import os%0Aimport glob%0Aimport re%0Aimport argparse%0A%0Aap = argparse.ArgumentParser()%0Aap.add_argument('-i', '--input_xml_dir', type=str, default='./annot', help='path to root dir of xmls')%0Aap.add_argument('-s', '--subfolder', type=str, default='images', help='name of image subfolder')%0Aargs = vars(ap.parse_args())%0A%0Axmls = glob.glob(os.path.join(args%5B'input_xml_dir'%5D, '*xml'))%0Aprint('found %25d xmls.' %25 len(xmls))%0Asubfolder = args%5B'subfolder'%5D if not args%5B'subfolder'%5D.endswith('/') else args%5B'subfolder'%5D%5B:-1%5D%0Aprint('image sub folder:', subfolder)%0A%0Apattern1 = r'%3Cfilename%3E(.*?)%3C/filename%3E'%0Apattern2 = r'%3Cfolder%3E.*?%3C/folder%3E'%0Apattern3 = r'%3Cpath%3E.*?%3C/path%3E'%0Afor xml in xmls:%0A with open(xml, 'r') as fin:%0A s = fin.read()%0A filename = re.findall(pattern1, s)%5B0%5D%0A s = re.sub(pattern2, '%3Cfolder%3E%25s%3C/folder%3E' %25 args%5B'subfolder'%5D, s)%0A s = re.sub(pattern3, '%3Cpath%3E%25s/%25s/%25s%3C/path%3E' %25 (os.getcwd(), args%5B'subfolder'%5D, filename), s)%0A with open(xml, 'wb') as fout:%0A fout.write(s)%0A
0266a6cec641f244a8788f50f80ac3f11f87e1e4
Add back fix_root script
scripts/fix_root.py
scripts/fix_root.py
Python
0.000001
@@ -0,0 +1,845 @@ +import sys%0Aimport logging%0Afrom website.app import setup_django%0Asetup_django()%0Afrom scripts import utils as script_utils%0Afrom osf.models import AbstractNode%0Afrom framework.database import paginated%0A%0Alogger = logging.getLogger(__name__)%0A%0Adef main(dry=True):%0A count = 0%0A for node in paginated(AbstractNode, increment=1000):%0A true_root = node.get_root()%0A if not node.root or node.root.id != true_root.id:%0A count += 1%0A logger.info('Setting root for node %7B%7D to %7B%7D'.format(node._id, true_root._id))%0A if not dry:%0A AbstractNode.objects.filter(id=node.id).update(root=true_root)%0A logger.info('Finished migrating %7B%7D nodes'.format(count))%0A%0Aif __name__ == '__main__':%0A dry = '--dry' in sys.argv%0A if not dry:%0A script_utils.add_file_logger(logger, __file__)%0A main(dry=dry)%0A
8578320e023dc3424da055c4a506931ec44b19ce
Save user's name to db when verifying AGA id
web/app/verify/views.py
web/app/verify/views.py
from . import verify from .aga_membership import get_aga_info from flask import abort, redirect, url_for, render_template, current_app from flask.ext.security import login_required from flask.ext.login import current_user from flask.ext.wtf import Form from flask.ext.mail import Message from sqlalchemy.sql import and_ from itsdangerous import BadSignature, URLSafeSerializer from app.models import User, db from wtforms import IntegerField, SubmitField from wtforms.validators import Required def get_serializer(secret_key=None): if secret_key is None: secret_key = current_app.config['SECRET_KEY'] return URLSafeSerializer(secret_key) @verify.route('/verify/<payload>') @login_required def verify_player(payload): s = get_serializer() try: user_id, aga_id = s.loads(payload) except BadSignature: current_app.logger.info('Verify called with invalid paylod') abort(404) if user_id != current_user.id: current_app.logger.warn("Verify called for id %s, but wrong user answered, %s" % (user_id, current_user)) abort(404) # TODO: Fetch the fake user account with this aga_id, take its AGA player # and reassign it to the real user user = User.query.get_or_404(user_id) user.aga_id = aga_id db.session.add(user) db.session.commit() msg = 'Linked account with AGA #%s' % user.aga_id current_app.logger.info(msg) return redirect(url_for('ratings.profile')) def get_verify_link(user, aga_id): s = get_serializer() payload = s.dumps([user.id, aga_id]) return url_for('.verify_player', payload=payload, _external=True) def aga_id_already_used(user, aga_id): exists = User.query.filter(and_(User.id!=user.id, User.aga_id==str(aga_id), User.fake==False)).count() > 0 return exists def send_verify_email(user, aga_id): aga_info = get_aga_info(aga_id) if aga_info is None: return False email_address = aga_info['email'] email_subject = "Confirm AGA ID for Online Ratings" email_body = render_template('verify/verification_email.html', user=user, aga_id=aga_id, verify_link=get_verify_link(user, aga_id)) email = Message( recipients=[email_address], subject=email_subject, html=email_body, ) current_app.extensions.get('mail').send(email) return True @verify.route('/verify', methods=['GET', 'POST']) @login_required def verify_form(): form = LinkUserWithAGANumberForm() if form.validate_on_submit(): aga_id = form.aga_id.data if aga_id_already_used(current_user, aga_id): return render_template('verify/verify_form_post_submit_conflict.html', aga_id=aga_id) success = send_verify_email(current_user, aga_id) if success: return render_template('verify/verify_form_post_submit.html') else: return render_template('verify/verify_form_post_submit_error.html', aga_id=aga_id) return render_template('verify/verifyform.html', form=form) class LinkUserWithAGANumberForm(Form): aga_id = IntegerField('Aga number?', validators=[Required()]) submit = SubmitField()
Python
0
@@ -1087,24 +1087,238 @@ abort(404)%0A%0A + aga_info = get_aga_info(aga_id)%0A if aga_info is None:%0A current_app.logger.warn(%22Could not fetch AGA info for aga_id %25s%22 %25 aga_id)%0A abort(404)%0A user_realname = aga_info.get('full_name', '')%0A%0A # TODO: @@ -1485,24 +1485,54 @@ id = aga_id%0A + user.name = user_realname%0A db.sessi
ac3a3b583b028e53d80749eaaee58b4eb80d1c6a
Implement stack functionality
stack/stack.py
stack/stack.py
Python
0.000002
@@ -0,0 +1,732 @@ +%0Aclass Node(object):%0A def __init__(self, value=None, next_node=None):%0A self.value = value%0A self.next_node = next_node%0A%0A%0Aclass Stack(object):%0A def __init__(self, head=None):%0A self.head = head%0A%0A def push(self, data):%0A self.head = Node(data, self.head)%0A%0A def pop(self):%0A if self.head:%0A retval = self.head.value%0A self.head = self.head.next_node%0A return retval%0A raise LookupError%0A%0A def write_output(self):%0A output = ''%0A count = 1%0A while self.head:%0A if count %25 2 != 0:%0A output += str(self.pop()) + ' '%0A else:%0A self.pop()%0A count += 1%0A return output.rstrip()%0A
a6137714c55ada55571759b851e1e4afa7818f29
Add cli tool to delete documents.
app/utils/scripts/delete-docs.py
app/utils/scripts/delete-docs.py
Python
0.000013
@@ -0,0 +1,2837 @@ +#!/usr/bin/python%0A#%0A# This program is free software: you can redistribute it and/or modify%0A# it under the terms of the GNU Affero General Public License as%0A# published by the Free Software Foundation, either version 3 of the%0A# License, or (at your option) any later version.%0A#%0A# This program is distributed in the hope that it will be useful,%0A# but WITHOUT ANY WARRANTY; without even the implied warranty of%0A# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the%0A# GNU Affero General Public License for more details.%0A#%0A# You should have received a copy of the GNU Affero General Public License%0A# along with this program. If not, see %3Chttp://www.gnu.org/licenses/%3E.%0A%0A%22%22%22Basic command line script to delete documents.%22%22%22%0A%0Aimport argparse%0Aimport sys%0A%0Aimport models%0Aimport utils%0Aimport utils.db%0A%0A%0ACOLLECTIONS = %5B%0A models.BOOT_COLLECTION,%0A models.DEFCONFIG_COLLECTION,%0A models.JOB_COLLECTION,%0A models.LAB_COLLECTION%0A%5D%0A%0AALL_COLLECTIONS = %5B%0A %22all%22%0A%5D%0AALL_COLLECTIONS.extend(COLLECTIONS)%0A%0A%0Adef parse_fields(fields):%0A for field in fields:%0A if %22=%22 in field:%0A yield field.split(%22=%22, 1)%0A else:%0A utils.LOG.error(%22Field %25s is not valid, not considered%22, field)%0A%0A%0Adef _delete_with_spec(collection, spec_or_id, database):%0A ret_val = None%0A if collection == %22all%22:%0A utils.LOG.info(%22Deleting documents in all collections%22)%0A for coll in COLLECTIONS:%0A utils.LOG.info(%22Deleting from %25s...%22, coll)%0A ret_val = utils.db.delete(database%5Bcoll%5D, spec)%0A else:%0A ret_val = utils.db.delete(database%5Bcollection%5D, spec_or_id)%0A%0A if ret_val == 200:%0A utils.LOG.info(%22Documents identified deleted: %25s%22, spec_or_id)%0A else:%0A utils.LOG.error(%0A %22Error deleting documents with the provided values: %25s%22,%0A spec_or_id)%0A sys.exit(1)%0A%0A%0Aif __name__ == %22__main__%22:%0A parser = argparse.ArgumentParser(%0A description=%22Import boots from disk%22,%0A version=0.1%0A )%0A parser.add_argument(%0A %22--collection%22, %22-c%22,%0A type=str,%0A help=%22The name of the job to import%22,%0A dest=%22collection%22,%0A required=True,%0A choices=ALL_COLLECTIONS%0A )%0A parser.add_argument(%0A %22--field%22, %22-f%22,%0A help=(%0A %22The necessary fields to identify the elements to delete; %22%0A %22they must be defined as key=value pairs%22%0A ),%0A dest=%22fields%22,%0A action=%22append%22,%0A required=True%0A )%0A%0A args = parser.parse_args()%0A%0A collection = args.collection%0A fields = args.fields%0A%0A spec = %7B%0A k: v for k, v in parse_fields(fields)%0A %7D%0A%0A if spec:%0A database = utils.db.get_db_connection(%7B%7D)%0A _delete_with_spec(collection, spec, database)%0A else:%0A utils.LOG.error(%22Don't know what to look for...%22)%0A sys.exit(1)%0A
c71a3f1adbf310c63ce9ab7611cf0e198ffe69da
Add load test
metakernel/magics/tests/test_load_magic.py
metakernel/magics/tests/test_load_magic.py
Python
0.000001
@@ -0,0 +1,212 @@ +%0Afrom metakernel.tests.utils import get_kernel%0A%0A%0Adef test_load_magic():%0A kernel = get_kernel()%0A ret = kernel.do_execute(%22%25%25load %25s%22 %25 __file__)%0A assert 'def test_load_magic' in ret%5B'payload'%5D%5B0%5D%5B'text'%5D%0A
e575f343f55fd54994fdb1f4d02fe6e2e52ba056
add phonetizer.py - really
phonetizer.py
phonetizer.py
Python
0
@@ -0,0 +1,2726 @@ +import re%0A%0Aclass Phonetizer():%0A%0A # Define shorthands for phonological classes%0A ph_classes = %7B%0A 'C' : 'p%7Ct%7Ck%7Cb%7Cd%7Cg',%0A 'V' : 'a%7Ce%7Ci%7Co%7Cu%7Cy'%0A %7D%0A%0A def __init__(self, mappings_filename):%0A with open(mappings_filename) as mfile:%0A self.read_mfile(mfile)%0A%0A def read_mfile(self, mfile):%0A %22%22%22%0A %22%22%22%0A self.ortho_maps = %5B%5D%0A self.phone_maps = %5B%5D%0A for line in mfile:%0A sline = line%5B:-1%5D.split('%5Ct') # fix this using csv so the user doesn't have to have an extra blank line!%0A if len(sline) == 2:%0A self.ortho_maps.append((sline%5B0%5D,sline%5B1%5D))%0A elif len(sline) == 3:%0A self.phone_maps.append((sline%5B0%5D,sline%5B1%5D))%0A self.ortho_maps.sort(key=lambda x: len(x%5B0%5D))%0A self.ortho_maps.reverse()%0A%0A def read_wfile(self, ttfilename):%0A with open(ttfilename) as ttfile:%0A return %5B(line%5B:-1%5D.split('%5Ct')%5B0%5D,line%5B:-1%5D.split('%5Ct')%5B1%5D) for line in ttfile%5D%0A%0A def run_tests(self, ttfilename):%0A cases = self.read_wfile(ttfilename)%0A for c in cases:%0A transcription = self.phonetize(c%5B0%5D)%0A if transcription != c%5B1%5D:%0A print('Output %5B%7B%7D%5D should have been %5B%7B%7D%5D.'.format(transcription, c%5B1%5D))%0A%0A def phonetize(self, ortho):%0A result = %5B'' for character in ortho%5D%0A%0A # go from ortho to initial transcription%0A for om in self.ortho_maps:%0A hits = re.finditer(om%5B0%5D, ortho)%0A for hit in hits:%0A result%5Bhit.start()%5D = om%5B1%5D%0A ortho = ''.join(%5B'*' if i in range(hit.start(), hit.end()) else c for i,c in enumerate(ortho)%5D)%0A for i,character in enumerate(ortho):%0A if character != '*':%0A result%5Bi%5D = character%0A result = ''.join(result)%0A%0A # apply %22phonology%22%0A loop_input_str = ''.join(result)%0A new_result = %5B'' for character in result%5D%0A while True:%0A loop_input = loop_input_str%0A new_result = %5Bc for c in loop_input_str%5D%0A for pm in self.phone_maps:%0A hits = re.finditer(pm%5B0%5D, loop_input_str)%0A for hit in hits:%0A new_result%5Bhit.start()%5D = pm%5B1%5D%0A for i in range(hit.start()+1, hit.end()):%0A new_result%5Bi%5D = ''%0A loop_input = ''.join(%5B'*' if i in range(hit.start(), hit.end()) else c for i,c in enumerate(loop_input)%5D)%0A%0A if ''.join(new_result) == loop_input_str:%0A return loop_input_str%0A else:%0A loop_input_str = ''.join(new_result)%0A%0A%0A%0A%0A#### Quick, temp lines for testing%0Ap = Phonetizer('test_mappings.txt')%0Ap.run_tests('test_ortho.txt')
163da52a48eb0d84cde47f7cfe99e1188350db47
Add MOBIB Basic reader script
mobib_basic.py
mobib_basic.py
Python
0
@@ -0,0 +1,1615 @@ +#!/bin/env python3%0A%0Aimport sys%0A%0Afrom smartcard.System import readers%0A%0ACALYPSO_CLA = %5B0x94%5D%0ASELECT_INS = %5B0xA4%5D%0AREAD_RECORD_INS = %5B0xB2%5D%0AGET_RESPONSE_INS = %5B0xC0%5D%0ATICKETING_COUNTERS_FILE_ID = %5B0x20, 0x69%5D%0A%0Adef main():%0A local_readers = readers()%0A%0A if local_readers:%0A if len(local_readers) == 1:%0A readerIndex = 0%0A else:%0A for i, reader in enumerate(local_readers):%0A print(%22%5B%7B%7D%5D: %7B%7D%22.format(i, reader))%0A readerIndex = int(input(%22Select a reader: %22))%0A else:%0A print(%22No reader detected%22)%0A sys.exit(1)%0A%0A calypso = local_readers%5BreaderIndex%5D.createConnection()%0A calypso.connect()%0A%0A select_apdu = CALYPSO_CLA + SELECT_INS + %5B0x00, 0x00, 0x02%5D + TICKETING_COUNTERS_FILE_ID + %5B0x00%5D%0A data, sw1, sw2 = calypso.transmit(select_apdu)%0A if sw1 == 0x61:%0A get_response_apdu = %5B0x00%5D + GET_RESPONSE_INS + %5B0x00, 0x00, sw2%5D%0A data, sw1, sw2 = calypso.transmit(get_repsonse_apdu)%0A%0A read_record_apdu = CALYPSO_CLA + READ_RECORD_INS + %5B0x01, 0x04, 0x1D%5D%0A data, sw1, sw2 = calypso.transmit(read_record_apdu)%0A%0A if sw1 == 0x90:%0A # FIXME: each chunk of remaining trips stored on 3 bytes?%0A #chunks = %5Bdata%5Bx:x+3%5D for x in range(0, len(data), 3)%5D%0A #total = 0%0A #for chunk in chunks:%0A # total += chunk%5B2%5D%0A #print(%22Number of remaining trips: %7B%7D%22.format(tot = chunks%5Bi%5D%5B2%5D for i in chunks))%0A print(%22Number of remaining trips: %7B%7D%22.format(sum(data)))%0A else:%0A print(%22Error getting number of remaining trips%22)%0A sys.exit(2)%0A%0Aif __name__ == '__main__':%0A main()%0A
97531bdb1501748c7039d194e98408245dc5d2b2
Make graphflow loading script
load-tx-to-graphflow.py
load-tx-to-graphflow.py
Python
0.000002
@@ -0,0 +1,1691 @@ +from constants import *%0Aimport csv%0A%0AwalletsMap=%7B%7D #address -%3E number OR transaction_id-%3Enumber%0AlastNumber = 0%0A%0Awith open(IN_TRANSACTION_CSV_LOCATION, 'rb') as tx_in_file:%0A in_reader = csv.reader(tx_in_file, delimiter=%22,%22)%0A for row in in_reader:%0A tx_hash = row%5B0%5D%0A wallet_addr = row%5B1%5D%0A tx_amt = row%5B2%5D%0A %0A if wallet_addr in walletsMap:%0A wallet_id = walletsMap%5Bwallet_addr%5D%0A else:%0A wallet_id = lastNumber%0A walletsMap%5Bwallet_addr%5D = wallet_id%0A lastNumber+=1%0A%0A if tx_hash in walletsMap:%0A tx_id = walletsMap%5Btx_hash%5D%0A else:%0A tx_id = lastNumber%0A walletsMap%5Btx_hash%5D = tx_id%0A lastNumber+=1%0A%0A print(%22CREATE (%22+str(wallet_id)+%22:wallet %7Baddress: %7B%22+wallet_addr+%22%7D%7D) -%5B:SENT %7Bsatoshi: %7B%22+str(tx_amt)+%22%7D%7D%5D -%3E (%22+str(tx_id)+%22:tx %7Bhash:%22+tx_hash+%22%7D)%22)%0A%0Awith open(OUT_TRANSACTION_CSV_LOCATION, 'rb') as tx_out_file:%0A out_reader = csv.reader(tx_out_file, delimiter=%22,%22)%0A for row in out_reader:%0A tx_hash = row%5B0%5D%0A wallet_addr = row%5B1%5D%0A tx_amt = row%5B2%5D%0A %0A if wallet_addr in walletsMap:%0A wallet_id = walletsMap%5Bwallet_addr%5D%0A else:%0A wallet_id = lastNumber%0A walletsMap%5Bwallet_addr%5D = wallet_id%0A lastNumber+=1%0A%0A if tx_hash in walletsMap:%0A tx_id = walletsMap%5Btx_hash%5D%0A else:%0A tx_id = lastNumber%0A walletsMap%5Btx_hash%5D = tx_id%0A lastNumber+=1%0A%0A%0A%0A print(%22CREATE (%22+str(wallet_id)+%22:wallet %7Baddress: %7B%22+wallet_addr+%22%7D%7D) -%5B:RECEIVED %7Bsatoshi: %7B%22+str(tx_amt)+%22%7D%7D%5D -%3E (%22+str(tx_id)+%22:tx %7Bhash:%22+tx_hash+%22%7D)%22)%0A
7f6aab7dc177dc1178eca30e0ba40874b217e7cf
Create *variable.py
*variable.py
*variable.py
Python
0.000001
@@ -0,0 +1,510 @@ +def num(*nums): // One * takes in any number of single data type, in this case : Int%0A sum = 0%0A for x in nums:%0A sum += x%0A return sum%0A %0Asum(22,33,44,55,66) // You can type as many numbers as you wish%0A%0A%0Adef whatever(**kwargs): // Double ** take more than just a type of data, in this case, there is Str and Int%0A print(first_name)%0A print(last_name)%0A print(age)%0A %0Awhatever('first_name': 'John', 'last_name': 'Lee', 'age': 22) // Create a dictionary%0A%0A%0A %0A
70da5f3657ee847f315b0d0dfbe5adb393c55ca6
add system_info.py
system_info.py
system_info.py
Python
0.000002
@@ -0,0 +1,1254 @@ +# -*- coding: utf-8 -*-%0A%22%22%22System info%22%22%22%0A%0Aimport platform%0Aimport subprocess%0Aimport sys%0A%0Aimport numpy%0A%0A%0Aclass SystemInfo:%0A %22%22%22Collect system info.%22%22%22%0A%0A @property%0A def platform(self):%0A %22%22%22Info on the underlying platform.%22%22%22%0A return platform.platform()%0A%0A @property%0A def architecture(self):%0A %22%22%22System architecture.%22%22%22%0A is_64bits = sys.maxsize %3E 2**32%0A arch = '64bits' if is_64bits else '32bits'%0A return arch%0A%0A @property%0A def python(self):%0A %22%22%22Python version.%22%22%22%0A return sys.version%0A%0A @property%0A def numpy(self):%0A %22%22%22Numpy version.%22%22%22%0A return numpy.__version__%0A%0A @property%0A def gfortran(self):%0A %22%22%22gfortran version.%22%22%22%0A return subprocess.run(%5B'gfortran', '-v'%5D,%0A stderr=subprocess.PIPE).stderr.decode()%0A%0A @classmethod%0A def attrs(cls):%0A %22%22%22Available system infos.%22%22%22%0A return %5Bp for p in dir(cls) if isinstance(getattr(cls, p), property)%5D%0A%0A def __repr__(self):%0A fmt = '%5Cn'.join(%5B'%25s'%5D * 3 + %5B'%5Cn'%5D)%0A return ''.join(%0A %5Bfmt %25 (a, '=' * len(a), getattr(self, a)) for a in self.attrs()%5D)%0A%0A%0Aif __name__ == '__main__':%0A # print out system info%0A print(SystemInfo())%0A
a2b462abb41724d92db7222087b017e5781e4191
add incident fields
content_creator.py
content_creator.py
import os import sys import yaml import glob import shutil CONTENT_DIRS = ['Integrations', 'Misc', 'Playbooks', 'Reports', 'Dashboards', 'Widgets', 'Scripts', 'Classifiers', 'Layouts'] # temp folder names BUNDLE_PRE = 'bundle_pre' BUNDLE_POST = 'bundle_post' # zip files names (the extension will be added later - shutil demands file name without extension) ZIP_PRE = 'content_yml' ZIP_POST = 'content_new' def is_ge_version(ver1, ver2): # fix the version to arrays of numbers if isinstance(ver1, str): ver1 = [int(i) for i in ver1.split('.')] if isinstance(ver2, str): ver2 = [int(i) for i in ver2.split('.')] for v1, v2 in zip(ver1, ver2): if v1 > v2: return False # most significant values are equal return len(ver1) <= len(ver2) def add_tools_to_bundle(bundle): for d in glob.glob(os.path.join('Tools', '*')): shutil.make_archive(os.path.join(bundle, 'tools-%s' % (os.path.basename(d), )), 'zip', d) def copy_dir_yml(dir_name, version_num, bundle_pre, bundle_post): scan_files = glob.glob(os.path.join(dir_name, '*.yml')) post_files = 0 for path in scan_files: with open(path, 'r') as f: yml_info = yaml.safe_load(f) ver = yml_info.get('fromversion', '0') if is_ge_version(version_num, ver): print ' - marked as post: %s (%s)' % (ver, path, ) shutil.copyfile(path, os.path.join(bundle_post, os.path.basename(path))) post_files += 1 else: # add the file to both bundles print ' - marked as pre: %s (%s)' % (ver, path, ) shutil.copyfile(path, os.path.join(bundle_pre, os.path.basename(path))) shutil.copyfile(path, os.path.join(bundle_post, os.path.basename(path))) print ' - total post files: %d' % (post_files, ) def copy_dir_json(dir_name, version_num, bundle_pre, bundle_post): # handle *.json files scan_files = glob.glob(os.path.join(dir_name, '*.json')) for path in scan_files: shutil.copyfile(path, os.path.join(bundle_post, os.path.basename(path))) shutil.copyfile(path, os.path.join(bundle_pre, os.path.basename(path))) def copy_dir_files(*args): # handle *.json files copy_dir_json(*args) # handle *.yml files copy_dir_yml(*args) def main(circle_artifacts): print 'starting create content artifact ...' # version that separate post bundle from pre bundle # e.i. any yml with "fromversion" of <version_num> or more will be only on post bundle version_num = "3.5" print 'creating dir for bundles ...' for b in [BUNDLE_PRE, BUNDLE_POST]: os.mkdir(b) add_tools_to_bundle(b) for d in CONTENT_DIRS: print 'copying dir %s to bundles ...' % (d,) copy_dir_files(d, version_num, BUNDLE_PRE, BUNDLE_POST) print 'copying content descriptor to bundles' for b in [BUNDLE_PRE, BUNDLE_POST]: shutil.copyfile('content-descriptor.json', os.path.join(b, 'content-descriptor.json')) print 'copying common server doc to bundles' for b in [BUNDLE_PRE, BUNDLE_POST]: shutil.copyfile('./Docs/doc-CommonServer.json', os.path.join(b, 'doc-CommonServer.json')) print 'compressing bundles ...' shutil.make_archive(ZIP_POST, 'zip', BUNDLE_POST) shutil.make_archive(ZIP_PRE, 'zip', BUNDLE_PRE) shutil.copyfile(ZIP_PRE + '.zip', os.path.join(circle_artifacts, ZIP_PRE + '.zip')) shutil.copyfile(ZIP_POST + '.zip', os.path.join(circle_artifacts, ZIP_POST + '.zip')) shutil.copyfile('release-notes.txt', os.path.join(circle_artifacts, 'release-notes.txt')) print 'finished create content artifact' def test_version_compare(version_num): V = ['3.5', '2.0', '2.1', '4.7', '1.1.1', '1.5', '3.10.0', '2.7.1', '3', '3.4.9', '3.5.1'] lower = [] greater = [] for v in V: if is_ge_version(version_num, v): greater.append(v) else: lower.append(v) print 'lower versions: %s' % (lower, ) print 'greater versions: %s' % (greater, ) if __name__ == '__main__': main(*sys.argv[1:])
Python
0
@@ -193,16 +193,34 @@ Layouts' +, 'IncidentFields' %5D%0A# temp
2910f54c75e3f7cc9d7be08886547060a7e69b69
Implement basic CLI control
pusher.py
pusher.py
Python
0.000001
@@ -0,0 +1,2033 @@ +from __future__ import print_function, absolute_import, unicode_literals, division%0Afrom stackable.stack import Stack%0Afrom stackable.utils import StackablePickler%0Afrom stackable.network import StackableSocket, StackablePacketAssembler%0Afrom stackable.stackable import StackableError%0Afrom runnable.network import RunnableServer, RequestObject%0A%0Afrom subprocess import Popen, PIPE%0Afrom threading import Thread, Lock%0Afrom sys import argv%0A%0Aclass DispatchPusher(object):%0A%09def __init__(self, ip=None, port=None):%0A%09%09self.stack = None%0A%09%09if ip != None and port != None:%0A%09%09%09self.connect(ip, port)%0A%0A%09def connect(self, ip, port):%0A%09%09self.stack = Stack((StackableSocket(ip=ip, port=port),%0A%09%09%09%09 %09 StackablePacketAssembler(),%0A%09%09%09%09 %09 StackablePickler()))%0A%0A%09def push_module(self, name, module):%0A%09%09self.stack.write(%7B'cmd': 'module', 'args': %7B'name': name, 'module': module%7D%7D)%0A%0A%09def dispatch(self, dispatcher, module):%0A%09%09self.stack.write(%7B'cmd': 'dispatch', 'args': %7B'dispatcher': dispatcher, 'module': module%7D%7D)%0A%0A%09def status(self, dispatcher, job):%0A%09%09self.stack.write(%7B'req': 'status', 'args': %7B'dispatcher': dispatcher, 'id': job%7D%7D)%0A%0A%09def close(self):%0A%09%09self.stack.close()%0A%0A%09def monitor(self):%0A%09%09while True:%0A%09%09%09o = self.stack.read()%0A%09%09%09print(o)%0A%0Adp = DispatchPusher(argv%5B1%5D, int(argv%5B2%5D))%0Aa = Thread(target=dp.monitor)%0Aa.daemon = True%0Aa.start()%0A%0Amode = 'file'%0Awhile True:%0A%09x = raw_input('%5B%25s%5D ' %25 mode)%0A%0A%09if x == '':%0A%09%09continue%0A%0A%09if x%5B:2%5D == '!!':%0A%09%09mode = x%5B2:%5D%0A%09%09print(' --%3E Changing mode to %25s' %25 mode)%0A%09%09continue%0A%0A%09if mode == 'file':%0A%09%09name = x.rpartition('/')%5B2%5D.partition('.py')%5B0%5D%0A%09%09f = b''%0A%09%09try:%0A%09%09%09f = open(x).read()%0A%09%09except:%0A%09%09%09print(' --%3E Failed to read %25s' %25 name)%0A%0A%09%09code = compile(f, name, mode='exec', dont_inherit=True)%0A%09%09print(' --%3E Prepared %25s' %25 name)%0A%0A%09%09dp.push_module(name, code)%0A%09elif mode == 'dispatch':%0A%09%09x = x.partition(' ')%0A%09%09print(' --%3E Dispatching', x%5B2%5D, 'to', x%5B0%5D)%0A%09%09dp.dispatch(x%5B0%5D, x%5B2%5D)%0A%09elif mode == 'console':%0A%09%09if x == 'close':%0A%09%09%09dp.close()%0A%09%09%09raise KeyboardInterrupt()%0A%0Aprint(%22%5BPUSHER%5D Ready%22)%0A
e10ed243f6cae2e020d468bbd13a619e45ed0c5d
Add a forgotten migration
sponsors/migrations/0011_auto_20170629_1208.py
sponsors/migrations/0011_auto_20170629_1208.py
Python
0.000029
@@ -0,0 +1,754 @@ +# -*- coding: utf-8 -*-%0A# Generated by Django 1.11.2 on 2017-06-29 10:08%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations, models%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('sponsors', '0010_auto_20170627_2001'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterField(%0A model_name='sponsor',%0A name='type',%0A field=models.CharField(choices=%5B('diamond', 'Diamond Sponsor'), ('lanyard', 'Lanyard Sponsor'), ('track', 'Track Sponsor'), ('foodanddrinks', 'Food & Drinks Sponsor'), ('standard', 'Standard Sponsor'), ('supporter', 'Supporter Sponsor'), ('mainmedia', 'Main Media Sponsor'), ('media', 'Media sponsors')%5D, default='standard', max_length=255),%0A ),%0A %5D%0A
ca5d47f3749c188d0858e996ba0253077260cd6c
Create GetUserGraphInstagram.py
GetUserGraphInstagram.py
GetUserGraphInstagram.py
Python
0
@@ -0,0 +1,296 @@ +#! /bin/bash%0A%0Afor (( i=1; i %3C= 5; i++ ))%0Ado%0A%0A userid=$i%0A%0A curl https://api.instagram.com/v1/users/$userid/follows?access_token=XXXXXX %3E followers/$userid.followers%0A curl https://api.instagram.com/v1/users/$userid/followed-by?access_token=XXXXXX %3E followedby/$userid.followedby%0A%0Adone%0A
a8f4f0aa06e1469e758d5775bfea4176c7561e9f
Create stop_playlist.py
HA/syno/stop_playlist.py
HA/syno/stop_playlist.py
Python
0.000008
@@ -0,0 +1,1466 @@ +#!/usr/bin/python%0Aimport sys%0Aimport http.cookiejar, urllib.request, urllib.error, urllib.parse%0Aimport json%0Aimport codecs%0A%0Acj = http.cookiejar.CookieJar()%0Aopener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))%0A%0AIP_syno = %22IP_OF_YOUR_NAS%22%0ALOGIN = %22********%22%0APASSWORD = %22********%22%0Aplayer = sys.argv%5B1%5D%0A%0Aopener.addheaders = %5B%0A ('User-Agent', 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.11) Gecko/20101012 Firefox/3.6.11'),%0A %5D%0A%0A#URL to send requests to Synology%0AurlAuth = %22http://%22 + IP_syno + %22:5000/webapi/auth.cgi?api=SYNO.API.Auth&version=2&method=login&account=%22 + LOGIN + %22&passwd=%22 %5C%0A+ PASSWORD + %22&session=AudioStation&format=cookie%22%0AurlPlayers = %22http://%22 + IP_syno + %22:5000/webapi/AudioStation/remote_player.cgi?api=SYNO.AudioStation.RemotePlayer&version=1&method=list%22%0Aopener.open(urlAuth)%0A%0A#Get Players list as JSON%0ApagePlayers = opener.open(urlPlayers)%0AstrPlayers = codecs.getreader(pagePlayers.headers.get_content_charset())%0AjsonPlayers = json.load(strPlayers(pagePlayers))%5B'data'%5D%5B'players'%5D%0A#print(jsonPlayers)%0A%0A#Get Player ID required to send http command to play content on the chosen player on Synology%0Afor d in jsonPlayers:%0A PlayerName = d%5B'name'%5D%0A if PlayerName == player:%0A PlayerID = d%5B'id'%5D%0A%0AurlStop = %22http://%22 + IP_syno + %22:5000/webapi/AudioStation/remote_player.cgi?api=SYNO.AudioStation.RemotePlayer&method=control&action=stop&id=%22 + PlayerID + %22&version=$%0A#print(urlStop)%0Aopener.open(urlStop)%0A
b6daa366a38f224132c8f276d3fbc212964900c2
add currency
zametki/currency.py
zametki/currency.py
Python
0.999995
@@ -0,0 +1,204 @@ +import requests as req%0A%0Adef getUSD_RUB():%0A currency_url = 'http://api.fixer.io/latest?symbols=RUB&base=USD'%0A res = req.get(currency_url).json()%0A return res%5B'rates'%5D%5B'RUB'%5D%0A%0A#print(getUSD_RUB())%0A%0A
16883c227549707ef2a66d7e6020809fe9ecd909
Add visitor base class
tater/visit.py
tater/visit.py
Python
0
@@ -0,0 +1,910 @@ +from tater.utils import CachedAttr%0A%0A%0Aclass _MethodDict(dict):%0A 'Dict for caching visitor methods.'%0A def __init__(self, visitor):%0A self.visitor = visitor%0A%0A def __missing__(self, node):%0A name = node.__class__.__name__%0A method = getattr(self.visitor, 'visit_' + name, None)%0A self%5Bname%5D = method%0A return method%0A%0A%0Aclass VisitorBase(object):%0A%0A @CachedAttr%0A def _methods(self):%0A return _MethodDict(visitor=self)%0A%0A def visit(self, node):%0A self.node = node%0A self._visit_nodes(node)%0A self.finalize()%0A%0A def _visit_nodes(self, node):%0A self._visit_node(node)%0A visit_nodes = self._visit_nodes%0A for child in node.children:%0A visit_nodes(child)%0A%0A def _visit_node(self, node):%0A func = self._methods%5Bnode%5D%0A if func is not None:%0A return func(node)%0A%0A def finalize(self):%0A pass%0A
7dd4919809c626d83cfc17447396aff98e636cfe
Add problem 13
problem_13.py
problem_13.py
Python
0.000001
@@ -0,0 +1,2055 @@ +from collections import OrderedDict%0Afrom crypto_library import ecb_aes_encrypt, ecb_aes_decrypt%0Afrom problem_12 import find_blocksize%0Afrom crypto_library import apply_pkcs_7_padding%0A%0AENCRYPTION_KEY = ',y!3%3CCWn@1?wwF%5D%5Cx0b'%0A%0A%0Adef oracle(adversary_input):%0A profile = profile_for(adversary_input)%0A return ecb_aes_encrypt(profile, ENCRYPTION_KEY)%0A%0A%0Adef destructure(structured):%0A attrs = structured.split('&')%0A destructured = %7B%7D%0A for a in attrs:%0A parameter, value = a.split('=')%0A destructured%5Bparameter%5D = value%0A return OrderedDict(destructured)%0A%0A%0Adef structure(destructured):%0A return '&'.join(%5B%0A '='.join(%5Bparameter, value%5D) for parameter, value in destructured.items()%0A %5D)%0A%0A%0Adef profile_for(email_addr):%0A if '&' in email_addr or '=' in email_addr:%0A raise ValueError('Email address cannot contain %22&%22 or %22=%22')%0A return structure(OrderedDict(%5B%0A ('email', email_addr),%0A ('uid', '10'),%0A ('role', 'user')%0A %5D))%0A%0Ablocksize = find_blocksize(oracle)%0A%0A# Admin mail length should result in length(%22email=%3Cadmin_mail%3E&uid=10&role=%22) multiple of blocksize%0Aadmin_mail = '[email protected]'%0Aciphertext = oracle(admin_mail)%0A# All blocks minus the last are the encryption of %22email=%3Cadmin_mail%3E&uid=10&role=%22%0Acipher_blocks = %5Bciphertext%5Bi*blocksize:(i+1)*blocksize%5D for i in range(len(ciphertext)/blocksize)%5D%0A%0Apadded_admin = apply_pkcs_7_padding('admin')%0Aencrypted_padded_admin = oracle((blocksize-len('email='))*'0' + padded_admin)%0Aencrypted_padded_admin_blocks = %5Bencrypted_padded_admin%5Bi*blocksize:(i+1)*blocksize%5D for i in range(len(encrypted_padded_admin)/blocksize)%5D%0A# The second block is the encryption of the padded %22admin%22 string%0Aencrypted_padded_admin_block = encrypted_padded_admin_blocks%5B1%5D%0A%0A# Replace the last block of the profile ciphertext with the valid padded %22admin%22 block%0Aadmin_encrypted_profile = ''.join(cipher_blocks%5B:-1%5D + %5Bencrypted_padded_admin_block%5D)%0Aprint 'Encrypted:', admin_encrypted_profile%0Aprint 'Decrypted:', ecb_aes_decrypt(admin_encrypted_profile, ENCRYPTION_KEY)%0A
253ad82c316bd6d11dcf798e626b7eaf638867bd
add simple font comparison tool in examples
examples/font_comparison.py
examples/font_comparison.py
Python
0
@@ -0,0 +1,3054 @@ +#!/usr/bin/env python%0A# ----------------------------------------------------------------------------%0A# pyglet%0A# Copyright (c) 2006-2008 Alex Holkner%0A# All rights reserved.%0A#%0A# Redistribution and use in source and binary forms, with or without%0A# modification, are permitted provided that the following conditions%0A# are met:%0A#%0A# * Redistributions of source code must retain the above copyright%0A# notice, this list of conditions and the following disclaimer.%0A# * Redistributions in binary form must reproduce the above copyright%0A# notice, this list of conditions and the following disclaimer in%0A# the documentation and/or other materials provided with the%0A# distribution.%0A# * Neither the name of pyglet nor the names of its%0A# contributors may be used to endorse or promote products%0A# derived from this software without specific prior written%0A# permission.%0A#%0A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS%0A# %22AS IS%22 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT%0A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS%0A# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE%0A# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,%0A# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,%0A# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;%0A# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER%0A# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT%0A# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN%0A# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE%0A# POSSIBILITY OF SUCH DAMAGE.%0A# ----------------------------------------------------------------------------%0A%0A'''A simple tool that may be used to compare font faces.%0A%0AUse the left/right cursor keys to change font faces.%0A'''%0A%0A__docformat__ = 'restructuredtext'%0A__version__ = '$Id: $'%0Aimport pyglet%0A%0AFONTS = %5B'Consolas', 'Andale Mono', 'Inconsolata', 'Inconsolata-dz', 'Monaco',%0A 'Menlo'%5D%0A%0ASAMPLE = '''class Spam(object):%0A%09def __init__(self):%0A%09%09# The quick brown fox%0A%09%09self.spam = %7B%22jumped%22: 'over'%7D%0A @the%0A%09def lazy(self, *dog):%0A%09%09self.dog = %5Blazy, lazy%5D'''%0A%0Aclass Window(pyglet.window.Window):%0A font_num = 0%0A def on_text_motion(self, motion):%0A if motion == pyglet.window.key.MOTION_RIGHT:%0A self.font_num += 1%0A if self.font_num == len(FONTS):%0A self.font_num = 0%0A elif motion == pyglet.window.key.MOTION_LEFT:%0A self.font_num -= 1%0A if self.font_num %3C 0:%0A self.font_num = len(FONTS) - 1%0A%0A face = FONTS%5Bself.font_num%5D%0A self.head = pyglet.text.Label(face, font_size=24, y=0,%0A anchor_y='bottom')%0A self.text = pyglet.text.Label(SAMPLE, font_name=face, font_size=18,%0A y=self.height, anchor_y='top', width=self.width, multiline=True)%0A%0A def on_draw(self):%0A self.clear()%0A self.head.draw()%0A self.text.draw()%0A%0Awindow = Window()%0Awindow.on_text_motion(None)%0Apyglet.app.run()%0A
3ac3c5fef523e8c643adc8479b82958cfe150b79
change contributors (#17656)
Utils/github_workflow_scripts/handle_external_pr.py
Utils/github_workflow_scripts/handle_external_pr.py
#!/usr/bin/env python3 import json from typing import List import urllib3 from blessings import Terminal from github import Github from github.Repository import Repository from utils import get_env_var, timestamped_print urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) print = timestamped_print REVIEWERS = ['yuvalbenshalom'] MARKETPLACE_CONTRIBUTION_PR_AUTHOR = 'xsoar-bot' WELCOME_MSG = 'Thank you for your contribution. Your generosity and caring are unrivaled! Rest assured - our content ' \ 'wizard @{selected_reviewer} will very shortly look over your proposed changes.' WELCOME_MSG_WITH_GFORM = 'Thank you for your contribution. Your generosity and caring are unrivaled! Make sure to ' \ 'register your contribution by filling the [Contribution Registration]' \ '(https://forms.gle/XDfxU4E61ZwEESSMA) form, ' \ 'so our content wizard @{selected_reviewer} will know he can start review the proposed ' \ 'changes.' def determine_reviewer(potential_reviewers: List[str], repo: Repository) -> str: """Checks the number of open 'Contribution' PRs that have either been assigned to a user or a review was requested from the user for each potential reviewer and returns the user with the smallest amount Args: potential_reviewers (List): The github usernames from which a reviewer will be selected repo (Repository): The relevant repo Returns: str: The github username to assign to a PR """ label_to_consider = 'contribution' pulls = repo.get_pulls(state='OPEN') assigned_prs_per_potential_reviewer = {reviewer: 0 for reviewer in potential_reviewers} for pull in pulls: # we only consider 'Contribution' prs when computing who to assign pr_labels = [label.name.casefold() for label in pull.labels] if label_to_consider not in pr_labels: continue assignees = {assignee.login for assignee in pull.assignees} requested_reviewers, _ = pull.get_review_requests() reviewers_info = {requested_reviewer.login for requested_reviewer in requested_reviewers} combined_list = assignees.union(reviewers_info) for reviewer in potential_reviewers: if reviewer in combined_list: assigned_prs_per_potential_reviewer[reviewer] = assigned_prs_per_potential_reviewer.get(reviewer, 0) + 1 selected_reviewer = sorted(assigned_prs_per_potential_reviewer, key=assigned_prs_per_potential_reviewer.get)[0] return selected_reviewer def main(): """Handles External PRs (PRs from forks) Performs the following operations: 1. If the external PR's base branch is master we create a new branch and set it as the base branch of the PR. 2. Labels the PR with the "Contribution" label. (Adds the "Hackathon" label where applicable.) 3. Assigns a Reviewer. 4. Creates a welcome comment Will use the following env vars: - CONTENTBOT_GH_ADMIN_TOKEN: token to use to update the PR - EVENT_PAYLOAD: json data from the pull_request event """ t = Terminal() payload_str = get_env_var('EVENT_PAYLOAD') if not payload_str: raise ValueError('EVENT_PAYLOAD env variable not set or empty') payload = json.loads(payload_str) print(f'{t.cyan}Processing PR started{t.normal}') org_name = 'demisto' repo_name = 'content' gh = Github(get_env_var('CONTENTBOT_GH_ADMIN_TOKEN'), verify=False) content_repo = gh.get_repo(f'{org_name}/{repo_name}') pr_number = payload.get('pull_request', {}).get('number') pr = content_repo.get_pull(pr_number) # Add 'Contribution' Label to PR contribution_label = 'Contribution' pr.add_to_labels(contribution_label) print(f'{t.cyan}Added "Contribution" label to the PR{t.normal}') # check base branch is master if pr.base.ref == 'master': print(f'{t.cyan}Determining name for new base branch{t.normal}') branch_prefix = 'contrib/' new_branch_name = f'{branch_prefix}{pr.head.label.replace(":", "_")}' existant_branches = content_repo.get_git_matching_refs(f'heads/{branch_prefix}') potential_conflicting_branch_names = [branch.ref.lstrip('refs/heads/') for branch in existant_branches] # make sure new branch name does not conflict with existing branch name while new_branch_name in potential_conflicting_branch_names: # append or increment digit if not new_branch_name[-1].isdigit(): new_branch_name += '-1' else: digit = str(int(new_branch_name[-1]) + 1) new_branch_name = f'{new_branch_name[:-1]}{digit}' master_branch_commit_sha = content_repo.get_branch('master').commit.sha # create new branch print(f'{t.cyan}Creating new branch "{new_branch_name}"{t.normal}') content_repo.create_git_ref(f'refs/heads/{new_branch_name}', master_branch_commit_sha) # update base branch of the PR pr.edit(base=new_branch_name) print(f'{t.cyan}Updated base branch of PR "{pr_number}" to "{new_branch_name}"{t.normal}') # assign reviewers / request review from reviewer_to_assign = determine_reviewer(REVIEWERS, content_repo) pr.add_to_assignees(reviewer_to_assign) pr.create_review_request(reviewers=[reviewer_to_assign]) print(f'{t.cyan}Assigned user "{reviewer_to_assign}" to the PR{t.normal}') print(f'{t.cyan}Requested review from user "{reviewer_to_assign}"{t.normal}') # create welcome comment (only users who contributed through Github need to have that contribution form filled) message_to_send = WELCOME_MSG if pr.user.login == MARKETPLACE_CONTRIBUTION_PR_AUTHOR else WELCOME_MSG_WITH_GFORM body = message_to_send.format(selected_reviewer=reviewer_to_assign) pr.create_issue_comment(body) print(f'{t.cyan}Created welcome comment{t.normal}') if __name__ == "__main__": main()
Python
0
@@ -331,22 +331,36 @@ = %5B' -yuvalbenshalom +bziser', 'GuyAfik', 'yucohen '%5D%0AM
a1ba3031171992e4c07bef13b6edcdb1b80e32e6
Create psyko-ddos.py
psyko-ddos.py
psyko-ddos.py
Python
0.000013
@@ -0,0 +1,1436 @@ +%22%22%22%0ATitle: Psyko DDoS%0AType: Hacking Tool%0AVersion: 1.0%0AAuthor: Brandon Hammond%0ASummary: Psyko DDoS is a Python DDoS%0A tool that uses TCP packets%0A to conduct a layer 4 DDoS%0A attack on the target IP%0A address at the given port.%0A It uses multithreading to %0A distribute the DDoS attack%0A over multiple threads, thus%0A amplifying it.%0A%22%22%22%0A%0Aimport os%0Aimport sys%0Aimport time%0Aimport socket%0Aimport threading%0A%0Adef ddosAttack(ip,port,timer):%0A #DDoS attack function%0A timeout=time.time()+timer%0A message=%22Psyko DDoS TCP Flood...%22%0A print(%22DDoSing %25s...%22 %25 ip)%0A while time.time()%3Ctimeout:%0A #Generate and send TCP packet to DDoS%0A sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)%0A sock.sendto(message,(ip,port))%0A print(%22DDoS ended...%22) #Display this when DDoS has timed out%0A %0Aif __name__==%22__main__%22:%0A #Main GUI%0A threads=%5B%5D%0A print(%22=%22)*50%0A print(%22Psyko DDoS%22)%0A print(%22v1.0%22)%0A print(%22By Brandon Hammond%22)%0A print(%22=%22)*50%0A try:%0A #Get all required values%0A ip=raw_input(%22IP: %22)%0A port=input(%22Port: %22)%0A timer=input(%22Time: %22)%0A threads=input(%22Threads: %22)%0A except:%0A #If invalid input type is entered this executes%0A print(%22Input error...%22)%0A for i in range(threads):%0A #Generate threads%0A t=threading.Thread(target=ddosAttack,args=(ip,port,timer))%0A t.start()%0A
dd36aef29cd1e45ec447260f9ac8848a86a430dc
Create ptb_reader.py
ptb_reader.py
ptb_reader.py
Python
0.000004
@@ -0,0 +1,1274 @@ +from __future__ import absolute_import%0Afrom __future__ import division%0Afrom __future__ import print_function%0A%0Aimport collections%0Aimport os%0Aimport sys%0A%0Aimport tensorflow as tf%0A%0A%0Adef _read_words(filename):%0A%09with open(filename, %22r%22) as f:%0A%09%09if sys.version_info%5B0%5D %3E= 3:%0A%09%09%09return f.read().replace(%22%5Cn%22, %22%3Ceos%3E%22).split()%0A%09%09else:%0A%09%09%09return f.read().decode(%22utf-8%22).replace(%22%5Cn%22, %22%3Ceos%3E%22).split()%0A%0A%0Adef _build_vocab(filename):%0A%09data = _read_words(filename)%0A%0A%09counter = collections.Counter(data)%0A%09count_pairs = sorted(counter.items(), key=lambda x: (-x%5B1%5D, x%5B0%5D))%0A%0A%09words, _ = list(zip(*count_pairs))%0A%09word_to_id = dict(zip(words, range(len(words))))%0A%0A%09return word_to_id%0A%0A%0Adef _file_to_word_ids(filename, word_to_id):%0A%09data = _read_words(filename)%0A%09return %5Bword_to_id%5Bword%5D for word in data if word in word_to_id%5D%0A%0A%0Adef ptb_raw_data(data_path = %22data/%22):%0A%09train_path = os.path.join(data_path, %22ptb.train.txt%22)%0A%09valid_path = os.path.join(data_path, %22ptb.valid.txt%22)%0A%09test_path = os.path.join(data_path, %22ptb.test.txt%22)%0A%0A%09word_to_id = _build_vocab(train_path)%0A%09train_data = _file_to_word_ids(train_path, word_to_id)%0A%09valid_data = _file_to_word_ids(valid_path, word_to_id)%0A%09test_data = _file_to_word_ids(test_path, word_to_id)%0A%09%0A%09return train_data, valid_data, test_data, word_to_id%0A%0A
532fdfa4a0fa4f0f5f441a572eef739f081e6522
Create hello.py
hello.py
hello.py
Python
0.999503
@@ -0,0 +1,43 @@ +#!/usr/bin/env python%0A%0Aprint 'hello world'%0A
98d956b6a249caeaee76732a0679c2dd3384cda7
Create pytemplate.py
pytemplate.py
pytemplate.py
Python
0.000004
@@ -0,0 +1,2378 @@ +import os,sys,string%0A%0Afile_name = %22%22%0Aif sys.argv%5B1%5D == %22%22:%0A file_name = %22template.tf%22%0Aelse:%0A file_name = sys.argv%5B1%5D%0A%0Apath = %5B%5D%0A%0Adef build_path():%0A s_path = %22%22%0A for i in path:%0A s_path += i + %22%5C%5C%22%0A return s_path%0A%0Atype_state = %5B%5D%0A%0Adef manage_state(word,operation):%0A if operation == %22append%22:%0A type_state.append(word)%0A elif (operation == %22pop%22):%0A type_state.pop()%0A%0Aclass f_tree:%0A identifier = 0%0A level = 0%0A name = %22%22%0A creation_type = %22%22%0A path = %22%22%0A father = None%0A%0A def __str__(self):%0A return str(self.identifier) + %22 %22 + self.creation_type + %22 %22 + self.name + %22 %22 + self.path%0A%0Af = open(file_name, 'r')%0A%0Atext = string.replace(f.read(), %22 %22,%22%22)%0A%0Aword_dictionary = %5B%5D%0Aword = %22%22%0A%0Aopen_tokens = %5B'%5B','%7B','('%5D%0Aclose_tokens = %5B'%5D','%7D',')'%5D%0Ageneral_tokens = %5B',','/','%5C%5C','%5Cn','%5Ct'%5D%0A%0Abreak_word = False%0A#states%0A#s -%3E none, folder, file, end_token%0A%0Areading_token = False%0A%0Aidentifier = 0%0Atemp_state_identifier = %22%22%0Apop_folder = False%0A%0Afor c in text:%0A%0A if general_tokens.count(c) %3E 0 or open_tokens.count(c) %3E 0 or close_tokens.count(c) %3E 0:%0A reading_token = True%0A break_word = True%0A else:%0A reading_token = False%0A%0A if break_word:%0A if word != %22%22:%0A f = f_tree()%0A f.identifier = identifier%0A f.name = word%0A f.creation_type = type_state%5B-1%5D%0A%0A f.Father = None%0A %0A word_dictionary.append(f)%0A%0A if type_state%5B-1%5D == %22folder%22:%0A if(len(type_state) == len(path)):%0A path.pop()%0A path.append(word)%0A%0A f.path = build_path()%0A if type_state%5B-1%5D == %22file%22:%0A f.path += word%0A%0A word = %22%22%0A identifier += 1%0A%0A if c == %22%5B%22:%0A type_state.append(%22folder%22)%0A elif c == %22%7B%22:%0A type_state.append(%22file%22)%0A%0A if c == %22%5D%22:%0A%0A type_state.pop()%0A path.pop()%0A%0A elif c == %22%7D%22:%0A%0A type_state.pop()%0A%0A if not reading_token and type_state%5B-1%5D != %22none%22:%0A word += c%0A %0A reading_token = False%0A break_word = False%0A%0Afor f in word_dictionary:%0A if f.creation_type == %22folder%22:%0A final_path = os.path.dirname(os.path.abspath(__file__)) +%22%5C%5C%22+ f.path%0A if not os.path.exists(f.path):os.makedirs(final_path)%0A if f.creation_type == %22file%22:%0A open(f.path,%22w+%22)%0A
f4d70c81c55e744ef6ff4dd9fded2ca6e771fe30
add missing profiles migration
profiles/migrations/0003_auto_20210225_1754.py
profiles/migrations/0003_auto_20210225_1754.py
Python
0.000001
@@ -0,0 +1,804 @@ +# Generated by Django 2.2.16 on 2021-02-25 17:54%0A%0Afrom django.db import migrations, models%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A (%22profiles%22, %220002_auto_20200903_1942%22),%0A %5D%0A%0A operations = %5B%0A migrations.AlterField(%0A model_name=%22profile%22,%0A name=%22api_tier%22,%0A field=models.SlugField(%0A choices=%5B%0A (%22inactive%22, %22Not Yet Activated%22),%0A (%22suspended%22, %22Suspended%22),%0A (%22default%22, %22Default (new user)%22),%0A (%22legacy%22, %22Legacy%22),%0A (%22bronze%22, %22Bronze%22),%0A (%22silver%22, %22Silver%22),%0A (%22unlimited%22, %22Unlimited%22),%0A %5D,%0A default=%22inactive%22,%0A ),%0A ),%0A %5D%0A
79acf77b7d711c88ea0ca8a733721ce5285f9a00
Create Randomkick.py
Randomkick.py
Randomkick.py
Python
0
@@ -0,0 +1,694 @@ +__module_name__ = 'Random Kick Reason'%0A__module_version__ = '0.1'%0A__module_description__ = 'Kicks the designated player with a random kick reason.'%0A__module_author__ = 'Jake0720'%0A%0Arkickhelp = '%5Cx02USAGE: /rk %3Cnick%3E'%0A%0Aimport xchat%0Aimport random%0A%0Adef rk(word, word_eol, userdata):%0A rkicks = (('Goodbye','See you later','Cya','Bye','Later!'))%0A try:%0A xchat.command('kick ' + word%5B1%5D + ' ' + random.choice(rkicks))%0A except:%0A xchat.prnt('%5Cx0304Error!')%0A%0Adef onUnload(userdata):%0A xchat.prnt('%5Cx0304 %25s has been unloaded.' %25 __module_name__)%0A%0Axchat.hook_command('rk', rk, help=rkickhelp)%0Axchat.hook_unload(onUnload)%0Axchat.prnt('%5Cx0304 %25s has been loaded.' %25 __module_name__)%0A
d021c05e483f556122d0f3251c2a299e0c47792c
add language detection code (even if it's not used)
src/detect_language.py
src/detect_language.py
Python
0
@@ -0,0 +1,531 @@ +def determine_language(item):%0A import langid%0A%0A # latin my ass%0A def classify(s):%0A rank = langid.rank(s)%0A if rank%5B0%5D%5B0%5D == 'la':%0A return rank%5B1%5D%5B0%5D%0A return rank%5B0%5D%5B0%5D%0A%0A # extract text%0A soup = boil_soup(item)%0A for tag in %5B'script', 'style'%5D:%0A for el in soup.find_all(tag):%0A el.extract()%0A%0A s = soup.body.text%0A%0A # determine language%0A lang = classify(s)%0A%0A if lang != 'en':%0A if classify(unidecode(s)) == 'en':%0A return 'en'%0A%0A return lang%0A
f0392ebda49fa0222a3b317f50002d7e03659f47
Test we can approve Flutterwave bank accounts
bluebottle/funding_flutterwave/tests/test_states.py
bluebottle/funding_flutterwave/tests/test_states.py
Python
0
@@ -0,0 +1,1412 @@ +from bluebottle.files.tests.factories import PrivateDocumentFactory%0Afrom bluebottle.funding.tests.factories import FundingFactory, PlainPayoutAccountFactory, %5C%0A BudgetLineFactory%0Afrom bluebottle.funding_flutterwave.tests.factories import FlutterwaveBankAccountFactory%0Afrom bluebottle.test.utils import BluebottleTestCase%0Afrom bluebottle.initiatives.tests.factories import InitiativeFactory%0A%0A%0Aclass FlutterwavePayoutAccountTestCase(BluebottleTestCase):%0A%0A def setUp(self):%0A self.initiative = InitiativeFactory.create(status='approved')%0A self.funding = FundingFactory.create(initiative=self.initiative)%0A self.document = PrivateDocumentFactory.create()%0A self.payout_account = PlainPayoutAccountFactory.create(document=self.document)%0A self.bank_account = FlutterwaveBankAccountFactory.create(connect_account=self.payout_account)%0A self.funding.bank_account = self.bank_account%0A self.funding.save()%0A BudgetLineFactory.create(activity=self.funding)%0A%0A def test_approve_bank_account(self):%0A self.bank_account.states.verify(save=True)%0A self.bank_account.refresh_from_db()%0A self.assertEqual(self.bank_account.status, 'verified')%0A self.payout_account.refresh_from_db()%0A self.assertEqual(self.payout_account.status, 'verified')%0A self.funding.refresh_from_db()%0A self.assertEqual(self.funding.status, 'submitted')%0A
c1fc0121b02656de7bc99c587743485b5e45e416
Create angelbambi.py
angelbambi.py
angelbambi.py
Python
0.002066
@@ -0,0 +1,1723 @@ +#the following lines will allow you to use buttons and leds%0Aimport btnlib as btn%0Aimport ledlib as led%0Aimport time%0A%0A#the led.startup() function cycles through the leds%0Aled.startup()%0Atime.sleep(1)%0A%0Aprint(%22All on and off%22)%0A#to turn on all leds, use the led.turn_on_all(2) function:%0Aled.turn_on_all()%0Atime.sleep(2)%0A#to turn off all:%0Aled.turn_off_all()%0Atime.sleep(1)%0A%0Aprint(%22Red on and off%22)%0A#to turn on a single led, use a command like this:%0Aled.turn_on(led.red)%0A#your choices for leds are led.red, led.yellow, led.green, led.blue%0Atime.sleep(2)%0A#to turn it off:%0Aled.turn_off(led.red)%0Atime.sleep(1)%0A%0Aprint(%22Yellow with isOn test%22)%0A#the led.isOn(led) function tells you if a particular led is currently on%0Aif led.isOn(led.yellow):%0A print(%22Yellow is on%22)%0Aelse :%0A print(%22Yellow is on%22)%0Atime.sleep(3)%0Aled.turn_on(led.yellow)%0Aif led.isOn(led.yellow):%0A print(%22Yellow is on%22)%0Aelse :%0A print(%22Yellow is off%22)%0Atime.sleep(6)%0Aled.turn_off(led.yellow)%0Atime.sleep(41)%0A%0Aprint(%22Green and blue switch%22)%0A#the led.switch(led) function knows whether an led is on or off and switches its value%0Aled.turn_on(led.green)%0Atime.sleep(3)%0Aled.switch(led.green)%0Aled.switch(led.blue)%0Atime.sleep(2.2)%0Aled.switch(led.blue)%0Atime.sleep(1.4)%0A%0Aprint(%22If switch is on, press yellow for yellow and red for red%22)%0A#the btn.isOn(btn) function tells you if a particular button is being pressed or if a switch is on%0A#your choices for buttons are currently btn.red, btn.yellow, btn.switch%0Awhile btn.isOn(btn.switch) :%0A if btn.isOn(btn.yellow):%0A led.switch(led.purple)%0A if btn.isOn(btn.red) :%0A led.switch(led.blue)%0A time.sleep(0.25) #this line keeps it from querying too fast and mistaking a long press for multiple presses%0A%0Aprint(%22Goodbye%22)%0Abtn.GPIO.cleanup()%0A