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
|
---|---|---|---|---|---|---|---|
2ecf595b29b3b45769ab0934be6d095a4f80ad56
|
Add mmtl unit teset
|
tests/metal/mmtl/test_mmtl.py
|
tests/metal/mmtl/test_mmtl.py
|
Python
| 0 |
@@ -0,0 +1,894 @@
+import unittest%0A%0Afrom metal.mmtl.BERT_tasks import create_tasks%0Afrom metal.mmtl.metal_model import MetalModel%0Afrom metal.mmtl.trainer import MultitaskTrainer%0A%0A%0Aclass MMTLTest(unittest.TestCase):%0A @classmethod%0A def setUpClass(cls):%0A task_names = %5B%0A %22COLA%22,%0A %22SST2%22,%0A %22MNLI%22,%0A %22RTE%22,%0A %22WNLI%22,%0A %22QQP%22,%0A %22MRPC%22,%0A %22STSB%22,%0A %22QNLI%22,%0A %5D%0A cls.tasks = create_tasks(%0A task_names, max_datapoints=100, dl_kwargs=%7B%22batch_size%22: 8%7D%0A )%0A%0A def test_mmtl_training(self):%0A model = MetalModel(self.tasks)%0A trainer = MultitaskTrainer()%0A trainer.train_model(%0A model,%0A self.tasks,%0A checkpoint_metric=%22train/loss%22,%0A checkpoint_metric_mode=%22min%22,%0A n_epochs=1,%0A verbose=False,%0A )%0A
|
|
34b1eb53ffbca24a36c103f2017b8780405c48f4
|
add prod wsgi to code
|
find.wsgi
|
find.wsgi
|
Python
| 0 |
@@ -0,0 +1,65 @@
+from openspending import core%0Aapplication = core.create_web_app()
|
|
59de1a12d44245b69ade0d4703c98bf772681751
|
Add tests for User admin_forms
|
user_management/models/tests/test_admin_forms.py
|
user_management/models/tests/test_admin_forms.py
|
Python
| 0 |
@@ -0,0 +1,1432 @@
+from django.core.exceptions import ValidationError%0Afrom django.test import TestCase%0A%0Afrom .. import admin_forms%0Afrom . factories import UserFactory%0A%0A%0Aclass UserCreationFormTest(TestCase):%0A def test_clean_email(self):%0A email = '[email protected]'%0A%0A form = admin_forms.UserCreationForm()%0A form.cleaned_data = %7B'email': email%7D%0A%0A self.assertEqual(form.clean_email(), email)%0A%0A def test_clean_duplicate_email(self):%0A user = UserFactory.create()%0A%0A form = admin_forms.UserCreationForm()%0A form.cleaned_data = %7B'email': user.email%7D%0A%0A with self.assertRaises(ValidationError):%0A form.clean_email()%0A%0A def test_clean(self):%0A data = %7B'password1': 'pass123', 'password2': 'pass123'%7D%0A%0A form = admin_forms.UserCreationForm()%0A form.cleaned_data = data%0A%0A self.assertEqual(form.clean(), data)%0A%0A def test_clean_mismatched(self):%0A data = %7B'password1': 'pass123', 'password2': 'pass321'%7D%0A%0A form = admin_forms.UserCreationForm()%0A form.cleaned_data = data%0A%0A with self.assertRaises(ValidationError):%0A form.clean()%0A%0A%0Aclass UserChangeFormTest(TestCase):%0A def test_clean_password(self):%0A password = 'pass123'%0A data = %7B'password': password%7D%0A user = UserFactory.build()%0A%0A form = admin_forms.UserChangeForm(data, instance=user)%0A%0A self.assertNotEqual(form.clean_password(), password)%0A
|
|
706e8a6318b50466ee00ae51f59ec7ab76f820d6
|
Create forecast.py
|
forecast.py
|
forecast.py
|
Python
| 0 |
@@ -0,0 +1,1971 @@
+# -*- coding: utf-8 -*-%0A# Weather Twitter Bot - AJBBB - 7/8/2015 v2.*%0A %0Aimport urllib2%0Aimport json%0Afrom birdy.twitter import UserClient%0Aimport tweepy%0A %0A#Twitter Keys%0ACONSUMER_KEY = %22YOUR CONSUMER KEY HERE%22%0ACONSUMER_SECRET = %22YOUR CONSUMER SECRET HERE%22%0AACCESS_TOKEN = %22YOUR ACCESS TOKEN HERE%22%0AACCESS_TOKEN_SECRET = %22YOUR ACCESS TOKEN SECRET%22%0A %0A#Get the wundergound json file to be read%0Af = urllib2.urlopen(%22http://api.wunderground.com/api/YOUR-WUNDERGROUND-API-KEY-HERE/geolookup/conditions/q/GB/London.json%22)%0A#read from the json file%0Ajson_string = f.read()%0A#parse the json file%0Aparsed_json = json.loads(json_string)%0A#get info from current_observation in json file%0Atemp_c = parsed_json%5B'current_observation'%5D%5B'temp_c'%5D%0Awind = parsed_json%5B'current_observation'%5D%5B'wind_kph'%5D%0Awinddir = parsed_json%5B'current_observation'%5D%5B'wind_dir'%5D%0Awindstr = parsed_json%5B'current_observation'%5D%5B'wind_string'%5D%0Aweather = parsed_json%5B'current_observation'%5D%5B'weather'%5D%0A %0A#Define the degree symbol%0Adegree = u'%5CN%7BDEGREE SIGN%7D'%0A %0A#Connect Using Tweepy%0Aauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)%0Aauth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)%0Aapi = tweepy.API(auth)%0A %0A#oAuth Client Info%0Aclient = UserClient(CONSUMER_KEY,%0A CONSUMER_SECRET,%0A ACCESS_TOKEN,%0A ACCESS_TOKEN_SECRET)%0A %0A %0Adef tweet(message):%0A #Simple tweet function to tweet whatever is passed to message.%0A client.api.statuses.update.post(status=message)%0A %0Aif wind %3E 0.0:%0A #Tweet out the current weather with numerical wind speed.%0A tweet(%22Current weather in London, UK: %22 + str(temp_c) +%0A degree + %22C%22 + %22 and %22 + str(weather) + %22. Wind: %22 + str(wind) +%0A %22 KPH #weather #london #news #UK http://is.gd/UyLFWz%22)%0Aelse:%0A #Tweet out the current weather with text.%0A tweet(%22Current weather in London, UK: %22 + str(temp_c) +%0A degree + %22C%22 + %22 and %22 + str(weather) +%0A %22. Little to no wind. #weather #london #news #UK http://is.gd/UyLFWz%22)%0A
|
|
ae1aaaddb8adbbe4167e9b2a073493df90f6fd60
|
Remove unused CACHE_VERSION
|
subliminal/cache.py
|
subliminal/cache.py
|
# -*- coding: utf-8 -*-
import datetime
from dogpile.cache import make_region
#: Subliminal's cache version
CACHE_VERSION = 1
#: Expiration time for show caching
SHOW_EXPIRATION_TIME = datetime.timedelta(weeks=3).total_seconds()
#: Expiration time for episode caching
EPISODE_EXPIRATION_TIME = datetime.timedelta(days=3).total_seconds()
region = make_region()
|
Python
| 0.000065 |
@@ -77,58 +77,8 @@
on%0A%0A
-%0A#: Subliminal's cache version%0ACACHE_VERSION = 1%0A%0A
#: E
|
1d5227941c4839ff781fb944f425865b8afdc01f
|
Add lc0732_my_calendar_iii.py
|
lc0732_my_calendar_iii.py
|
lc0732_my_calendar_iii.py
|
Python
| 0.000225 |
@@ -0,0 +1,1939 @@
+%22%22%22Leetcode 732. My Calendar III%0AHard%0A%0AURL: https://leetcode.com/problems/my-calendar-iii/%0A%0AImplement a MyCalendarThree class to store your events. A new event can always be added.%0A%0AYour class will have one method, book(int start, int end). Formally, this represents a%0Abooking on the half open interval %5Bstart, end), the range of real numbers x such that%0Astart %3C= x %3C end.%0A%0AA K-booking happens when K events have some non-empty intersection (ie., there is some%0Atime that is common to all K events.)%0A%0AFor each call to the method MyCalendar.book, return an integer K representing the%0Alargest integer such that there exists a K-booking in the calendar.%0A%0AYour class will be called like this: %0AMyCalendarThree cal = new MyCalendarThree();%0AMyCalendarThree.book(start, end)%0A%0AExample 1:%0AMyCalendarThree();%0AMyCalendarThree.book(10, 20); // returns 1%0AMyCalendarThree.book(50, 60); // returns 1%0AMyCalendarThree.book(10, 40); // returns 2%0AMyCalendarThree.book(5, 15); // returns 3%0AMyCalendarThree.book(5, 10); // returns 3%0AMyCalendarThree.book(25, 55); // returns 3%0AExplanation: %0AThe first two events can be booked and are disjoint, so the maximum K-booking is a 1-booking.%0AThe third event %5B10, 40) intersects the first event, and the maximum K-booking is a 2-booking.%0AThe remaining events cause the maximum K-booking to be only a 3-booking.%0ANote that the last event locally causes a 2-booking, but the answer is still 3 because%0Aeg. %5B10, 20), %5B10, 40), and %5B5, 15) are still triple booked.%0A%0ANote:%0A- The number of calls to MyCalendarThree.book per test case will be at most 400.%0A- In calls to MyCalendarThree.book(start, end), start and end are integers in the range %5B0, 10%5E9%5D.%0A%22%22%22%0A%0Aclass MyCalendarThree(object):%0A def __init__(self):%0A pass%0A%0A def book(self, start, end):%0A %22%22%22%0A :type start: int%0A :type end: int%0A :rtype: int%0A %22%22%22%0A pass%0A%0A%0Adef main():%0A pass%0A%0A%0Aif __name__ == '__main__':%0A main()%0A
|
|
5dc8e70bc081646fdeb37e9af1090a78e016d91b
|
add script inserting initial datas in selected database
|
insert_initial_datas.py
|
insert_initial_datas.py
|
Python
| 0 |
@@ -0,0 +1,1236 @@
+#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A%0Aimport psycopg2%0Aimport sys%0Aimport argparse%0A%0APOSTGRESQL_connection = u%22host='localhost' port=5432 user='postgres' password='postgres'%22%0A%0Adef main():%0A parser = argparse.ArgumentParser(description=%22Script d'insertion des donn%C3%A9es initiales d'une base ENDIV.%22)%0A parser.add_argument(%22database%22, help=%22Sp%C3%A9cifie le nom de la base de donn%C3%A9es%22)%0A args = parser.parse_args()%0A%0A try:%0A connection_string = POSTGRESQL_connection%0A connection_string += u%22dbname='%7B0%7D'%22.format(args.database)%0A connection = psycopg2.connect(connection_string)%0A except psycopg2.Error as e:%0A print u%22connection %C3%A0 la base de donn%C3%A9es impossible %7B0%7D%22.format(e)%0A sys.exit(1)%0A%0A query = ''%0A try:%0A cursor = connection.cursor()%0A try:%0A cursor.execute(open(%22insert_initial_data.sql%22, %22r%22).read())%0A cursor.execute(%22COMMIT%22)%0A except psycopg2.Error, e:%0A print %22error while inserting initial datas: %7B0%7D%22.format(e)%0A sys.exit(1)%0A finally:%0A if cursor:%0A cursor.close()%0A if connection:%0A connection.close()%0A print u'insertions OK'%0A sys.exit(0)%0A%0Aif __name__ == %22__main__%22:%0A main()%0A
|
|
2aa90b34951bde36696bbcb773940a6adc245f23
|
Add Authenticater plugin
|
plugins/Authenticater.py
|
plugins/Authenticater.py
|
Python
| 0 |
@@ -0,0 +1,2405 @@
+from ts3observer.models import Plugin, Action%0A%0Aimport MySQLdb%0A%0A%0Aclass Meta:%0A author_name = 'Tim Fechner'%0A author_email = '[email protected]'%0A version = '1.0'%0A%0Aclass Config:%0A enable = False%0A interval = 5%0A yaml = %7B%0A 'general': %7B%0A 'servergroup_id': 0,%0A 'remove_if_deleted': True,%0A %7D,%0A 'database': %7B%0A 'hostname': 'localhost',%0A 'username': '',%0A 'password': '',%0A 'database': '',%0A 'table': '',%0A %7D,%0A %7D%0A%0Aclass Authenticater(Plugin):%0A%0A def setup(self):%0A self.connection = MySQLdb.connect(%0A host=self.config%5B'database'%5D%5B'hostname'%5D,%0A user=self.config%5B'database'%5D%5B'username'%5D,%0A passwd=self.config%5B'database'%5D%5B'password'%5D,%0A db=self.config%5B'database'%5D%5B'database'%5D%0A )%0A self.cursor = self.connection.cursor(MySQLdb.cursors.DictCursor)%0A%0A def run(self, clients, channels, server_info):%0A auth_list = self.get_authenticated_users()%0A%0A for clid, client in clients.items():%0A if (client.unique_identifier, True) in auth_list:%0A if not self.already_has_group(client):%0A self.add_group(client)%0A else:%0A if self.already_has_group(client):%0A self.remove_group(client)%0A%0A def get_authenticated_users(self):%0A self.cursor.execute('''SELECT ts3o_uid, ts3o_active FROM %7B%7D'''.format(self.config%5B'database'%5D%5B'table'%5D))%0A self.connection.commit()%0A users = self.cursor.fetchall()%0A return %5B(pair%5B'ts3o_uid'%5D, bool(pair%5B'ts3o_active'%5D)) for pair in users%5D%0A%0A def already_has_group(self, client):%0A for group in client.servergroups:%0A if group == self.config%5B'general'%5D%5B'servergroup_id'%5D:%0A return True%0A return False%0A%0A def add_group(self, client):%0A self._register_action(client, 'add')%0A%0A def remove_group(self, client):%0A self._register_action(client, 'remove')%0A%0A def shutdown(self):%0A self.connection.close()%0A%0A def _register_action(self, client, atype):%0A Action(%0A 'Authenticater',%0A ts3o.run_id,%0A client,%0A '%7B%7D_group'.format(atype),%0A function_kwargs = %7B%0A 'servergroup_id': self.config%5B'general'%5D%5B'servergroup_id'%5D,%0A %7D,%0A reason=atype%0A ).register()%0A
|
|
571dbf74bfc9f893d25ad7d626de800b2b3d6c73
|
move load document functionality to deserializer. prepare for post/put methods
|
jsonapi/deserializer.py
|
jsonapi/deserializer.py
|
Python
| 0.000002 |
@@ -0,0 +1,355 @@
+%22%22%22 Deserializer definition.%22%22%22%0A%0A%0Aclass DeserializerMeta(object):%0A pass%0A%0A%0Aclass Deserializer(object):%0A%0A Meta = DeserializerMeta%0A%0A @classmethod%0A def load_document(cls, document):%0A %22%22%22 Given document get model.%0A%0A :param dict document: Document%0A :return django.db.models.Model model: model instance%0A%0A %22%22%22%0A pass%0A
|
|
6537dc8853bb7f8d9fb93b0fb2b1c0241bb08b6b
|
Create client.py
|
python-scripts/client.py
|
python-scripts/client.py
|
Python
| 0 |
@@ -0,0 +1,1361 @@
+import socket%0Afrom datetime import datetime, time%0A%0As=socket.socket(socket.AF_INET, socket.SOCK_STREAM) # create a client socket%0Aport=9999%0A%0A# get the current date-time%0Atime1=datetime.now()%0A%0As.connect((%2210.0.0.2%22, port)) # connect to server socket which is at address 10.0.0.2 and port 9999%0Atm=s.recv(1024) # this will read atmost 1024 bytes%0A%0A# get the current date-time (after receiving current time from server)%0Atime2=datetime.now()%0A%0AserverTime=datetime.strptime(tm, %22%25Y-%25m-%25d %25H:%25M:%25S.%25f%22)%0A%0A# terminate client socket%0As.close()%0A%0A# printing out time received from the time-server in console%0Aprint(%22The time got from the server is: %5Cn%22)%0Aprint %22Hour: %25d %5Cn%22 %25 serverTime.hour%0Aprint %22Minute: %25d %5Cn%22 %25 serverTime.minute%0Aprint %22Second: %25d %5Cn%22 %25 serverTime.second%0Aprint %22Microsecond: %25d %5Cn%22 %25serverTime.microsecond%0A%0A# Applying Cristian%60s algorithm%0At1=time1.second*1000000+time1.microsecond%0At2=time2.second*1000000+time2.microsecond%0Adiff=(t2-t1)/2%0A%0A# computed value of actual micro-sec time to be added to obtained server time%0AnewMicro = serverTime.microsecond+diff%0A%0A# printing out actual time in console after application of Cristian%60s algorithm%0Aprint(%22Applying Cristian%60s algorithm the actual time is: %5Cn%22)%0Aprint %22Hour: %25d %5Cn%22 %25 serverTime.hour%0Aprint %22Minute: %25d %5Cn%22 %25 serverTime.minute%0Aprint %22Second: %25d %5Cn%22 %25 serverTime.second%0Aprint %22Microsecond: %25d %5Cn%22 %25 newMicro%0A
|
|
bae50495106ce5c9cb39143a58e0e73a4e823d29
|
Implement DispatchLoader (metapath import hook)
|
loader.py
|
loader.py
|
Python
| 0 |
@@ -0,0 +1,1130 @@
+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 sys import modules%0Afrom types import ModuleType%0A%0Aclass DispatchLoader(object):%0A%09def __init__(self, ip, port):%0A%09%09self.stack = Stack((StackableSocket(ip=ip, port=port),%0A%09%09%09%09 StackablePacketAssembler(),%0A%09%09%09%09 StackablePickler()))%0A%09%09self.cache = %7B%7D%0A%0A%09def get_module(self, name):%0A%09%09if name in self.cache:%0A%09%09%09return self.cache%5Bname%5D%0A%09%09else:%0A%09%09%09self.stack.write(%7B'load': name%7D)%0A%09%09%09o = self.stack.read()%0A%09%09%09if o%5B'module'%5D != None:%0A%09%09%09%09self.cache%5Bname%5D = o%5B'module'%5D%0A%09%09%09%09return o%5B'module'%5D%0A%0A%09def find_module(self, fullname, path=None):%0A%09%09if self.get_module(fullname) != None:%0A%09%09%09self.path = path%0A%09%09%09return self%0A%09%09return None%0A%0A%09def load_module(self, name):%0A%09%09if name in modules:%0A%09%09%09return modules%5Bname%5D%0A%0A%09%09m = ModuleType(name, name)%0A%09%09modules%5Bname%5D = m%0A%09%09mod = self.get_module(name)%0A%09%09if mod == None:%0A%09%09%09raise ImportError(%22No such module%22)%0A%09%09exec mod in m.__dict__%0A%09%09return m%0A
|
|
0f79cf1d15292476f2bead6d85d15e6f0db6ebbf
|
Revert "Remove manage.py in the root"
|
manage.py
|
manage.py
|
Python
| 0 |
@@ -0,0 +1,811 @@
+#!/usr/bin/env python%0Aimport os%0Aimport sys%0A%0Aif __name__ == %22__main__%22:%0A os.environ.setdefault(%22DJANGO_SETTINGS_MODULE%22, %22tests.sandbox.settings%22)%0A try:%0A from django.core.management import execute_from_command_line%0A except ImportError:%0A # The above import may fail for some other reason. Ensure that the%0A # issue is really that Django is missing to avoid masking other%0A # exceptions on Python 2.%0A try:%0A import django%0A except ImportError:%0A raise ImportError(%0A %22Couldn't import Django. Are you sure it's installed and %22%0A %22available on your PYTHONPATH environment variable? Did you %22%0A %22forget to activate a virtual environment?%22%0A )%0A raise%0A execute_from_command_line(sys.argv)%0A
|
|
540ab945736486ce78452750486ea73128b29d7b
|
Add parse_xml.py
|
parse_xml.py
|
parse_xml.py
|
Python
| 0.000263 |
@@ -0,0 +1,802 @@
+import sys%0Aimport os%0Afrom bs4 import BeautifulSoup%0Afrom zipfile import ZipFile%0A%0Adef main(argv):%0A root, ext = os.path.splitext(argv%5B1%5D)%0A with ZipFile(argv%5B1%5D) as myzip:%0A with myzip.open(%22content.xml%22) as f:%0A soup = BeautifulSoup(f.read(), %22lxml%22)%0A%0A # print(soup)%0A notes = soup.findAll(%22draw:frame%22, %7B%22presentation:class%22: %22notes%22%7D)%0A with open(%22%7B%7D.script.txt%22.format(root), %22w%22) as f:%0A for index, note in enumerate(notes):%0A bits = note.findAll(%22text:s%22)%0A for bit in bits:%0A note.find(%22text:s%22).replace_with(%22 %22)%0A print(%22_Slide %7B%7D%22.format(index))%0A f.write(%22_Slide %7B%7D%5Cn%22.format(index))%0A print(note.text)%0A f.write(%22%7B%7D%5Cn%22.format(note.text))%0A%0Aif __name__ == %22__main__%22:%0A main(sys.argv)%0A
|
|
269b779fe560fb85ca527cdda2ebd4e5e9b3a89c
|
Add monkeyrunner script to common operations
|
monkey/common.py
|
monkey/common.py
|
Python
| 0 |
@@ -0,0 +1,1323 @@
+from com.android.monkeyrunner import MonkeyDevice as mkd%0Afrom com.android.monkeyrunner import MonkeyRunner as mkr%0A%0A_ddmm_pkg = 'br.ufpe.emilianofirmino.ddmm'%0A%0Adef open_dev():%0A %22%22%22Estabilish a MonkeyDevice connection to android%22%22%22%0A return mkr.waitForConnection(1000)%0A%0Adef open_app(device, package, activity = '.MainActivity'):%0A %22%22%22Launch activity on device specified by package%5B, activity%5D%22%22%22%0A app = package + '/' + activity%0A device.startActivity(component=app)%0A%0Adef press_back(device):%0A %22%22%22Press back button on device%22%22%22%0A device.press('KEYCODE_BACK', mkd.DOWN_AND_UP)%0A%0Adef lock_screen(device):%0A %22%22%22Lock device%22%22%22%0A device.press('KEYCODE_POWER', mkd.DOWN_AND_UP)%0A%0Adef unlock_screen(device):%0A %22%22%22Unlock device%22%22%22%0A device.wake()%0A (x1, x2, y) = (768/2, 50, 1000)%0A device.drag((x1,y), (x2,y), duration=1.0, steps=50)%0A%0Adef start_ddmm(device):%0A %22%22%22Start DDMM Profiler%22%22%22%0A open_app(device, _ddmm_pkg)%0A mkr.sleep(2)%0A device.touch(20, 200, mkd.DOWN_AND_UP) # check prevent sleep%0A device.touch(384, 300, mkd.DOWN_AND_UP) # start ddmm%0A mkr.sleep(2)%0A press_back(device) # close app%0A%0Adef stop_ddmm(device):%0A %22%22%22Stop DDMM Profiler%22%22%22%0A open_app(device, _ddmm_pkg)%0A mkr.sleep(2)%0A device.touch(384, 300, mkd.DOWN_AND_UP) # stop ddmm%0A press_back(device) # close app%0A%0A
|
|
e0d075661677b4b02fa29d108472e80b9fbcad02
|
Add quote fixture
|
SoftLayer/testing/fixtures/Billing_Order_Quote.py
|
SoftLayer/testing/fixtures/Billing_Order_Quote.py
|
Python
| 0 |
@@ -0,0 +1,347 @@
+getObject = %7B%0A 'accountId': 1234,%0A 'id': 1234,%0A 'name': 'TestQuote1234',%0A 'quoteKey': '1234test4321',%0A%7D%0A%0AgetRecalculatedOrderContainer = %7B%0A 'orderContainers': %5B%7B%0A 'presetId': '',%0A 'prices': %5B%7B%0A 'id': 1921%0A %7D%5D,%0A 'quantity': 1,%0A 'packageId': 50,%0A 'useHourlyPricing': '',%0A %7D%5D,%0A%7D%0A
|
|
07b6e59a5c7f581bd3e67f6ce254a8388e8b97e1
|
add test
|
minitds/test_minitds.py
|
minitds/test_minitds.py
|
Python
| 0.000002 |
@@ -0,0 +1,1907 @@
+#!/usr/bin/env python3%0A##############################################################################%0A# The MIT License (MIT)%0A#%0A# Copyright (c) 2016 Hajime Nakagami%0A#%0A# Permission is hereby granted, free of charge, to any person obtaining a copy%0A# of this software and associated documentation files (the %22Software%22), to deal%0A# in the Software without restriction, including without limitation the rights%0A# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell%0A# copies of the Software, and to permit persons to whom the Software is%0A# furnished to do 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##############################################################################%0Aimport unittest%0Aimport minitds%0A%0Aclass TestMiniTds(unittest.TestCase):%0A host = 'localhost'%0A user = 'sa'%0A password = 'secret'%0A database = 'test'%0A%0A def setUp(self):%0A self.connection = minitds.connect(%0A host=self.host,%0A user=self.user,%0A password=self.password,%0A database=self.database,%0A port=14333,%0A )%0A%0A def tearDown(self):%0A self.connection.close()%0A%0A def test_basic(self):%0A cur = self.connection.cursor()%0A cur.execute(%22select 1 n, @@version version%22)%0A%0Aif __name__ == %22__main__%22:%0A unittest.main()%0A
|
|
a13ee62b02d3fe1958f2cbecd903c3e8b32562da
|
Add dummy test file #2
|
tests/test_dummy.py
|
tests/test_dummy.py
|
Python
| 0.000001 |
@@ -0,0 +1,670 @@
+#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A%0A#%0A# Copyright 2017 Jun-ya HASEBA%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%0A%0Adef test_dummy():%0A assert 1 + 1 == 2%0A
|
|
5d795253180ef11117ae27447fa597fa15b40734
|
Add testing for graphing code
|
tests/test_graph.py
|
tests/test_graph.py
|
Python
| 0 |
@@ -0,0 +1,1304 @@
+import os%0A%0Afrom click.testing import CliRunner%0A%0Afrom cli.script import cli%0A%0A%0Adef get_graph_code():%0A return '''%0Afrom copy import deepcopy as dc%0A%0Aclass StringCopier(object):%0A def __init__(self):%0A self.copied_strings = set()%0A%0A def copy(self):%0A string1 = 'this'%0A string2 = dc(string1)%0A string1.add(string1)%0A return string2%0A%0Aclass DoSomething(object):%0A def something(self):%0A copier = StringCopier()%0A copied_string = copier.copy()%0A'''%0A%0A%0Adef test_produce_graph():%0A runner = CliRunner()%0A with runner.isolated_filesystem():%0A with open('code.py', 'w') as f:%0A f.write(get_graph_code())%0A%0A runner.invoke(cli, %5B'code.py', '--output', 'code_output'%5D)%0A assert 'code_output' in os.listdir(os.path.curdir)%0A assert 'code_output.pdf' in os.listdir(os.path.curdir)%0A%0A%0Adef test_file_extension():%0A runner = CliRunner()%0A with runner.isolated_filesystem():%0A with open('code.py', 'w') as f:%0A f.write(get_graph_code())%0A%0A runner.invoke(cli, %5B'code.py', '--output', 'code_output', '--output-format', 'png'%5D)%0A assert 'code_output' in os.listdir(os.path.curdir)%0A assert 'code_output.png' in os.listdir(os.path.curdir)%0A assert 'code_output.pdf' not in os.listdir(os.path.curdir)%0A
|
|
66989005b6e9443c65c082ea1c2e4386ffae1330
|
Add a few basic pages tests ahead of #406
|
tests/test_pages.py
|
tests/test_pages.py
|
Python
| 0 |
@@ -0,0 +1,994 @@
+from gittip.testing import serve_request, load, setup_tips%0A%0A%0Adef test_homepage():%0A actual = serve_request('/').body%0A expected = %22Gittip happens every Thursday.%22%0A assert expected in actual, actual%0A%0Adef test_profile():%0A with load(*setup_tips((%22cheese%22, %22puffs%22, 0))):%0A expected = %22I’m grateful for tips%22%0A actual = serve_request('/cheese/').body%0A assert expected in actual, actual%0A%0Adef test_widget():%0A with load(*setup_tips((%22cheese%22, %22puffs%22, 0))):%0A expected = %22javascript: window.open%22%0A actual = serve_request('/cheese/widget.html').body%0A assert expected in actual, actual%0A%0A%0A# These hit the network.%0A%0Adef test_github_proxy():%0A expected = %22%3Cb%3Elgtest%3C/b%3E has not joined%22%0A actual = serve_request('/on/github/lgtest/').body%0A assert expected in actual, actual%0A%0Adef test_twitter_proxy():%0A expected = %22%3Cb%3ETwitter%3C/b%3E has not joined%22%0A actual = serve_request('/on/twitter/twitter/').body%0A assert expected in actual, actual%0A
|
|
7a5b46d5a9d0e45b928bcadfeb91a6285868d8f3
|
Create medium_RunLength.py
|
medium_RunLength.py
|
medium_RunLength.py
|
Python
| 0.000004 |
@@ -0,0 +1,466 @@
+%22%22%22%0ADetermine the run length%0Aof a string%0Aex: aaabbrerr %3E 3a2b1r1e2r%0A%22%22%22%0Adef RunLength(string):%0A val = string%5B0%5D%0A count = 1%0A ret = %22%22%0A for char in string%5B1:%5D:%0A if char != val:%0A ret += str(count)%0A ret += val%0A val = char%0A count = 1%0A else:%0A count += 1%0A ret += str(count)%0A ret += val%0A return ret%0A %0A %0A# keep this function call here %0A# to see how to enter arguments in Python scroll down%0Aprint RunLength(raw_input()) %0A
|
|
f3c8117755537ca96c3c8c72d5f54b8c244c260b
|
add top-level class
|
mwdust/DustMap3D.py
|
mwdust/DustMap3D.py
|
Python
| 0.000566 |
@@ -0,0 +1,943 @@
+###############################################################################%0A#%0A# DustMap3D: top-level class for a 3D dust map; all other dust maps inherit%0A# from this%0A#%0A###############################################################################%0Aclass DustMap3D:%0A %22%22%22top-level class for a 3D dust map; all other dust maps inherit from this%22%22%22%0A def __init__(self):%0A %22%22%22%0A NAME:%0A __init__%0A PURPOSE:%0A Initialize the dust map%0A INPUT:%0A OUTPUT:%0A HISTORY:%0A 2013-11-24 - Started - Bovy (IAS)%0A %22%22%22%0A return None%0A%0A def __call__(self,*args,**kwargs):%0A %22%22%22%0A NAME:%0A __call__%0A PURPOSE:%0A evaluate the dust map%0A INPUT:%0A OUTPUT:%0A HISTORY:%0A 2013-11-24 - Started - Bovy (IAS)%0A %22%22%22%0A raise NotImplementedError(%22'__call__' for this DustMap3D not implemented yet%22)%0A%0A
|
|
20cebf2b93a310dac4c491b5a59f1a2846f51073
|
Add basic implementation
|
triegex/__init__.py
|
triegex/__init__.py
|
Python
| 0.000002 |
@@ -0,0 +1,1110 @@
+__all__ = ('Triegex',)%0A%0A%0Aclass TriegexNode:%0A%0A def __init__(self, char: str, childrens=()):%0A self.char = char%0A self.childrens = %7Bchildren.char: children for children in childrens%7D%0A%0A def render(self):%0A if not self.childrens:%0A return self.char%0A return self.char + r'(?:%7B0%7D)'.format(%0A r'%7C'.join(%0A %5Bchildren.render() for key, children in sorted(self.childrens.items())%5D%0A )%0A )%0A%0A%0Aclass Triegex:%0A%0A def __init__(self, *words):%0A self._root = TriegexNode('')%0A for word in words:%0A self.add(word)%0A%0A def add(self, word: str):%0A current = self._root%0A for letter in word:%0A current = current.childrens.setdefault(letter, TriegexNode(letter))%0A%0A def render(self):%0A return self._root.render()%0A%0A%0A def __iter__(self):%0A return self%0A%0A%0A%0A%0A%0Aif __name__ == '__main__':%0A triegex = Triegex('spam', 'eggs')%0A triegex.add('foo')%0A triegex.add('bar')%0A triegex.add('baz')%0A print(triegex.render())%0A import re%0A print(re.findall(triegex.render(), 'baz spam eggs'))
|
|
465956eb780ace1835e08ca2c87895d7ff1326cf
|
save a legacy script, may have to use again some year
|
util/wisc_ingest.py
|
util/wisc_ingest.py
|
Python
| 0 |
@@ -0,0 +1,681 @@
+import subprocess%0Aimport os%0Aimport glob%0Aimport mx.DateTime%0A%0Asts = mx.DateTime.DateTime(2011,12,1)%0Aets = mx.DateTime.DateTime(2012,1,1)%0A%0AWANT = %5B'EAST-CONUS','NHEM-COMP','SUPER-NATIONAL','NHEM-MULTICOMP','WEST-CONUS'%5D%0A%0Adef dodate(now, dir):%0A base = now.strftime(%22/mesonet/gini/%25Y_%25m_%25d/sat/%22+dir)%0A for (d2,bogus,files) in os.walk(base):%0A if len(files) == 0:%0A continue%0A for file in files:%0A cmd = %22cat %25s/%25s %7C /usr/bin/python gini2gis.py%22 %25 (d2, file)%0A print cmd%0A subprocess.call(cmd, shell=True)%0A%0Anow = sts%0Awhile now %3C ets:%0A for dir in WANT:%0A dodate(now, dir)%0A%0A now += mx.DateTime.RelativeDateTime(days=1)%0A
|
|
099151db3a18384ebb4b7abc17c1a38567e5d2cb
|
add crash scan for reporting
|
utils/crash_scan.py
|
utils/crash_scan.py
|
Python
| 0 |
@@ -0,0 +1,1546 @@
+#!/usr/bin/python%0A%0Aimport subprocess%0Aimport re%0Aimport os%0A%0Ap = subprocess.Popen(%5B'adb', 'devices'%5D, stdout=subprocess.PIPE)%0Ares = p.communicate()%5B0%5D.split('%5Cn')%0Ares.pop(0)%0A%0Adevices = %5B%5D%0Afor li in res:%0A m = re.search('(%5Cw+)', li)%0A if(m is not None):%0A devices.append(m.group(0))%0A%0Atotal_crash_num = 0%0Acrash_stat_url = 'https://crash-stats.mozilla.com/report/index/'%0Afor dev in devices:%0A os.environ%5B'ANDROID_SERIAL'%5D = dev%0A crash_num = 0%0A base_dir = %22/data/b2g/mozilla/Crash Reports/%22%0A scan_cmd = %5B'adb', 'shell', 'ls -l'%5D%0A submit_dir = base_dir + 'submitted'%0A pending_dir = base_dir + 'pending'%0A p = subprocess.Popen(scan_cmd + %5Bsubmit_dir%5D, stdout=subprocess.PIPE, stderr=subprocess.PIPE)%0A output = p.communicate()%5B0%5D%0A crash_id = %5B%5D%0A if %22No such%22 not in output:%0A for out in output.split('%5Cn'):%0A if out.strip() != %22%22:%0A cid = re.search('%5Csbp-(%5CS+)%5C.txt$', out.strip()).group(1)%0A crash_id.append(cid)%0A crash_num += 1%0A q = subprocess.Popen(scan_cmd + %5Bpending_dir%5D, stdout=subprocess.PIPE, stderr=subprocess.PIPE)%0A output = q.communicate()%5B0%5D%0A if %22No such%22 not in output:%0A for out in output.split('%5Cn'):%0A if out.strip() != %22%22:%0A crash_num += 1%0A print(%22device %22 + dev + %22 has %22 + str(crash_num) + %22 crashes.%22)%0A total_crash_num += crash_num%0A if crash_id:%0A print(%22Submitted: %22)%0A for cid in crash_id:%0A print(crash_stat_url + cid)%0Aprint(%22Total crash number = %22 + str(total_crash_num))%0A
|
|
2cb013d3d8f185cf92589dc2e927ef54057972ec
|
version bump for 0.88.3.
|
oneflow/__init__.py
|
oneflow/__init__.py
|
VERSION = '0.88.2'
|
Python
| 0 |
@@ -14,8 +14,8 @@
.88.
-2
+3
'%0A%0A
|
70b921cf951b65cc67fff48a3c853ecf45817a63
|
version bump for 0.88.4.
|
oneflow/__init__.py
|
oneflow/__init__.py
|
VERSION = '0.88.3'
|
Python
| 0 |
@@ -14,8 +14,8 @@
.88.
-3
+4
'%0A%0A
|
13cf0fdc5ac54abbf746880306cdcacd158e81a2
|
version bump for 0.83.8.
|
oneflow/__init__.py
|
oneflow/__init__.py
|
VERSION = '0.83.7'
|
Python
| 0 |
@@ -14,8 +14,8 @@
.83.
-7
+8
'%0A%0A
|
52cf673833196ef76158beee5ca877af356c76fc
|
version bump for 0.20.14.16.
|
oneflow/__init__.py
|
oneflow/__init__.py
|
VERSION = '0.20.14.15'
|
Python
| 0 |
@@ -18,8 +18,8 @@
14.1
-5
+6
'%0A%0A
|
49a173312f720042c8ca9778e6225b1de2b3dfd8
|
version bump for 0.25.1.5.
|
oneflow/__init__.py
|
oneflow/__init__.py
|
VERSION = '0.25.1.4'
|
Python
| 0 |
@@ -16,8 +16,8 @@
5.1.
-4
+5
'%0A%0A
|
9ddb89b4b652fb3026632ffd79dea9321f58cc31
|
bump version in __init__.py
|
oneflow/__init__.py
|
oneflow/__init__.py
|
VERSION = '0.16.3.1'
|
Python
| 0.000023 |
@@ -14,9 +14,7 @@
.16.
-3.1
+4
'%0A
|
9d994180a38976939e5da1757303ef8ed76f5e07
|
bump version in __init__.py
|
oneflow/__init__.py
|
oneflow/__init__.py
|
VERSION = '0.19'
|
Python
| 0.000023 |
@@ -9,10 +9,12 @@
= '0.19
+.1
'%0A
|
8a3273d9ef3612902671e4288be2462f0ba0696a
|
Use send_mass_mail instead of send_mail so only one connection needs to be opened to the mailserver for the whole lot
|
volunteers/admin.py
|
volunteers/admin.py
|
from django.contrib import admin
from django.core.mail import send_mail
from django.db import models
from django.forms import TextInput, Textarea, Form, CharField, MultipleHiddenInput
from django.http import HttpResponseRedirect
from django.shortcuts import render
from volunteers.models import Edition
from volunteers.models import Track
from volunteers.models import Talk
from volunteers.models import TaskCategory
from volunteers.models import TaskTemplate
from volunteers.models import Task
from volunteers.models import Volunteer
from volunteers.models import VolunteerStatus
from volunteers.models import VolunteerTask
from volunteers.models import VolunteerCategory
class DayListFilter(admin.SimpleListFilter):
# Human-readable title which will be displayed in the
# right admin sidebar just above the filter options.
title = 'day'
parameter_name = 'day'
def lookups(self, request, model_admin):
return (
(6, 'Friday'),
(7, 'Saturday'),
(1, 'Sunday'),
(2, 'Monday'),
)
def queryset(self, request, queryset):
if self.value():
return queryset.filter(date__year=Edition.get_current_year(), \
date__week_day=self.value())
else:
return queryset
class VolunteerTaskInline(admin.TabularInline):
model = VolunteerTask
extra = 1
class VolunteerCategoryInline(admin.TabularInline):
model = VolunteerCategory
extra = 1
class EditionAdmin(admin.ModelAdmin):
fields = ['year', 'start_date', 'end_date']
list_display = ['year', 'start_date', 'end_date']
class TrackAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['edition', 'date', 'start_time']}),
(None, {'fields': ['title', 'description']}),
]
list_display = ['edition', 'date', 'start_time', 'title']
class TalkAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['track', 'speaker', 'title']}),
(None, {'fields': ['description']}),
(None, {'fields': ['date', 'start_time', 'end_time']}),
]
list_display = ['link', 'title', 'track', 'date', 'start_time']
list_editable = ['title', 'track', 'date', 'start_time']
list_filter = [DayListFilter, 'track']
class TaskCategoryAdmin(admin.ModelAdmin):
fields = ['name', 'description']
inlines = (VolunteerCategoryInline, )
list_display = ['name', 'assigned_volunteers']
class TaskTemplateAdmin(admin.ModelAdmin):
fields = ['name', 'description', 'category']
list_display = ['name', 'category']
class TaskAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['name', 'nbr_volunteers', 'nbr_volunteers_min', 'nbr_volunteers_max', 'date', 'start_time', 'end_time']}),
(None, {'fields': ['talk', 'template']}),
(None, {'fields': ['description']}),
]
inlines = (VolunteerTaskInline, )
list_display = ['link', 'name', 'date', 'start_time', 'end_time', 'assigned_volunteers', 'nbr_volunteers', 'nbr_volunteers_min', 'nbr_volunteers_max']
list_editable = ['name', 'date', 'start_time', 'end_time', 'nbr_volunteers', 'nbr_volunteers_min', 'nbr_volunteers_max']
list_filter = [DayListFilter, 'template', 'talk__track']
class VolunteerAdmin(admin.ModelAdmin):
fields = ['user', 'full_name', 'email', 'mobile_nbr', 'private_staff_rating', 'private_staff_notes']
inlines = (VolunteerCategoryInline, VolunteerTaskInline)
list_display = ['user', 'full_name', 'email', 'private_staff_rating', 'private_staff_notes', 'mobile_nbr']
list_editable = ['private_staff_rating', 'private_staff_notes', 'mobile_nbr']
list_filter = ['private_staff_rating']
readonly_fields = ['full_name', 'email']
formfield_overrides = {
models.CharField: {'widget': TextInput(attrs={'size':'20'})},
models.TextField: {'widget': Textarea(attrs={'rows':2, 'cols':20})},
}
actions = ['mass_mail_volunteer']
# Mass mail action
class MassMailForm(Form):
_selected_action = CharField(widget=MultipleHiddenInput)
subject = CharField()
message = CharField(widget=Textarea)
def mass_mail_volunteer(self, request, queryset):
form = None
if 'send' in request.POST:
form = self.MassMailForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
count = 0
plural = ''
for volunteer in queryset:
# TODO: actually send the mail
if volunteer.user.email:
send_mail(subject, message, '[email protected]', [volunteer.user.email], fail_silently=False)
count += 1
if count > 1:
plural = 's'
self.message_user(request, 'Mail with subject "%s" sent to %d volunteer%s.' % (subject, count, plural))
return HttpResponseRedirect(request.get_full_path())
if not form:
form = self.MassMailForm(initial={'_selected_action': request.POST.getlist(admin.ACTION_CHECKBOX_NAME)})
return render(request, 'admin/massmail.html', {'volunteers': queryset,
'massmail_form': form,
})
mass_mail_volunteer.short_description = "Send mass mail"
class VolunteerStatusAdmin(admin.ModelAdmin):
fields = ['edition', 'volunteer', 'active']
list_display = ['edition', 'volunteer', 'active']
admin.site.register(Edition, EditionAdmin)
admin.site.register(Track, TrackAdmin)
admin.site.register(Talk, TalkAdmin)
admin.site.register(TaskCategory, TaskCategoryAdmin)
admin.site.register(TaskTemplate, TaskTemplateAdmin)
admin.site.register(Task, TaskAdmin)
admin.site.register(Volunteer, VolunteerAdmin)
admin.site.register(VolunteerStatus, VolunteerStatusAdmin)
|
Python
| 0 |
@@ -26,16 +26,49 @@
t admin%0A
+from django.conf import settings%0A
from dja
@@ -89,24 +89,29 @@
import send_
+mass_
mail%0Afrom dj
@@ -4538,16 +4538,53 @@
al = ''%0A
+ volunteer_mails = %5B%5D%0A
@@ -4618,16 +4618,16 @@
eryset:%0A
-
@@ -4742,64 +4742,168 @@
-send_mail(subject, message, '[email protected]'
+volunteer_mails.append(volunteer.user.email)%0A count += 1%0A send_mass_mail(((subject, message, settings.DEFAULT_FROM_EMAIL
,
-%5B
volu
@@ -4911,20 +4911,17 @@
teer
-.user.email%5D
+_mails),)
, fa
@@ -4943,43 +4943,8 @@
se)%0A
- count += 1%0A
|
aaca641f968bf12eb2177460f8cf809d62ea3bd4
|
Add a strict version of itertools.groupby
|
bidb/utils/itertools.py
|
bidb/utils/itertools.py
|
Python
| 0.000003 |
@@ -0,0 +1,231 @@
+from __future__ import absolute_import%0A%0Aimport itertools%0A%0Adef groupby(iterable, keyfunc, sortfunc=lambda x: x):%0A return %5B%0A (x, list(sorted(y, key=sortfunc)))%0A for x, y in itertools.groupby(iterable, keyfunc)%0A %5D%0A
|
|
d2c414576cfcf935ed36ffe2c5fb594911be0832
|
work on sge module started
|
sge.py
|
sge.py
|
Python
| 0 |
@@ -0,0 +1,1731 @@
+from collections import OrderedDict%0A%0A__author__ = 'sfranky'%0Afrom lxml import etree%0A%0Afn = '/home/sfranky/PycharmProjects/results/gef_sge1/qstat.F.xml.stdout'%0Atree = etree.parse(fn)%0Aroot = tree.getroot()%0A%0A%0Adef extract_job_info(elem, elem_text):%0A %22%22%22%0A inside elem, iterates over subelems named elem_text and extracts relevant job information%0A %22%22%22%0A jobs = %5B%5D%0A for subelem in elem.iter(elem_text):%0A job = dict()%0A job%5B'job_state'%5D = subelem.find('./state').text%0A job%5B'job_name'%5D = subelem.find('./JB_name').text%0A job%5B'job_owner'%5D = subelem.find('./JB_owner').text%0A job%5B'job_slots'%5D = subelem.find('./slots').text%0A job%5B'job_nr'%5D = subelem.find('./JB_job_number').text%0A jobs.append(job)%0A # print '%5Ct' + job%5B'job_state'%5D, job%5B'job_name'%5D, job%5B'job_owner'%5D, job%5B'job_slots'%5D, job%5B'job_nr'%5D%0A return jobs%0A%0A%0Aworker_nodes = list()%0Afor queue_elem in root.iter('Queue-List'):%0A d = OrderedDict()%0A queue_name = queue_elem.find('./resource%5B@name=%22qname%22%5D').text%0A d%5B'domainname'%5D = host_name = queue_elem.find('./resource%5B@name=%22hostname%22%5D').text%0A slots_total = queue_elem.find('./slots_total').text%0A d%5B'np'%5D = queue_elem.find('./resource%5B@name=%22num_proc%22%5D').text%0A slots_used = queue_elem.find('./slots_used').text%0A slots_resv = queue_elem.find('./slots_resv').text%0A # print queue_name, host_name, slots_total, slots_used, slots_resv%0A%0A running_jobs = extract_job_info(queue_elem, 'job_list')%0A d%5B'core_job_map'%5D = %5B%7B'core': idx, 'job': job%5B'job_nr'%5D%7D for idx, job in enumerate(running_jobs)%5D%0A worker_nodes.append(d)%0A%0A%0Ajob_info_elem = root.find('./job_info')%0A# print 'PENDING JOBS'%0Apending_jobs = extract_job_info(job_info_elem, 'job_list')%0A%0A%0A%0A%0A
|
|
482a2639911b676bf68dcd529dcc1ffecaaf10ea
|
Create shortner.py
|
plugins/shortner.py
|
plugins/shortner.py
|
Python
| 0.000002 |
@@ -0,0 +1 @@
+%0A
|
|
5ae58621bd766aeaa6f1838397b045039568887c
|
Add driver to find plate solutions
|
platesolve.py
|
platesolve.py
|
Python
| 0 |
@@ -0,0 +1,303 @@
+import babeldix%0A%0Aimport sys%0Aimport operator%0A%0A# Print solutions in order of increasing score%0A%0Afor plate in sys.argv%5B1:%5D:%0A solns = babeldix.Plates.get_solutions(plate)%0A for (soln,score) in sorted(solns.items(), key=operator.itemgetter(1)):%0A print '%7B0:s%7D %7B1:d%7D %7B2:s%7D'.format(plate,score,soln)%0A
|
|
c1bfe92878edc3f9598a6d97046775cb8d9b0aa0
|
Make migration for item-visibility change
|
depot/migrations/0009_auto_20170330_1342.py
|
depot/migrations/0009_auto_20170330_1342.py
|
Python
| 0.000006 |
@@ -0,0 +1,513 @@
+# -*- coding: utf-8 -*-%0A# Generated by Django 1.10.6 on 2017-03-30 13:42%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations, models%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('depot', '0008_auto_20170330_0855'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterField(%0A model_name='item',%0A name='visibility',%0A field=models.CharField(choices=%5B('1', 'public'), ('2', 'private'), ('3', 'deleted')%5D, max_length=1),%0A ),%0A %5D%0A
|
|
03ecddce6f34d04957ca5161eb7d776daf02ed47
|
Add blobdb messages
|
protocol/blobdb.py
|
protocol/blobdb.py
|
Python
| 0 |
@@ -0,0 +1,618 @@
+__author__ = 'katharine'%0A%0Afrom base import PebblePacket%0Afrom base.types import *%0A%0A%0Aclass InsertCommand(PebblePacket):%0A key_size = Uint8()%0A key = BinaryArray(length=key_size)%0A value_size = Uint16()%0A value = BinaryArray(length=value_size)%0A%0A%0Aclass DeleteCommand(PebblePacket):%0A key_size = Uint8()%0A key = BinaryArray(length=key_size)%0A%0A%0Aclass ClearCommand(PebblePacket):%0A pass%0A%0A%0Aclass BlobCommand(PebblePacket):%0A command = Uint8()%0A token = Uint16()%0A database = Uint8()%0A content = Union(command, %7B%0A 0x01: InsertCommand,%0A 0x04: DeleteCommand,%0A 0x05: ClearCommand,%0A %7D)%0A
|
|
cf0310a7111bdb79b4bbe2a52095c8344778c80c
|
Add admin.py for protocols
|
protocols/admin.py
|
protocols/admin.py
|
Python
| 0 |
@@ -0,0 +1,92 @@
+from django.contrib import admin%0Afrom .models import Protocol%0A%0Aadmin.site.register(Protocol)
|
|
98ed7f3f682bf1ba23bb0030aa81e8fff23e54ad
|
Add harvester
|
scrapi/harvesters/uow.py
|
scrapi/harvesters/uow.py
|
Python
| 0.000012 |
@@ -0,0 +1,541 @@
+'''%0AHarvester for the Research Online for the SHARE project%0A%0AExample API call: http://ro.uow.edu.au/do/oai/?verb=ListRecords&metadataPrefix=oai_dc%0A'''%0Afrom __future__ import unicode_literals%0A%0Afrom scrapi.base import OAIHarvester%0A%0A%0Aclass UowHarvester(OAIHarvester):%0A short_name = 'uow'%0A long_name = 'University of Wollongong Research Online'%0A url = 'http://ro.uow.edu.au'%0A%0A base_url = 'http://ro.uow.edu.au/do/oai/'%0A property_list = %5B'date', 'source', 'identifier', 'type', 'format', 'setSpec'%5D%0A timezone_granularity = True%0A
|
|
1b4ca9e9afccfc1492aeea955f2cd3c783f1dc80
|
Create file_parser.py
|
file_parser.py
|
file_parser.py
|
Python
| 0 |
@@ -0,0 +1,2979 @@
+# -*- coding: utf-8 -*-%0A%22%22%22%0ACreated on Thu Mar 19 17:03:35 2015%0A%0A@author: pedro.correia%0A%22%22%22%0A%0Afrom __future__ import division # Just making sure that correct integer division is working%0Aimport numpy as np # This is numpy,python numerical library%0Aimport xlrd as xcl # This library allow you to manipulate (read and write) excel files%0Aimport cPickle as pickle # Library used to save and load dictionaries%0Aimport objects_parser as obj # Our local objects library.%0A%0Adef __open_excel_book__(path):%0A %22%22%22%0A NOTE: internal function. Use open_excel_file function.%0A User gives a string path and this function returns the open excel book.%0A %22%22%22%0A book = xcl.open_workbook(path,on_demand=True)%0A return book%0A %0Adef __array_by_type__(sheet,col,null=-999):%0A %22%22%22%0A NOTE: internal function. Use open_excel_file function.%0A This function receives sheet and column number and returns an array with the%0A correct type. The null is by default -999 but you can change it on the third%0A argument.%0A %22%22%22%0A try:%0A float(sheet.cell_value(1, col))%0A return np.zeros(sheet.nrows,dtype=type(sheet.cell_value(1, col))),null%0A except ValueError:%0A return np.zeros(sheet.nrows,dtype='%7CS15'),str(null) #type(sheet.cell_value(1, col))),str(null)%0A %0Adef __build_excel_dictionary__(book,null=-999):%0A %22%22%22%0A NOTE: internal function. Use open_excel_file function.%0A Function that receives an excel book (see: __open_excel_book__) and extracts to%0A dictionaries (with numpy arrays) all information from the excel book. Empty%0A cells are given the null value (default is -999).%0A %22%22%22%0A sheet_dictionary = %7B%7D%0A for name in book.sheet_names():%0A sheet = book.sheet_by_name(name)%0A local_dictionary = %7B%7D%0A for col in xrange(sheet.ncols):%0A local_array,null = __array_by_type__(sheet,col,null)%0A for row in xrange(1,sheet.nrows):%0A if sheet.cell_type(row, col) in (xcl.XL_CELL_EMPTY, xcl.XL_CELL_BLANK):%0A local_array%5Brow%5D = null%0A else:%0A local_array%5Brow%5D = sheet.cell_value(row, col)%0A local_dictionary%5Bsheet.cell_value(0, col)%5D = local_array%0A sheet_dictionary%5Bname%5D = local_dictionary%0A return sheet_dictionary%0A %0Adef open_excel_file(path,null=-999):%0A %22%22%22%0A Function that opens excel file into a excel_class_object and return the%0A last.%0A %22%22%22%0A book = __open_excel_book__(path)%0A data = obj.excelObject(__build_excel_dictionary__(book,null),null)%0A return data%0A %0Adef save_excel_object(path,obj):%0A %22%22%22%0A Saves excel object to file. Give path and excel object.%0A %22%22%22%0A with open(path, 'wb') as outfile:%0A pickle.dump(obj.me, outfile, protocol=pickle.HIGHEST_PROTOCOL)%0A %0Adef open_excel_object(path,null=-999):%0A %22%22%22%0A Creates an excel object from epy (pickle) loaded file.%0A %22%22%22%0A return obj.excelObject(pickle.load(open(path, %22rb%22 )),null)%0A
|
|
26d364765cdb0e4e4bf755286d92c305b8dabb0c
|
Add files via upload
|
find_qCodes.py
|
find_qCodes.py
|
Python
| 0 |
@@ -0,0 +1,786 @@
+__author__ = 'zoorobmj'%0D%0Aimport re%0D%0Aimport csv%0D%0Aimport os%0D%0A%0D%0A%0D%0Aif __name__ == '__main__':%0D%0A folder = %22C:%5CUsers%5Czoorobmj%5CPycharmProjects%5CQuestion_Matrix%22 # my directory%0D%0A files = %5Bf for f in os.listdir(folder) if f.endswith('.txt')%5D%0D%0A q_list = %5B%5D%0D%0A for f in folder:%0D%0A Qs = open('CoreESP2016.txt', 'r').read()%0D%0A # print Qs%0D%0A # find all meeting this pattern%0D%0A # get unique values%0D%0A # return as csv%0D%0A q_codes = re.findall(r%22%5BA-Z%5D+%5BA-Z0-9%5D*%5B.%5D%22, Qs)%0D%0A q_list.append(q_codes)%0D%0A%0D%0A with open(%22CoreESP2016.csv%22, 'wb') as output:%0D%0A writer = csv.writer(output, lineterminator='%5Cn')%0D%0A for val in q_list:%0D%0A if len(val)==2:%0D%0A print val%0D%0A else:%0D%0A writer.writerow(%5Bval%5D)
|
|
5ae45bfbbd6559d344eb641853ef8e83b3ff1c90
|
Add wowza blueprint
|
blues/wowza.py
|
blues/wowza.py
|
Python
| 0 |
@@ -0,0 +1,1394 @@
+%22%22%22%0AWowza Blueprint%0A===============%0A%0A**Fabric environment:**%0A%0A.. code-block:: yaml%0A%0A blueprints:%0A - blues.wowza%0A%0A%22%22%22%0Afrom fabric.decorators import task%0A%0Afrom refabric.api import run, info%0Afrom refabric.context_managers import sudo%0Afrom refabric.contrib import blueprints%0A%0Afrom . import debian%0A%0A__all__ = %5B'start', 'stop', 'restart', 'setup', 'configure'%5D%0A%0A%0Ablueprint = blueprints.get(__name__)%0A%0Astart = debian.service_task('WowzaStreamingEngine', 'start')%0Astop = debian.service_task('WowzaStreamingEngine', 'stop')%0Arestart = debian.service_task('WowzaStreamingEngine', 'restart')%0A%0Awowza_root ='/usr/local/WowzaMediaServer/'%0A%0A@task%0Adef setup():%0A %22%22%22%0A Install and configure Wowza%0A %22%22%22%0A install()%0A configure()%0A%0A%0Adef install():%0A with sudo():%0A%0A info('Downloading wowza')%0A version = blueprint.get('wowza_version', '4.1.2')%0A binary = 'WowzaStreamingEngine-%7B%7D.deb.bin'.format(version)%0A version_path = version.replace('.', '-')%0A url = 'http://www.wowza.com/downloads/WowzaStreamingEngine-%7B%7D/%7B%7D'.format(version_path,%0A binary)%0A run('wget -P /tmp/ %7Burl%7D'.format(url=url))%0A%0A debian.chmod('/tmp/%7B%7D'.format(binary), '+x')%0A info('Installing wowza')%0A run('/tmp/%7B%7D'.format(binary))%0A%0A%0A@task%0Adef configure():%0A %22%22%22%0A Configure Wowza%0A %22%22%22%0A
|
|
0e53f398bf2cf885393865ec1f899308bb56625b
|
Add a low-level example for creating views.
|
examples/create_a_view_low_level.py
|
examples/create_a_view_low_level.py
|
Python
| 0 |
@@ -0,0 +1,490 @@
+%22%22%22%0AA low level example:%0AThis is how JenkinsAPI creates views%0A%22%22%22%0Aimport requests%0Aimport json%0A%0Aurl = 'http://localhost:8080/newView'%0Astr_view_name = %22ddsfddfd%22%0Aparams = %7B%7D# %7B'name': str_view_name%7D%0Aheaders = %7B'Content-Type': 'application/x-www-form-urlencoded'%7D%0Adata = %7B%0A %22mode%22: %22hudson.model.ListView%22,%0A #%22Submit%22: %22OK%22,%0A %22name%22: str_view_name%0A%7D%0A# Try 1%0Aresult = requests.post(url, params=params, data=%7B'json':json.dumps(data)%7D, headers=headers)%0Aprint result.text.encode('UTF-8')%0A
|
|
35f3cd96c6bd8c3a8772fc0f74c5e19d33d0a4ba
|
Revert "show how threading could work"
|
examples/csv_example/csv_example.py
|
examples/csv_example/csv_example.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This code demonstrates how to use dedupe with a comma separated values
(CSV) file. All operations are performed in memory, so will run very
quickly on datasets up to ~10,000 rows.
We start with a CSV file containing our messy data. In this example,
it is listings of early childhood education centers in Chicago
compiled from several different sources.
The output will be a CSV with our clustered results.
For larger datasets, see our [mysql_example](http://open-city.github.com/dedupe/doc/mysql_example.html)
"""
import os
import csv
import re
import collections
import logging
import optparse
from numpy import nan
import threading
import datetime
import dedupe
class ThreadClass(threading.Thread):
deduper = None
def run(self):
self.deduper.train()
now = datetime.datetime.now()
print "%s says Hello World at time: %s" % (self.getName(), now)
# ## Logging
# Dedupe uses Python logging to show or suppress verbose output. Added for convenience.
# To enable verbose logging, run `python examples/csv_example/csv_example.py -v`
optp = optparse.OptionParser()
optp.add_option('-v', '--verbose', dest='verbose', action='count',
help='Increase verbosity (specify multiple times for more)'
)
(opts, args) = optp.parse_args()
log_level = logging.WARNING
if opts.verbose == 1:
log_level = logging.INFO
elif opts.verbose >= 2:
log_level = logging.DEBUG
logging.basicConfig(level=log_level)
# ## Setup
# Switch to our working directory and set up our input and out put paths,
# as well as our settings and training file locations
os.chdir('./examples/csv_example/')
input_file = 'csv_example_messy_input.csv'
output_file = 'csv_example_output.csv'
settings_file = 'csv_example_learned_settings'
training_file = 'csv_example_training.json'
# Dedupe can take custom field comparison functions, here's one
# we'll use for zipcodes
def sameOrNotComparator(field_1, field_2) :
if field_1 and field_2 :
if field_1 == field_2 :
return 1
else:
return 0
else :
return nan
def preProcess(column):
"""
Do a little bit of data cleaning with the help of
[AsciiDammit](https://github.com/tnajdek/ASCII--Dammit) and
Regex. Things like casing, extra spaces, quotes and new lines can
be ignored.
"""
column = dedupe.asciiDammit(column)
column = re.sub(' +', ' ', column)
column = re.sub('\n', ' ', column)
column = column.strip().strip('"').strip("'").lower().strip()
return column
def readData(filename):
"""
Read in our data from a CSV file and create a dictionary of records,
where the key is a unique record ID and each value is dict
"""
data_d = {}
with open(filename) as f:
reader = csv.DictReader(f)
for row in reader:
clean_row = [(k, preProcess(v)) for (k, v) in row.items()]
row_id = int(row['Id'])
data_d[row_id] = dict(clean_row)
return data_d
print 'importing data ...'
data_d = readData(input_file)
# ## Training
if os.path.exists(settings_file):
print 'reading from', settings_file
deduper = dedupe.StaticDedupe(settings_file)
else:
# Define the fields dedupe will pay attention to
#
# Notice how we are telling dedupe to use a custom field comparator
# for the 'Zip' field.
fields = {
'Site name': {'type': 'String'},
'Address': {'type': 'String'},
'Zip': {'type': 'Custom',
'comparator' : sameOrNotComparator,
'Has Missing' : True},
'Phone': {'type': 'String', 'Has Missing' : True},
}
# Create a new deduper object and pass our data model to it.
deduper = dedupe.Dedupe(fields)
# To train dedupe, we feed it a random sample of records.
deduper.sample(data_d, 150000)
# If we have training data saved from a previous run of dedupe,
# look for it an load it in.
# __Note:__ if you want to train from scratch, delete the training_file
if os.path.exists(training_file):
print 'reading labeled examples from ', training_file
deduper.readTraining(training_file)
# ## Active learning
# Dedupe will find the next pair of records
# it is least certain about and ask you to label them as duplicates
# or not.
# use 'y', 'n' and 'u' keys to flag duplicates
# press 'f' when you are finished
print 'starting active labeling...'
dedupe.consoleLabel(deduper)
t = ThreadClass()
t.deduper = deduper
t.start()
# When finished, save our training away to disk
deduper.writeTraining(training_file)
# Save our weights and predicates to disk. If the settings file
# exists, we will skip all the training and learning next time we run
# this file.
deduper.writeSettings(settings_file)
# ## Blocking
print 'blocking...'
# ## Clustering
# Find the threshold that will maximize a weighted average of our precision and recall.
# When we set the recall weight to 2, we are saying we care twice as much
# about recall as we do precision.
#
# If we had more data, we would not pass in all the blocked data into
# this function but a representative sample.
threshold = deduper.threshold(data_d, recall_weight=2)
# `duplicateClusters` will return sets of record IDs that dedupe
# believes are all referring to the same entity.
print 'clustering...'
clustered_dupes = deduper.match(data_d, threshold)
print '# duplicate sets', len(clustered_dupes)
# ## Writing Results
# Write our original data back out to a CSV with a new column called
# 'Cluster ID' which indicates which records refer to each other.
cluster_membership = collections.defaultdict(lambda : 'x')
for (cluster_id, cluster) in enumerate(clustered_dupes):
for record_id in cluster:
cluster_membership[record_id] = cluster_id
with open(output_file, 'w') as f:
writer = csv.writer(f)
with open(input_file) as f_input :
reader = csv.reader(f_input)
heading_row = reader.next()
heading_row.insert(0, 'Cluster ID')
writer.writerow(heading_row)
for row in reader:
row_id = int(row[0])
cluster_id = cluster_membership[row_id]
row.insert(0, cluster_id)
writer.writerow(row)
|
Python
| 0 |
@@ -664,281 +664,22 @@
nan%0A
-import threading%0Aimport datetime%0A %0A%0Aimport dedupe%0A%0Aclass ThreadClass(threading.Thread):%0A deduper = None%0A%0A def run(self):%0A self.deduper.train()%0A%0A now = datetime.datetime.now()%0A print %22%25s says Hello World at time: %25s%22 %25 (self.getName(), now)
+%0Aimport dedupe
%0A%0A#
@@ -2128,17 +2128,16 @@
gnored.%0A
-%0A
%22%22%22%0A
@@ -4309,62 +4309,21 @@
-t = ThreadClass()%0A t.deduper = deduper%0A%0A t.start
+deduper.train
()%0A%0A
@@ -4619,17 +4619,16 @@
file)%0A%0A%0A
-%0A
# ## Blo
|
4c73cad398d5dac85b264187f709a860f356b311
|
Add new file with mixin for mysql
|
smipyping/_mysqldbmixin.py
|
smipyping/_mysqldbmixin.py
|
Python
| 0 |
@@ -0,0 +1,2607 @@
+#!/usr/bin/env python%0A# (C) Copyright 2017 Inova Development Inc.%0A# All Rights Reserved%0A#%0A# Licensed under the Apache License, Version 2.0 (the %22License%22);%0A# you may not use this file except in compliance with the License.%0A# You may obtain a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS,%0A# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A# See the License for the specific language governing permissions and%0A# limitations under the License.%0A%0Afrom __future__ import print_function, absolute_import%0A%0Afrom mysql.connector import MySQLConnection%0A%0Aclass MySQLDBMixin(object):%0A %22%22%22%0A Provides some common methods to mixin in with the MySQL...Tables%0A classes%0A %22%22%22%0A def connectdb(self, db_dict, verbose):%0A %22%22%22Connect the db%22%22%22%0A try:%0A connection = MySQLConnection(host=db_dict%5B'host'%5D,%0A database=db_dict%5B'database'%5D,%0A user=db_dict%5B'user'%5D,%0A password=db_dict%5B'password'%5D)%0A%0A if connection.is_connected():%0A self.connection = connection%0A if verbose:%0A print('sql db connection established. host %25s, db %25s' %25%0A (db_dict%5B'host'%5D, db_dict%5B'database'%5D))%0A else:%0A print('SQL database connection failed. host %25s, db %25s' %25%0A (db_dict%5B'host'%5D, db_dict%5B'database'%5D))%0A raise ValueError('Connection to database failed')%0A except Exception as ex:%0A raise ValueError('Could not connect to sql database %25r. '%0A ' Exception: %25r'%0A %25 (db_dict, ex))%0A%0A def _load_table(self):%0A %22%22%22%0A Load the internal dictionary from the database based on the%0A fields definition%0A %22%22%22%0A try:%0A cursor = self.connection.cursor(dictionary=True)%0A%0A fields = ', '.join(self.fields)%0A sql = 'SELECT %25s FROM %25s' %25 (fields, self.table_name)%0A cursor.execute(sql)%0A rows = cursor.fetchall()%0A for row in rows:%0A key = row%5Bself.key_field%5D%0A self.data_dict%5Bkey%5D = row%0A%0A except Exception as ex:%0A raise ValueError('Error: setup sql based targets table %25r. '%0A 'Exception: %25r'%0A %25 (self.db_dict, ex))%0A
|
|
206c99420101655d7495000d659d571ef729300b
|
Add areas spider
|
soccerway/spiders/areas.py
|
soccerway/spiders/areas.py
|
Python
| 0.000002 |
@@ -0,0 +1,1348 @@
+# -*- coding: utf-8 -*-%0Aimport scrapy%0Afrom soccerway.items import Match%0Afrom urllib.parse import urlencode%0A%0Aclass AreasSpider(scrapy.Spider):%0A name = %22areas%22%0A allowed_domains = %5B%22http://www.soccerway.mobi%22%5D%0A start_urls = %5B'http://www.soccerway.mobi/?'%5D%0A params = %7B%0A %22sport%22: %22soccer%22,%0A %22page%22: %22leagues%22,%0A %22view%22 : %22by_area%22,%0A %22area_id%22 : %22212%22,%0A %22localization_id%22: %22www%22%0A %7D%0A def start_requests(self):%0A for i in range(8,11):%0A self.params%5B'area_id'%5D = str(i)%0A request = scrapy.Request(url=self.start_urls%5B0%5D+urlencode(self.params), callback=self.parse)%0A request.meta%5B'proxy'%5D = 'http://127.0.0.1:8118'%0A yield request%0A%0A def parse(self, response):%0A self.log('URL: %7B%7D'.format(response.url))%0A%0A %22%22%22%0A def parse(self, response):%0A venue = Venue()%0A venue%5B'country'%5D, venue%5B'city'%5D, venue%5B'name'%5D = response.css('title::text')%5B0%5D.extract().split(',')%0A res = response.xpath('//td//b/text()')%0A if len(res) %3E 0:%0A venue%5B'opened'%5D = res%5B0%5D.extract()%0A res = response.xpath('//td//b/text()')%0A if len(res) %3E 1:%0A venue%5B'capacity'%5D = res%5B1%5D.extract()%0A venue%5B'lat'%5D, venue%5B'lng'%5D = response.xpath('//script/text()')%5B1%5D.re(r'%5C((.*)%5C)')%5B1%5D.split(',')%0A return venue%0A %22%22%22%0A%0A
|
|
e39bce6ba02ad4ed3c20768c234606afb48ac86a
|
Solve Largest Product
|
python/euler008.py
|
python/euler008.py
|
Python
| 0.999999 |
@@ -0,0 +1,926 @@
+#!/bin/python3%0A%0Aimport sys%0Afrom functools import reduce%0A%0Aclass LargestProduct:%0A%0A def __init__(self, num, num_consecutive_digits):%0A self.num = num%0A self.num_consecutive_digits = num_consecutive_digits%0A%0A def largest_product(self):%0A return max(map(LargestProduct.product, LargestProduct.slices(LargestProduct.digits(self.num), self.num_consecutive_digits)))%0A%0A @staticmethod%0A def slices(array, slice_length):%0A return %5Barray%5Bi:i + slice_length%5D for i in range(len(array) - slice_length)%5D%0A%0A @staticmethod%0A def digits(num):%0A return %5Bint(x) for x in str(num)%5D%0A%0A @staticmethod%0A def product(array):%0A return reduce((lambda x, y: x * y), array)%0A%0At = int(input().strip())%0Afor a0 in range(t):%0A _, num_consecutive_digits = map(int, input().strip().split(' '))%0A num = input().strip()%0A lp = LargestProduct(num, num_consecutive_digits)%0A print (lp.largest_product())%0A
|
|
dc4620b46cdca4084fe0b64e3f8e08025e511cea
|
fix sanitizer
|
intelmq/bots/experts/sanitizer/sanitizer.py
|
intelmq/bots/experts/sanitizer/sanitizer.py
|
from intelmq.lib.bot import Bot, sys
from intelmq.bots import utils
class SanitizerBot(Bot):
def process(self):
event = self.receive_message()
if event:
keys_pairs = [
(
"source_ip",
"source_domain_name",
"source_url"
),
(
"destination_ip",
"destination_domain_name",
"destination_url"
)
]
for keys in keys_pairs:
ip = domain_name = url = None
for key in keys:
if not event.contains(key):
continue
value = event.value(key)
if len(value) <= 2: # ignore invalid values
continue
result = utils.is_ip(value)
if result:
ip = result
result = utils.is_domain_name(value)
if result:
domain_name = result
result = utils.is_url(value)
if result:
url = result
if not domain_name and url:
domain_name = utils.get_domain_name_from_url(url)
if not ip and domain_name:
ip = utils.get_ip_from_domain_name(domain_name)
if not ip and url:
ip = utils.get_ip_from_url(url)
for key in keys:
event.clear(key)
if "url" in key and url:
event.add(key, url)
if "domain_name" in key and domain_name:
event.add(key, domain_name)
if "ip" in key and ip:
event.add(key, ip)
self.send_message(event)
self.acknowledge_message()
if __name__ == "__main__":
bot = SanitizerBot(sys.argv[1])
bot.start()
|
Python
| 0.000001 |
@@ -378,25 +378,71 @@
%22source_url%22
+,%0A %22source_asn%22
%0A
-
@@ -648,16 +648,67 @@
ion_url%22
+,%0A %22destination_asn%22
%0A
@@ -915,32 +915,123 @@
%0A
+ if %22asn%22 in key:%0A continue%0A %0A
@@ -2104,45 +2104,8 @@
ys:%0A
- event.clear(key)%0A
@@ -2158,32 +2158,73 @@
in key and url:%0A
+ event.clear(key)%0A
@@ -2329,32 +2329,73 @@
nd domain_name:%0A
+ event.clear(key)%0A
@@ -2532,19 +2532,265 @@
ent.
-add(key, ip
+clear(key)%0A event.add(key, ip)%0A%0A if %22asn%22 in key:%0A try:%0A int(event.value(key))%0A except ValueError:%0A event.clear(key
)%0A%0A
|
cd239be7ec84ccb000992841700effeb4bc6a508
|
Add quickstart fabfile.py
|
streamparse/bootstrap/project/fabfile.py
|
streamparse/bootstrap/project/fabfile.py
|
Python
| 0.000001 |
@@ -0,0 +1,706 @@
+%22%22%22fab env:prod deploy:wordcount%22%22%22%0Aimport json%0A%0Afrom fabric.api import run, put, env as _env%0Afrom fabric.decorators import task%0A%0A%0A@task%0Adef env(e=None):%0A %22%22%22Activate a particular environment from the config.json file.%22%22%22%0A with open('config.json', 'r') as fp:%0A config = json.load(fp)%0A _env.hosts = config%5B'envs'%5D%5Be%5D%5B'hosts'%5D%0A%0A%0A@task%0Adef deploy(topology=None):%0A %22%22%22Deploy a topology to a remote host. Deploying a streamparse topology%0A accomplishes two things:%0A 1. Create an uberjar which contains all code.%0A 2. Push the topology virtualenv requirements to remote.%0A 3. Update virtualenv on host server.%0A 4. Submit topology (in uberjar) to remote Storm cluster.%22%22%22%0A pass%0A
|
|
348b10962f12e1c49ed5c4caf06a838b89b1e5af
|
Create plasma.py
|
plasma.py
|
plasma.py
|
Python
| 0.000003 |
@@ -0,0 +1,16 @@
+import geometry%0A
|
|
bd05625c2e0a164f0b720c8c13fb06540d4fcdb9
|
Create ica_demo.py (#496)
|
scripts/ica_demo.py
|
scripts/ica_demo.py
|
Python
| 0 |
@@ -0,0 +1,1715 @@
+# Blind source separation using FastICA and PCA%0A# Author : Aleyna Kara%0A# This file is based on https://github.com/probml/pmtk3/blob/master/demos/icaDemo.m%0A%0Afrom sklearn.decomposition import PCA, FastICA%0Aimport numpy as np%0Aimport matplotlib.pyplot as plt%0Aimport pyprobml_utils as pml%0A%0Adef plot_signals(signals, suptitle, file_name):%0A plt.figure(figsize=(8, 4))%0A for i, signal in enumerate(signals, 1):%0A plt.subplot(n_signals, 1, i)%0A plt.plot(signal)%0A plt.xlim(%5B0, N%5D)%0A plt.tight_layout()%0A plt.suptitle(suptitle)%0A plt.subplots_adjust(top=0.85)%0A pml.savefig(f'%7Bfile_name%7D.pdf')%0A plt.show()%0A%0A# https://github.com/davidkun/FastICA/blob/master/demosig.m%0Adef generate_signals():%0A v = np.arange(0, 500)%0A signals = np.zeros((n_signals, N))%0A%0A signals%5B0, :%5D = np.sin(v/2) # sinusoid%0A signals%5B1, :%5D = ((v %25 23 - 11) / 9)**5%0A signals%5B2, :%5D = ((v %25 27 - 13)/ 9) # sawtooth%0A%0A rand = np.random.rand(1, N)%0A signals%5B3, :%5D = np.where(rand %3C 0.5, rand * 2 -1, -1) * np.log(np.random.rand(1, N)) #impulsive noise%0A%0A signals /= signals.std(axis=1).reshape((-1,1))%0A signals -= signals.mean(axis=1).reshape((-1,1))%0A A = np.random.rand(n_signals, n_signals) # mixing matrix%0A return signals, A @ signals%0A%0Anp.random.seed(0)%0An_signals, N = 4, 500%0Asignals, mixed_signals = generate_signals()%0A%0Aplot_signals(signals, 'Truth', 'ica-truth')%0A%0Aplot_signals(mixed_signals, 'Observed Signals', 'ica-obs')%0A%0Apca = PCA(whiten=True, n_components=4)%0Asignals_pca = pca.fit(mixed_signals.T).transform(mixed_signals.T)%0A%0Aica = FastICA(algorithm='deflation', n_components=4)%0Asignals_ica = ica.fit_transform(mixed_signals.T)%0A%0Aplot_signals(signals_pca.T, 'PCA estimate','ica-pca')%0A%0Aplot_signals(signals_ica.T, 'ICA estimate', 'ica-ica')
|
|
a8add82f2f9092d07f9ef40420c4b303700c912d
|
add a 'uniq' function
|
lib/uniq.py
|
lib/uniq.py
|
Python
| 0.999997 |
@@ -0,0 +1,346 @@
+# from http://www.peterbe.com/plog/uniqifiers-benchmark%0A%0A%0Adef identity(x):%0A return x%0A%0A%0Adef uniq(seq, idfun=identity):%0A # order preserving%0A seen = %7B%7D%0A result = %5B%5D%0A for item in seq:%0A marker = idfun(item)%0A if marker in seen:%0A continue%0A seen%5Bmarker%5D = True%0A result.append(item)%0A return result%0A
|
|
c57c672aae98fb5b280f70b68ac27fc2d94a243f
|
Add test class to cover the RandomForestClassifier in Go
|
tests/estimator/classifier/RandomForestClassifier/RandomForestClassifierGoTest.py
|
tests/estimator/classifier/RandomForestClassifier/RandomForestClassifierGoTest.py
|
Python
| 0 |
@@ -0,0 +1,563 @@
+# -*- coding: utf-8 -*-%0A%0Afrom unittest import TestCase%0A%0Afrom sklearn.ensemble import RandomForestClassifier%0A%0Afrom tests.estimator.classifier.Classifier import Classifier%0Afrom tests.language.Go import Go%0A%0A%0Aclass RandomForestClassifierGoTest(Go, Classifier, TestCase):%0A%0A def setUp(self):%0A super(RandomForestClassifierGoTest, self).setUp()%0A self.estimator = RandomForestClassifier(n_estimators=100,%0A random_state=0)%0A%0A def tearDown(self):%0A super(RandomForestClassifierGoTest, self).tearDown()%0A
|
|
e045a7bd1c3d791de40412bafa62702bee59132e
|
Add Python solution for day 15.
|
day15/solution.py
|
day15/solution.py
|
Python
| 0.000004 |
@@ -0,0 +1,1389 @@
+%0Adata = open(%22data%22, %22r%22).read()%0A%0Aingredients = %5B%5D%0A%0Afor line in data.split(%22%5Cn%22):%0A%09name = line.split(%22: %22)%5B0%5D%0A%0A%09properties = line.split(%22: %22)%5B1%5D.split(%22, %22)%0A%0A%09props = %7B 'value': 0 %7D%0A%09for prop in properties:%0A%09%09props%5Bprop.split(%22 %22)%5B0%5D%5D = int(prop.split(%22 %22)%5B1%5D)%0A%0A%09ingredients.append(props)%0A%0Adef getPropertyScore(property, ingredients):%0A%09value = 0%0A%09for ingredient in ingredients:%0A%09%09value += ingredient%5Bproperty%5D * ingredient%5B'value'%5D%0A%0A%09if value %3C= 0:%0A%09%09return 0%0A%09else:%0A%09%09return value%0A%0Adef calculateScore(ingredients):%0A%09score = getPropertyScore(%22capacity%22, ingredients)%0A%09score *= getPropertyScore(%22durability%22, ingredients)%0A%09score *= getPropertyScore(%22flavor%22, ingredients)%0A%09score *= getPropertyScore(%22texture%22, ingredients)%0A%0A%09calories = getPropertyScore(%22calories%22, ingredients)%0A%0A%09return score, calories%0A%0Adef addValue(ingredient, value):%0A%09ingredient%5B'value'%5D = value%0A%09return ingredient%0A%0AmaxScore = -100%0A%0AoptionsTried = 0%0Afor i in xrange(1, 100):%0A%09for j in xrange(1, 100 - i):%0A%09%09for k in xrange(1, 100 - i - j):%0A%09%09%09h = 100 - i - j - k%0A%0A%09%09%09scoreInput = %5B%0A%09%09%09%09addValue(ingredients%5B0%5D, i),%0A%09%09%09%09addValue(ingredients%5B1%5D, j),%0A%09%09%09%09addValue(ingredients%5B2%5D, k),%0A%09%09%09%09addValue(ingredients%5B3%5D, h)%0A%09%09%09%5D%0A%0A%09%09%09score, calories = calculateScore(scoreInput)%0A%0A%09%09%09if calories == 500 and maxScore %3C score:%0A%09%09%09%09maxScore = score%0A%0A%09%09%09optionsTried += 1%0A%0Aprint %22maxScore:%22, maxScore%0Aprint %22optionsTried:%22, optionsTried%0A
|
|
df68e5aa8ab620f03c668ae886ed8a1beef3c697
|
Add HKDF-SHA256 implementation.
|
hkdf-sha256.py
|
hkdf-sha256.py
|
Python
| 0 |
@@ -0,0 +1,1304 @@
+#!/usr/bin/python%0A# -*- coding: utf-8 -*-%0A%0Afrom Crypto.Hash import HMAC%0Afrom Crypto.Hash import SHA256%0A%0Aimport obfsproxy.transports.base as base%0A%0Aimport math%0A%0A%0Aclass HKDF_SHA256( object ):%0A%09%22%22%22%0A%09Implements HKDF using SHA256: https://tools.ietf.org/html/rfc5869%0A%09This class only implements the %60expand' but not the %60extract' stage.%0A%09%22%22%22%0A%0A%09def __init__( self, prk, info=%22%22, length=32 ):%0A%0A%09%09self.HashLen = 32%0A%0A%09%09if length %3E (self.HashLen * 255):%0A%09%09%09raise ValueError(%22The OKM's length cannot be larger than %25d.%22 %25 %5C%0A%09%09%09%09%09(self.HashLen * 255))%0A%0A%09%09if len(prk) %3C self.HashLen:%0A%09%09%09raise ValueError(%22The PRK must be at least %25d bytes in length.%22 %25 %5C%0A%09%09%09%09%09self.HashLen)%0A%0A%09%09self.N = math.ceil(float(length) / self.HashLen)%0A%09%09self.prk = prk%0A%09%09self.info = info%0A%09%09self.length = length%0A%09%09self.ctr = 1%0A%09%09self.T = %22%22%0A%0A%0A%09def expand( self ):%0A%09%09%22%22%22Expands, based on PRK, info and L, the given input material to the%0A%09%09output key material.%22%22%22%0A%0A%09%09tmp = %22%22%0A%0A%09%09# Prevent the accidental re-use of output keying material.%0A%09%09if len(self.T) %3E 0:%0A%09%09%09raise base.PluggableTransportError(%22HKDF-SHA256 OKM must not %22 %5C%0A%09%09%09%09%09%22be re-used by application.%22)%0A%0A%09%09while self.length %3E len(self.T):%0A%09%09%09tmp = HMAC.new(self.prk, tmp + self.info + chr(self.ctr),%0A%09%09%09%09%09SHA256).digest()%0A%09%09%09self.T += tmp%0A%09%09%09self.ctr += 1%0A%0A%09%09return self.T%5B:self.length%5D%0A
|
|
d4adf3e0e177e80ce7bc825f1cb4e461e5551b2f
|
Add basic configuration support to oonib
|
oonib/config.py
|
oonib/config.py
|
Python
| 0 |
@@ -0,0 +1,581 @@
+from ooni.utils import Storage%0Aimport os%0A%0A# XXX convert this to something that is a proper config file%0Amain = Storage()%0Amain.reporting_port = 8888%0Amain.http_port = 8080%0Amain.dns_udp_port = 5354%0Amain.dns_tcp_port = 8002%0Amain.daphn3_port = 9666%0Amain.server_version = %22Apache%22%0A#main.ssl_private_key = /path/to/data/private.key%0A#main.ssl_certificate = /path/to/data/certificate.crt%0A#main.ssl_port = 8433%0A%0Ahelpers = Storage()%0Ahelpers.http_return_request_port = 1234%0A%0Adaphn3 = Storage()%0Adaphn3.yaml_file = %22/path/to/data/oonib/daphn3.yaml%22%0Adaphn3.pcap_file = %22/path/to/data/server.pcap%22%0A
|
|
48e9887d92e08fb3f001957adb5e4f009699b864
|
Fix key release in keyhandler
|
shell/view/keyhandler.py
|
shell/view/keyhandler.py
|
import dbus
import gobject
from sugar import env
from hardware import hardwaremanager
from model.ShellModel import ShellModel
from _sugar import KeyGrabber
import sugar
_actions_table = {
'F1' : 'zoom_mesh',
'F2' : 'zoom_friends',
'F3' : 'zoom_home',
'F4' : 'zoom_activity',
'F5' : 'brightness_1',
'F6' : 'brightness_2',
'F7' : 'brightness_3',
'F8' : 'brightness_4',
'F9' : 'volume_1',
'F10' : 'volume_2',
'F11' : 'volume_3',
'F12' : 'volume_4',
'<alt>F5' : 'color_mode',
'<alt>F8' : 'b_and_w_mode',
'<alt>equal' : 'console',
'<alt>0' : 'console',
'<alt>f' : 'frame',
'0x93' : 'frame',
'<alt>o' : 'overlay',
'0xE0' : 'overlay',
'0xDC' : 'camera',
'0x7C' : 'shutdown',
'<alt><shift>s' : 'shutdown',
'0xEB' : 'rotate',
'<alt>r' : 'rotate',
'0xEC' : 'keyboard_brightness',
'<alt>Tab' : 'home'
}
class KeyHandler(object):
def __init__(self, shell):
self._shell = shell
self._audio_manager = hardwaremanager.get_audio_manager()
self._screen_rotation = 0
self._key_grabber = KeyGrabber()
self._key_grabber.connect('key-pressed',
self._key_pressed_cb)
self._key_grabber.connect('key-released',
self._key_released_cb)
for key in _actions_table.keys():
self._key_grabber.grab(key)
def _set_display_brightness(self, level):
hw_manager = hardwaremanager.get_hardware_manager()
if hw_manager:
hw_manager.set_display_brightness(level)
def _set_display_mode(self, mode):
hw_manager = hardwaremanager.get_hardware_manager()
if hw_manager:
hw_manager.set_display_mode(mode)
def handle_zoom_mesh(self):
self._shell.set_zoom_level(sugar.ZOOM_MESH)
def handle_zoom_friends(self):
self._shell.set_zoom_level(sugar.ZOOM_FRIENDS)
def handle_zoom_home(self):
self._shell.set_zoom_level(sugar.ZOOM_HOME)
def handle_zoom_activity(self):
self._shell.set_zoom_level(sugar.ZOOM_ACTIVITY)
def handle_brightness_1(self):
self._set_display_brightness(0)
def handle_brightness_2(self):
self._set_display_brightness(5)
def handle_brightness_3(self):
self._set_display_brightness(9)
def handle_brightness_4(self):
self._set_display_brightness(15)
def handle_volume_1(self):
self._audio_manager.set_volume(0)
def handle_volume_2(self):
self._audio_manager.set_volume(50)
def handle_volume_3(self):
self._audio_manager.set_volume(80)
def handle_volume_4(self):
self._audio_manager.set_volume(100)
def handle_color_mode(self):
self._set_display_mode(hardwaremanager.COLOR_MODE)
def handle_b_and_w_mode(self):
self._set_display_mode(hardwaremanager.B_AND_W_MODE)
def handle_console(self):
gobject.idle_add(self._toggle_console_visibility_cb)
def handle_frame(self):
self._shell.get_frame().notify_key_press()
def handle_overlay(self):
self._shell.toggle_chat_visibility()
def handle_camera(self):
current_activity = self._shell.get_current_activity()
if current_activity:
if current_activity.execute('camera', []):
return
self._shell.start_activity('org.laptop.CameraActivity')
def handle_shutdown(self):
model = self._shell.get_model()
model.props.state = ShellModel.STATE_SHUTDOWN
if env.is_emulator():
return
bus = dbus.SystemBus()
proxy = bus.get_object('org.freedesktop.Hal',
'/org/freedesktop/Hal/devices/computer')
mgr = dbus.Interface(proxy, 'org.freedesktop.Hal.Device.SystemPowerManagement')
mgr.Shutdown()
def handle_keyboard_brightness(self):
hw_manager = hardwaremanager.get_hardware_manager()
if hw_manager:
hw_manager.toggle_keyboard_brightness()
def handle_rotate(self):
states = [ 'normal', 'left', 'inverted', 'right']
self._screen_rotation += 1
if self._screen_rotation == len(states):
self._screen_rotation = 0
gobject.spawn_async(['xrandr', '-o', states[self._screen_rotation]],
flags=gobject.SPAWN_SEARCH_PATH)
def handle_home(self):
# FIXME: finish alt+tab support
pass
def _key_pressed_cb(self, grabber, key):
action = _actions_table[key]
method = getattr(self, 'handle_' + action)
method()
def _key_released_cb(self, grabber, key):
if key == '<shft><alt>F9':
self._frame.notify_key_release()
elif key == '0x93':
self._frame.notify_key_release()
def _toggle_console_visibility_cb(self):
bus = dbus.SessionBus()
proxy = bus.get_object('org.laptop.sugar.Console',
'/org/laptop/sugar/Console')
console = dbus.Interface(proxy, 'org.laptop.sugar.Console')
console.toggle_visibility()
|
Python
| 0.000001 |
@@ -4971,37 +4971,49 @@
self._
+shell.get_
frame
+()
.notify_key_rele
@@ -5064,21 +5064,33 @@
self._
+shell.get_
frame
+()
.notify_
|
2d76f1375ef1eb4d7ea1e8735d9ff55cfd12cea0
|
introducing inline echo. print to stdout without the Fine newline
|
inline_echo.py
|
inline_echo.py
|
Python
| 0.999926 |
@@ -0,0 +1,267 @@
+#!/usr/bin/env python%0A%0Aimport sys%0Aimport os%0A%0Adef puaq(): # Print Usage And Quit%0A print(%22Usage: %25s string_content%22 %25 os.path.basename(__file__))%0A sys.exit(1)%0A%0Aif __name__ == %22__main__%22:%0A if len(sys.argv) %3C 2:%0A puaq()%0A sys.stdout.write(sys.argv%5B1%5D)%0A%0A
|
|
58f05fe7736ce387bb8086128bc9de32b8cd6a59
|
Add simplify.py
|
livesync/indico_livesync/simplify.py
|
livesync/indico_livesync/simplify.py
|
Python
| 0.000725 |
@@ -0,0 +1,1716 @@
+# This file is part of Indico.%0A# Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN).%0A#%0A# Indico is free software; you can redistribute it and/or%0A# modify it under the terms of the GNU 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# Indico is distributed in the hope that it will be useful, but%0A# WITHOUT ANY WARRANTY; without even the implied warranty of%0A# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU%0A# General Public License for more details.%0A#%0A# You should have received a copy of the GNU General Public License%0A# along with Indico; if not, see %3Chttp://www.gnu.org/licenses/%3E.%0A%0Afrom indico_livesync.models.queue import ChangeType%0A%0A%0Adef process_records(records):%0A changes = %7B%7D%0A%0A for record in records:%0A if record.type != ChangeType.deleted and record.object is None:%0A continue%0A if record.type == ChangeType.created:%0A changes%5Brecord.obj%5D = ChangeType.type%0A elif record.type == ChangeType.deleted:%0A changes%5Brecord.obj%5D = ChangeType.type%0A elif record.type in %7BChangeType.moved, ChangeType.protection_changed%7D:%0A changes.update(_cascade_change(record))%0A elif record.type == ChangeType.title_changed:%0A pass%0A elif record.type == ChangeType.data_changed and not record.category_id:%0A changes%5Brecord.obj%5D = ChangeType.type%0A%0A for obj, state in records.iteritems():%0A pass%0A%0A%0Adef _cascade_change(record):%0A changes = %7Brecord.obj: record.type%7D%0A for subrecord in record.subrecords():%0A changes.update(_cascade_change(subrecord))%0A return changes%0A
|
|
6a65d102bfcd667c382704ea3430d76faaa1b3d1
|
Add tests
|
tests/test_salut.py
|
tests/test_salut.py
|
Python
| 0.000001 |
@@ -0,0 +1,3105 @@
+import unittest%0Afrom mock import MagicMock%0A%0Aimport socket%0Aimport gevent%0Aimport gevent.socket%0A%0Afrom otis.common.salut import Announcer, Browser%0A%0A%0Aclass TestSalut(unittest.TestCase):%0A def setUp(self):%0A pass%0A%0A def tearDown(self):%0A pass%0A%0A def test_announce(self):%0A announcer = Announcer('Test', '_otis_test._tcp', 9999)%0A%0A while not announcer.announced:%0A gevent.sleep(0.05)%0A%0A announcer.stop()%0A%0A def test_announce_registered_callback(self):%0A callback = MagicMock()%0A announcer = Announcer(%0A 'Test', '_otis_test._tcp', 9999, callback.registered)%0A%0A while not announcer.announced:%0A gevent.sleep(0.05)%0A callback.registered.assert_called_once_with(%0A 'local.', '_otis_test._tcp.', 'Test')%0A%0A announcer.stop()%0A%0A def test_browse(self):%0A announcer = Announcer('Test', '_otis_test._tcp', 9999)%0A while not announcer.announced:%0A gevent.sleep(0.05)%0A%0A browser = Browser(%0A 'Test', '_otis_test._tcp')%0A%0A while not browser.resolved:%0A gevent.sleep(0.05)%0A%0A browser.stop()%0A announcer.stop()%0A%0A def test_browse_resolved_callback(self):%0A ip = gevent.socket.gethostbyname(socket.gethostname())%0A port = 9999%0A announcer = Announcer('Test', '_otis_test._tcp', port)%0A while not announcer.announced:%0A gevent.sleep(0.05)%0A%0A callback = MagicMock()%0A browser = Browser(%0A 'Test', '_otis_test._tcp',%0A resolved_callback=callback.resolved)%0A%0A while not browser.resolved:%0A gevent.sleep(0.05)%0A callback.resolved.assert_called_once_with(ip, port)%0A%0A browser.stop()%0A announcer.stop()%0A%0A def test_browse_unresolved_callback(self):%0A announcer = Announcer('Test', '_otis_test._tcp', 9999)%0A while not announcer.announced:%0A gevent.sleep(0.05)%0A%0A callback = MagicMock()%0A browser = Browser(%0A 'Test', '_otis_test._tcp',%0A unresolved_callback=callback.unresolved)%0A%0A while not browser.resolved:%0A gevent.sleep(0.05)%0A%0A announcer.stop()%0A while announcer.announced:%0A gevent.sleep(0.05)%0A announcer = None%0A%0A while browser.resolved:%0A gevent.sleep(0.05)%0A callback.unresolved.assert_called_once()%0A%0A browser.stop()%0A%0A def test_unresolve_resolve(self):%0A announcer = Announcer('Test', '_otis_test._tcp', 9999)%0A while not announcer.announced:%0A gevent.sleep(0.05)%0A%0A browser = Browser('Test', '_otis_test._tcp')%0A while not browser.resolved:%0A gevent.sleep(0.05)%0A%0A announcer.stop()%0A while announcer.announced:%0A gevent.sleep(0.05)%0A announcer = None%0A%0A while browser.resolved:%0A gevent.sleep(0.05)%0A%0A announcer = Announcer('Test', '_otis_test._tcp', 9999)%0A while not announcer.announced:%0A gevent.sleep(0.05)%0A while not browser.resolved:%0A gevent.sleep(0.05)%0A%0A browser.stop()%0A
|
|
f65a6c12dd615d235a306b130ebd63358429e8c6
|
Create boss.py
|
boss.py
|
boss.py
|
Python
| 0.000002 |
@@ -0,0 +1,1171 @@
+# -*- coding: utf-8 -*-%0A%0Aimport urllib%0Aimport urllib2%0Aimport re%0Afrom cookielib import CookieJar%0A%0Areg = re.compile(r'href=%22%5C.%5C/in%5B%5E%22%5C%5C%5D*(?:%5C%5C.%5B%5E%22%5C%5C%5D*)*%22')%0A%0Astager = re.compile(r'%3E.+100.')%0A%0Aanswers = %7B1: '/index.php?answer=42', 2: '/index.php?answer=bt'%7D%0A%0Awrong = set()%0A%0Acj = CookieJar()%0Aopener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))%0Aresponse = opener.open(%22http://maze.qctf.ru/index.php%22)%0Acontent = response.read()%0A%0Astage = int(stager.findall(content)%5B0%5D%5B1:-6%5D)%0A%0Achosen = answers%5B1%5D%0A%0Aresponse = opener.open(%22http://maze.qctf.ru%22+answers%5B1%5D)%0Aprev_stage = 1%0Awhile True:%0A%0A%09content = response.read()%0A%09stage = int(stager.findall(content)%5B0%5D%5B1:-6%5D)%0A%09if stage == prev_stage+1:%0A%09%09if stage %3E len(answers):%0A%09%09%09print content%0A%09%09%09print %22Stage %22+str(stage)%0A%09%09%09print %22Success %22+str(stage-1)+%22 with %22+chosen%0A%09%09%09answers%5Bstage-1%5D = chosen%0A%09else:%0A%09%09wrong.add(chosen)%0A%09%0A%09if len(answers) %3C stage:%0A%09%09v = %5Bx%5B7:-1%5D for x in reg.findall(content)%5D%0A%09%09for x in v:%0A%09%09%09if x not in wrong:%0A%09%09%09%09chosen = x%0A%09%09%09%09break%0A%09%09response = opener.open(%22http://maze.qctf.ru%22+chosen)%0A%09else:%0A%09%09chosen = answers%5Bstage%5D%0A%09%09response = opener.open(%22http://maze.qctf.ru%22+answers%5Bstage%5D)%0A%09prev_stage = stage%0A
|
|
df7235e13c14f13dd27ede6c098a9b5b80b4b297
|
Add test_functions
|
neuralmonkey/tests/test_functions.py
|
neuralmonkey/tests/test_functions.py
|
Python
| 0.000018 |
@@ -0,0 +1,819 @@
+#!/usr/bin/env python3%0A%22%22%22Unit tests for functions.py.%22%22%22%0A# tests: mypy, lint%0A%0Aimport unittest%0Aimport tensorflow as tf%0A%0Afrom neuralmonkey.functions import piecewise_function%0A%0A%0Aclass TestPiecewiseFunction(unittest.TestCase):%0A%0A def test_piecewise_constant(self):%0A x = tf.placeholder(dtype=tf.int32)%0A y = piecewise_function(x, %5B-0.5, 1.2, 3, 2%5D, %5B-1, 2, 1000%5D,%0A dtype=tf.float32)%0A%0A with tf.Session() as sess:%0A self.assertAlmostEqual(sess.run(y, %7Bx: -2%7D), -0.5)%0A self.assertAlmostEqual(sess.run(y, %7Bx: -1%7D), 1.2)%0A self.assertAlmostEqual(sess.run(y, %7Bx: 999%7D), 3)%0A self.assertAlmostEqual(sess.run(y, %7Bx: 1000%7D), 2)%0A self.assertAlmostEqual(sess.run(y, %7Bx: 1001%7D), 2)%0A%0A%0Aif __name__ == %22__main__%22:%0A unittest.main()%0A
|
|
b2acb7dfd7dc08afd64d80f25ab0a76469e5fff6
|
add import script for North Lanarkshire
|
polling_stations/apps/data_collection/management/commands/import_north_lanarkshire.py
|
polling_stations/apps/data_collection/management/commands/import_north_lanarkshire.py
|
Python
| 0 |
@@ -0,0 +1,756 @@
+from data_collection.management.commands import BaseScotlandSpatialHubImporter%0A%0A%22%22%22%0ANote:%0AThis importer provides coverage for 173/174 districts%0Adue to incomplete/poor quality data%0A%22%22%22%0Aclass Command(BaseScotlandSpatialHubImporter):%0A council_id = 'S12000044'%0A council_name = 'North Lanarkshire'%0A elections = %5B'local.north-lanarkshire.2017-05-04'%5D%0A%0A def station_record_to_dict(self, record):%0A # clean up codes%0A record%5B1%5D = self.parse_string(record%5B1%5D).replace(' ', '').upper()%0A return super().station_record_to_dict(record)%0A%0A def district_record_to_dict(self, record):%0A # clean up codes%0A record%5B0%5D = self.parse_string(record%5B0%5D).replace(' ', '').upper()%0A return super().district_record_to_dict(record)%0A
|
|
cc907c9b8f22bd08ed6460e5e99ebb4e8ce5a499
|
add import script for Perth and Kinross
|
polling_stations/apps/data_collection/management/commands/import_perth_and_kinross.py
|
polling_stations/apps/data_collection/management/commands/import_perth_and_kinross.py
|
Python
| 0 |
@@ -0,0 +1,354 @@
+from data_collection.management.commands import BaseScotlandSpatialHubImporter%0A%0A%22%22%22%0ANote:%0AThis importer provides coverage for 104/107 districts%0Adue to incomplete/poor quality data%0A%22%22%22%0Aclass Command(BaseScotlandSpatialHubImporter):%0A council_id = 'S12000024'%0A council_name = 'Perth and Kinross'%0A elections = %5B'local.perth-and-kinross.2017-05-04'%5D%0A
|
|
a9ed1a52a552d76246028d892cc6d01e5ac069cf
|
Move sidecar to api
|
api/events/monitors/sidecar.py
|
api/events/monitors/sidecar.py
|
Python
| 0.000001 |
@@ -0,0 +1,2487 @@
+# -*- coding: utf-8 -*-%0Afrom __future__ import absolute_import, division, print_function%0A%0Aimport logging%0Aimport os%0Aimport time%0A%0Afrom django.conf import settings%0A%0Afrom polyaxon_k8s.constants import PodLifeCycle%0Afrom polyaxon_k8s.manager import K8SManager%0A%0Afrom api.config_settings import CeleryPublishTask%0Afrom api.celery_api import app as celery_app%0Afrom libs.redis_db import RedisToStream%0Afrom events.tasks import handle_events_job_logs%0A%0Alogger = logging.getLogger('polyaxon.monitors.sidecar')%0A%0A%0Adef run(k8s_manager, pod_id, job_id):%0A raw = k8s_manager.k8s_api.read_namespaced_pod_log(pod_id,%0A k8s_manager.namespace,%0A container=job_id,%0A follow=True,%0A _preload_content=False)%0A for log_line in raw.stream():%0A experiment_id = 0 # TODO extract experiment id%0A logger.info(%22Publishing event: %7B%7D%22.format(log_line))%0A handle_events_job_logs.delay(experiment_id=experiment_id,%0A job_id=job_id,%0A log_line=log_line,%0A persist=settings.PERSIST_EVENTS)%0A if (RedisToStream.is_monitored_job_logs(job_id) or%0A RedisToStream.is_monitored_experiment_logs(experiment_id)):%0A celery_app.send_task(CeleryPublishTask.PUBLISH_LOGS_SIDECAR,%0A kwargs=%7B'experiment_id': experiment_id,%0A 'job_id': job_id,%0A 'log_line': log_line%7D)%0A%0A%0Adef can_log(k8s_manager, pod_id):%0A status = k8s_manager.k8s_api.read_namespaced_pod_status(pod_id,%0A k8s_manager.namespace)%0A logger.debug(status)%0A while status.status.phase != PodLifeCycle.RUNNING:%0A time.sleep(settings.LOG_SLEEP_INTERVAL)%0A status = k8s_manager.k8s_api.read_namespaced_pod_status(pod_id,%0A k8s_manager.namespace)%0A%0A%0Adef main():%0A pod_id = os.environ%5B'POLYAXON_POD_ID'%5D%0A job_id = os.environ%5B'POLYAXON_JOB_ID'%5D%0A k8s_manager = K8SManager(namespace=settings.NAMESPACE, in_cluster=True)%0A can_log(k8s_manager, pod_id)%0A run(k8s_manager, pod_id, job_id)%0A logger.debug('Finished logging')%0A%0A%0Aif __name__ == '__main__':%0A main()%0A
|
|
6b81d938ed99a943e8e81816b9a013b488d4dfd8
|
Add util.py to decode wordpiece ids in Transformer
|
fluid/neural_machine_translation/transformer/util.py
|
fluid/neural_machine_translation/transformer/util.py
|
Python
| 0.000002 |
@@ -0,0 +1,2102 @@
+import sys%0Aimport re%0Aimport six%0Aimport unicodedata%0A%0A# Regular expression for unescaping token strings.%0A# '%5Cu' is converted to '_'%0A# '%5C%5C' is converted to '%5C'%0A# '%5C213;' is converted to unichr(213)%0A# Inverse of escaping.%0A_UNESCAPE_REGEX = re.compile(r%22%5C%5Cu%7C%5C%5C%5C%5C%7C%5C%5C(%5B0-9%5D+);%22)%0A%0A# This set contains all letter and number characters.%0A_ALPHANUMERIC_CHAR_SET = set(%0A six.unichr(i) for i in range(sys.maxunicode)%0A if (unicodedata.category(six.unichr(i)).startswith(%22L%22) or%0A unicodedata.category(six.unichr(i)).startswith(%22N%22)))%0A%0A%0Adef tokens_to_ustr(tokens):%0A %22%22%22%0A Convert a list of tokens to a unicode string.%0A %22%22%22%0A token_is_alnum = %5Bt%5B0%5D in _ALPHANUMERIC_CHAR_SET for t in tokens%5D%0A ret = %5B%5D%0A for i, token in enumerate(tokens):%0A if i %3E 0 and token_is_alnum%5Bi - 1%5D and token_is_alnum%5Bi%5D:%0A ret.append(u%22 %22)%0A ret.append(token)%0A return %22%22.join(ret)%0A%0A%0Adef subtoken_ids_to_tokens(subtoken_ids, vocabs):%0A %22%22%22%0A Convert a list of subtoken(wordpiece) ids to a list of tokens.%0A %22%22%22%0A concatenated = %22%22.join(%0A %5Bvocabs.get(subtoken_id, u%22%22) for subtoken_id in subtoken_ids%5D)%0A split = concatenated.split(%22_%22)%0A ret = %5B%5D%0A for t in split:%0A if t:%0A unescaped = unescape_token(t + %22_%22)%0A if unescaped:%0A ret.append(unescaped)%0A return ret%0A%0A%0Adef unescape_token(escaped_token):%0A %22%22%22%0A Inverse of encoding escaping.%0A %22%22%22%0A%0A def match(m):%0A if m.group(1) is None:%0A return u%22_%22 if m.group(0) == u%22%5C%5Cu%22 else u%22%5C%5C%22%0A%0A try:%0A return six.unichr(int(m.group(1)))%0A except (ValueError, OverflowError) as _:%0A return u%22%5Cu3013%22 # Unicode for undefined character.%0A%0A trimmed = escaped_token%5B:-1%5D if escaped_token.endswith(%0A %22_%22) else escaped_token%0A return _UNESCAPE_REGEX.sub(match, trimmed)%0A%0A%0Adef subword_ids_to_str(ids, vocabs):%0A %22%22%22%0A Convert a list of subtoken(word piece) ids to a native string.%0A Refer to SubwordTextEncoder in Tensor2Tensor. %0A %22%22%22%0A return tokens_to_ustr(subtoken_ids_to_tokens(ids, vocabs)).decode(%22utf-8%22)%0A
|
|
e69da5fb3550703c466cd8ec0e084e131fb97150
|
add first small and simple tests about the transcoder manager
|
coherence/test/test_transcoder.py
|
coherence/test/test_transcoder.py
|
Python
| 0 |
@@ -0,0 +1,1460 @@
+%0Afrom twisted.trial.unittest import TestCase%0A%0Afrom coherence.transcoder import TranscoderManager%0A%0Afrom coherence.transcoder import (PCMTranscoder, WAVTranscoder, MP3Transcoder,%0A MP4Transcoder, MP2TSTranscoder, ThumbTranscoder)%0A%0Aknown_transcoders = %5BPCMTranscoder, WAVTranscoder, MP3Transcoder, MP4Transcoder,%0A MP2TSTranscoder, ThumbTranscoder%5D%0A%0A# move this into the implementation to allow easier overwriting%0Adef getuniquename(transcoder_class):%0A return getattr(transcoder_class, 'id')%0A%0Aclass TranscoderTestMixin(object):%0A def setUp(self):%0A self.manager = TranscoderManager()%0A%0A def tearDown(self):%0A # as it is a singleton ensuring that we always get a clean%0A # and fresh one is tricky and hacks the internals%0A TranscoderManager._instance = None%0A del self.manager%0A%0Aclass TestTranscoderManagerSingletony(TranscoderTestMixin, TestCase):%0A%0A def test_is_really_singleton(self):%0A #FIXME: singleton tests should be outsourced some when%0A old_id = id(self.manager)%0A new_manager = TranscoderManager()%0A self.assertEquals(old_id, id(new_manager))%0A%0Aclass TestTranscoderAutoloading(TranscoderTestMixin, TestCase):%0A%0A def setUp(self):%0A self.manager = None%0A%0A def test_is_loading_all_known_transcoders(self):%0A self.manager = TranscoderManager()%0A for klass in known_transcoders:%0A self.assertEquals(self.manager.transcoders%5Bgetuniquename(klass)%5D, klass)%0A
|
|
9698e473615233819f886c5c51220d3a213b5545
|
Add initial prototype
|
script.py
|
script.py
|
Python
| 0.000002 |
@@ -0,0 +1,786 @@
+#!/usr/bin/env python%0A%0Aimport sys%0Aimport subprocess as subp%0A%0A%0Acmd = '' if len(sys.argv) %3C= 1 else str(sys.argv%5B1%5D)%0A%0Aif cmd in %5B'prev', 'next'%5D:%0A%0A log = subp.check_output(%5B'git', 'rev-list', '--all'%5D).strip()%0A log = %5Bline.strip() for line in log.split('%5Cn')%5D%0A%0A pos = subp.check_output(%5B'git', 'rev-parse', 'HEAD'%5D).strip()%0A idx = log.index(pos)%0A%0A # Next commit:%0A if cmd == 'next':%0A if idx %3E 0:%0A subp.call(%5B'git', 'checkout', log%5Bidx - 1%5D%5D)%0A else:%0A print(%22You're already on the latest commit.%22)%0A%0A # Previous commit:%0A else:%0A if idx + 1 %3C= len(log) - 1:%0A subp.call(%5B'git', 'checkout', 'HEAD%5E'%5D)%0A else:%0A print(%22You're already on the first commit.%22)%0A%0Aelse:%0A print('Usage: git walk prev%7Cnext')%0A
|
|
6500bc2682aeecb29c79a9ee9eff4e33439c2b49
|
Add verifica_diff script
|
conjectura/teste/verifica_diff.py
|
conjectura/teste/verifica_diff.py
|
Python
| 0.000001 |
@@ -0,0 +1,462 @@
+from sh import cp, rm, diff%0Aimport sh%0Aimport os%0A%0ASURSA_VERIFICATA = 'conjectura-inturi.cpp'%0A%0Acp('../' + SURSA_VERIFICATA, '.')%0Aos.system('g++ ' + SURSA_VERIFICATA)%0A%0Afilename = 'grader_test'%0Afor i in range(1, 11):%0A print 'Testul ', i%0A cp(filename + str(i) + '.in', 'conjectura.in')%0A os.system('./a.out')%0A print diff('conjectura.out', filename + str(i) + '.ok')%0A%0Afor extension in %5B'in', 'out'%5D:%0A rm('conjectura.' + extension)%0Arm(SURSA_VERIFICATA)%0Arm('a.out')%0A
|
|
5d769d651947384e18e4e9c21a10f86762a3e950
|
add more tests
|
test/test_api/test_api_announcement.py
|
test/test_api/test_api_announcement.py
|
Python
| 0 |
@@ -0,0 +1,1625 @@
+# -*- coding: utf8 -*-%0A# This file is part of PYBOSSA.%0A#%0A# Copyright (C) 2017 Scifabric LTD.%0A#%0A# PYBOSSA is free software: you can redistribute it and/or modify%0A# it under the terms of the GNU Affero General Public License as published by%0A# the Free Software Foundation, either version 3 of the License, or%0A# (at your option) any later version.%0A#%0A# PYBOSSA 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 PYBOSSA. If not, see %3Chttp://www.gnu.org/licenses/%3E.%0Aimport json%0Afrom default import db, with_context%0Afrom test_api import TestAPI%0Afrom factories import AnnouncementFactory%0Afrom factories import UserFactory, HelpingMaterialFactory, ProjectFactory%0Afrom pybossa.repositories import AnnouncementRepository%0Afrom mock import patch%0A%0Aannouncement_repo = AnnouncementRepository(db)%0A%0A%0Aclass TestAnnouncementAPI(TestAPI):%0A%0A @with_context%0A def test_query_announcement(self):%0A %22%22%22Test API query for announcement endpoint works%22%22%22%0A owner = UserFactory.create()%0A user = UserFactory.create()%0A # project = ProjectFactory(owner=owner)%0A announcements = AnnouncementFactory.create_batch(9)%0A announcement = AnnouncementFactory.create()%0A%0A # As anon%0A url = '/announcements/'%0A res = self.app_get_json(url)%0A data = json.loads(res.data)%0A assert len(data%5B'announcements'%5D) == 10, data%0A%0A
|
|
3a1f37ea0e46ea396c2ce407a938677e86dc6655
|
Adding a test Hello World
|
hello_world.py
|
hello_world.py
|
Python
| 0.999909 |
@@ -0,0 +1,22 @@
+print %22Hello World !%22%0A
|
|
a1f411be91a9db2193267de71eb52db2f334641b
|
add a file that prints hello lesley
|
hellolesley.py
|
hellolesley.py
|
Python
| 0.000258 |
@@ -0,0 +1,73 @@
+#This is my hello world program to say hi to Lesley%0Aprint 'Hello Lesley'%0A
|
|
03b80665f6db39002e0887ddf56975f6d31cc767
|
Create __init__.py
|
server/__init__.py
|
server/__init__.py
|
Python
| 0.000429 |
@@ -0,0 +1 @@
+%0A
|
|
33581b5a2f9ca321819abfd7df94eb5078ab3e7c
|
Add domain.Box bw compatibility shim w/deprecation warning
|
lepton/domain.py
|
lepton/domain.py
|
#############################################################################
#
# Copyright (c) 2008 by Casey Duncan and contributors
# All Rights Reserved.
#
# This software is subject to the provisions of the MIT License
# A copy of the license should accompany this distribution.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
#
#############################################################################
"""Domains represent regions of space and are used for generating vectors
(positions, velocities, colors). Domains are also used by controllers to test
for collision. Colliding with domains can then influence particle
behavior
"""
__version__ = '$Id$'
from random import random, uniform
from math import sqrt
from particle_struct import Vec3
from _domain import Line, Plane, AABox, Sphere
class Domain(object):
"""Domain abstract base class"""
def generate(self):
"""Return a point within the domain as a 3-tuple. For domains with a
non-zero volume, 'point in domain' is guaranteed to return true.
"""
raise NotImplementedError
def __contains__(self, point):
"""Return true if point is inside the domain, false if not."""
raise NotImplementedError
def intersect(self, start_point, end_point):
"""For the line segment defined by the start and end point specified
(coordinate 3-tuples), return the point closest to the start point
where the line segment intersects surface of the domain, and the
surface normal unit vector at that point as a 2-tuple. If the line
segment does not intersect the domain, return the 2-tuple (None,
None).
Only 2 or 3 dimensional domains may be intersected.
Note performance is more important than absolute accuracy with this
method, so approximations are acceptable.
"""
raise NotImplementedError
|
Python
| 0 |
@@ -1943,8 +1943,415 @@
dError%0A%0A
+%0Adef Box(*args, **kw):%0A%09%22%22%22Axis-aligned box domain (same as AABox for now)%0A%0A%09WARNING: Deprecated, use AABox instead. This domain will mean something different%0A%09in future versions of lepton%0A%09%22%22%22%0A%09import warnings%0A%09warnings.warn(%22lepton.domain.Box is deprecated, use AABox instead. %22%0A%09%09%22This domain class will mean something different in future versions of lepton%22,%0A%09%09stacklevel=2)%0A%09return AABox(*args, **kw)%0A%0A
|
03fdc41437f96cb1d6ba636c3a5d8c5dc15430b1
|
Create requirements.py
|
requirements.py
|
requirements.py
|
Python
| 0 |
@@ -0,0 +1 @@
+%0A
|
|
ab99f855f708dec213c9eea1489643c01526e0b0
|
Add unittests for bridgedb.parse.versions module.
|
lib/bridgedb/test/test_parse_versions.py
|
lib/bridgedb/test/test_parse_versions.py
|
Python
| 0 |
@@ -0,0 +1,1559 @@
+# -*- coding: utf-8 -*-%0A#_____________________________________________________________________________%0A#%0A# This file is part of BridgeDB, a Tor bridge distribution system.%0A#%0A# :authors: Isis Lovecruft 0xA3ADB67A2CDB8B35 %[email protected]%3E%0A# please also see AUTHORS file%0A# :copyright: (c) 2014, The Tor Project, Inc.%0A# (c) 2014, Isis Lovecruft%0A# :license: see LICENSE for licensing information%0A#_____________________________________________________________________________%0A%0A%22%22%22Unittests for :mod:%60bridgedb.parse.versions%60.%22%22%22%0A%0A%0Afrom __future__ import print_function%0A%0Afrom twisted.trial import unittest%0A%0Afrom bridgedb.parse import versions%0A%0A%0Aclass ParseVersionTests(unittest.TestCase):%0A %22%22%22Unitests for :class:%60bridgedb.parse.versions.Version%60.%22%22%22%0A%0A def test_Version_with_bad_delimiter(self):%0A %22%22%22Test parsing a version number which uses '-' as a delimiter.%22%22%22%0A self.assertRaises(versions.InvalidVersionStringFormat,%0A versions.Version, '2-6-0', package='tor')%0A%0A def test_Version_really_long_version_string(self):%0A %22%22%22Parsing a version number which is way too long should raise%0A an IndexError which is ignored.%0A %22%22%22%0A v = versions.Version('2.6.0.0.beta', package='tor')%0A self.assertEqual(v.prerelease, 'beta')%0A self.assertEqual(v.major, 6)%0A%0A def test_Version_string(self):%0A %22%22%22Test converting a valid Version object into string form.%22%22%22%0A v = versions.Version('0.2.5.4', package='tor')%0A self.assertEqual(v.base(), '0.2.5.4')%0A
|
|
caef0059d803fc885d268ccd66b9c70a0b2ab129
|
Create Exercise4_VariablesAndNames.py
|
Exercise4_VariablesAndNames.py
|
Exercise4_VariablesAndNames.py
|
Python
| 0 |
@@ -0,0 +1,602 @@
+# Exercise 4 : Variables and Names%0A%0Acars = 100%0Aspace_in_a_car = 4.0%0Adrivers = 30%0Apassengers = 90%0Acars_not_driven = cars - drivers%0Acars_driven = drivers%0Acarpool_capacity = cars_driven * space_in_a_car%0Aaverage_passengers_per_cars = passengers / cars_driven%0A%0Aprint(%22There are%22, cars, %22cars available.%22)%0Aprint(%22There are only%22, drivers, %22drivers available.%22)%0Aprint(%22There will be%22, cars_not_driven, %22empty cars today.%22)%0Aprint(%22We can transport%22, carpool_capacity, %22people today.%22)%0Aprint(%22We have%22, passengers, %22to carpool today.%22)%0Aprint(%22We need to put about%22, average_passengers_per_cars, %22in each car.%22)%0A
|
|
1a4db50c848a3e7bb1323ae9e6b26c884187c575
|
Add my fibonacci sequence homework.
|
training/level-1-the-zen-of-python/dragon-warrior/fibonacci/rwharris-nd_fibonacci.py
|
training/level-1-the-zen-of-python/dragon-warrior/fibonacci/rwharris-nd_fibonacci.py
|
Python
| 0.000003 |
@@ -0,0 +1,257 @@
+def even_fibonacci_sum(a:int,b:int,max:int) -%3E int:%0D%0A temp = 0%0D%0A sum = 0%0D%0A%0D%0A while (b %3C= max):%0D%0A if (b%252 == 0):%0D%0A sum += b%0D%0A temp = a + b%0D%0A a = b%0D%0A b = temp%0D%0A%0D%0A print(sum)%0D%0A%0D%0Aeven_fibonacci_sum(1,2,4000000)
|
|
f14c483283984b793f1209255e059d7b9deb414c
|
Add in the db migration
|
migrations/versions/8081a5906af_.py
|
migrations/versions/8081a5906af_.py
|
Python
| 0.000001 |
@@ -0,0 +1,627 @@
+%22%22%22empty message%0A%0ARevision ID: 8081a5906af%0ARevises: 575d8824e34c%0ACreate Date: 2015-08-25 18:04:56.738898%0A%0A%22%22%22%0A%0A# revision identifiers, used by Alembic.%0Arevision = '8081a5906af'%0Adown_revision = '575d8824e34c'%0A%0Afrom alembic import op%0Aimport sqlalchemy as sa%0A%0A%0Adef upgrade():%0A ### commands auto generated by Alembic - please adjust! ###%0A op.add_column('organization', sa.Column('member_count', sa.Integer(), nullable=True))%0A ### end Alembic commands ###%0A%0A%0Adef downgrade():%0A ### commands auto generated by Alembic - please adjust! ###%0A op.drop_column('organization', 'member_count')%0A ### end Alembic commands ###%0A
|
|
2dff474fe7723ebc7d7559fc77791924532d58db
|
reorder imports for pep8
|
boltons/timeutils.py
|
boltons/timeutils.py
|
# -*- coding: utf-8 -*-
import datetime
from datetime import timedelta
from strutils import cardinalize
def total_seconds(td):
"""\
A pure-Python implementation of Python 2.7's timedelta.total_seconds().
Accepts a timedelta object, returns number of total seconds.
>>> td = datetime.timedelta(days=4, seconds=33)
>>> total_seconds(td)
345633.0
"""
a_milli = 1000000.0
td_ds = td.seconds + (td.days * 86400) # 24 * 60 * 60
td_micro = td.microseconds + (td_ds * a_milli)
return td_micro / a_milli
import bisect
_BOUNDS = [(0, timedelta(seconds=1), 'second'),
(1, timedelta(seconds=60), 'minute'),
(1, timedelta(seconds=3600), 'hour'),
(1, timedelta(days=1), 'day'),
(1, timedelta(days=7), 'week'),
(2, timedelta(days=30), 'month'),
(1, timedelta(days=365), 'year')]
_BOUNDS = [(b[0] * b[1], b[1], b[2]) for b in _BOUNDS]
_BOUND_DELTAS = [b[0] for b in _BOUNDS]
def decimal_relative_time(d, other=None, ndigits=0):
"""\
>>> now = datetime.datetime.utcnow()
>>> decimal_relative_time(now - timedelta(days=1, seconds=3600), now)
(1.0, 'day')
>>> decimal_relative_time(now - timedelta(seconds=0.002), now, ndigits=5)
(0.002, 'seconds')
>>> '%g %s' % _
'0.002 seconds'
"""
if other is None:
other = datetime.datetime.utcnow()
diff = other - d
diff_seconds = total_seconds(diff)
abs_diff = abs(diff)
b_idx = bisect.bisect(_BOUND_DELTAS, abs_diff) - 1
bbound, bunit, bname = _BOUNDS[b_idx]
#f_diff, f_mod = divmod(diff_seconds, total_seconds(bunit))
f_diff = diff_seconds / total_seconds(bunit)
rounded_diff = round(f_diff, ndigits)
return rounded_diff, cardinalize(bname, abs(rounded_diff))
def relative_time(d, other=None, ndigits=0):
"""\
>>> now = datetime.datetime.utcnow()
>>> relative_time(now, ndigits=1)
'0 seconds ago'
>>> relative_time(now - timedelta(days=1, seconds=36000), ndigits=1)
'1.4 days ago'
>>> relative_time(now + timedelta(days=7), now, ndigits=1)
'1 week from now'
"""
drt, unit = decimal_relative_time(d, other, ndigits)
phrase = 'ago'
if drt < 0:
phrase = 'from now'
return '%g %s %s' % (abs(drt), unit, phrase)
|
Python
| 0 |
@@ -18,16 +18,30 @@
-8 -*-%0A%0A
+import bisect%0A
import d
@@ -558,23 +558,8 @@
i%0A%0A%0A
-import bisect%0A%0A
_BOU
|
c86835059c6fcc657290382e743922b14e7e7656
|
add server
|
server.py
|
server.py
|
Python
| 0.000001 |
@@ -0,0 +1,189 @@
+from flask import Flask, request%0A%0Aapp = Flask(__name__)%0A%[email protected]('/')%0Adef root():%0A print(request.json)%0A%0A return %22hi%22%0A%0Aif __name__ == '__main__':%0A app.run(debug=True, port=5000)%0A
|
|
a4bc16a375dc30e37034993bd07d3014f3b936e1
|
Fix corrupt abstract field data
|
migrations/versions/201610041721_8b5ab7da2d5_fix_corrupt_abstract_field_data.py
|
migrations/versions/201610041721_8b5ab7da2d5_fix_corrupt_abstract_field_data.py
|
Python
| 0.000414 |
@@ -0,0 +1,972 @@
+%22%22%22Fix corrupt abstract field data%0A%0ARevision ID: 8b5ab7da2d5%0ARevises: 52d970fb6a74%0ACreate Date: 2016-10-04 17:21:19.186125%0A%22%22%22%0A%0Aimport sqlalchemy as sa%0Afrom alembic import op%0A%0A%0A# revision identifiers, used by Alembic.%0Arevision = '8b5ab7da2d5'%0Adown_revision = '52d970fb6a74'%0A%0A%0Adef upgrade():%0A # We don't want any dicts in abstract field values...%0A # Single choice fields with no value should be %60null%60, text fields should be empty%0A op.execute('''%0A UPDATE event_abstracts.abstract_field_values fv%0A SET data = 'null'::json%0A FROM events.contribution_fields cf%0A WHERE data::jsonb = '%7B%7D'::jsonb AND cf.id = fv.contribution_field_id AND cf.field_type = 'single_choice';%0A%0A UPDATE event_abstracts.abstract_field_values fv%0A SET data = '%22%22'::json%0A FROM events.contribution_fields cf%0A WHERE data::jsonb = '%7B%7D'::jsonb AND cf.id = fv.contribution_field_id AND cf.field_type = 'text';%0A ''')%0A%0A%0Adef downgrade():%0A pass%0A
|
|
ef745ed086ebd8e77e158c89b577c77296630320
|
Add solution for 118 pascals triangle
|
Python/118_Pascals_Triangle.py
|
Python/118_Pascals_Triangle.py
|
Python
| 0.000864 |
@@ -0,0 +1,584 @@
+class Solution(object):%0A def generate(self, numRows):%0A %22%22%22%0A :type numRows: int%0A :rtype: List%5BList%5Bint%5D%5D%0A %22%22%22%0A res = %5B%5B1%5D,%5B1,1%5D%5D%0A if numRows == 0:%0A %09return %5B%5D%0A elif numRows == 1:%0A %09return %5B%5B1%5D%5D%0A else:%0A%09 old = %5B1,1%5D%0A %09for i in xrange(numRows-2):%0A%09 %09temp = %5B1%5D%0A%09 %09for j in xrange(len(old)-1):%0A%09 %09%09temp.append(old%5Bj%5D+old%5Bj+1%5D)%0A%09 %09temp.append(1)%0A%09 %09res.append(temp)%0A%09 %09old = temp%0A %09return res%0A%0Aif __name__ == '__main__':%0A%09print Solution().generate(6)%0A%09%0A
|
|
60841e5b5a5f7e89c986fa202633ccf1a0f35315
|
Add main module
|
src/validator.py
|
src/validator.py
|
Python
| 0.000001 |
@@ -0,0 +1,2032 @@
+# -*- coding: utf-8 -*-%0A#%0A# This module is part of the GeoTag-X project validator tool.%0A#%0A# Author: Jeremy Othieno ([email protected])%0A#%0A# Copyright (c) 2016 UNITAR/UNOSAT%0A#%0A# The MIT License (MIT)%0A# Permission is hereby granted, free of charge, to any person obtaining a copy%0A# of this software and associated documentation files (the %22Software%22), to deal%0A# in the Software without restriction, including without limitation the rights%0A# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell%0A# copies of the Software, and to permit persons to whom the Software is%0A# furnished to do 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,%0A# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF%0A# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.%0A# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,%0A# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR%0A# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE%0A# OR OTHER DEALINGS IN THE SOFTWARE.%0Adef main():%0A %22%22%22Executes the application.%0A %22%22%22%0A import sys%0A parser = _get_argparser()%0A return run(parser.parse_args(sys.argv%5B1:%5D))%0A%0A%0Adef run(arguments):%0A %22%22%22Executes the application with the specified command-line arguments.%0A%0A Args:%0A arguments (list): A list of command-line argument strings.%0A %22%22%22%0A raise NotImplementedError()%0A%0A%0Adef _version():%0A %22%22%22Returns the tool's version string.%0A %22%22%22%0A from __init__ import __version__%0A return %22GeoTag-X Project Validator v%25s, Copyright (C) 2016 UNITAR/UNOSAT.%22 %25 __version__%0A%0A%0Adef _get_argparser():%0A %22%22%22Constructs the application's command-line argument parser.%0A%0A Returns:%0A argparse.ArgumentParser: A command-line argument parser instance.%0A %22%22%22%0A raise NotImplementedError()%0A
|
|
344ee4f5aafa19271a428d171f14b52d26a3f588
|
Create solver.py
|
solver.py
|
solver.py
|
Python
| 0 |
@@ -0,0 +1,2331 @@
+from models import Table%0Afrom utils import sector_counter, clearscreen%0A%0A#start with blank screen%0Aclearscreen()%0A# building the blank sudoku table%0Asudoku = Table()%0A# Having the user enter the sudoku puzzle%0Asudoku.get_table()%0A%0Aprint(%22This is your sudoku puzzle:%22)%0Aprint(sudoku)%0Anum = 1%0Arow = 0%0Acol = 0%0Acounter = 0%0Amax_tries = 1000%0A# This will loop through while the puzzle isn't solved, or until it's reached the maximum tries.%0Awhile sudoku.puzzle_has_blanks() and counter %3C max_tries:%0A for num in range(10):%0A # this will cause it to iterate through the sectors in the grid%0A for sector_id in range(9):%0A #setting the number of flagged/possible spots to 0%0A sudoku.flagged_spots = 0%0A # the massive if statements that looks at a box in the puzzle to determine if those things are all true.%0A for number_in_block,row,col in sudoku.iter_sector(sector_id):%0A if (sudoku.current_box_is_blank(row,col)%0A and sudoku.num_is_not_in_sector(row, col, num) %0A and sudoku.num_is_not_in_row(row, col, num) %0A and sudoku.num_is_not_in_col(row, col, num)): %0A # if all are true, it flags that spot as a possible solution, and records it.%0A sudoku.flagged_spots += 1%0A sudoku.flag_num = num%0A sudoku.flag_row = row%0A sudoku.flag_col = col%0A number_that_was_in_block = number_in_block%0A # print(%22I'm flagging %7B%7D,%7B%7D, for number: %7B%7D which is in sector %7B%7D, and this is the %7B%7D flag.%22.format(row,col,num,sector_id,sudoku.flagged_spots))%0A # prior to going to the next number, if only one flag has been created in the section, the spot must be good, so it updates the table.%0A if sudoku.flagged_spots == 1:%0A sudoku.table%5Bsudoku.flag_row%5D%5Bsudoku.flag_col%5D = sudoku.flag_num%0A print(%22Putting %7B%7D in sector %7B%7D at %7B%7D row %7B%7D col.%22.format(num, sector_id+1, sudoku.flag_row+1, sudoku.flag_col+1))%0A%0A counter +=1%0A %0A%0Aif counter == max_tries:%0A print (%22The solver took %7B%7D passes at it, and this is the best if could do:%22.format(counter))%0Aelse:%0A print(%22Here is your solved puzzle! It took %7B%7D passes.%22.format(counter))%0Aprint(sudoku)%0A
|
|
8752c36c89e3b2a6b012761d1b24183391245fea
|
Create Node.py
|
service/Node.py
|
service/Node.py
|
Python
| 0.000003 |
@@ -0,0 +1,269 @@
+#########################################%0A# Node.py%0A# description: embedded node js%0A# categories: %5Bprogramming%5D%0A# possibly more info @: http://myrobotlab.org/service/Node%0A#########################################%0A# start the service%0Anode = Runtime.start(%22node%22,%22Node%22)%0A
|
|
3874a618fa30787b48578430d8abcdc29549102d
|
solve problem no.1991
|
01xxx/1991/answer.py
|
01xxx/1991/answer.py
|
Python
| 0.017639 |
@@ -0,0 +1,1403 @@
+from typing import Dict%0D%0A%0D%0Aclass Node:%0D%0A def __init__(self, value):%0D%0A self.value: str = value%0D%0A self.left: Node = None%0D%0A self.right: Node = None%0D%0A%0D%0A def preorder_traversal(self):%0D%0A print(self.value, end='')%0D%0A if self.left:%0D%0A self.left.preorder_traversal()%0D%0A if self.right:%0D%0A self.right.preorder_traversal()%0D%0A%0D%0A def inorder_traversal(self):%0D%0A if self.left:%0D%0A self.left.inorder_traversal()%0D%0A print(self.value, end='')%0D%0A if self.right:%0D%0A self.right.inorder_traversal()%0D%0A%0D%0A def postorder_traversal(self):%0D%0A if self.left:%0D%0A self.left.postorder_traversal()%0D%0A if self.right:%0D%0A self.right.postorder_traversal()%0D%0A print(self.value, end='')%0D%0A%0D%0ANodes: Dict%5Bstr, Node%5D = %7B%7D%0D%0AN: int = int(input())%0D%0Avalue:str%0D%0Aleft:str%0D%0Aright:str%0D%0Afor _ in range(N):%0D%0A value, left, right = input().split()%0D%0A if value not in Nodes:%0D%0A Nodes%5Bvalue%5D = Node(value)%0D%0A%0D%0A if left != '.':%0D%0A if left not in Nodes:%0D%0A Nodes%5Bleft%5D = Node(left)%0D%0A Nodes%5Bvalue%5D.left = Nodes%5Bleft%5D%0D%0A%0D%0A if right != '.':%0D%0A if right not in Nodes:%0D%0A Nodes%5Bright%5D = Node(right)%0D%0A Nodes%5Bvalue%5D.right = Nodes%5Bright%5D%0D%0A%0D%0ANodes%5B'A'%5D.preorder_traversal()%0D%0Aprint()%0D%0ANodes%5B'A'%5D.inorder_traversal()%0D%0Aprint()%0D%0ANodes%5B'A'%5D.postorder_traversal()
|
|
f77b45b06f88912d154a5fd5b04d69780618110b
|
Fix migration [WAL-616]
|
src/nodeconductor_openstack/openstack_tenant/migrations/0024_add_backup_size.py
|
src/nodeconductor_openstack/openstack_tenant/migrations/0024_add_backup_size.py
|
Python
| 0 |
@@ -0,0 +1,564 @@
+# -*- coding: utf-8 -*-%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations%0A%0Afrom nodeconductor_openstack.openstack_tenant.models import Backup%0A%0A%0Adef add_backup_size_to_metadata(apps, schema_editor):%0A for backup in Backup.objects.iterator():%0A backup.metadata%5B'size'%5D = backup.instance.size%0A backup.save()%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('openstack_tenant', '0023_remove_instance_external_ip'),%0A %5D%0A%0A operations = %5B%0A migrations.RunPython(add_backup_size_to_metadata),%0A %5D%0A
|
|
398a6d23266e52436e6b8efd9d7ab053f490eb45
|
add a lib to support requests with retries
|
octopus/lib/requests_get_with_retries.py
|
octopus/lib/requests_get_with_retries.py
|
Python
| 0 |
@@ -0,0 +1,394 @@
+import requests%0Afrom time import sleep%0A%0Adef http_get_with_backoff_retries(url, max_retries=5, timeout=30):%0A if not url:%0A return%0A attempt = 0%0A r = None%0A%0A while attempt %3C= max_retries:%0A try:%0A r = requests.get(url, timeout=timeout)%0A break%0A except requests.exceptions.Timeout:%0A attempt += 1%0A sleep(2 ** attempt)%0A%0A return r
|
|
a8b524318d7f9d4406193d610b2bb3ef8e56e147
|
Add frameless drag region example.
|
examples/frameless_drag_region.py
|
examples/frameless_drag_region.py
|
Python
| 0 |
@@ -0,0 +1,732 @@
+import webview%0A%0A'''%0AThis example demonstrates a user-provided %22drag region%22 to move a frameless window%0Aaround, whilst maintaining normal mouse down/move events elsewhere. This roughly%0Areplicates %60-webkit-drag-region%60.%0A'''%0A%0Ahtml = '''%0A%3Chead%3E%0A %3Cstyle type=%22text/css%22%3E%0A .pywebview-drag-region %7B%0A width: 50px;%0A height: 50px;%0A margin-top: 50px;%0A margin-left: 50px;%0A background: orange;%0A %7D%0A %3C/style%3E%0A%3C/head%3E%0A%3Cbody%3E%0A %3Cdiv class=%22pywebview-drag-region%22%3EDrag me!%3C/div%3E%0A%3C/body%3E%0A'''%0A%0A%0Aif __name__ == '__main__':%0A window = webview.create_window(%0A 'API example',%0A html=html,%0A frameless=True,%0A easy_drag=False,%0A )%0A webview.start()%0A
|
|
6fde041c3a92f0d0a0b92da55b12c8e60ecc7196
|
Create handle_file.py
|
handle_file.py
|
handle_file.py
|
Python
| 0.000003 |
@@ -0,0 +1,1018 @@
+import os,sys,subprocess%0Ag_dbg = '-dbg' in sys.argv or False%0A%0Adef handle_generic(fp,fn,fe):%0A%09print 'Unknown extension for %5B%7B%7D%5D'.format(fp)%0Adef handle_md(fp,fn,fe):%0A%09started = False; exec_cmd = %5B%5D;%0A%09with open(fp, %22r%22) as ifile:%0A%09%09lines = %5Bx.rstrip().strip() for x in ifile.readlines()%5D%0A%09%09for line in lines:%0A%09%09%09if started or line.startswith('%3C!---'):%0A%09%09%09%09started = True%0A%09%09%09%09exec_cmd.append(line.replace('%3C!---', ''))%0A%09%09%09%09if '--%3E' in exec_cmd%5B-1%5D:%0A%09%09%09%09%09exec_cmd%5B-1%5D = exec_cmd%5B-1%5D.split('--%3E')%5B0%5D%0A%09%09%09%09%09break%0A%09if len(exec_cmd):%0A%09%09exec_cmd = ''.join(exec_cmd)%0A%09%09if g_dbg:%0A%09%09%09print 'exec_cmd = %5B%7B%7D%5D'.format(exec_cmd)%0A%09%09sys.stdout.flush()%0A%09%09print 'running ...'; sys.stdout.flush()%0A%09%09os.chdir(os.path.dirname(fp))%0A%09%09pop = subprocess.Popen(exec_cmd.split())%0A%09%09pop.wait()%0A%09%09print 'done'%0A%09else:%0A%09%09print 'No command found for %5B%7B%7D%5D'.format(fp)%0A%0Ak_ext_handlers = %7B'.md': handle_md%7D%0Afp,(fn,fe) = sys.argv%5B1%5D, os.path.splitext(sys.argv%5B1%5D)%0Aif g_dbg:%0A%09print 'fp,(fn,fe) = ', fp,(fn,fe)%0Ak_ext_handlers.get(fe, handle_generic)(fp,fn,fe)%0A
|
|
85a604a1991b5dc9a017514848645723921247a7
|
add missing file
|
mcp/constants.py
|
mcp/constants.py
|
Python
| 0.000003 |
@@ -0,0 +1,80 @@
+#%0A# Copyright (c) 2007 rPath, Inc.%0A#%0A# All rights reserved%0A#%0A%0Aversion = '1.0.0'%0A
|
|
8dd52b8163a98caaf2f076cfa4ac427ca330730c
|
Allow comments in JSON.
|
readconf.py
|
readconf.py
|
# Copyright(C) 2011 by John Tobey <[email protected]>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Affero General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see
# <http://www.gnu.org/licenses/gpl.html>.
def include(filename, conf):
_include(set(), filename, conf)
def _include(seen, filename, conf):
if filename in seen:
raise Exception('Config file recursion')
with open(filename) as fp:
entries = read(fp)
for var, val, additive in entries:
var = var.replace('-', '_')
if var == 'config':
import os
_include(seen | set(filename),
os.path.join(os.path.dirname(filename), val), conf)
elif additive:
add(conf, var, val)
else:
conf[var] = val
return
def read(fp):
"""
Read name-value pairs from fp and return the results as a list of
triples: (name, value, additive) where "additive" is true if "+="
occurred between name and value.
"NAME=VALUE" and "NAME VALUE" are equivalent. Whitespace around
names and values is ignored, as are lines starting with '#' and
empty lines. Values may be JSON strings, arrays, or objects. A
value that does not start with '"' or '{' or '[' is read as a
one-line string. A line with just "NAME" stores True as the
value.
"""
entries = []
def store(name, value, additive):
entries.append((name, value, additive))
def skipspace(c):
while c in (' ', '\t', '\r'):
c = fp.read(1)
return c
c = fp.read(1)
while True:
c = skipspace(c)
if c == '':
break
if c == '\n':
c = fp.read(1)
continue
if c == '#':
fp.readline()
c = fp.read(1)
continue
name = ''
while c not in (' ', '\t', '\r', '\n', '=', '+', ''):
name += c
c = fp.read(1)
if c not in ('=', '+'):
c = skipspace(c)
if c in ('\n', ''):
store(name, True, False)
continue
additive = False
if c in ('=', '+'):
if c == '+':
c = fp.read(1)
if c != '=':
raise SyntaxError("Unquoted '+'")
additive = True
c = skipspace(fp.read(1))
if c in ('"', '[', '{'):
js, c = scan_json(fp, c)
import json
store(name, json.loads(js), additive)
continue
# Unquoted, one-line string.
value = ''
while c not in ('\n', ''):
value += c
c = fp.read(1)
store(name, value.rstrip(), additive)
return entries
def add(conf, var, val):
if var not in conf:
conf[var] = val
return
if isinstance(val, dict) and isinstance(conf[var], dict):
conf[var].update(val)
return
if not isinstance(conf[var], list):
conf[var] = [conf[var]]
if isinstance(val, list):
conf[var] += val
else:
conf[var].append(val)
# Scan to end of JSON object. Grrr, why can't json.py do this without
# reading all of fp?
def _scan_json_string(fp):
ret = '"'
while True:
c = fp.read(1)
if c == '':
raise SyntaxError('End of file in JSON string')
ret += c
if c == '"':
return ret, fp.read(1)
if c == '\\':
c = fp.read(1)
ret += c
def _scan_json_nonstring(fp, c):
# Assume we are at a number or true|false|null.
# Scan the token.
ret = ''
while c != '' and c in '-+0123456789.eEtrufalsn':
ret += c
c = fp.read(1)
return ret, c
def _scan_json_space(fp, c):
# Scan whitespace including "," and ":".
ret = ''
while c != '' and c in ' \t\r\n,:':
ret += c
c = fp.read(1)
return ret, c
def _scan_json_compound(fp, c, end):
# Scan a JSON array or object.
ret = c
cs, c = _scan_json_space(fp, fp.read(1))
ret += cs
if c == end:
return ret + c, fp.read(1)
while True:
if c == '':
raise SyntaxError('End of file in JSON value')
cs, c = scan_json(fp, c)
ret += cs
cs, c = _scan_json_space(fp, c)
ret += cs
if c == end:
return ret + c, fp.read(1)
def scan_json(fp, c):
# Scan a JSON value.
if c == '"':
return _scan_json_string(fp)
if c == '[':
return _scan_json_compound(fp, c, ']')
if c == '{':
return _scan_json_compound(fp, c, '}')
cs, c = _scan_json_nonstring(fp, c)
if cs == '':
raise SyntaxError('Invalid initial JSON character: ' + c)
return cs, c
|
Python
| 0 |
@@ -4304,16 +4304,50 @@
and %22:%22.
+ Strip comments for good measure.
%0A ret
@@ -4389,19 +4389,111 @@
%5Ct%5Cr%5Cn,:
+#
':%0A
+ if c == '#':%0A while c not in ('', '%5Cn'):%0A c = fp.read(1)%0A
|
a857340a2d67a8055b9e3802327800dcdd652df4
|
Update TFRT dependency to use revision http://github.com/tensorflow/runtime/commit/037eb7657cb3f49c70c18f959421831e6cb9e4ad.
|
third_party/tf_runtime/workspace.bzl
|
third_party/tf_runtime/workspace.bzl
|
"""Provides the repository macro to import TFRT."""
load("//third_party:repo.bzl", "tf_http_archive", "tf_mirror_urls")
def repo():
"""Imports TFRT."""
# Attention: tools parse and update these lines.
TFRT_COMMIT = "d6884515d2b821161b35c1375d6ea25fe6811d62"
TFRT_SHA256 = "0771a906d327a92bdc46b02c8ac3ee1593542ceadc07220e53790aa8c7ea5702"
tf_http_archive(
name = "tf_runtime",
sha256 = TFRT_SHA256,
strip_prefix = "runtime-{commit}".format(commit = TFRT_COMMIT),
urls = tf_mirror_urls("https://github.com/tensorflow/runtime/archive/{commit}.tar.gz".format(commit = TFRT_COMMIT)),
# A patch file can be provided for atomic commits to both TF and TFRT.
# The job that bumps the TFRT_COMMIT also resets patch_file to 'None'.
patch_file = None,
)
|
Python
| 0.000002 |
@@ -228,133 +228,133 @@
= %22
-d6884515d2b821161b35c1375d6ea25fe6811d62%22%0A TFRT_SHA256 = %220771a906d327a92bdc46b02c8ac3ee1593542ceadc07220e53790aa8c7ea5702
+037eb7657cb3f49c70c18f959421831e6cb9e4ad%22%0A TFRT_SHA256 = %2280194df160fb8c91c7fcc84f34a60c16d69bd66f6b2f8e5404fae5e7d1221533
%22%0A%0A
|
c563f12bcb8b10daca64e19ade3c373c112cb659
|
Update TFRT dependency to use revision http://github.com/tensorflow/runtime/commit/8f7619fa042357fa754002104f575a8a72ee69ed.
|
third_party/tf_runtime/workspace.bzl
|
third_party/tf_runtime/workspace.bzl
|
"""Provides the repository macro to import TFRT."""
load("//third_party:repo.bzl", "tf_http_archive")
def repo():
"""Imports TFRT."""
# Attention: tools parse and update these lines.
TFRT_COMMIT = "584ba7eab84bd45941fabc28fbe8fa43c74673d8"
TFRT_SHA256 = "e2f45638580ba52116f099d52b73c3edcf2ad81736a434fb639def38ae4cb225"
tf_http_archive(
name = "tf_runtime",
sha256 = TFRT_SHA256,
strip_prefix = "runtime-{commit}".format(commit = TFRT_COMMIT),
urls = [
"http://mirror.tensorflow.org/github.com/tensorflow/runtime/archive/{commit}.tar.gz".format(commit = TFRT_COMMIT),
"https://github.com/tensorflow/runtime/archive/{commit}.tar.gz".format(commit = TFRT_COMMIT),
],
)
|
Python
| 0.000001 |
@@ -210,133 +210,133 @@
= %22
-584ba7eab84bd45941fabc28fbe8fa43c74673d8%22%0A TFRT_SHA256 = %22e2f45638580ba52116f099d52b73c3edcf2ad81736a434fb639def38ae4cb225
+8f7619fa042357fa754002104f575a8a72ee69ed%22%0A TFRT_SHA256 = %222cb8410fb4655d71c099fb9f2d3721d0e485c8db518553347ce21ca09e0e1b43
%22%0A%0A
|
29e3d6b706a33780b1cb4863200ec7525ff035ce
|
Update TFRT dependency to use revision http://github.com/tensorflow/runtime/commit/cdf6d36e9a5c07770160ebac25b153481c37a247.
|
third_party/tf_runtime/workspace.bzl
|
third_party/tf_runtime/workspace.bzl
|
"""Provides the repository macro to import TFRT."""
load("//third_party:repo.bzl", "tf_http_archive")
def repo():
"""Imports TFRT."""
# Attention: tools parse and update these lines.
TFRT_COMMIT = "6ca8a6dff0e5d4f3a17b0c0879aa5de622683680"
TFRT_SHA256 = "09779efe84cc84e859e206dd49ae6b993577d7dae41f90491e5b862d7a70ba51"
tf_http_archive(
name = "tf_runtime",
sha256 = TFRT_SHA256,
strip_prefix = "runtime-{commit}".format(commit = TFRT_COMMIT),
urls = [
"http://mirror.tensorflow.org/github.com/tensorflow/runtime/archive/{commit}.tar.gz".format(commit = TFRT_COMMIT),
"https://github.com/tensorflow/runtime/archive/{commit}.tar.gz".format(commit = TFRT_COMMIT),
],
)
|
Python
| 0.000002 |
@@ -210,133 +210,133 @@
= %22
-6ca8a6dff0e5d4f3a17b0c0879aa5de622683680%22%0A TFRT_SHA256 = %2209779efe84cc84e859e206dd49ae6b993577d7dae41f90491e5b862d7a70ba51
+cdf6d36e9a5c07770160ebac25b153481c37a247%22%0A TFRT_SHA256 = %22c197f9b3584cae2d65fc765f999298ae8b70d9424ec0d4dd30dbdad506fb98bb
%22%0A%0A
|
6276cf142d233db377dc490a47c5ad56d2906c75
|
Add version module
|
cards/version.py
|
cards/version.py
|
Python
| 0 |
@@ -0,0 +1,38 @@
+# coding=utf-8%0A%0A__version__ = '0.4.9'%0A
|
|
6c7df140c6dccb4b56500ba25f6b66ab7ea3b605
|
solve 1 problem
|
solutions/reverse-bits.py
|
solutions/reverse-bits.py
|
Python
| 0.000027 |
@@ -0,0 +1,616 @@
+#!/usr/bin/env python%0A# encoding: utf-8%0A%0A%22%22%22%0Areverse-bits.py%0A %0ACreated by Shuailong on 2016-03-02.%0A%0Ahttps://leetcode.com/problems/reverse-bits/.%0A%0A%22%22%22%0A%0Aclass Solution(object):%0A def reverseBits(self, n):%0A %22%22%22%0A :type n: int%0A :rtype: int%0A %22%22%22%0A res = 0%0A count = 0%0A while n:%0A d = n & 1%0A n %3E%3E= 1%0A res %3C%3C= 1%0A res += d%0A count += 1%0A res %3C%3C= 32-count%0A%0A return res%0A%0Adef main():%0A solution = Solution()%0A n = 43261596%0A print solution.reverseBits(n)%0A %0Aif __name__ == '__main__':%0A main()%0A%0A
|
|
793b273c3fdcef428ffb6aec5dbcbb768989f175
|
Add 0004 file
|
Drake-Z/0004/0004.py
|
Drake-Z/0004/0004.py
|
Python
| 0.000001 |
@@ -0,0 +1,327 @@
+#!/usr/bin/env python3%0A# -*- coding: utf-8 -*-%0A%0A'%E7%AC%AC 0004 %E9%A2%98%EF%BC%9A%E4%BB%BB%E4%B8%80%E4%B8%AA%E8%8B%B1%E6%96%87%E7%9A%84%E7%BA%AF%E6%96%87%E6%9C%AC%E6%96%87%E4%BB%B6%EF%BC%8C%E7%BB%9F%E8%AE%A1%E5%85%B6%E4%B8%AD%E7%9A%84%E5%8D%95%E8%AF%8D%E5%87%BA%E7%8E%B0%E7%9A%84%E4%B8%AA%E6%95%B0%E3%80%82'%0A%0A__author__ = 'Drake-Z'%0A%0Aimport re%0A%0Adef tongji(file_path):%0A f = open(file_path, 'r').read()%0A f = re.split(r'%5B%5Cs%5C,%5C;,%5Cn%5D+', f)%0A print(len(f))%0A return 0%0A%0Aif __name__ == '__main__':%0A file_path = 'English.txt'%0A tongji(file_path)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.