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
|
|---|---|---|---|---|---|---|---|
16275938769c16c79b89349612e8e7b2891de815
|
Add migration for user manager
|
kolibri/auth/migrations/0008_auto_20180222_1244.py
|
kolibri/auth/migrations/0008_auto_20180222_1244.py
|
Python
| 0.000001 |
@@ -0,0 +1,519 @@
+# -*- coding: utf-8 -*-%0A# Generated by Django 1.9.13 on 2018-02-22 20:44%0Afrom __future__ import unicode_literals%0A%0Aimport kolibri.auth.models%0Afrom django.db import migrations%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('kolibriauth', '0007_auto_20171226_1125'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterModelManagers(%0A name='facilityuser',%0A managers=%5B%0A ('objects', kolibri.auth.models.FacilityUserModelManager()),%0A %5D,%0A ),%0A %5D%0A
|
|
74450edae5d327659ec618f7e160bc5dd37bd512
|
添加在Python2DWrapper中使用的Python文件
|
PluginSDK/BasicRecon/Python/Py2C.py
|
PluginSDK/BasicRecon/Python/Py2C.py
|
Python
| 0 |
@@ -0,0 +1,1048 @@
+from PIL import Image%0Aimport numpy as np%0A%0A%0Aimport matplotlib%0A%0A%22%22%22%0AThis is Module Py2C for c++%0A%22%22%22%0A%0Aclass A: pass%0A%0Aclass B: pass%0A%0Adef ShowImage(image, width, height):%0A img = %5B%5B%5D%5D * width%0A for x in range(width):%0A for y in range(height):%0A img%5Bx%5D = img%5Bx%5D + %5Bimage%5Bx*width + y%5D%5D%0A npimg = np.array(img)%0A npimg = npimg / npimg.max() *255%0A pil_image = Image.fromarray(npimg)%0A pil_image.show()%0A return 'success!'%0A%0A## image is 2d list%0Adef ShowImage2D(image, width, height):%0A pil_image = Image.fromarray(np.array(image))%0A pil_image2 = Image.fromarray(np.array(image)*2)%0A pil_image.show()%0A pil_image2.show()%0A return np.array(image)%0A%0Aif __name__=='__main__':%0A width = 256%0A height = 256%0A li = %5Bi for i in range(width*height)%5D%0A image = ShowImage(li, width, height)%0A li2d = %5B%5Bi for j in range(height)%5D for i in range(width)%5D # *width+j)*255/(width*height)%0A image2d = ShowImage2D(li2d,width, height)%0A
|
|
883aac8a282d4525e82d3eb151ea293c5577424c
|
Add data migration to create gesinv
|
core/migrations/0002_auto_20141008_0853.py
|
core/migrations/0002_auto_20141008_0853.py
|
Python
| 0 |
@@ -0,0 +1,790 @@
+# -*- coding: utf-8 -*-%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import models, migrations%0A%0A%0Adef create_extra_users(apps, schema_editor):%0A user = apps.get_model(%22auth.User%22).objects.create(username='GesInv-ULL')%0A apps.get_model(%22core%22, %22UserProfile%22).objects.create(user=user,%0A documento='00000000A')%0A%0A%0Adef delete_extra_users(apps, schema_editor):%0A user = apps.get_model(%22auth.User%22).objects.get(username='GesInv-ULL')%0A apps.get_model(%22core%22, %22UserProfile%22).objects.get(user=user).delete()%0A user.delete()%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('core', '0001_initial'),%0A %5D%0A%0A operations = %5B%0A migrations.RunPython(create_extra_users, delete_extra_users),%0A %5D%0A
|
|
eceffd58e62378287aacab29f4849d0a6e983e49
|
Factor out the timestamp-related functionality to a class that outputs json strings
|
src/Timestamp.py
|
src/Timestamp.py
|
Python
| 0.999997 |
@@ -0,0 +1,1093 @@
+#!/usr/bin/python%0Aimport time%0A%0Aclass Timestamp:%0A hour = -1%0A minute = -1%0A%0A def __init__(self, date):%0A%09self.year = int(date%5B0:4%5D)%0A %09self.month = int(self.month_name_to_num(date%5B5:8%5D))%0A %09self.day = int(date%5B9:11%5D)%0A%09try:%0A%09 self.hour = int(date%5B12:14%5D)%0A%09 self.minute = int(date%5B15:17%5D)%0A%09except ValueError:%0A%09 return%0A%0A def month_name_to_num(self, month):%0A%09return time.strptime(month, '%25b').tm_mon%0A%0A def json(self):%0A json = ''%0A units = %5B%22year%22, %22month%22, %22day%22, %22hour%22, %22minute%22%5D%0A value = %7B%22year%22:self.year, %22month%22:self.month, %22day%22:self.day, %0A %22hour%22:self.hour, %22minute%22:self.minute%7D%0A for key in units:%0A json += '%22' + key + '%22:' + str(value%5Bkey%5D) + ','%0A return '%7B' + json%5B:-1%5D + '%7D'%0A%0Adef main():%0A # Test Timestamp class:%0A p = Timestamp(%222222 Jan 26 0210%22) # full date%0A print p.year, p.month, p.day, p.hour, p.minute%0A print p.json()%0A%0A q = Timestamp(%222000 Feb 13%22) # no hours/minutes%0A print q.year, q.month, q.day, q.hour, q.minute%0A print q.json()%0A%0A%0Aif __name__ == %22__main__%22:%0A main()%0A%0A
|
|
e6181c5d7c95af23ee6d51d125642104782f5cf1
|
Add solution for 136_Single Number with XOR operation.
|
Python/136_SingleNumber.py
|
Python/136_SingleNumber.py
|
Python
| 0 |
@@ -0,0 +1,555 @@
+class Solution(object):%0A def singleNumber(self, nums):%0A %22%22%22%0A :type nums: List%5Bint%5D%0A :rtype: int%0A %22%22%22%0A%0A #Using XOR to find the single number.%0A #Because every number appears twice, while N%5EN=0, 0%5EN=N,%0A #XOR is cummutative, so the order of elements does not matter.%0A #Finally, it will be res = 0 %5E singlenumber ==%3E res = singlenumber%0A res = 0%0A for num in nums:%0A res %5E= num%0A return res%0A%0Anums = %5B1,1,5,5,3,4,4,9,9,8,8,7,7%5D%0Afoo = Solution()%0Aprint foo.singleNumber(nums)%0A
|
|
83ebfe1ff774f8d5fb5ae610590ca8fca1c87100
|
add migration for on_delete changes
|
app/backend/wells/migrations/0034_auto_20181127_0230.py
|
app/backend/wells/migrations/0034_auto_20181127_0230.py
|
Python
| 0 |
@@ -0,0 +1,2132 @@
+# Generated by Django 2.1.3 on 2018-11-27 02:30%0A%0Afrom django.db import migrations, models%0Aimport django.db.models.deletion%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('wells', '0033_auto_20181119_1857'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterField(%0A model_name='activitysubmission',%0A name='decommission_method',%0A field=models.ForeignKey(blank=True, db_column='decommission_method_code', null=True, on_delete=django.db.models.deletion.PROTECT, to='wells.DecommissionMethodCode', verbose_name='Method of Decommission'),%0A ),%0A migrations.AlterField(%0A model_name='productiondata',%0A name='well_yield_unit',%0A field=models.ForeignKey(blank=True, db_column='well_yield_unit_code', null=True, on_delete=django.db.models.deletion.PROTECT, to='wells.WellYieldUnitCode'),%0A ),%0A migrations.AlterField(%0A model_name='well',%0A name='aquifer',%0A field=models.ForeignKey(blank=True, db_column='aquifer_id', null=True, on_delete=django.db.models.deletion.PROTECT, to='aquifers.Aquifer', verbose_name='Aquifer ID Number'),%0A ),%0A migrations.AlterField(%0A model_name='well',%0A name='bcgs_id',%0A field=models.ForeignKey(blank=True, db_column='bcgs_id', null=True, on_delete=django.db.models.deletion.PROTECT, to='wells.BCGS_Numbers', verbose_name='BCGS Mapsheet Number'),%0A ),%0A migrations.AlterField(%0A model_name='well',%0A name='decommission_method',%0A field=models.ForeignKey(blank=True, db_column='decommission_method_code', null='True', on_delete=django.db.models.deletion.PROTECT, to='wells.DecommissionMethodCode', verbose_name='Method of Decommission'),%0A ),%0A migrations.AlterField(%0A model_name='well',%0A name='observation_well_status',%0A field=models.ForeignKey(blank=True, db_column='obs_well_status_code', null='True', on_delete=django.db.models.deletion.PROTECT, to='wells.ObsWellStatusCode', verbose_name='Observation Well Status'),%0A ),%0A %5D%0A
|
|
59c62bb0f13be7910bf2280126a0909ffbe716f0
|
Create simple_trie.py
|
simple_trie.py
|
simple_trie.py
|
Python
| 0.000002 |
@@ -0,0 +1,1055 @@
+class Trie:%0A def __init__(self):%0A self.node = %7B%7D%0A self.word = None%0A %0A def add(self,string):%0A node = self.node%0A currentNode = None%0A for char in string:%0A currentNode = node.get(char, None)%0A if not currentNode:%0A node%5Bchar%5D = Trie()%0A currentNode = node%5Bchar%5D%0A node = currentNode.node%0A currentNode.word = string %0A%0A def find(self, query):%0A node = self%0A result = %5B%5D%0A for char in query:%0A currentNode = node.node.get(char, None)%0A if not currentNode:%0A return result%0A node = currentNode%0A return self.findall(node, result)%0A%0A def findall(self, node, result):%0A if node.word:%0A result.append(node.word)%0A for value in node.node.values():%0A self.findall(value, result)%0A return result%0A%0At = Trie()%0At.add(%22cat%22)%0At.add(%22cats%22)%0At.add(%22cow%22)%0At.add(%22camp%22)%0Aprint t.find('c')%0Aprint t.find('ca')%0Aprint t.find(%22abcde%22)%0Aprint t.find(%22cows%22)%0A
|
|
983f041b25b0de77f3720378e12b22e7d8f2e040
|
Create same_first_last.py
|
Python/CodingBat/same_first_last.py
|
Python/CodingBat/same_first_last.py
|
Python
| 0.00113 |
@@ -0,0 +1,116 @@
+# http://codingbat.com/prob/p179078%0A%0Adef same_first_last(nums):%0A return ( len(nums) %3E= 1 and nums%5B0%5D == nums%5B-1%5D )%0A
|
|
ae6c6f3aa0863b919e0f00543cab737ae9e94129
|
Add bubblesort as a placeholder for a refactored implementation
|
bubblesort.py
|
bubblesort.py
|
Python
| 0 |
@@ -0,0 +1,1182 @@
+#!/usr/bin/env python%0A%0A# TBD: Sort animation could take a pattern that it assumed to be %22final%22,%0A# shuffle it, then take a sort generator that produced a step in the sort%0A# algorithm at every call. It would be sorting shuffled indices that the%0A# animation would use to construct each frame.%0A%0Afrom blinkytape import blinkytape, blinkycolor, blinkyplayer%0Afrom patterns import gradient%0Aimport random, sys, time%0A%0Atape = blinkytape.BlinkyTape.find_first()%0A%0Astart_color = blinkycolor.BlinkyColor.from_string(sys.argv%5B1%5D)%0Aend_color = blinkycolor.BlinkyColor.from_string(sys.argv%5B2%5D)%0Apattern = gradient.Gradient(tape.pixel_count, start_color, end_color)%0A%0Aindexes = range(0, tape.pixel_count)%0Arandom.shuffle(indexes)%0Apixels = %5Bpattern.pixels%5Bindex%5D for index in indexes%5D%0Atape.update(pixels)%0A%0Atime.sleep(5)%0A%0Aswap_occurred = True%0Awhile swap_occurred:%0A swap_occurred = False%0A for i in range(1, tape.pixel_count):%0A if indexes%5Bi - 1%5D %3E indexes%5Bi%5D:%0A temp = indexes%5Bi - 1%5D%0A indexes%5Bi - 1%5D = indexes%5Bi%5D%0A indexes%5Bi%5D = temp%0A swap_occurred = True%0A pixels = %5Bpattern.pixels%5Bindex%5D for index in indexes%5D%0A tape.update(pixels)%0A
|
|
3852ae6fcf6271ef19a182e5dfb199e4539536a1
|
Create 6kyu_spelling_bee.py
|
Solutions/6kyu/6kyu_spelling_bee.py
|
Solutions/6kyu/6kyu_spelling_bee.py
|
Python
| 0.000103 |
@@ -0,0 +1,268 @@
+from itertools import zip_longest as zlo%0A%0Adef how_many_bees(hive):%0A return sum(''.join(x).count('bee') + ''.join(x).count('eeb') for x in hive) + %5C%0A sum(''.join(y).count('bee') + ''.join(y).count('eeb') for y in zlo(*hive, fillvalue = '')) if hive else 0%0A
|
|
ddb58206a52ef46f5194bf6f5c11ac68b16ab9a8
|
Create minimum-window-subsequence.py
|
Python/minimum-window-subsequence.py
|
Python/minimum-window-subsequence.py
|
Python
| 0.00046 |
@@ -0,0 +1,871 @@
+# Time: O(S * T)%0A# Space: O(S)%0A%0Aclass Solution(object):%0A def minWindow(self, S, T):%0A %22%22%22%0A :type S: str%0A :type T: str%0A :rtype: str%0A %22%22%22%0A dp = %5B%5BNone for _ in xrange(len(S))%5D for _ in xrange(2)%5D%0A for i, c in enumerate(S):%0A if c == T%5B0%5D:%0A dp%5B0%5D%5Bi%5D = i%0A %0A for j in xrange(1, len(T)):%0A prev = None%0A dp%5Bj%252%5D = %5BNone%5D * len(S)%0A for i, c in enumerate(S):%0A if prev is not None and c == T%5Bj%5D:%0A dp%5Bj%252%5D%5Bi%5D = prev%0A if dp%5B(j-1)%252%5D%5Bi%5D is not None:%0A prev = dp%5B(j-1)%252%5D%5Bi%5D%0A%0A start, end = 0, len(S)%0A for j, i in enumerate(dp%5B(len(T)-1)%252%5D):%0A if i %3E= 0 and j-i %3C end-start:%0A start, end = i, j%0A return S%5Bstart:end+1%5D if end %3C len(S) else %22%22%0A
|
|
077d4b8954918ed51c43429efd74b4911083c4f4
|
Add instance_id field.
|
kolibri/content/migrations/0002_auto_20160630_1959.py
|
kolibri/content/migrations/0002_auto_20160630_1959.py
|
Python
| 0 |
@@ -0,0 +1,1602 @@
+# -*- coding: utf-8 -*-%0A# Generated by Django 1.9.1 on 2016-06-30 19:59%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations, models%0Aimport kolibri.content.models%0Aimport uuid%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('content', '0001_initial'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterModelOptions(%0A name='contentnode',%0A options=%7B%7D,%0A ),%0A migrations.AddField(%0A model_name='contentnode',%0A name='instance_id',%0A field=kolibri.content.models.UUIDField(default=uuid.uuid4, editable=False, max_length=32, unique=True),%0A ),%0A migrations.AlterField(%0A model_name='contentnode',%0A name='kind',%0A field=models.CharField(blank=True, choices=%5B('topic', 'Topic'), ('video', 'Video'), ('audio', 'Audio'), ('exercise', 'Exercise'), ('document', 'Document'), ('image', 'Image')%5D, max_length=200),%0A ),%0A migrations.AlterField(%0A model_name='file',%0A name='extension',%0A field=models.CharField(blank=True, choices=%5B('mp4', 'mp4'), ('vtt', 'vtt'), ('srt', 'srt'), ('mp3', 'mp3'), ('pdf', 'pdf')%5D, max_length=40),%0A ),%0A migrations.AlterField(%0A model_name='file',%0A name='preset',%0A field=models.CharField(blank=True, choices=%5B('high_res_video', 'High resolution video'), ('low_res_video', 'Low resolution video'), ('vector_video', 'Vertor video'), ('thumbnail', 'Thumbnail'), ('thumbnail', 'Thumbnail'), ('caption', 'Caption')%5D, max_length=150),%0A ),%0A %5D%0A
|
|
48172fa94043fb004dfaf564afac42e632be2bc0
|
add test for DataManager
|
mpf/tests/test_DataManager.py
|
mpf/tests/test_DataManager.py
|
Python
| 0 |
@@ -0,0 +1,1460 @@
+%22%22%22Test the bonus mode.%22%22%22%0Aimport time%0Afrom unittest.mock import mock_open, patch%0A%0Afrom mpf.file_interfaces.yaml_interface import YamlInterface%0Afrom mpf.core.data_manager import DataManager%0Afrom mpf.tests.MpfTestCase import MpfTestCase%0A%0A%0Aclass TestDataManager(MpfTestCase):%0A%0A def testSaveAndLoad(self):%0A YamlInterface.cache = False%0A open_mock = mock_open(read_data=%22%22)%0A with patch('mpf.file_interfaces.yaml_interface.open', open_mock, create=True):%0A manager = DataManager(self.machine, %22machine_vars%22)%0A self.assertTrue(open_mock.called)%0A%0A self.assertNotIn(%22hallo%22, manager.get_data())%0A%0A open_mock = mock_open(read_data=%22%22)%0A with patch('mpf.file_interfaces.yaml_interface.open', open_mock, create=True):%0A with patch('mpf.core.file_manager.os.rename') as move_mock:%0A manager.save_key(%22hallo%22, %22world%22)%0A while not move_mock.called:%0A time.sleep(.00001)%0A open_mock().write.assert_called_once_with('hallo: world%5Cn')%0A self.assertTrue(move_mock.called)%0A%0A open_mock = mock_open(read_data='hallo: world%5Cn')%0A with patch('mpf.file_interfaces.yaml_interface.open', open_mock, create=True):%0A manager2 = DataManager(self.machine, %22machine_vars%22)%0A self.assertTrue(open_mock.called)%0A%0A self.assertEqual(%22world%22, manager2.get_data()%5B%22hallo%22%5D)%0A%0A YamlInterface.cache = True%0A
|
|
3dcfc2f7e9a2ed696a2b4a006e4d8a233a494f2f
|
move sitemap to core
|
djangobb_forum/sitemap.py
|
djangobb_forum/sitemap.py
|
Python
| 0 |
@@ -0,0 +1,304 @@
+from django.contrib.sitemaps import Sitemap%0Afrom djangobb_forum.models import Forum, Topic%0A%0A%0Aclass SitemapForum(Sitemap):%0A priority = 0.5%0A%0A def items(self):%0A return Forum.objects.all()%0A%0A%0Aclass SitemapTopic(Sitemap):%0A priority = 0.5%0A%0A def items(self):%0A return Topic.objects.all()
|
|
a6f26893189376f64b6be5121e840acc4cfeebae
|
ADD utils.py : model_to_json / expand_user_database methods
|
packages/syft/src/syft/core/node/common/tables/utils.py
|
packages/syft/src/syft/core/node/common/tables/utils.py
|
Python
| 0.000004 |
@@ -0,0 +1,2401 @@
+# grid relative%0Afrom .groups import Group%0Afrom .usergroup import UserGroup%0Afrom .roles import Role%0A%0A%0Adef model_to_json(model):%0A %22%22%22Returns a JSON representation of an SQLAlchemy-backed object.%22%22%22%0A json = %7B%7D%0A for col in model.__mapper__.attrs.keys():%0A if col != %22hashed_password%22 and col != %22salt%22:%0A if col == %22date%22 or col == %22created_at%22 or col == %22destroyed_at%22:%0A # Cast datetime object to string%0A json%5Bcol%5D = str(getattr(model, col))%0A else:%0A json%5Bcol%5D = getattr(model, col)%0A%0A return json%0A%0A%0Adef expand_user_object(user, db):%0A def get_group(user_group):%0A query = db.session().query%0A group = user_group.group%0A group = query(Group).get(group)%0A group = model_to_json(group)%0A return group%0A%0A query = db.session().query%0A user = model_to_json(user)%0A user%5B%22role%22%5D = query(Role).get(user%5B%22role%22%5D)%0A user%5B%22role%22%5D = model_to_json(user%5B%22role%22%5D)%0A user%5B%22groups%22%5D = query(UserGroup).filter_by(user=user%5B%22id%22%5D).all()%0A user%5B%22groups%22%5D = %5Bget_group(user_group) for user_group in user%5B%22groups%22%5D%5D%0A%0A return user%0A%0A%0Adef seed_db(db):%0A%0A new_role = Role(%0A name=%22User%22,%0A can_triage_requests=False,%0A can_edit_settings=False,%0A can_create_users=False,%0A can_create_groups=False,%0A can_edit_roles=False,%0A can_manage_infrastructure=False,%0A can_upload_data=False,%0A )%0A db.add(new_role)%0A%0A new_role = Role(%0A name=%22Compliance Officer%22,%0A can_triage_requests=True,%0A can_edit_settings=False,%0A can_create_users=False,%0A can_create_groups=False,%0A can_edit_roles=False,%0A can_manage_infrastructure=False,%0A can_upload_data=False,%0A )%0A db.add(new_role)%0A%0A new_role = Role(%0A name=%22Administrator%22,%0A can_triage_requests=True,%0A can_edit_settings=True,%0A can_create_users=True,%0A can_create_groups=True,%0A can_edit_roles=False,%0A can_manage_infrastructure=False,%0A can_upload_data=True,%0A )%0A db.add(new_role)%0A%0A new_role = Role(%0A name=%22Owner%22,%0A can_triage_requests=True,%0A can_edit_settings=True,%0A can_create_users=True,%0A can_create_groups=True,%0A can_edit_roles=True,%0A can_manage_infrastructure=True,%0A can_upload_data=True,%0A )%0A db.add(new_role)%0A db.commit()%0A
|
|
d7d0af678a52b357ecf479660ccee1eab43c443f
|
Add gender choices model
|
accelerator/models/gender_choices.py
|
accelerator/models/gender_choices.py
|
Python
| 0.000534 |
@@ -0,0 +1,364 @@
+# MIT License%0A# Copyright (c) 2017 MassChallenge, Inc.%0A%0Afrom __future__ import unicode_literals%0A%0Aimport swapper%0A%0Afrom accelerator_abstract.models import BaseGenderChoices%0A%0A%0A%0Aclass GenderChoices(BaseGenderChoices):%0A class Meta(BaseGenderChoices.Meta):%0A swappable = swapper.swappable_setting(%0A BaseGenderChoices.Meta.app_label, %22GenderChoices%22)%0A
|
|
95edeaa711e8c33e1b431f792e0f2638126ed461
|
Add test case for dynamic ast
|
pymtl/tools/translation/dynamic_ast_test.py
|
pymtl/tools/translation/dynamic_ast_test.py
|
Python
| 0.000002 |
@@ -0,0 +1,2581 @@
+#=======================================================================%0A# verilog_from_ast_test.py%0A#=======================================================================%0A# This is the test case that verifies the dynamic AST support of PyMTL.%0A# This test is contributed by Zhuanhao Wu through #169, #170 of PyMTL v2.%0A#%0A# Author : Zhuanhao Wu, Peitian Pan%0A# Date : Jan 23, 2019%0A%0Aimport pytest%0Aimport random%0A%0Afrom ast import *%0Afrom pymtl import *%0Afrom pclib.test import run_test_vector_sim%0Afrom verilator_sim import TranslationTool%0A%0Apytestmark = requires_verilator%0A%0Aclass ASTRTLModel(Model):%0A def __init__( s ):%0A s.a = InPort(2)%0A s.b = InPort(2)%0A%0A s.out = OutPort(2)%0A%0A # a simple clocked adder%0A # @s.posedge_clk%0A # def logic():%0A # s.out.next = s.a + s.b%0A%0A # generate the model from ast%0A tree = Module(body=%5B%0A FunctionDef(name='logic', args=arguments(args=%5B%5D, defaults=%5B%5D), %0A body= %5B%0A Assign(targets=%5B%0A Attribute(value=Attribute(value=Name(id='s', ctx=Load()), attr='out', ctx=Load()), attr='next', ctx=Store())%0A %5D, %0A value=BinOp(left=Attribute(value=Name(id='s', ctx=Load()), attr='a', ctx=Load()), op=Add(), right=Attribute(value=Name(id='s', ctx=Load()), attr='b', ctx=Load()))%0A )%0A %5D,%0A decorator_list=%5B%0A Attribute(value=Name(id='s', ctx=Load()), attr='posedge_clk', ctx=Load())%0A %5D,%0A returns=None)%0A %5D)%0A tree = fix_missing_locations(tree)%0A%0A # Specifiy the union of globals() and locals() so the free%0A # variables in the closure can be captured.%0A exec(compile(tree, filename='%3Cast%3E', mode='exec')) in globals().update( locals() )%0A%0A # As with #175, the user needs to supplement the dynamic AST to%0A # the .ast field of the generated function object. %0A logic.ast = tree%0A%0Adef test_ast_rtl_model_works_in_simulation():%0A mod = ASTRTLModel()%0A%0A test_vector_table = %5B('a', 'b', 'out*')%5D%0A last_result = '?'%0A for i in xrange(3):%0A rv1 = Bits(2, random.randint(0, 3))%0A rv2 = Bits(2, random.randint(0, 3))%0A test_vector_table.append( %5B rv1, rv2, last_result %5D )%0A last_result = Bits(2, rv1 + rv2)%0A%0A run_test_vector_sim(mod, test_vector_table)%0A%0Adef test_ast_rtl_model_to_verilog():%0A mod = ASTRTLModel()%0A # TranslationTool should successfully compile ASTRTLModel%0A tool = TranslationTool(mod)%0A
|
|
49cab51aa8697a56c7cf74e45b77d9a20ad1a178
|
add topk/gen.py
|
topk/gen.py
|
topk/gen.py
|
Python
| 0 |
@@ -0,0 +1,449 @@
+#!/usr/bin/python%0A%0Aimport random%0A%0Aword_len = 5%0Aalphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-'%0A%0Aoutput = open('word_count', 'w')%0Awords = set()%0AN = 1000*1000%0Afor x in xrange(N):%0A arr = %5Brandom.choice(alphabet) for i in range(word_len)%5D%0A words.add(''.join(arr))%0A%0Aprint len(words)%0Afor word in words:%0A output.write(word)%0A output.write('%5Ct')%0A output.write(str(random.randint(1, 2*N)))%0A output.write('%5Cn')%0A%0A
|
|
c5da52c38d280873066288977f021621cb9653d0
|
Apply orphaned migration
|
project/apps/api/migrations/0010_remove_chart_song.py
|
project/apps/api/migrations/0010_remove_chart_song.py
|
Python
| 0 |
@@ -0,0 +1,345 @@
+# -*- coding: utf-8 -*-%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import models, migrations%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('api', '0009_auto_20150722_1041'),%0A %5D%0A%0A operations = %5B%0A migrations.RemoveField(%0A model_name='chart',%0A name='song',%0A ),%0A %5D%0A
|
|
ab5d1fd5728b9c2f27d74c2896e05a94b061f3f9
|
add config.py
|
config.py
|
config.py
|
Python
| 0.000002 |
@@ -0,0 +1,49 @@
+# twilio account details%0Aaccount = %22%22%0Atoken = %22%22%0A
|
|
42cc2864f03480e29e55bb0ef0b30e823c11eb2f
|
complete check online window
|
check_online_window.py
|
check_online_window.py
|
Python
| 0 |
@@ -0,0 +1,1229 @@
+import tkinter as tk%0Aimport tkinter.messagebox as tkmb%0Afrom online_check import CheckSomeoneOnline%0A%0Aclass open_check_online_window():%0A def __init__(self, x, y):%0A self.co = tk.Tk()%0A self.co.title('enter ip to check')%0A self.co.resizable(False, False)%0A self.co.wm_attributes(%22-toolwindow%22, 1)%0A self.entry = tk.Entry(self.co, width=15)%0A self.entry.pack(side = 'left', fill = 'both')%0A check = tk.Button(self.co,%0A text='check',%0A relief = 'flat',%0A command=self.check_online)%0A check.pack(side = 'right', fill = 'both')%0A self.co.geometry('+%25d+%25d'%25 (x,y))%0A self.co.mainloop()%0A %0A def on_return(self, event):%0A self.check_online()%0A %0A def check_online(self):%0A ip = self.entry.get()%0A try:%0A if True:#if CheckSomeoneOnline(ip) == True:%0A tkmb.showinfo('online check', ip+'is online')%0A else:%0A tkmb.showinfo('online check', ip+'is offline')%0A except Exception as err:%0A tkmb.showerror('Error', err)%0A self.co.quit()%0A %0Aif __name__ == '__main__':%0A open_check_online_window(600, 300)
|
|
956da3bc7ff7971b9b6cc76495fcb5b2e4145d6e
|
Handle smtplib.SMTPRecipientsRefused and defer the message properly.
|
mailerdev/mailer/engine.py
|
mailerdev/mailer/engine.py
|
import time
from lockfile import FileLock
from socket import error as socket_error
from models import Message, DontSendEntry, MessageLog
from django.core.mail import send_mail as core_send_mail
## configuration settings
# @@@ eventually move to settings.py
# when queue is empty, how long to wait (in seconds) before checking again
EMPTY_QUEUE_SLEEP = 30
def prioritize():
"""
Yield the messages in the queue in the order they should be sent.
"""
while True:
while Message.objects.high_priority().count() or Message.objects.medium_priority().count():
while Message.objects.high_priority().count():
for message in Message.objects.high_priority().order_by('when_added'):
yield message
while Message.objects.high_priority().count() == 0 and Message.objects.medium_priority().count():
yield Message.objects.medium_priority().order_by('when_added')[0]
while Message.objects.high_priority().count() == 0 and Message.objects.medium_priority().count() == 0 and Message.objects.low_priority().count():
yield Message.objects.low_priority().order_by('when_added')[0]
if Message.objects.non_deferred().count() == 0:
break
def send_all():
"""
Send all eligible messages in the queue.
"""
print "-" * 72
lock = FileLock("send_mail")
print "acquiring lock..."
lock.acquire()
print "acquired."
start_time = time.time()
dont_send = 0
deferred = 0
sent = 0
try:
for message in prioritize():
if DontSendEntry.objects.has_address(message.to_address):
print "skipping email to %s as on don't send list " % message.to_address
MessageLog.objects.log(message, 2) # @@@ avoid using literal result code
message.delete()
dont_send += 1
else:
try:
print "sending message '%s' to %s" % (message.subject.encode("utf-8"), message.to_address.encode("utf-8"))
core_send_mail(message.subject, message.message_body, message.from_address, [message.to_address])
MessageLog.objects.log(message, 1) # @@@ avoid using literal result code
message.delete()
sent += 1
# @@@ need to catch some other things here too
except socket_error, err:
message.defer()
print "message deferred due to failure: %s" % err
MessageLog.objects.log(message, 3, log_message=str(err)) # @@@ avoid using literal result code
deferred += 1
finally:
print "releasing lock..."
lock.release()
print "released."
print
print "%s sent; %s deferred; %s don't send" % (sent, deferred, dont_send)
print "done in %.2f seconds" % (time.time() - start_time)
def send_loop():
"""
Loop indefinitely, checking queue at intervals of EMPTY_QUEUE_SLEEP and
sending messages if any are on queue.
"""
while True:
while not Message.objects.all():
print 'sleeping for %s seconds before checking queue again' % EMPTY_QUEUE_SLEEP
time.sleep(EMPTY_QUEUE_SLEEP)
send_all()
|
Python
| 0.000377 |
@@ -5,16 +5,31 @@
rt time%0A
+import smtplib%0A
from loc
@@ -2466,16 +2466,17 @@
except
+(
socket_e
@@ -2480,16 +2480,48 @@
t_error,
+ smtplib.SMTPRecipientsRefused),
err:%0A
|
05b9859fb7d4577dfa95ec9edd3a6f16bf0fd86e
|
Create __init__.py
|
fade/fade/__init__.py
|
fade/fade/__init__.py
|
Python
| 0.000429 |
@@ -0,0 +1 @@
+%0A
|
|
49a1cfa758f3b704bacebfcf48d45679fe2658e1
|
fix #3043
|
gratipay/utils/history.py
|
gratipay/utils/history.py
|
from datetime import datetime
from decimal import Decimal
from psycopg2 import IntegrityError
def get_end_of_year_balance(db, participant, year, current_year):
if year == current_year:
return participant.balance
if year < participant.claimed_time.year:
return Decimal('0.00')
balance = db.one("""
SELECT balance
FROM balances_at
WHERE participant = %s
AND "at" = %s
""", (participant.id, datetime(year+1, 1, 1)))
if balance is not None:
return balance
username = participant.username
start_balance = get_end_of_year_balance(db, participant, year-1, current_year)
delta = db.one("""
SELECT (
SELECT COALESCE(sum(amount), 0) AS a
FROM exchanges
WHERE participant = %(username)s
AND extract(year from timestamp) = %(year)s
AND amount > 0
AND (status is null OR status = 'succeeded')
) + (
SELECT COALESCE(sum(amount-fee), 0) AS a
FROM exchanges
WHERE participant = %(username)s
AND extract(year from timestamp) = %(year)s
AND amount < 0
AND (status is null OR status <> 'failed')
) + (
SELECT COALESCE(sum(-amount), 0) AS a
FROM transfers
WHERE tipper = %(username)s
AND extract(year from timestamp) = %(year)s
) + (
SELECT COALESCE(sum(amount), 0) AS a
FROM transfers
WHERE tippee = %(username)s
AND extract(year from timestamp) = %(year)s
) AS delta
""", locals())
balance = start_balance + delta
try:
db.run("""
INSERT INTO balances_at
(participant, at, balance)
VALUES (%s, %s, %s)
""", (participant.id, datetime(year+1, 1, 1), balance))
except IntegrityError:
pass
return balance
def iter_payday_events(db, participant, year=None):
"""Yields payday events for the given participant.
"""
current_year = datetime.utcnow().year
year = year or current_year
username = participant.username
exchanges = db.all("""
SELECT *
FROM exchanges
WHERE participant=%(username)s
AND extract(year from timestamp) = %(year)s
""", locals(), back_as=dict)
transfers = db.all("""
SELECT *
FROM transfers
WHERE (tipper=%(username)s OR tippee=%(username)s)
AND extract(year from timestamp) = %(year)s
""", locals(), back_as=dict)
if not (exchanges or transfers):
return
if transfers:
yield dict(
kind='totals',
given=sum(t['amount'] for t in transfers if t['tipper'] == username),
received=sum(t['amount'] for t in transfers if t['tippee'] == username),
)
payday_dates = db.all("""
SELECT ts_start::date
FROM paydays
ORDER BY ts_start ASC
""")
balance = get_end_of_year_balance(db, participant, year, current_year)
prev_date = None
get_timestamp = lambda e: e['timestamp']
events = sorted(exchanges+transfers, key=get_timestamp, reverse=True)
for event in events:
event['balance'] = balance
event_date = event['timestamp'].date()
if event_date != prev_date:
if prev_date:
yield dict(kind='day-close', balance=balance)
day_open = dict(kind='day-open', date=event_date, balance=balance)
if payday_dates:
while payday_dates and payday_dates[-1] > event_date:
payday_dates.pop()
payday_date = payday_dates[-1] if payday_dates else None
if event_date == payday_date:
day_open['payday_number'] = len(payday_dates) - 1
yield day_open
prev_date = event_date
if 'fee' in event:
if event['amount'] > 0:
kind = 'charge'
if event['status'] in (None, 'succeeded'):
balance -= event['amount']
else:
kind = 'credit'
if event['status'] != 'failed':
balance -= event['amount'] - event['fee']
else:
kind = 'transfer'
if event['tippee'] == username:
balance -= event['amount']
else:
balance += event['amount']
event['kind'] = kind
yield event
yield dict(kind='day-close', balance=balance)
|
Python
| 0.000001 |
@@ -2967,32 +2967,59 @@
er'%5D == username
+ and t%5B'context'%5D != 'take'
),%0A r
|
1b6fecb5819fbead0aadcc1a8669e915542c5ea0
|
Add script for gameifying testing
|
other/testing-game.py
|
other/testing-game.py
|
Python
| 0 |
@@ -0,0 +1,1654 @@
+#!/usr/bin/python%0A# -*- coding: utf-8 -*-%0A%0Aimport argparse%0Aimport os%0Aimport subprocess%0Aimport re%0A%0Aparser = argparse.ArgumentParser()%0Aparser.add_argument('-d', '--directory', help='The directory to search for files in', required=False, default=os.getcwd())%0Aargs = parser.parse_args()%0A%0Anames = %7B%7D%0A%0Afor root, dirs, files in os.walk(args.directory):%0A for name in files:%0A filename, fileextension = os.path.splitext(name)%0A %0A absfile = os.path.join(root, name)%0A %0A if fileextension == '.m' or fileextension == '.mm':%0A try:%0A with open(absfile) as sourcefile:%0A source = sourcefile.read()%0A if source.find('XCTestCase') != -1:%0A p = subprocess.Popen(%5B'git', 'blame', absfile%5D, stdout=subprocess.PIPE, stderr=subprocess.PIPE)%0A out, err = p.communicate()%0A %0A for blame_line in out.splitlines():%0A if blame_line.replace(' ', '').find('-(void)test') != -1:%0A blame_info = blame_line%5Bblame_line.find('(')+1:%5D%0A blame_info = blame_info%5B:blame_info.find(')')%5D%0A blame_components = blame_info.split()%0A name_components = blame_components%5B:len(blame_components)-4%5D%0A name = ' '.join(name_components)%0A name_count = names.get(name, 0)%0A names%5Bname%5D = name_count + 1%0A except:%0A 'Could not open file: ' + absfile%0A%0Aprint names
|
|
908013aa5e64589b6c1c6495812a13109244a69a
|
add dottests testconfig, but leave it deactivted yet. lots of import failures, since no imports are declared explicitly
|
src/icalendar/tests/XXX_test_doctests.py
|
src/icalendar/tests/XXX_test_doctests.py
|
Python
| 0 |
@@ -0,0 +1,967 @@
+from interlude import interact%0A%0Aimport doctest%0Aimport os.path%0Aimport unittest%0A%0A%0AOPTIONFLAGS = doctest.NORMALIZE_WHITESPACE %7C doctest.ELLIPSIS%0ADOCFILES = %5B%0A 'example.txt',%0A 'groupscheduled.txt',%0A 'multiple.txt',%0A 'recurrence.txt',%0A 'small.txt'%0A%5D%0ADOCMODS = %5B%0A 'icalendar.caselessdict',%0A 'icalendar.cal',%0A 'icalendar.parser',%0A 'icalendar.prop',%0A%5D%0A%0Adef test_suite():%0A suite = unittest.TestSuite()%0A suite.addTests(%5B%0A doctest.DocFileSuite(%0A os.path.join(os.path.dirname(__file__), docfile),%0A module_relative=False,%0A optionflags=OPTIONFLAGS,%0A globs=%7B'interact': interact%7D%0A ) for docfile in DOCFILES%0A %5D)%0A suite.addTests(%5B%0A doctest.DocTestSuite(%0A docmod,%0A optionflags=OPTIONFLAGS,%0A globs=%7B'interact': interact%7D%0A ) for docmod in DOCMODS%0A %5D)%0A return suite%0A%0Aif __name__ == '__main__':%0A unittest.main(defaultTest='test_suite')%0A
|
|
4a99dcd629a830ad1ec0c658f312a4793dec240b
|
add basic file for parser
|
RedBlue/Parser3.py
|
RedBlue/Parser3.py
|
Python
| 0.000001 |
@@ -0,0 +1,85 @@
+%0Aclass Parser(object):%0A%0A @classmethod%0A def read_html(cls, html):%0A pass%0A%0A
|
|
0648ca26ba195e4d5ce55d801975a161907e655f
|
Add test for translation
|
aldryn_faq/tests/test_aldryn_faq.py
|
aldryn_faq/tests/test_aldryn_faq.py
|
Python
| 0.000001 |
@@ -0,0 +1,2926 @@
+# -*- coding: utf-8 -*-%0A%0Afrom __future__ import unicode_literals%0A%0Afrom django.test import TestCase # , TransactionTestCase%0A# from django.utils import translation%0Afrom hvad.test_utils.context_managers import LanguageOverride%0A%0Afrom aldryn_faq.models import Category, Question%0A%0AEN_CAT_NAME = %22Example%22%0AEN_CAT_SLUG = %22example%22%0AEN_QUE_TITLE = %22Test Question%22%0AEN_QUE_ANSWER_TEXT = %22Test Answer%22%0A%0ADE_CAT_NAME = %22Beispiel%22%0ADE_CAT_SLUG = %22beispiel%22%0ADE_QUE_TITLE = %22Testfrage%22%0ADE_QUE_ANSWER_TEXT = %22Test Antwort%22%0A%0A%0Aclass AldrynFaqTestMixin(object):%0A%0A @staticmethod%0A def reload(object):%0A %22%22%22Simple convenience method for re-fetching an object from the ORM.%22%22%22%0A return object.__class__.objects.get(id=object.id)%0A%0A def mktranslation(self, obj, lang, **kwargs):%0A %22%22%22Simple method of adding a translation to an existing object.%22%22%22%0A obj.translate(lang)%0A for k, v in kwargs.iteritems():%0A setattr(obj, k, v)%0A obj.save()%0A%0A def setUp(self):%0A %22%22%22Setup a prebuilt and translated Question with Category%0A for testing.%22%22%22%0A with LanguageOverride(%22en%22):%0A self.category = Category(**%7B%0A %22name%22: EN_CAT_NAME,%0A %22slug%22: EN_CAT_SLUG%0A %7D)%0A self.category.save()%0A self.question = Question(**%7B%0A %22title%22: EN_QUE_TITLE,%0A %22answer_text%22: EN_QUE_ANSWER_TEXT,%0A %7D)%0A self.question.category = self.category%0A self.question.save()%0A%0A # Make a DE translation of the category%0A self.mktranslation(self.category, %22de%22, **%7B%0A %22name%22: DE_CAT_NAME,%0A %22slug%22: DE_CAT_SLUG,%0A %7D)%0A # Make a DE translation of the question%0A self.mktranslation(self.question, %22de%22, **%7B%0A %22title%22: DE_QUE_TITLE,%0A %22answer_text%22: DE_QUE_ANSWER_TEXT,%0A %7D)%0A%0A%0Aclass TestFAQTranslations(AldrynFaqTestMixin, TestCase):%0A%0A def test_fetch_faq_translations(self):%0A %22%22%22Test we can fetch arbitrary translations of the question and%0A its category.%22%22%22%0A # Can we target the EN values?%0A with LanguageOverride(%22en%22):%0A question = self.reload(self.question)%0A category = self.reload(self.question.category)%0A self.assertEqual(question.title, EN_QUE_TITLE)%0A self.assertEqual(question.answer_text, EN_QUE_ANSWER_TEXT)%0A self.assertEqual(category.name, EN_CAT_NAME)%0A self.assertEqual(category.slug, EN_CAT_SLUG)%0A%0A # And the DE values?%0A with LanguageOverride(%22de%22):%0A question = self.reload(self.question)%0A category = self.reload(self.question.category)%0A self.assertEqual(question.title, DE_QUE_TITLE)%0A self.assertEqual(question.answer_text, DE_QUE_ANSWER_TEXT)%0A self.assertEqual(category.name, DE_CAT_NAME)%0A self.assertEqual(category.slug, DE_CAT_SLUG)%0A
|
|
d1f71e1c6468799247d07d810a6db7d0ad5f89b0
|
add support for jinja2 template engine
|
alaocl/jinja2.py
|
alaocl/jinja2.py
|
Python
| 0 |
@@ -0,0 +1,1857 @@
+from alaocl import *%0A%0A#__all__ = (%0A# 'addOCLtoEnvironment',%0A#)%0A_FILTERS = %7B%0A 'asSet': asSet,%0A 'asBag': asBag,%0A 'asSeq': asSeq,%0A%7D%0A%0A_GLOBALS = %7B%0A 'floor': floor,%0A 'isUndefined': isUndefined,%0A 'oclIsUndefined': oclIsUndefined,%0A 'oclIsKindOf': oclIsKindOf,%0A 'oclIsTypeOf': oclIsTypeOf,%0A 'isCollection': isCollection,%0A 'asSet': asSet,%0A 'asBag': asBag,%0A 'asSeq': emptyCollection%0A%7D%0A%0Atry:%0A # noinspection PyUnresolvedReferences%0A from org.modelio.api.modelio import Modelio%0A%0A WITH_MODELIO = True%0Aexcept:%0A WITH_MODELIO = False%0A%0Aif WITH_MODELIO:%0A%0A # TODO: in fact, this piece of code should be in modelio%0A # and it should be possible to import global stuff at once%0A # - at the top level script%0A # - as jinja global%0A # - in any python module%0A # Lambda expressions cannot be defined directly in the loop. See below:%0A # http://stackoverflow.com/questions/841555/%0A # whats-going-on-with-the-lambda-expression-in-this-python-function?rq=1%0A def _newIsInstanceFun(metaInterface):%0A return lambda e: isinstance(e, metaInterface)%0A%0A from alaocl.modelio import allMetaInterfaces%0A for m_interface in allMetaInterfaces():%0A metaName = m_interface.metaName%0A _GLOBALS%5BmetaName%5D = m_interface%0A%0A isFunction = _newIsInstanceFun(m_interface)%0A _GLOBALS%5B'is' + metaName%5D = isFunction%0A globals()%5B'is' + metaName%5D = isFunction%0A%0Adef addOCLtoEnvironment(jinja2Environment):%0A %22%22%22%0A Add OCL functions to a jinja2 environment so that OCL can be%0A used in jinja2 templates.%0A%0A :param jinja2Environment: Jinja2 environment to be instrumented.%0A :type jinja2Environment: jinja2.Environment%0A :return: The modified environment.%0A :rtype: jinja2.Environment%0A %22%22%22%0A jinja2Environment.filters.update(_FILTERS)%0A jinja2Environment.globals.update(_GLOBALS)%0A%0A%0A
|
|
7cb62f554fa293a2ba4d0456ed8d04e8f277d2c1
|
Add migrations/0146_clean_lexeme_romanised_3.py
|
ielex/lexicon/migrations/0146_clean_lexeme_romanised_3.py
|
ielex/lexicon/migrations/0146_clean_lexeme_romanised_3.py
|
Python
| 0 |
@@ -0,0 +1,753 @@
+# -*- coding: utf-8 -*-%0Afrom __future__ import unicode_literals, print_function%0Afrom django.db import migrations%0A%0A%0Adef forwards_func(apps, schema_editor):%0A Lexeme = apps.get_model(%22lexicon%22, %22Lexeme%22)%0A replaceMap = %7B%0A '%CE%BB': '%CA%8E',%0A '%CF%86': '%C9%B8'%0A %7D%0A for lexeme in Lexeme.objects.all():%0A if len(set(replaceMap.keys()) & set(lexeme.romanised)):%0A for k, v in replaceMap.items():%0A lexeme.romanised = lexeme.romanised.replace(k, v)%0A lexeme.save()%0A%0A%0Adef reverse_func(apps, schema_editor):%0A pass%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B('lexicon', '0145_fix_language_distributions')%5D%0A%0A operations = %5B%0A migrations.RunPython(forwards_func, reverse_func),%0A %5D%0A
|
|
8f1b1ef01e74782f57da9c9489a3a7f6555bbee6
|
Add tests for reports views.
|
annotran/reports/test/views_test.py
|
annotran/reports/test/views_test.py
|
Python
| 0 |
@@ -0,0 +1,145 @@
+# -*- coding: utf-8 -*-%0Aimport mock%0Aimport pytest%0Afrom pyramid import httpexceptions%0A%0A%0Afrom annotran.reports import views%0A%0A%0A%0A_SENTINEL = object()
|
|
691ae15cb0f46400762c27305fb74f57fa1ffccf
|
Implement account.py
|
src/account.py
|
src/account.py
|
Python
| 0.000009 |
@@ -0,0 +1,2801 @@
+from datetime import datetime%0Afrom hashlib import md5%0Afrom re import match, search, DOTALL%0Afrom requests.sessions import Session%0Afrom bs4 import BeautifulSoup%0A%0ABASE_URL = 'https://usereg.tsinghua.edu.cn'%0ALOGIN_PAGE = BASE_URL + '/do.php'%0AINFO_PAGE = BASE_URL + '/user_info.php'%0A%0Aclass Account(object):%0A %22%22%22Tsinghua Account%22%22%22%0A def __init__(self, username, password, is_md5=False):%0A super(Account, self).__init__()%0A self.username = username%0A%0A if is_md5:%0A if len(password) != 32:%0A raise ValueError('Length of a MD5 string must be 32')%0A self.md5_pass = password%0A else:%0A self.md5_pass = md5(password.encode()).hexdigest()%0A%0A # Account Infomations.%0A self.name = ''%0A self.id = ''%0A%0A # Balance & Usage.%0A self.balance = 0%0A self.ipv4_byte = 0%0A self.ipv6_byte = 0%0A self.last_check = None%0A%0A # Status.%0A self.valid = False%0A%0A%0A def check(self):%0A try:%0A s = Session()%0A payload = dict(action='login',%0A user_login_name=self.username,%0A user_password=self.md5_pass)%0A%0A login = s.post(LOGIN_PAGE, payload)%0A if not login: # Not a normal response, mayby the server is down?%0A return False%0A%0A if login.text == 'ok':%0A self.valid = True%0A self.update_infos(s)%0A else:%0A self.valid = False%0A%0A # Checking complete.%0A self.last_check = datetime.today()%0A return True%0A except: # Things happened so checking did not finish.%0A return False%0A%0A def update_infos(self, session):%0A # Parse HTML.%0A soup = BeautifulSoup(session.get(INFO_PAGE).text, 'html.parser')%0A blocks = map(BeautifulSoup.get_text, soup.select('.maintd'))%0A i = map(str.strip, blocks) # Only works in python 3.%0A infos = dict(zip(i, i))%0A%0A self.name = infos%5B'%E5%A7%93%E5%90%8D'%5D%0A self.id = infos%5B'%E8%AF%81%E4%BB%B6%E5%8F%B7'%5D%0A%0A self.balance = head_float(infos%5B'%E5%B8%90%E6%88%B7%E4%BD%99%E9%A2%9D'%5D)%0A self.ipv4_byte = head_int(infos%5B'%E4%BD%BF%E7%94%A8%E6%B5%81%E9%87%8F(IPV4)'%5D)%0A self.ipv6_byte = head_int(infos%5B'%E4%BD%BF%E7%94%A8%E6%B5%81%E9%87%8F(IPV6)'%5D)%0A%0A def __repr__(self):%0A return '%3CAccount(%25s, %25s, %25sB, %C2%A5%25s, %25s)%3E' %25 (self.username,%0A self.valid,%0A self.ipv4_byte,%0A self.balance,%0A self.last_check)%0A%0A%0Adef head_int(s):%0A return int(match(r'%5Cd+', s).group())%0A%0Adef head_float(s):%0A return float(match(r'%5Cd+(%5C.%5Cd+)?', s).group())%0A%0Aif __name__ == '__main__':%0A acc = Account(%22lisihan13%22, %221L2S3H@th%22)%0A acc.check()%0A print(acc)%0A
|
|
940299a7bfd967653899b176ce76e6f1cf02ca83
|
Add script to generate pairs of LIWC categories
|
liwcpairs2es.py
|
liwcpairs2es.py
|
Python
| 0 |
@@ -0,0 +1,2003 @@
+#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0Afrom elasticsearch import Elasticsearch, helpers%0Afrom collections import Counter%0Afrom datetime import datetime%0A%0A%0Adef find_pairs(list1, list2):%0A pairs = %5B%5D%0A if list1 and list2:%0A for item1 in list1:%0A for item2 in list2:%0A pairs.append(u'%7B%7D@%7B%7D'.format(item1, item2))%0A return pairs%0A%0A%0Aes = Elasticsearch()%0Aindex_name = 'embem'%0Adoc_type = 'event'%0Acat1 = 'Body'%0Acat2 = 'Posemo'%0A%0Atimestamp = datetime.now().isoformat()%0A%0Apairs_count = Counter()%0Ayears = %7B%7D%0A%0Aq = %7B%0A %22query%22: %7B%0A %22wildcard%22: %7B%22text_id%22: %22*%22%7D%0A %7D%0A%7D%0A%0Aresults = helpers.scan(client=es, query=q, index=index_name, doc_type=doc_type)%0Afor r in results:%0A # get tags%0A cat1_tags = r.get('_source').get('liwc-entities').get('data').get(cat1)%0A cat2_tags = r.get('_source').get('liwc-entities').get('data').get(cat2)%0A%0A # find all pairs%0A pairs = find_pairs(cat1_tags, cat2_tags)%0A%0A if pairs:%0A for pair in pairs:%0A pairs_count%5Bpair%5D += 1%0A year = r.get('_source').get('year')%0A if year not in years.keys():%0A years%5Byear%5D = Counter()%0A years%5Byear%5D%5Bpair%5D += 1%0A%0A # save pairs to ES%0A doc = %7B%0A 'doc': %7B%0A 'pairs-%7B%7D-%7B%7D'.format(cat1, cat2): %7B%0A 'data': pairs,%0A 'num_pairs': len(pairs),%0A 'timestamp': timestamp%0A %7D%0A %7D%0A %7D%0A es.update(index=index_name, doc_type=doc_type,%0A id=r.get('_id'), body=doc)%0A%0Asorted_years = years.keys()%0Asorted_years.sort()%0A%0Aprint '%7B%7D%5Ct%7B%7D%5CtFrequency'.format(cat1, cat2) + %5C%0A ''.join(%5B'%5Ct%7B%7D'.format(k) for k in sorted_years%5D)%0Aprint 'TOTAL%5CtTOTAL%5Ct%7B%7D'.format(sum(pairs_count.values())) + %5C%0A ''.join(%5B'%5Ct%7B%7D'.format(sum(years%5Bk%5D.values())) for k in sorted_years%5D)%0Afor p, f in pairs_count.most_common():%0A (w1, w2) = p.split('@')%0A print u'%7B%7D%5Ct%7B%7D%5Ct%7B%7D'.format(w1, w2, f).encode('utf-8') + %5C%0A ''.join(%5B'%5Ct%7B%7D'.format(years%5Bk%5D%5Bp%5D) for k in sorted_years%5D)%0A
|
|
73292532767d736a77ec8b122cfd4ff19b7d991b
|
Create Account dashboard backend
|
UI/account_dash.py
|
UI/account_dash.py
|
Python
| 0.000001 |
@@ -0,0 +1,2847 @@
+# -*- coding: utf-8 -*-%0Aimport threading%0Afrom PyQt4 import QtCore, QtGui%0Afrom qt_interfaces.account_dash_ui import Ui_AccountDash%0Afrom engine import StorjEngine%0Afrom utilities.tools import Tools%0A%0A%0A# Synchronization menu section #%0Aclass AccountDashUI(QtGui.QMainWindow):%0A%0A def __init__(self, parent=None,):%0A QtGui.QWidget.__init__(self, parent)%0A self.account_dash_ui = Ui_AccountDash()%0A self.account_dash_ui.setupUi(self)%0A%0A self.storj_engine = StorjEngine() # init StorjEngine%0A self.tools = Tools()%0A%0A self.initialize_buckets_stats_table()%0A%0A self.createNewBucketsStatsGetThread()%0A%0A%0A def createNewBucketsStatsGetThread(self):%0A thread = threading.Thread(target=self.fill_buckets_stats_table, args=())%0A thread.start()%0A%0A%0A def initialize_buckets_stats_table(self):%0A self.table_header = %5B'Bucket name', 'Files count', 'Total used space'%5D%0A self.account_dash_ui.buckets_stats_table.setColumnCount(3)%0A self.account_dash_ui.buckets_stats_table.setRowCount(0)%0A horHeaders = self.table_header%0A self.account_dash_ui.buckets_stats_table.setHorizontalHeaderLabels(horHeaders)%0A self.account_dash_ui.buckets_stats_table.resizeColumnsToContents()%0A self.account_dash_ui.buckets_stats_table.resizeRowsToContents()%0A%0A self.account_dash_ui.buckets_stats_table.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch)%0A%0A def fill_buckets_stats_table(self):%0A total_files_size = 0%0A total_files_count = 0%0A for bucket in self.storj_engine.storj_client.bucket_list():%0A total_bucket_files_size = 0%0A total_bucket_files_count = 0%0A # fill table%0A table_row_count = self.account_dash_ui.buckets_stats_table.rowCount()%0A%0A self.account_dash_ui.buckets_stats_table.setRowCount(%0A table_row_count + 1)%0A%0A for file in self.storj_engine.storj_client.bucket_files(bucket_id=bucket.id):%0A total_bucket_files_size += int(file%5B'size'%5D)%0A total_bucket_files_count += 1%0A%0A self.account_dash_ui.buckets_stats_table.setItem(%0A table_row_count, 0, QtGui.QTableWidgetItem(bucket.name))%0A%0A self.account_dash_ui.buckets_stats_table.setItem(%0A table_row_count, 1, QtGui.QTableWidgetItem(str(total_bucket_files_count)))%0A%0A self.account_dash_ui.buckets_stats_table.setItem(%0A table_row_count, 2, QtGui.QTableWidgetItem(str(self.tools.human_size(total_bucket_files_size))))%0A%0A total_files_count += total_bucket_files_count%0A total_files_size += total_bucket_files_size%0A%0A self.account_dash_ui.files_total_count.setText(str(total_files_count))%0A self.account_dash_ui.total_used_space.setText(str(self.tools.human_size(total_files_size)))%0A%0A%0A%0A%0A
|
|
53258a9ffd869dd958fd818874b2c8406acca143
|
add pytest for util.store
|
pytests/util/test_store.py
|
pytests/util/test_store.py
|
Python
| 0 |
@@ -0,0 +1,909 @@
+import pytest%0A%0Aimport util.store%0A%0A%[email protected]%0Adef emptyStore():%0A return util.store.Store()%0A%0A%[email protected]%0Adef store():%0A return util.store.Store()%0A%0A%0Adef test_get_of_unset_key(emptyStore):%0A assert emptyStore.get(%22any-key%22) == None%0A assert emptyStore.get(%22any-key%22, %22default-value%22) == %22default-value%22%0A%0A%0Adef test_get_of_set_key(store):%0A store.set(%22key%22, %22value%22)%0A assert store.get(%22key%22) == %22value%22%0A%0A%0Adef test_overwrite_set(store):%0A store.set(%22key%22, %22value 1%22)%0A store.set(%22key%22, %22value 2%22)%0A%0A assert store.get(%22key%22) == %22value 2%22%0A%0A%0Adef test_unused_keys(store):%0A store.set(%22key 1%22, %22value x%22)%0A store.set(%22key 2%22, %22value y%22)%0A%0A assert store.unused_keys() == sorted(%5B%22key 1%22, %22key 2%22%5D)%0A%0A store.get(%22key 2%22)%0A%0A assert store.unused_keys() == %5B%22key 1%22%5D%0A%0A store.get(%22key 1%22)%0A%0A assert store.unused_keys() == %5B%5D%0A%0A%0A# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4%0A
|
|
5bde5b5904abc30506e56865cd58fd88a97942aa
|
Add `deprecated` decorator
|
linux/keyman-config/keyman_config/deprecated_decorator.py
|
linux/keyman-config/keyman_config/deprecated_decorator.py
|
Python
| 0.000001 |
@@ -0,0 +1,858 @@
+#!/usr/bin/python3%0A# based on https://stackoverflow.com/a/40301488%0Aimport logging%0A%0A%0Astring_types = (type(b''), type(u''))%0A%0A%0Adef deprecated(reason):%0A if isinstance(reason, string_types):%0A # The @deprecated is used with a 'reason'.%0A def decorator(func1):%0A def new_func1(*args, **kwargs):%0A logging.warning(%22Call to deprecated function '%7Bname%7D': %7Breason%7D.%22.format(%0A name=func1.__name__, reason=reason))%0A return func1(*args, **kwargs)%0A return new_func1%0A return decorator%0A else:%0A # The @deprecated is used without any 'reason'.%0A def new_func2(*args, **kwargs):%0A func2 = reason%0A logging.warning(%22Call to deprecated function '%7Bname%7D'.%22.format(name=func2.__name__))%0A return func2(*args, **kwargs)%0A return new_func2%0A
|
|
f6519493dd75d7f5a8b65a952b5d7048bd101ec4
|
Create locationanalysis.py
|
locationanalysis.py
|
locationanalysis.py
|
Python
| 0.000001 |
@@ -0,0 +1,155 @@
+import json%0A%0Aprint 'test'%0A%0Af = open('location.json', 'r')%0Ajsoncontent = f.read()%0Aprint jsoncontent%0A%0Alocation = json.loads(jsoncontent)%0Aprint len(location)%0A
|
|
f6d417e69efa4554008bc441a5c82a5b9f93a082
|
Add sql.conventions.objects.Items
|
garage/sql/conventions/objects.py
|
garage/sql/conventions/objects.py
|
Python
| 0.003446 |
@@ -0,0 +1,798 @@
+__all__ = %5B%0A 'Items',%0A%5D%0A%0Afrom garage.functools import nondata_property%0Afrom garage.sql.utils import insert_or_ignore, make_select_by%0A%0A%0Aclass Items:%0A %22%22%22A thin layer on top of tables of two columns: (id, value)%22%22%22%0A%0A def __init__(self, table, id_name, value_name):%0A self.table = table%0A self.value_name = value_name%0A self._select_ids = make_select_by(%0A getattr(self.table.c, value_name),%0A getattr(self.table.c, id_name),%0A )%0A%0A @nondata_property%0A def conn(self):%0A raise NotImplementedError%0A%0A def select_ids(self, values):%0A return dict(self._select_ids(self.conn, values))%0A%0A def insert(self, values):%0A insert_or_ignore(self.conn, self.table, %5B%0A %7Bself.value_name: value%7D for value in values%0A %5D)%0A
|
|
313f5c8c54002a736a323410c5d9ec96fcc2f50b
|
Create RespostaVer.py
|
backend/Models/Predio/RespostaVer.py
|
backend/Models/Predio/RespostaVer.py
|
Python
| 0 |
@@ -0,0 +1,189 @@
+from Framework.Resposta import Resposta%0Afrom Models.Campus.Campus import Campus as ModelCampus%0A%0Aclass RespostaVer(Resposta):%0A%0A%09def __init__(self,campus):%0A%09%09self.corpo = ModelCampus(campus)%0A
|
|
95f5b7cd2325a61f537bffb783e950b30c97da5f
|
Add a demo about learning the shape parameter of gamma dist
|
bayespy/demos/gamma_shape.py
|
bayespy/demos/gamma_shape.py
|
Python
| 0 |
@@ -0,0 +1,484 @@
+%0A%0Afrom bayespy import nodes%0Afrom bayespy.inference import VB%0A%0A%0Adef run():%0A%0A a = nodes.GammaShape(name='a')%0A b = nodes.Gamma(1e-5, 1e-5, name='b')%0A%0A tau = nodes.Gamma(a, b, plates=(1000,), name='tau')%0A tau.observe(nodes.Gamma(10, 20, plates=(1000,)).random())%0A%0A Q = VB(tau, a, b)%0A%0A Q.update(repeat=1000)%0A%0A print(%22True gamma parameters:%22, 10.0, 20.0)%0A print(%22Estimated parameters from 1000 samples:%22, a.u%5B0%5D, b.u%5B0%5D)%0A%0A%0Aif __name__ == %22__main__%22:%0A%0A %0A run()%0A
|
|
538417b8522f5805d3a9cd59c0cdc71073c122ac
|
Remove admin requirement for shared network actions
|
openstack_dashboard/dashboards/project/networks/tables.py
|
openstack_dashboard/dashboards/project/networks/tables.py
|
# Copyright 2012 NEC Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging
from django.core.urlresolvers import reverse
from django import template
from django.template import defaultfilters as filters
from django.utils.translation import pgettext_lazy
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ungettext_lazy
from horizon import exceptions
from horizon import tables
from openstack_dashboard import api
from openstack_dashboard import policy
from openstack_dashboard.usage import quotas
LOG = logging.getLogger(__name__)
class CheckNetworkEditable(object):
"""Mixin class to determine the specified network is editable."""
def allowed(self, request, datum=None):
# Only administrator is allowed to create and manage shared networks.
if datum and datum.shared:
return False
return True
class DeleteNetwork(policy.PolicyTargetMixin, CheckNetworkEditable,
tables.DeleteAction):
@staticmethod
def action_present(count):
return ungettext_lazy(
u"Delete Network",
u"Delete Networks",
count
)
@staticmethod
def action_past(count):
return ungettext_lazy(
u"Deleted Network",
u"Deleted Networks",
count
)
policy_rules = (("network", "delete_network"),)
def delete(self, request, network_id):
network_name = network_id
try:
# Retrieve the network list.
network = api.neutron.network_get(request, network_id,
expand_subnet=False)
network_name = network.name
LOG.debug('Network %(network_id)s has subnets: %(subnets)s',
{'network_id': network_id, 'subnets': network.subnets})
for subnet_id in network.subnets:
api.neutron.subnet_delete(request, subnet_id)
LOG.debug('Deleted subnet %s', subnet_id)
api.neutron.network_delete(request, network_id)
LOG.debug('Deleted network %s successfully', network_id)
except Exception as e:
LOG.info('Failed to delete network %(id)s: %(exc)s',
{'id': network_id, 'exc': e})
msg = _('Failed to delete network %s')
redirect = reverse("horizon:project:networks:index")
exceptions.handle(request, msg % network_name, redirect=redirect)
class CreateNetwork(tables.LinkAction):
name = "create"
verbose_name = _("Create Network")
url = "horizon:project:networks:create"
classes = ("ajax-modal",)
icon = "plus"
policy_rules = (("network", "create_network"),)
def allowed(self, request, datum=None):
usages = quotas.tenant_quota_usages(request, targets=('networks', ))
# when Settings.OPENSTACK_NEUTRON_NETWORK['enable_quotas'] = False
# usages["networks"] is empty
if usages.get('networks', {}).get('available', 1) <= 0:
if "disabled" not in self.classes:
self.classes = [c for c in self.classes] + ["disabled"]
self.verbose_name = _("Create Network (Quota exceeded)")
else:
self.verbose_name = _("Create Network")
self.classes = [c for c in self.classes if c != "disabled"]
return True
class EditNetwork(policy.PolicyTargetMixin, CheckNetworkEditable,
tables.LinkAction):
name = "update"
verbose_name = _("Edit Network")
url = "horizon:project:networks:update"
classes = ("ajax-modal",)
icon = "pencil"
policy_rules = (("network", "update_network"),)
class CreateSubnet(policy.PolicyTargetMixin, CheckNetworkEditable,
tables.LinkAction):
name = "subnet"
verbose_name = _("Create Subnet")
url = "horizon:project:networks:createsubnet"
classes = ("ajax-modal",)
icon = "plus"
policy_rules = (("network", "create_subnet"),)
# neutron has used both in their policy files, supporting both
policy_target_attrs = (("network:tenant_id", "tenant_id"),
("network:project_id", "tenant_id"),)
def allowed(self, request, datum=None):
usages = quotas.tenant_quota_usages(request, targets=('subnets', ))
# when Settings.OPENSTACK_NEUTRON_NETWORK['enable_quotas'] = False
# usages["subnets'] is empty
if usages.get('subnets', {}).get('available', 1) <= 0:
if 'disabled' not in self.classes:
self.classes = [c for c in self.classes] + ['disabled']
self.verbose_name = _('Create Subnet (Quota exceeded)')
else:
self.verbose_name = _('Create Subnet')
self.classes = [c for c in self.classes if c != 'disabled']
return True
def get_subnets(network):
template_name = 'project/networks/_network_ips.html'
context = {"subnets": network.subnets}
return template.loader.render_to_string(template_name, context)
DISPLAY_CHOICES = (
("up", pgettext_lazy("Admin state of a Network", u"UP")),
("down", pgettext_lazy("Admin state of a Network", u"DOWN")),
)
STATUS_DISPLAY_CHOICES = (
("active", pgettext_lazy("Current status of a Network", u"Active")),
("build", pgettext_lazy("Current status of a Network", u"Build")),
("down", pgettext_lazy("Current status of a Network", u"Down")),
("error", pgettext_lazy("Current status of a Network", u"Error")),
)
class ProjectNetworksFilterAction(tables.FilterAction):
name = "filter_project_networks"
filter_type = "server"
filter_choices = (('name', _("Name ="), True),
('shared', _("Shared ="), True,
_("e.g. Yes / No")),
('router:external', _("External ="), True,
_("e.g. Yes / No")),
('status', _("Status ="), True),
('admin_state_up', _("Admin State ="), True,
_("e.g. UP / DOWN")))
class NetworksTable(tables.DataTable):
name = tables.WrappingColumn("name_or_id",
verbose_name=_("Name"),
link='horizon:project:networks:detail')
subnets = tables.Column(get_subnets,
verbose_name=_("Subnets Associated"),)
shared = tables.Column("shared", verbose_name=_("Shared"),
filters=(filters.yesno, filters.capfirst))
external = tables.Column("router:external", verbose_name=_("External"),
filters=(filters.yesno, filters.capfirst))
status = tables.Column("status", verbose_name=_("Status"),
display_choices=STATUS_DISPLAY_CHOICES)
admin_state = tables.Column("admin_state",
verbose_name=_("Admin State"),
display_choices=DISPLAY_CHOICES)
def get_object_display(self, network):
return network.name_or_id
class Meta(object):
name = "networks"
verbose_name = _("Networks")
table_actions = (CreateNetwork, DeleteNetwork,
ProjectNetworksFilterAction)
row_actions = (EditNetwork, CreateSubnet, DeleteNetwork)
|
Python
| 0.000001 |
@@ -1130,400 +1130,47 @@
ass
-CheckNetworkEditable(object):%0A %22%22%22Mixin class to determine the specified network is editable.%22%22%22%0A%0A def allowed(self, request, datum=None):%0A # Only administrator is allowed to create and manage shared networks.%0A if datum and datum.shared:%0A return False%0A return True%0A%0A%0Aclass DeleteNetwork(policy.PolicyTargetMixin, CheckNetworkEditable,%0A
+DeleteNetwork(policy.PolicyTargetMixin,
tab
@@ -3620,48 +3620,8 @@
xin,
- CheckNetworkEditable,%0A
tab
@@ -3890,49 +3890,8 @@
xin,
- CheckNetworkEditable,%0A
tab
|
d90bab60bf5f5423a7fee57ece8cd44acba113c1
|
setup the environment and print the 'Hello World'
|
Base/D_00_HelloWorld.py
|
Base/D_00_HelloWorld.py
|
Python
| 0.999999 |
@@ -0,0 +1,243 @@
+__author__ = 'James.Hongnian.Zhang'%0A# This is my first Python program.%0A# This means I have setup the environment for Python.%0A# Download it from https://www.python.org and install it.%0A# Then add it to your PATH%0A# That's it.%0Aprint 'Hello World'%0A
|
|
3c618e8424e64a62168c2a2c683748d2496ef7cb
|
Add Urban Dictionary module.
|
modules/urbandictionary.py
|
modules/urbandictionary.py
|
Python
| 0 |
@@ -0,0 +1,1128 @@
+%22%22%22Looks up a term from urban dictionary%0A@package ppbot%0A%0A@syntax ud %3Cword%3E%0A%0A%22%22%22%0Aimport requests%0Aimport json%0A%0Afrom modules import *%0A%0Aclass Urbandictionary(Module):%0A%0A def __init__(self, *args, **kwargs):%0A %22%22%22Constructor%22%22%22%0A Module.__init__(self, kwargs=kwargs)%0A self.url = %22http://www.urbandictionary.com/iphone/search/define?term=%25s%22%0A%0A def _register_events(self):%0A %22%22%22Register module commands.%22%22%22%0A%0A self.add_command('ud')%0A%0A def ud(self, event):%0A %22%22%22Action to react/respond to user calls.%22%22%22%0A%0A if self.num_args %3E= 1:%0A word = '%2520'.join(event%5B'args'%5D)%0A r = requests.get(self.url %25 (word))%0A ur = json.loads(r.text)%0A%0A try:%0A definition = ur%5B'list'%5D%5B0%5D%0A message = %22%25(word)s (%25(thumbs_up)d/%25(thumbs_down)d): %25(definition)s (ex: %25(example)s)%22 %25 (definition)%0A self.msg(event%5B'target'%5D, message)%0A except KeyError:%0A self.msg(event%5B'target'%5D, 'Could find word %22%25s%22' %25 ' '.join(event%5B'args'%5D))%0A else:%0A self.syntax_message(event%5B'nick'%5D, '.ud %3Cword%3E')%0A
|
|
d8fff759f2bff24f20cdbe98370ede9e5f3b7b13
|
Add 2D helmholtz convergence test
|
convergence_tests/2D_helmholtz.py
|
convergence_tests/2D_helmholtz.py
|
Python
| 0 |
@@ -0,0 +1,1639 @@
+from __future__ import absolute_import, division%0Afrom firedrake import *%0Aimport numpy as np%0A%0A%0Adef helmholtz_mixed(x, V1, V2):%0A # Create mesh and define function space%0A mesh = UnitSquareMesh(2**x, 2**x)%0A V1 = FunctionSpace(mesh, *V1, name=%22V%22)%0A V2 = FunctionSpace(mesh, *V2, name=%22P%22)%0A W = V1 * V2%0A%0A # Define variational problem%0A lmbda = 1%0A u, p = TrialFunctions(W)%0A v, q = TestFunctions(W)%0A f = Function(V2)%0A%0A f.interpolate(Expression(%22(1+8*pi*pi)*sin(x%5B0%5D*pi*2)*sin(x%5B1%5D*pi*2)%22))%0A a = (p*q - q*div(u) + lmbda*inner(v, u) + div(v)*p) * dx%0A L = f*q*dx%0A%0A # Compute solution%0A x = Function(W)%0A%0A params = %7B'mat_type': 'matfree',%0A 'ksp_type': 'preonly',%0A 'pc_type': 'python',%0A 'pc_python_type': 'firedrake.HybridizationPC',%0A 'hybridization': %7B'ksp_type': 'preonly',%0A 'pc_type': 'lu',%0A 'hdiv_residual': %7B'ksp_type': 'cg',%0A 'ksp_rtol': 1e-14%7D,%0A 'use_reconstructor': True%7D%7D%0A solve(a == L, x, solver_parameters=params)%0A%0A # Analytical solution%0A f.interpolate(Expression(%22sin(x%5B0%5D*pi*2)*sin(x%5B1%5D*pi*2)%22))%0A u, p = x.split()%0A err = sqrt(assemble(dot(p - f, p - f) * dx))%0A return x, err%0A%0AV1 = ('RT', 1)%0AV2 = ('DG', 0)%0Ax, err = helmholtz_mixed(8, V1, V2)%0A%0Aprint err%0AFile(%22helmholtz_mixed.pvd%22).write(x.split()%5B0%5D, x.split()%5B1%5D)%0A%0Al2errs = %5B%5D%0Afor i in range(1, 9):%0A l2errs.append(helmholtz_mixed(i, V1, V2)%5B1%5D)%0A%0Al2errs = np.array(l2errs)%0Aconv = np.log2(l2errs%5B:-1%5D / l2errs%5B1:%5D)%5B-1%5D%0Aprint conv%0A
|
|
478995eb7ab80d8c2c11998d871f395cbc61cb3f
|
make data column header objects iterable
|
corehq/apps/reports/datatables.py
|
corehq/apps/reports/datatables.py
|
class DTSortType:
NUMERIC = "title-numeric"
class DTSortDirection:
ASC = "asc"
DSC = "desc"
class DataTablesColumn(object):
rowspan = 1
def __init__(self, name, span=0, sort_type=None, sort_direction=None, help_text=None, sortable=True):
self.html = name
self.css_span = span
self.sort_type = sort_type
self.sort_direction = sort_direction if sort_direction else [DTSortDirection.ASC, DTSortDirection.DSC]
self.help_text = help_text
self.sortable = sortable
@property
def render_html(self):
template = '<th%(rowspan)s%(css_class)s>%(sort_icon)s %(title)s%(help_text)s</th>'
sort_icon = '<i class="icon-hq-white icon-hq-doublechevron"></i>' if self.sortable else ''
rowspan = ' rowspan="%d"' % self.rowspan if self.rowspan > 1 else ''
css_class = ' class="span%d"' % self.css_span if self.css_span > 0 else ''
help_text = ' <i class="icon-white icon-question-sign header-tooltip" title="%s"></i>' % self.help_text \
if self.help_text else ''
return template % dict(title=self.html, sort_icon=sort_icon,
rowspan=rowspan, css_class=css_class, help_text=help_text)
@property
def render_aoColumns(self):
aoColumns = dict(asSorting=self.sort_direction)
if self.sort_type:
aoColumns["sType"] = self.sort_type
if not self.sortable:
aoColumns["bSortable"] = self.sortable
return aoColumns
class DataTablesColumnGroup(object):
css_span = 0
def __init__(self, name, *args):
self.columns = list()
self.html = name
for col in args:
if isinstance(col, DataTablesColumn):
self.add_column(col)
def add_column(self, column):
self.columns.append(column)
self.css_span += column.css_span
def remove_column(self, column):
self.columns.remove(column)
self.css_span -= column.css_span
@property
def render_html(self):
template = '<th%(css_class)s colspan="%(colspan)d"><strong>%(title)s</strong></th>'
css_class = ' class="span%d"' % self.css_span if self.css_span > 0 else ''
return template % dict(title=self.html, css_class=css_class, colspan=len(self.columns)) if self.columns else ""
@property
def render_group_html(self):
group = list()
for col in self.columns:
group.append(col.render_html)
return "\n".join(group)
@property
def render_aoColumns(self):
aoColumns = list()
for col in self.columns:
aoColumns.append(col.render_aoColumns)
return aoColumns
class DataTablesHeader(object):
has_group = False
no_sort = False
complex = True
span = 0
custom_sort = None
def __init__(self, *args):
self.header = list()
for col in args:
if isinstance(col, DataTablesColumnGroup):
self.has_group = True
if isinstance(col, DataTablesColumnGroup) or \
isinstance(col, DataTablesColumn):
self.add_column(col)
def add_column(self, column):
self.header.append(column)
self.span += column.css_span
self.check_auto_width()
def remove_column(self, column):
self.header.remove(column)
self.span -= column.css_span
self.check_auto_width()
def prepend_column(self, column):
self.header = [column] + self.header
self.span += column.css_span
self.check_auto_width()
def insert_column(self, column, index):
self.span += column.css_span
self.header = self.header[:index] + [column] + self.header[index:]
self.check_auto_width()
def check_auto_width(self):
self.auto_width = bool(0 < self.span <= 12)
@property
def as_table(self):
head = list()
groups = list()
use_groups = False
for column in self.header:
if isinstance(column, DataTablesColumnGroup):
use_groups = True
groups.extend([column.html] + [" "]*(len(column.columns)-1))
for child_columns in column.columns:
head.append(child_columns.html)
else:
head.append(column.html)
groups.append(" ")
if use_groups:
return [groups, head]
else:
return [head]
@property
def render_html(self):
head = list()
groups = list()
head.append("<tr>")
groups.append("<tr>")
for column in self.header:
if isinstance(column, DataTablesColumn):
column.rowspan = 2 if self.has_group else 1
if self.no_sort:
column.sortable = False
elif isinstance(column, DataTablesColumnGroup):
groups.append(column.render_group_html)
head.append(column.render_html)
head.append("</tr>")
groups.append("</tr>")
if len(groups) > 2:
head.extend(groups)
return "\n".join(head)
@property
def render_aoColumns(self):
aoColumns = list()
for column in self.header:
if isinstance(column, DataTablesColumnGroup):
aoColumns.extend(column.render_aoColumns)
else:
aoColumns.append(column.render_aoColumns)
return aoColumns
|
Python
| 0.000003 |
@@ -5470,14 +5470,95 @@
olumns%0A%0A
-%0A%0A
+ def __iter__(self):%0A for column in self.header:%0A yield column
%0A%0A%0A%0A
|
c98109af519241a28c40217e8378a19903d4db0b
|
fix broken logic for fluff calcs using indicator_calculator
|
corehq/fluff/calculators/xform.py
|
corehq/fluff/calculators/xform.py
|
from datetime import timedelta
from corehq.fluff.calculators.logic import ANDCalculator, ORCalculator
import fluff
def default_date(form):
return form.received_on
# operators
EQUAL = lambda input, reference: input == reference
NOT_EQUAL = lambda input, reference: input != reference
IN = lambda input, reference_list: input in reference_list
IN_MULTISELECT = lambda input, reference: reference in (input or '').split(' ')
ANY = lambda input, reference: bool(input)
def ANY_IN_MULTISELECT(input, reference):
"""
For 'this multiselect contains any one of these N items'
"""
return any([subval in (input or '').split(' ') for subval in reference])
class IntegerPropertyReference(object):
"""
Returns the integer value of the property_path passed in.
By default FilteredFormPropertyCalculator would use 1 for all results
but this will let you return the actual number to be summed.
Accepts an optional transform lambda/method that would modify the
resulting integer before returning it.
"""
def __init__(self, property_path, transform=None):
self.property_path = property_path
self.transform = transform
def __call__(self, form):
value = int(form.xpath(self.property_path) or 0)
if value and self.transform:
value = self.transform(value)
return value
class FilteredFormPropertyCalculator(fluff.Calculator):
"""
Enables filtering forms by xmlns and (optionally) property == value.
Let's you easily define indicators such as:
- all adult registration forms
- all child registration forms with foo.bar == baz
- all newborn followups with bippity != bop
By default just emits a single "total" value for anything matching the filter,
though additional fields can be added by subclassing.
These can also be chained using logic operators for fun and profit.
"""
xmlns = None
property_path = None
property_value = None
indicator_calculator = None
window = timedelta(days=1)
@fluff.date_emitter
def total(self, form):
if self.indicator_calculator:
yield default_date(form)
else:
yield [default_date(form), self.indicator_calculator(form)]
def __init__(self, xmlns=None, property_path=None, property_value=None,
operator=EQUAL, indicator_calculator=None, window=None):
def _conditional_setattr(key, value):
if value:
setattr(self, key, value)
_conditional_setattr('xmlns', xmlns)
assert self.xmlns is not None
_conditional_setattr('property_path', property_path)
_conditional_setattr('property_value', property_value)
if self.property_path is not None and operator != ANY:
assert self.property_value is not None
self.operator = operator
_conditional_setattr('indicator_calculator', indicator_calculator)
super(FilteredFormPropertyCalculator, self).__init__(window)
def filter(self, form):
# filter
return (
form.xmlns == self.xmlns and (
self.property_path is None or
self.operator(form.xpath(self.property_path), self.property_value)
)
)
# meh this is a little redundant but convenient
class FormANDCalculator(ANDCalculator):
window = timedelta(days=1)
@fluff.date_emitter
def total(self, form):
yield default_date(form)
class FormORCalculator(ORCalculator):
window = timedelta(days=1)
@fluff.date_emitter
def total(self, form):
yield default_date(form)
class FormSUMCalculator(ORCalculator):
window = timedelta(days=1)
@fluff.date_emitter
def total(self, form):
for calc in self.calculators:
if calc.passes_filter(form):
for total in calc.total(form):
yield total
|
Python
| 0.000001 |
@@ -2097,24 +2097,28 @@
%0A if
+not
self.indicat
|
5206a15d59bc8881629c48bb4136bb1a9cb7b4d0
|
Create ms_old_identifiers.py
|
identifiers/ms_old_identifiers.py
|
identifiers/ms_old_identifiers.py
|
Python
| 0.000111 |
@@ -0,0 +1,743 @@
+from identifier import *%0Aimport collections %0A %0ACFBInfo = collections.namedtuple('CFBInfo', %5B'name', 'descripion', 'pattern'%5D) %0A%0AOFFICE_PATTERNS = %5B%0A 'D0 CF 11 E0 A1 B1 1A E1'%0A%5D%0A%0AFILE_PATTERNS = %5B%0A CFBInfo('DOC', 'Microsoft Word 97-2003', bytes.fromhex('EC A5 C1 20')),%0A CFBInfo('XLS', 'Microsoft Excel 97-2003', bytes.fromhex('09 08 10 20 20 06 05 20 A6 45 CD 07')),%0A%5D%0A%0Aclass CfbResolver:%0A def identify(self, stream):%0A data = stream.read(128)%0A for filepat in FILE_PATTERNS:%0A index = data.find(filepat.pattern)%0A if index != -1:%0A return Result(filepat.name, filepat.description)%0A return Result('CFB') %0A%0Adef load(hound):%0A hound.add_matches(OFFICE_PATTERNS, CfbResolver())%0A%0A
|
|
835a7b9bea1b006b5a096665d706b64b778d45ab
|
fix default param
|
python/federatedml/ensemble/test/hack_encrypter.py
|
python/federatedml/ensemble/test/hack_encrypter.py
|
Python
| 0.000002 |
@@ -0,0 +1,118 @@
+class HackDecrypter():%0A%0A def encrypt(self, val):%0A return val%0A%0A def decrypt(self, val):%0A return val
|
|
aeb671484bc8e68a8aba3eaa80523ae153b8e9c9
|
Add files via upload
|
youtube_list.py
|
youtube_list.py
|
Python
| 0 |
@@ -0,0 +1,1367 @@
+from apiclient.discovery import build%0Afrom apiclient.errors import HttpError%0Afrom oauth2client.tools import argparser%0Aimport pafy%0A%0ADEVELOPER_KEY = %22AIzaSyCsrKjMf7_mHYrT6rIJ-oaA6KL5IYg389A%22%0AYOUTUBE_API_SERVICE_NAME = %22youtube%22%0AYOUTUBE_API_VERSION = %22v3%22%0A%0A%0Adef youtube_search(options):%0A youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,%0A developerKey=DEVELOPER_KEY)%0A%0A # Call the search.list method to retrieve results matching the specified%0A # query term.%0A search_response = youtube.search().list(%0A q=%22Never Give%22,%0A part=%22id,snippet%22%0A ).execute()%0A%0A videos = %5B%5D%0A channels = %5B%5D%0A playlists = %5B%5D%0A%0A # Add each result to the appropriate list, and then display the lists of%0A # matching videos, channels, and playlists.%0A for search_result in search_response.get(%22items%22, %5B%5D):%0A if search_result%5B%22id%22%5D%5B%22kind%22%5D == %22youtube#video%22:%0A videos.append(%22%25s%22 %25 (search_result%5B%22id%22%5D%5B%22videoId%22%5D))%0A %0A print videos%5B0%5D,%22/n%22%0A%0A #Papy audio stream URL%0A%0A audio = pafy.new(videos%5B0%5D)%0A print audio.audiostreams%5B0%5D.url%0A%0A%0Aif __name__ == %22__main__%22:%0A argparser.add_argument(%22--q%22, help=%22Search term%22, default=%22Google%22)%0A argparser.add_argument(%22--max-results%22, help=%22Max results%22, default=25)%0A args = argparser.parse_args()%0A%0A try:%0A youtube_search(args)%0A except HttpError, e:%0A print %22An HTTP error %25d occurred:%5Cn%25s%22 %25 (e.resp.status, e.content)%0A
|
|
0770fab7c4985704e2793ab98150c9f1a2729e01
|
Create easy_17_ArrayAdditionI.py
|
easy_17_ArrayAdditionI.py
|
easy_17_ArrayAdditionI.py
|
Python
| 0.000034 |
@@ -0,0 +1,659 @@
+import itertools%0A%0A#################################################%0A# This function will see if there is any #%0A# possible combination of the numbers in #%0A# the array that will give the largest number #%0A#################################################%0Adef ArrayAdditionI(arr):%0A %0A #sort, remove last element%0A result = %22false%22%0A arr.sort()%0A large = arr%5B-1%5D%0A arr = arr%5B:-1%5D%0A %0A #go through every combination and see if sum = large%0A for x in range(2,len(arr) + 1):%0A for comb in itertools.combinations(arr,x):%0A if large == sum(comb):%0A result = %22true%22%0A break%0A return result%0A %0Aprint ArrayAdditionI(raw_input()) %0A
|
|
1cc15f3ae9a0b7fa5b2dae4bcdd9f0f3c061ce4d
|
Fix relate_name on Bug model
|
reclama/sprints/migrations/0002_auto_20150130_1751.py
|
reclama/sprints/migrations/0002_auto_20150130_1751.py
|
Python
| 0 |
@@ -0,0 +1,454 @@
+# -*- coding: utf-8 -*-%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import models, migrations%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('sprints', '0001_initial'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterField(%0A model_name='bug',%0A name='event',%0A field=models.ManyToManyField(related_name='bugs', to='sprints.Event'),%0A preserve_default=True,%0A ),%0A %5D%0A
|
|
de65724abf0a01660e413189d1738a72d5afd297
|
add simple test for create_wininst.
|
bento/commands/tests/test_wininst.py
|
bento/commands/tests/test_wininst.py
|
Python
| 0 |
@@ -0,0 +1,1539 @@
+import os%0Aimport shutil%0Aimport tempfile%0Aimport zipfile%0A%0Aimport os.path as op%0A%0Aimport mock%0A%0Aimport bento.commands.build_wininst%0A%0Afrom bento.commands.build_wininst %5C%0A import %5C%0A create_wininst%0Afrom bento.compat.api.moves %5C%0A import %5C%0A unittest%0Afrom bento.core.node %5C%0A import %5C%0A create_base_nodes%0Afrom bento.installed_package_description %5C%0A import %5C%0A InstalledPkgDescription%0A%0Aclass TestWininstInfo(unittest.TestCase):%0A def setUp(self):%0A self.old_dir = None%0A self.tmpdir = None%0A%0A self.old_dir = os.getcwd()%0A self.tmpdir = tempfile.mkdtemp()%0A%0A try:%0A self.top_node, self.build_node, self.run_node = %5C%0A create_base_nodes(self.tmpdir, op.join(self.tmpdir, %22build%22))%0A os.chdir(self.tmpdir)%0A except:%0A shutil.rmtree(self.tmpdir)%0A raise%0A%0A def tearDown(self):%0A os.chdir(self.old_dir)%0A shutil.rmtree(self.tmpdir)%0A%0A @mock.patch(%22bento.commands.build_wininst.create_exe%22, mock.MagicMock())%0A def test_simple(self):%0A %22%22%22This just tests whether create_wininst runs at all and produces a zip-file.%22%22%22%0A ipackage = InstalledPkgDescription(%7B%7D, %7B%22name%22: %22foo%22, %22version%22: %221.0%22%7D, %7B%7D)%0A create_wininst(ipackage, self.build_node, self.build_node, wininst=%22foo.exe%22, output_dir=%22dist%22)%0A arcname = bento.commands.build_wininst.create_exe.call_args%5B0%5D%5B1%5D%0A fp = zipfile.ZipFile(arcname)%0A try:%0A fp.namelist()%0A finally:%0A fp.close()%0A
|
|
edfd6ddf8e7af41a8b5ed228360b92377bfc8964
|
add 167. First 200 problems have been finished!
|
vol4/167.py
|
vol4/167.py
|
Python
| 0 |
@@ -0,0 +1,1081 @@
+import time%0A%0Adef ulam(a, b):%0A%09yield a%0A%09yield b%0A%09u = %5Ba, b%5D%0A%09even_element = 0%0A%09while even_element == 0 or u%5B-1%5D %3C 2 * even_element:%0A%09%09sums = %7B%7D%0A%09%09for i in range(len(u)):%0A%09%09%09for j in range(i + 1, len(u)):%0A%09%09%09%09sums%5Bu%5Bi%5D + u%5Bj%5D%5D = sums.get(u%5Bi%5D + u%5Bj%5D, 0) + 1%0A%09%09u.append(min(k for k, v in sums.iteritems() if v == 1 and k %3E u%5B-1%5D))%0A%09%09yield u%5B-1%5D%0A%09%09if u%5B-1%5D %25 2 == 0:%0A%09%09%09even_element = u%5B-1%5D%0A%09index = 0%0A%09while even_element + u%5Bindex%5D %3C= u%5B-1%5D:%0A%09%09index += 1%0A%09while True:%0A%09%09if even_element + u%5Bindex%5D %3E u%5B-1%5D + 2:%0A%09%09%09u.append(u%5B-1%5D + 2)%0A%09%09else:%0A%09%09%09u.append(even_element + u%5Bindex + 1%5D)%0A%09%09%09index = index + 2%0A%09%09yield u%5B-1%5D%0A%0Aif __name__ == %22__main__%22:%0A%09N = 10 ** 11%0A%09ans = 0%0A%09periods = %5B32, 26, 444, 1628, 5906, 80, 126960, 380882, 2097152%5D%0A%09diffs = %5B126, 126, 1778, 6510, 23622, 510, 507842, 1523526, 8388606%5D%0A%09for n in range(2, 11):%0A%09%09u = ulam(2, 2 * n + 1)%0A%09%09index = 0%0A%09%09even = False%0A%09%09while not even or (N - index) %25 periods%5Bn - 2%5D != 0:%0A%09%09%09num = u.next()%0A%09%09%09if num %25 2 == 0 and num %3E 2:%0A%09%09%09%09even = True%0A%09%09%09index += 1%0A%09%09ans += num + (N - index) / periods%5Bn - 2%5D * diffs%5Bn - 2%5D%0A%09print ans
|
|
a7db805db727fbe1c6e9f37152e6c3c2f94d406d
|
add require internet
|
i3pystatus/external_ip.py
|
i3pystatus/external_ip.py
|
from i3pystatus import IntervalModule, formatp
import GeoIP
import urllib.request
class ExternalIP(IntervalModule):
"""
Shows the external IP with the country code/name.
Requires the PyPI package `GeoIP`.
.. rubric:: Available formatters
* {country_name} the full name of the country from the IP (eg. 'United States')
* {country_code} the country code of the country from the IP (eg. 'US')
* {ip} the ip
"""
settings = (
"format",
"color",
("color_down", "color when the http request failed"),
("color_hide", "color when the user has decide to switch to the hide format"),
("format_down", "format when the http request failed"),
("format_hide", "format when the user has decide to switch to the hide format"),
("ip_website", "http website where the IP is directly available as raw"),
("timeout", "timeout in seconds when the http request is taking too much time"),
)
interval = 15
format = "{country_name} {country_code} {ip}"
format_hide = "{country_code}"
format_down = "Timeout"
ip_website = "https://api.ipify.org"
timeout = 5
color = "#FFFFFF"
color_hide = "#FFFF00"
color_down = "#FF0000"
on_leftclick = "switch_hide"
on_rightclick = "run"
def run(self):
try:
request = urllib.request.urlopen(self.ip_website,
timeout=self.timeout)
ip = request.read().decode().strip()
except Exception:
return self.disable()
gi = GeoIP.GeoIP(GeoIP.GEOIP_STANDARD)
country_code = gi.country_code_by_addr(ip)
country_name = gi.country_name_by_addr(ip)
if not ip or not country_code:
return self.disable() # fail here in the case of a bad IP
fdict = {
"country_name": country_name,
"country_code": country_code,
"ip": ip
}
self.output = {
"full_text": formatp(self.format, **fdict).strip(),
"color": self.color
}
def disable(self):
self.output = {
"full_text": self.format_down,
"color": self.color_down
}
def switch_hide(self):
self.format, self.format_hide = self.format_hide, self.format
self.color, self.color_hide = self.color_hide, self.color
self.run()
|
Python
| 0.000013 |
@@ -39,16 +39,67 @@
formatp
+%0Afrom i3pystatus.core.util import internet, require
%0A%0Aimport
@@ -489,16 +489,34 @@
%0A %22%22%22
+%0A interval = 15
%0A%0A se
@@ -1041,34 +1041,16 @@
%0A )%0A%0A
- interval = 15%0A
form
@@ -1357,15 +1357,50 @@
-def run
+@require(internet)%0A def get_external_ip
(sel
@@ -1561,12 +1561,14 @@
-ip =
+return
req
@@ -1622,16 +1622,115 @@
eption:%0A
+ return None%0A%0A def run(self):%0A ip = self.get_external_ip()%0A if not ip:%0A
@@ -1925,18 +1925,8 @@
not
-ip or not
coun
|
e4d222c4e1b05f8d34b2236d05269827c345b0c7
|
Handle also running rebot
|
src/robot/jarrunner.py
|
src/robot/jarrunner.py
|
# Copyright 2008-2010 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from org.robotframework import RobotRunner
from robot import runner, run_from_cli
class JarRunner(RobotRunner):
"""Used for Java-Jython interop when RF is executed from .jar file"""
def run(self, args):
try:
run_from_cli(args, runner.__doc__)
except SystemExit, err:
return err.code
|
Python
| 0 |
@@ -680,16 +680,39 @@
from_cli
+, rebot, rebot_from_cli
%0A%0A%0Aclass
@@ -848,13 +848,207 @@
-try:%0A
+print rebot, rebot.__file__%0A try:%0A if args and args%5B0%5D == 'rebot':%0A print rebot.__doc__%0A rebot_from_cli(args%5B1:%5D, rebot.__doc__)%0A else:%0A
|
76399574b7fb914d1baa2719a0e493d4b22bb730
|
Create PedidoEditar.py
|
backend/Models/Grau/PedidoEditar.py
|
backend/Models/Grau/PedidoEditar.py
|
Python
| 0 |
@@ -0,0 +1,342 @@
+from Framework.Pedido import Pedido%0Afrom Framework.ErroNoHTTP import ErroNoHTTP%0A%0Aclass PedidoEditar(Pedido):%0A%0A%09def __init__(self,variaveis_do_ambiente):%0A%09%09super(PedidoEditar, self).__init__(variaveis_do_ambiente)%0A%09%09try:%0A%09%09%09self.nome = self.corpo%5B'nome'%5D%0A%09%09%09%0A%09%09except:%0A%09%09%09raise ErroNoHTTP(400)%0A%09%09%0A%09%0A%09def getNome(self):%0A%09%09return self.nome%0A%0A%09%0A%09%0A
|
|
df146818d004e65102cc6647373b0fddb0d383fd
|
add basic integration tests
|
integration-tests/test_builder.py
|
integration-tests/test_builder.py
|
Python
| 0 |
@@ -0,0 +1,2437 @@
+import os%0Aimport subprocess%0Aimport tempfile%0A%0Afrom vdist.builder import Builder%0Afrom vdist.source import git, git_directory, directory%0A%0A%0Adef test_generate_deb_from_git():%0A builder = Builder()%0A builder.add_build(%0A app='vdist-test-generate-deb-from-git',%0A version='1.0',%0A source=git(%0A uri='https://github.com/objectified/vdist',%0A branch='master'%0A ),%0A profile='ubuntu-trusty'%0A )%0A builder.build()%0A%0A cwd = os.getcwd()%0A target_file = os.path.join(%0A cwd,%0A 'dist',%0A 'vdist-test-generate-deb-from-git-1.0-ubuntu-trusty',%0A 'vdist-test-generate-deb-from-git_1.0_amd64.deb'%0A )%0A assert os.path.isfile(target_file)%0A assert os.path.getsize(target_file) %3E 0%0A%0A%0Adef test_generate_deb_from_git_directory():%0A tempdir = tempfile.gettempdir()%0A checkout_dir = os.path.join(tempdir, 'vdist')%0A%0A git_p = subprocess.Popen(%0A %5B'git', 'clone',%0A 'https://github.com/objectified/vdist',%0A checkout_dir%5D)%0A git_p.communicate()%0A%0A builder = Builder()%0A builder.add_build(%0A app='vdist-test-generate-deb-from-git-dir',%0A version='1.0',%0A source=git_directory(%0A path=checkout_dir,%0A branch='master'%0A ),%0A profile='ubuntu-trusty'%0A )%0A builder.build()%0A%0A cwd = os.getcwd()%0A target_file = os.path.join(%0A cwd,%0A 'dist',%0A 'vdist-test-generate-deb-from-git-dir-1.0-ubuntu-trusty',%0A 'vdist-test-generate-deb-from-git-dir_1.0_amd64.deb'%0A )%0A assert os.path.isfile(target_file)%0A assert os.path.getsize(target_file) %3E 0%0A%0A%0Adef test_generate_deb_from_directory():%0A tempdir = tempfile.gettempdir()%0A checkout_dir = os.path.join(tempdir, 'vdist')%0A%0A git_p = subprocess.Popen(%0A %5B'git', 'clone',%0A 'https://github.com/objectified/vdist',%0A checkout_dir%5D)%0A git_p.communicate()%0A%0A builder = Builder()%0A builder.add_build(%0A app='vdist-test-generate-deb-from-dir',%0A version='1.0',%0A source=directory(%0A path=checkout_dir,%0A ),%0A profile='ubuntu-trusty'%0A )%0A builder.build()%0A%0A cwd = os.getcwd()%0A target_file = os.path.join(%0A cwd,%0A 'dist',%0A 'vdist-test-generate-deb-from-dir-1.0-ubuntu-trusty',%0A 'vdist-test-generate-deb-from-dir_1.0_amd64.deb'%0A )%0A assert os.path.isfile(target_file)%0A assert os.path.getsize(target_file) %3E 0%0A
|
|
dc0ecffd6c4115019cfcbcc13b17a20511888c9b
|
Add ut for fused ops
|
python/paddle/fluid/tests/unittests/test_fused_emb_seq_pool_op.py
|
python/paddle/fluid/tests/unittests/test_fused_emb_seq_pool_op.py
|
Python
| 0 |
@@ -0,0 +1,1776 @@
+# Copyright (c) 2018 PaddlePaddle Authors. 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%0A%0Aimport unittest%0Aimport numpy as np%0Afrom op_test import OpTest%0Aimport paddle.fluid.core as core%0Aimport paddle.fluid as fluid%0Afrom paddle.fluid.op import Operator%0Aimport paddle.compat as cpt%0A%0A%0Aclass TestFusedEmbeddingSeqPoolOp(OpTest):%0A def setUp(self):%0A self.op_type = %22fused_embedding_seq_pool%22%0A self.emb_size = 2%0A table = np.random.random((17, self.emb_size)).astype(%22float32%22)%0A ids = np.array(%5B%5B%5B4%5D, %5B3%5D%5D, %5B%5B4%5D, %5B3%5D%5D, %5B%5B2%5D, %5B1%5D%5D,%0A %5B%5B16%5D, %5B1%5D%5D%5D).astype(%22int64%22)%0A merged_ids = np.array(%5B4, 2, 16%5D).astype(%22int64%22)%0A ids_expand = np.expand_dims(ids, axis=1)%0A self.lod = %5B%5B3, 1%5D%5D%0A self.attrs = %7B'is_sparse': True%7D%0A self.inputs = %7B'W': table, 'Ids': (ids_expand, self.lod)%7D%0A self.outputs = %7B%0A 'Out': np.reshape(%0A np.array(%5B%0A table%5B%5B4, 3%5D%5D + table%5B%5B4, 3%5D%5D + table%5B%5B2, 1%5D%5D,%0A table%5B%5B16, 1%5D%5D%0A %5D), %5Blen(self.lod%5B0%5D), 2 * self.emb_size%5D)%0A %7D%0A%0A def test_check_output(self):%0A self.check_output()%0A%0A%0Aif __name__ == %22__main__%22:%0A unittest.main()%0A
|
|
a852de81afdf8426cb243115a87856e2767a8d40
|
Add construct test for known bad inplace string operations.
|
tests/benchmarks/constructs/InplaceOperationStringAdd.py
|
tests/benchmarks/constructs/InplaceOperationStringAdd.py
|
Python
| 0.000001 |
@@ -0,0 +1,1341 @@
+# Copyright 2015, Kay Hayen, mailto:[email protected]%0A#%0A# Python test originally created or extracted from other peoples work. The%0A# parts from me are licensed as below. It is at least Free Softwar where%0A# it's copied from other people. In these cases, that will normally be%0A# indicated.%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%0Amodule_value1 = 5%0Amodule_value2 = 3%0A%0Adef calledRepeatedly():%0A # Force frame and eliminate forward propagation (currently).%0A module_value1%0A%0A # Make sure we have a local variable x anyway%0A s = %222%22%0A%0A additiv = %22*%22 * 1000%0A%0A local_value = module_value1%0A%0A for x in range(local_value, local_value+15):%0A# construct_begin%0A s += additiv%0A# construct_end%0A pass%0A%0Afor x in xrange(50000):%0A calledRepeatedly()%0A%0Aprint(%22OK.%22)%0A
|
|
28df83848a04e45059f4c672fde53f4f84dbd28d
|
Add module module_pubivisat.py
|
module_pubivisat.py
|
module_pubivisat.py
|
Python
| 0.000003 |
@@ -0,0 +1,622 @@
+#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0Aimport urllib2%0Afrom bs4 import BeautifulSoup%0A%0Adef command_pubivisat(bot, user, channel, args):%0A%09%22%22%22Fetches todays pub quizzes for Tampere from pubivisat.fi%22%22%22%0A%09url = %22http://pubivisat.fi/tampere%22%0A%0A%09f = urllib2.urlopen(url)%0A%09d = f.read()%0A%09f.close()%0A%0A%09bs = BeautifulSoup(d)%0A%09data = bs.find('table', %7B'class': 'quiz_list'%7D).find('tbody').findAll('tr')%0A%0A%09quizzes = %5B%5D%0A%09for row in data:%0A%09%09name = row.find('a').string%0A%09%09time = row.findAll('td')%5B1%5D.string%0A%0A%09%09quizzes.append(%22%25s: %25s%22 %25 (str(name), str(time)))%0A%0A%09output = ' %7C '.join(reversed(quizzes))%0A%09return(bot.say(channel, output))
|
|
e5736370568adab1334f653c44dd060c06093fae
|
add basic twisted soap server.
|
src/rpclib/test/interop/server/soap_http_basic_twisted.py
|
src/rpclib/test/interop/server/soap_http_basic_twisted.py
|
Python
| 0 |
@@ -0,0 +1,1684 @@
+#!/usr/bin/env python%0A#%0A# rpclib - Copyright (C) Rpclib contributors.%0A#%0A# This library is free software; you can redistribute it and/or%0A# modify it under the terms of the GNU Lesser General Public%0A# License as published by the Free Software Foundation; either%0A# version 2.1 of the License, or (at your option) any later version.%0A#%0A# This library 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 GNU%0A# Lesser General Public License for more details.%0A#%0A# You should have received a copy of the GNU Lesser General Public%0A# License along with this library; if not, write to the Free Software%0A# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301%0A#%0A%0Aimport logging%0Alogging.basicConfig(level=logging.DEBUG)%0Alogger = logging.getLogger('rpclib.wsgi')%0Alogger.setLevel(logging.DEBUG)%0A%0Aimport os%0A%0Afrom rpclib.test.interop.server.soap_http_basic import soap_application%0Afrom rpclib.server.twisted_ import TwistedWebApplication%0A%0Ahost = '127.0.0.1'%0Aport = 9753%0A%0Adef main(argv):%0A from twisted.python import log%0A from twisted.web.server import Site%0A from twisted.web.static import File%0A from twisted.internet import reactor%0A from twisted.python import log%0A%0A observer = log.PythonLoggingObserver('twisted')%0A log.startLoggingWithObserver(observer.emit, setStdout=False)%0A%0A wr = TwistedWebApplication(soap_application)%0A site = Site(wr)%0A%0A reactor.listenTCP(port, site)%0A logging.info(%22listening on: %25s:%25d%22 %25 (host,port))%0A%0A return reactor.run()%0A%0A%0Aif __name__ == '__main__':%0A import sys%0A sys.exit(main(sys.argv))%0A
|
|
e83edea432f16ed6a2c9edcaa6da70c928d75eb5
|
Create module containing constants
|
export_layers/pygimplib/constants.py
|
export_layers/pygimplib/constants.py
|
Python
| 0 |
@@ -0,0 +1,1132 @@
+#%0A# This file is part of pygimplib.%0A#%0A# Copyright (C) 2014, 2015 khalim19 %[email protected]%3E%0A#%0A# pygimplib is free software: you can redistribute it and/or modify%0A# it under the terms of the GNU 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# pygimplib 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 General Public License for more details.%0A#%0A# You should have received a copy of the GNU General Public License%0A# along with pygimplib. If not, see %3Chttp://www.gnu.org/licenses/%3E.%0A#%0A%0A%22%22%22%0AThis module contains constants used in other modules.%0A%22%22%22%0A%0Afrom __future__ import absolute_import%0Afrom __future__ import division%0Afrom __future__ import print_function%0Afrom __future__ import unicode_literals%0A%0Astr = unicode%0A%0A#===============================================================================%0A%0A_LOG_OUTPUT_MODES = (LOG_EXCEPTIONS_ONLY, LOG_OUTPUT_FILES, LOG_OUTPUT_GIMP_CONSOLE) = (0, 1, 2)%0A
|
|
78fe96841a72731f76e52a0cf7acc6375b008942
|
handle 'certificate-authority-data' when talking to eg. GKE
|
kubernetes/K8sConfig.py
|
kubernetes/K8sConfig.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is subject to the terms and conditions defined in
# file 'LICENSE.md', which is part of this source code package.
#
import re
from os.path import expanduser, isfile
import yaml
from yaml import YAMLError
DEFAULT_KUBECONFIG = "{0}/.kube/config".format(expanduser("~"))
DEFAULT_API_HOST = "localhost:8888"
DEFAULT_API_VERSION = "v1"
DEFAULT_NAMESPACE = "default"
VALID_API_VERSIONS = ["v1"]
VALID_IP_RE = re.compile(r'^(http[s]?\:\/\/)?((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3})(:[0-9]+)?$')
VALID_HOST_RE = re.compile(r'^(http[s]?\:\/\/)?([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9]\.)*([A-Za-z]|[A-Za-z][A-Za-z\-]*[A-Za-z])(:[0-9]+)?$')
class K8sConfig(object):
def __init__(self, kubeconfig=DEFAULT_KUBECONFIG, api_host=DEFAULT_API_HOST, auth=None, cert=None,
namespace=DEFAULT_NAMESPACE, pull_secret=None, token=None, version=DEFAULT_API_VERSION):
"""
Pulls configuration from a kubeconfig file, if present, otherwise accepts user-defined parameters.s
See http://kubernetes.io/docs/user-guide/kubeconfig-file/ for information on the kubeconfig file.
:param kubeconfig: Absolute path to the kubeconfig file, if any.
:param api_host: Absolute URI where the API server resides.
:param auth: A tuple of (username, password) for basic authentication.
:param namespace: The namespace to use. Defaults to 'default'
:param pull_secret: The password to use when pulling images from the container repository.
:param token: An authentication token. Mutually exclusive with 'auth'.
:param version: The version of the API to target. Defaults to 'v1'.
"""
dotconf = None
if kubeconfig is not None:
if not isfile(kubeconfig):
raise IOError('K8sConfig: kubeconfig: [ {0} ] doesn\'t exist.'.format(kubeconfig))
try:
with open(kubeconfig, 'r') as stream:
dotconf = yaml.load(stream)
except YAMLError as err:
raise SyntaxError('K8sConfig: kubeconfig: [ {0} ] is not a valid YAML file.'.format(kubeconfig))
if dotconf is not None:
# we're pulling configuration from a kubeconfig file
self.api_host = None
self.ca_cert = None
self.auth = None
self.token = None
self.client_certificate = None
self.client_key = None
self.cert = None
self.clusters = dotconf['clusters']
self.contexts = dotconf['contexts']
self.current_context = dotconf['current-context']
self.preferences = dotconf['preferences']
self.pull_secret = pull_secret
self.users = dotconf['users']
self.version = dotconf['apiVersion']
for cluster in self.clusters:
if cluster['name'] == self.current_context:
self.api_host = cluster['cluster']['server']
self.ca_cert = cluster['cluster']['certificate-authority']
for user in self.users:
if user['name'] == self.current_context:
if 'username' in user['user'] and 'password' in user['user']:
self.auth = (user['user']['username'], user['user']['password'])
if 'token' in user['user']:
self.token = user['user']['token']
if 'client-certificate' in user['user'] and 'client-key' in user['user']:
self.client_certificate = user['user']['client-certificate']
self.client_key = user['user']['client-key']
self.cert = (self.client_certificate, self.client_key)
for context in self.contexts:
if context['name'] == self.current_context:
if 'namespace' in context['context']:
self.namespace = context['context']['namespace']
else:
self.namespace = namespace
if dotconf is None:
# we're using user-supplied config; run some sanity checks.
if not isinstance(api_host, str) or not isinstance(version, str):
raise SyntaxError('K8sConfig: host: [ {0} ] and version: [ {1} ] must be strings.'.format(api_host, version))
if not (VALID_IP_RE.match(api_host) or VALID_HOST_RE.match(api_host)):
raise SyntaxError('K8sConfig: host: [ {0} ] is invalid.'.format(api_host))
if auth is not None and not isinstance(auth, tuple):
raise SyntaxError('K8sConfig: auth: [ {0} ] must be a tuple for basic authentication.'.format(auth))
if not isinstance(namespace, str):
raise SyntaxError('K8sConfig: namespace: [ {0} ] must be a string.'.format(namespace))
if pull_secret is not None and not isinstance(pull_secret, str):
raise SyntaxError('K8sConfig: pull_secret: [ {0} ] must be a string.'.format(pull_secret))
if token is not None and not isinstance(token, str):
raise SyntaxError('K8sConfig: token: [ {0} ] must be a string.'.format(token))
if version not in VALID_API_VERSIONS:
valid = ", ".join(VALID_API_VERSIONS)
raise SyntaxError('K8sConfig: api_version: [ {0} ] must be in: [ {1} ]'.format(version, valid))
schema_re = re.compile(r"^http[s]*")
if not schema_re.search(api_host):
api_host = "http://{0}".format(api_host)
self.api_host = api_host
self.auth = auth
self.cert = cert
self.namespace = namespace
self.pull_secret = pull_secret
self.token = token
self.version = version
|
Python
| 0.000004 |
@@ -2384,32 +2384,69 @@
.ca_cert = None%0A
+ self.ca_cert_data = None%0A
self
@@ -3037,32 +3037,91 @@
urrent_context:%0A
+ if 'server' in cluster%5B'cluster'%5D:%0A
@@ -3193,64 +3193,306 @@
-self.ca_cert = cluster%5B'cluster'%5D%5B'certificate-authority
+if 'certificate-authority' in cluster%5B'cluster'%5D:%0A self.ca_cert = cluster%5B'cluster'%5D%5B'certificate-authority'%5D%0A if 'certificate-authority-data' in cluster%5B'cluster'%5D:%0A self.ca_cert_data = cluster%5B'cluster'%5D%5B'certificate-authority-data
'%5D%0A%0A
|
0421adb2eb391c57d02dfa0b1b14e3c620c53dfc
|
Create tarea7.py
|
tareas/tarea7.py
|
tareas/tarea7.py
|
Python
| 0.000001 |
@@ -0,0 +1,3209 @@
+#josue de leon%0A# Tarea 7%0A#8-876-2357%0A'''1.Crear una aplicacion en Kivy que maneje un registro de asistencia. Basicamente la aplicacion debe contener una %0A etiqueta que diga %22Nombre: %22, un campo para ingresar cadenas de texto, un boton que diga %22Guardar%22 y otro botin %0A que diga %22Exportar%22. El botn para guardar agrega el contenido del campo a una lista de asistencia. El boton para %0Aexportar salva la lista de asistencia a un fichero con extension TXT'''%0A%0A%0Aimport listasutils as lu%0Afrom kivy.app import App %0Afrom kivy.config import Config%0Afrom kivy.uix.boxlayout import BoxLayout%0Afrom kivy.uix.label import Label%0Afrom kivy.uix.floatlayout import FloatLayout%0Afrom kivy.properties import ObjectProperty%0A%0A%0A%0AConfig.set('graphics', 'resizable', '0')%0AConfig.set('graphics', 'width', '640')%0AConfig.set('graphics', 'height', '480')%0A%0Aclass Fondo(FloatLayout):%0A lista = %5B%5D%0A listgrid = ObjectProperty(None)%0A textbox = ObjectProperty(None)%0A%0A def OnGuardarClick(self,texto):%0A%0A if texto != %22%22:%0A grid = self.listgrid%0A grid.bind(minimum_height=grid.setter('height'), minimum_width=grid.setter('width'))%0A%0A self.textbox.text = ''%0A self.lista.append(texto)%0A%0A RowNombre = Label(text='%7B0%7D'.format(texto))%0A grid.add_widget(RowNombre)%0A%0A def OnExportarClick(self):%0A lu.salvarLista(%22Tarea7.txt%22,self.lista)%0A%0Aclass AsistenciaApp(App):%0A def build(self):%0A return Fondo()%0A%0Aif __name__ == '__main__': %0A AsistenciaApp().run() %0A%0A%0A%0A%0A%0A%3CFondo%3E:%0A scroll_view: scrollviewID%0A listgrid: gridlayoutID%0A textbox: textboxID%0A BoxLayout:%0A orientation: 'vertical'%0A size_hint: 1,0.1%0A pos_hint: %7B'top':1%7D%0A BoxLayout:%0A orientation: 'horizontal'%0A Label:%0A text: 'Nombre'%0A TextInput:%0A id: textboxID%0A multiline: False%0A BoxLayout:%0A orientation: 'vertical'%0A size_hint: 1,0.8%0A pos_hint: %7B'top':0.9%7D%0A canvas:%0A Color:%0A rgba: (0.2, 0.2, 0.2, 1)%0A Rectangle:%0A pos: self.pos%0A size: self.size%0A ScrollView:%0A id: scrollviewID%0A orientation: 'vertical'%0A pos_hint: %7B'x': 0, 'y': 0%7D%0A bar_width: '20dp'%0A GridLayout:%0A id: gridlayoutID%0A cols: 1%0A size_hint: 1, None%0A row_default_height: 40%0A row_force_default: False%0A BoxLayout:%0A canvas:%0A Color:%0A rgba: (0.4, 0.4, 0.4, 1)%0A Rectangle:%0A pos: self.pos%0A size: self.size%0A Label:%0A text: 'Nombre'%0A BoxLayout:%0A orientation: 'vertical'%0A size_hint: 1,0.1%0A pos_hint: %7B'top':0.1%7D%0A BoxLayout:%0A orientation: 'horizontal'%0A Button:%0A text: 'Guardar'%0A on_release: root.OnGuardarClick(textboxID.text)%0A Button:%0A text: 'Exportar'%0A on_release: root.OnExportarClick()%0A
|
|
b260040bc3ca48b4e76d73c6efe60b964fa5c108
|
Add test of removing unreachable terminals
|
tests/UnreachableSymbolsRemove/RemovingTerminalsTest.py
|
tests/UnreachableSymbolsRemove/RemovingTerminalsTest.py
|
Python
| 0.000001 |
@@ -0,0 +1,2167 @@
+#!/usr/bin/env python%0A%22%22%22%0A:Author Patrik Valkovic%0A:Created 17.08.2017 14:23%0A:Licence GNUv3%0APart of grammpy-transforms%0A%0A%22%22%22%0A%0A%0Afrom unittest import main, TestCase%0Afrom grammpy import *%0Afrom grammpy_transforms import *%0A%0A%0Aclass A(Nonterminal): pass%0Aclass B(Nonterminal): pass%0Aclass C(Nonterminal): pass%0Aclass D(Nonterminal): pass%0Aclass E(Nonterminal): pass%0Aclass F(Nonterminal): pass%0Aclass RuleAto0B(Rule): rule = (%5BA%5D, %5B0, B%5D)%0Aclass RuleBto1C(Rule): rule = (%5BB%5D, %5B1, C%5D)%0Aclass RuleCto2C(Rule): rule = (%5BC%5D, %5B2, C%5D)%0A%0A%0A%0A%0Aclass RemovingTerminalsTest(TestCase):%0A def test_removingTerminals(self):%0A g = Grammar(terminals=%5B0, 1, 2, 3%5D,%0A nonterminals=%5BA, B, C, D, E, F%5D,%0A rules=%5BRuleAto0B, RuleBto1C, RuleCto2C%5D,%0A start_symbol=A)%0A com = ContextFree.remove_unreachable_symbols(g)%0A self.assertTrue(com.have_term(%5B0, 1, 2%5D))%0A self.assertFalse(com.have_term(3))%0A self.assertTrue(com.have_nonterm(%5BA, B, C%5D))%0A self.assertFalse(com.have_nonterm(D))%0A self.assertFalse(com.have_nonterm(E))%0A self.assertFalse(com.have_nonterm(F))%0A%0A def test_removingTerminalsShouldNotChange(self):%0A g = Grammar(terminals=%5B0, 1, 2, 3%5D,%0A nonterminals=%5BA, B, C, D, E, F%5D,%0A rules=%5BRuleAto0B, RuleBto1C, RuleCto2C%5D,%0A start_symbol=A)%0A ContextFree.remove_unreachable_symbols(g)%0A self.assertTrue(g.have_term(%5B0, 1, 2, 3%5D))%0A self.assertTrue(g.have_nonterm(%5BA, B, C, D, E, F%5D))%0A%0A def test_removingTerminalsShouldChange(self):%0A g = Grammar(terminals=%5B0, 1, 2, 3%5D,%0A nonterminals=%5BA, B, C, D, E, F%5D,%0A rules=%5BRuleAto0B, RuleBto1C, RuleCto2C%5D,%0A start_symbol=A)%0A ContextFree.remove_unreachable_symbols(g, transform_grammar=True)%0A self.assertTrue(g.have_term(%5B0, 1, 2%5D))%0A self.assertFalse(g.have_term(3))%0A self.assertTrue(g.have_nonterm(%5BA, B, C%5D))%0A self.assertFalse(g.have_nonterm(D))%0A self.assertFalse(g.have_nonterm(E))%0A self.assertFalse(g.have_nonterm(F))%0A%0A%0Aif __name__ == '__main__':%0A main()%0A
|
|
c82473efdeb7b1713f44370de761ec9022d02b5e
|
Add management command to fill and clear cache
|
akvo/rsr/management/commands/populate_project_directory_cache.py
|
akvo/rsr/management/commands/populate_project_directory_cache.py
|
Python
| 0 |
@@ -0,0 +1,1218 @@
+#!/usr/bin/env python3%0A# -*- coding: utf-8 -*-%0A%0A# Akvo Reporting is covered by the GNU Affero General Public License.%0A# See more details in the license.txt file located at the root folder of the Akvo RSR module.%0A# For additional details on the GNU license please see %3C http://www.gnu.org/licenses/agpl.html %3E.%0A%0A%22%22%22Populate the project directory cache for all the projects.%0A%0AUsage:%0A%0A python manage.py populate_project_directory_cache%0A%0A%22%22%22%0A%0Afrom django.core.management.base import BaseCommand%0A%0Afrom akvo.rest.views.project import serialized_project%0Afrom akvo.rest.cache import delete_project_from_project_directory_cache%0Afrom akvo.rsr.models import Project%0A%0A%0Aclass Command(BaseCommand):%0A help = __doc__%0A%0A def add_arguments(self, parser):%0A parser.add_argument('action', choices=%5B'clear', 'fill'%5D, help='Action to perform')%0A%0A def handle(self, *args, **options):%0A projects = Project.objects.public().published().values_list('pk', flat=True)%0A%0A if options%5B'action'%5D == 'clear':%0A for project_id in projects:%0A delete_project_from_project_directory_cache(project_id)%0A%0A else:%0A for project_id in projects:%0A serialized_project(project_id)%0A
|
|
4e6f2ede0a8a9291befe262cbec77d3e7cd873b0
|
add new package (#26514)
|
var/spack/repos/builtin/packages/py-rsatoolbox/package.py
|
var/spack/repos/builtin/packages/py-rsatoolbox/package.py
|
Python
| 0 |
@@ -0,0 +1,1227 @@
+# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other%0A# Spack Project Developers. See the top-level COPYRIGHT file for details.%0A#%0A# SPDX-License-Identifier: (Apache-2.0 OR MIT)%0A%0Afrom spack import *%0A%0A%0Aclass PyRsatoolbox(PythonPackage):%0A %22%22%22Representational Similarity Analysis (RSA) in Python.%22%22%22%0A%0A homepage = %22https://github.com/rsagroup/rsatoolbox%22%0A pypi = %22rsatoolbox/rsatoolbox-0.0.3.tar.gz%22%0A%0A version('0.0.3', sha256='9bf6e16d9feadc081f9daaaaab7ef38fc1cd64dd8ef0ccd9f74adb5fe6166649')%0A%0A depends_on('py-setuptools', type='build')%0A depends_on('py-coverage', type=('build', 'run'))%0A depends_on('[email protected]:', type=('build', 'run'))%0A depends_on('py-scipy', type=('build', 'run'))%0A depends_on('py-scikit-learn', type=('build', 'run'))%0A depends_on('py-scikit-image', type=('build', 'run'))%0A depends_on('py-tqdm', type=('build', 'run'))%0A depends_on('py-h5py', type=('build', 'run'))%0A depends_on('py-matplotlib', type=('build', 'run'))%0A depends_on('py-joblib', type=('build', 'run'))%0A%0A def patch(self):%0A # tests are looking for a not existing requirements.txt file%0A with working_dir('tests'):%0A open('requirements.txt', 'a').close()%0A
|
|
0ac0c81a3427f35447f52c1643229f5dbe607002
|
Add a merge migration and bring up to date
|
osf/migrations/0099_merge_20180426_0930.py
|
osf/migrations/0099_merge_20180426_0930.py
|
Python
| 0 |
@@ -0,0 +1,339 @@
+# -*- coding: utf-8 -*-%0A# Generated by Django 1.11.11 on 2018-04-26 14:30%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('osf', '0098_merge_20180416_1807'),%0A ('osf', '0096_add_provider_doi_prefixes'),%0A %5D%0A%0A operations = %5B%0A %5D%0A
|
|
2731aba68f86c0adcb26f4105c7418ffa35e3d09
|
add first auto-test
|
test/run_test.py
|
test/run_test.py
|
Python
| 0.000382 |
@@ -0,0 +1,1905 @@
+#!/usr/bin/env python%0Aimport sys%0Aimport os%0Afrom subprocess import Popen, PIPE%0Aimport re%0A%0Aclass TestFailure(Exception):%0A pass%0A%0Adef do_bgrep(pattern, paths, options=%5B%5D, retcode=0):%0A bgrep_path = '../bgrep'%0A%0A args = %5Bbgrep_path%5D%0A args += list(options)%0A args.append(pattern.encode('hex'))%0A args += list(paths)%0A %0A p = Popen(args, stdout=PIPE)%0A stdout, stderr = p.communicate()%0A%0A if p.returncode != retcode:%0A raise TestFailure('Return code: %7B0%7D, expected: %7B1%7D'.format(p.returncode, retcode))%0A%0A pat = re.compile('%5E(.*):(0x%5B0-9A-Fa-f%5D+).*')%0A%0A result = %7B%7D%0A%0A for line in stdout.splitlines():%0A m = pat.match(line)%0A if not m: continue%0A%0A filename = m.group(1)%0A offset = int(m.group(2), 16)%0A%0A if not filename in result:%0A result%5Bfilename%5D = %5B%5D%0A%0A result%5Bfilename%5D.append(offset)%0A%0A return result%0A%0A%0Adef assert_equal(expected, actual):%0A if not expected == actual:%0A raise TestFailure('Expected: %7B0%7D, Actual %7B1%7D'.format(expected, actual))%0A%0A%0Adef single_test(data, pattern, offsets):%0A filename = 'test.bin'%0A with open(filename, 'wb') as f:%0A f.write(data)%0A%0A try:%0A for retfilename, retoffsets in do_bgrep(pattern, %5Bfilename%5D).iteritems():%0A assert_equal(filename, retfilename)%0A assert_equal(set(offsets), set(retoffsets))%0A finally:%0A os.remove(filename)%0A%0A%0A%0Adef test1():%0A n = 100%0A pattern = '%5Cx12%5Cx34%5Cx56%5Cx78' %0A data = '%5C0'*n + pattern + '%5C0'*n%0A offsets = %5Bn%5D%0A%0A single_test(data, pattern, offsets)%0A%0Aall_tests = %5B%0A test1,%0A%5D%0A%0Adef main():%0A for t in all_tests:%0A name = t.__name__%0A print '%7B0%7D: Starting'.format(name)%0A try:%0A t()%0A except TestFailure as tf:%0A print '%7B0%7D: Failure: %7B1%7D'.format(name, tf)%0A else:%0A print '%7B0%7D: Success'.format(name)%0A%0A%0Aif __name__ == '__main__':%0A main()%0A
|
|
d6315d28ed55b76f3caa3fff26141815f7da7dec
|
add migration
|
accelerator/migrations/0027_modify_video_url_help_text.py
|
accelerator/migrations/0027_modify_video_url_help_text.py
|
Python
| 0.000001 |
@@ -0,0 +1,1252 @@
+# -*- coding: utf-8 -*-%0A# Generated by Django 1.11.14 on 2018-12-05 16:27%0Afrom __future__ import unicode_literals%0A%0Afrom django.conf import settings%0Afrom django.db import migrations, models%0Aimport embed_video.fields%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('accelerator', '0026_startup_acknowledgement'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterField(%0A model_name='startup',%0A name='additional_industries',%0A field=models.ManyToManyField(%0A blank=True,%0A db_table='accelerator_startup_related_industry',%0A help_text='You may select up to 5 related industries.',%0A related_name='secondary_startups',%0A to=settings.MPTT_SWAPPABLE_INDUSTRY_MODEL,%0A verbose_name='Additional Industries'),%0A ),%0A migrations.AlterField(%0A model_name='startup',%0A name='video_elevator_pitch_url',%0A field=embed_video.fields.EmbedVideoField(%0A blank=True,%0A help_text=(%0A 'Upload your 1-3 minute video pitch to Vimeo or '%0A 'Youtube. Paste the shared link here.'),%0A max_length=100),%0A ),%0A %5D%0A
|
|
d573d33cc37ad666d3a4f47a5ac9dfec5a9b5fc5
|
add app config
|
app/appconfig.py
|
app/appconfig.py
|
Python
| 0.000002 |
@@ -0,0 +1,123 @@
+# -*- coding:utf8 -*-%0A# Author: [email protected]%0A# github: https://github.com/imndszy%0AHOST = %22https://www.njuszy.cn/%22%0A
|
|
ffc32773953da2cf9e1d6e84aed1b53debc2c7c7
|
Create __init__.py
|
cltk/stem/middle_english/__init__.py
|
cltk/stem/middle_english/__init__.py
|
Python
| 0.000429 |
@@ -0,0 +1 @@
+%0A
|
|
c7529927174b1626a0dc34f635b1d5939f565add
|
Add problem77.py
|
euler_python/problem77.py
|
euler_python/problem77.py
|
Python
| 0.000164 |
@@ -0,0 +1,1085 @@
+%22%22%22%0Aproblem77.py%0A%0AIt is possible to write ten as the sum of primes in exactly five different ways:%0A%0A 7 + 3%0A 5 + 5%0A 5 + 3 + 2%0A 3 + 3 + 2 + 2%0A 2 + 2 + 2 + 2 + 2%0A%0AWhat is the first value which can be written as the sum of primes in over five%0Athousand different ways? %22%22%22%0Afrom itertools import count, takewhile%0Afrom toolset import get_primes, memoize_mutable%0A%0A@memoize_mutable%0Adef num_partitions(n, primes):%0A # Using a slightly different algorithm than problem 76.%0A # This one is adapted from SICP: https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html%0A # See the section entitled 'Example: Counting change'. Their logic is%0A # more intuitive than that which I presented in the previous problem.%0A if n %3C 0:%0A return 0%0A elif n == 0:%0A return 1%0A elif primes == %5B%5D:%0A return 0%0A else:%0A return num_partitions(n, primes%5B1:%5D) + num_partitions(n - primes%5B0%5D, primes)%0A%0Adef problem77():%0A primes = list(takewhile(lambda x: x %3C 100, get_primes()))%0A return next(filter(lambda x: num_partitions(x, primes) %3E 5000, count(2)))%0A
|
|
f93a79aedde8883241b247244b4d15311ed2967a
|
Add explanation of url encoding
|
elasticsearch/connection/http_urllib3.py
|
elasticsearch/connection/http_urllib3.py
|
import time
import urllib3
from .base import Connection
from ..exceptions import ConnectionError
from ..compat import urlencode
class Urllib3HttpConnection(Connection):
"""
Default connection class using the `urllib3` library and the http protocol.
:arg http_auth: optional http auth information as either ':' separated
string or a tuple
:arg use_ssl: use ssl for the connection if `True`
:arg maxsize: the maximum number of connections which will be kept open to
this host.
"""
def __init__(self, host='localhost', port=9200, http_auth=None, use_ssl=False, maxsize=10, **kwargs):
super(Urllib3HttpConnection, self).__init__(host=host, port=port, **kwargs)
self.headers = {}
if http_auth is not None:
if isinstance(http_auth, (tuple, list)):
http_auth = ':'.join(http_auth)
self.headers = urllib3.make_headers(basic_auth=http_auth)
pool_class = urllib3.HTTPConnectionPool
if use_ssl:
pool_class = urllib3.HTTPSConnectionPool
self.pool = pool_class(host, port=port, timeout=self.timeout, maxsize=maxsize)
def perform_request(self, method, url, params=None, body=None, timeout=None, ignore=()):
url = self.url_prefix + url
if params:
url = '%s?%s' % (url, urlencode(params or {}))
full_url = self.host + url
start = time.time()
try:
kw = {}
if timeout:
kw['timeout'] = timeout
if not isinstance(url, str):
url = url.encode('utf-8')
response = self.pool.urlopen(method, url, body, retries=False, headers=self.headers, **kw)
duration = time.time() - start
raw_data = response.data.decode('utf-8')
except Exception as e:
self.log_request_fail(method, full_url, body, time.time() - start, exception=e)
raise ConnectionError('N/A', str(e), e)
if not (200 <= response.status < 300) and response.status not in ignore:
self.log_request_fail(method, url, body, duration, response.status)
self._raise_error(response.status, raw_data)
self.log_request_success(method, full_url, url, body, response.status,
raw_data, duration)
return response.status, response.getheaders(), raw_data
|
Python
| 0.000007 |
@@ -1514,16 +1514,180 @@
timeout
+%0A%0A # in python2 we need to make sure the url is not unicode. Otherwise%0A # the body will be decoded into unicode too and that will fail (#133).
%0A
@@ -1754,32 +1754,33 @@
encode('utf-8')%0A
+%0A
resp
|
11cbc92e292a54b219f8b5ec64ae8ab58577362d
|
add standalone davidson test w/ near-degeneracies
|
tests/test021.py
|
tests/test021.py
|
Python
| 0.000001 |
@@ -0,0 +1,424 @@
+import numpy as np%0Afrom mmd.utils.davidson import davidson %0A%0Adef test_davidson():%0A%0A np.random.seed(0)%0A dim = 1000%0A A = np.diag(np.arange(dim,dtype=np.float64))%0A A%5B1:3,1:3%5D = 0%0A M = np.random.randn(dim,dim)%0A M += M.T%0A A += 1e-4*M%0A%0A roots = 5%0A E, C = davidson(A, roots)%0A%0A E_true, C_true = np.linalg.eigh(A)%0A E_true, C_true = E_true%5B:roots%5D, C_true%5B:,:roots%5D%0A%0A assert np.allclose(E, E_true)%0A
|
|
781d43e48e83f00e4cd18e805efed7558b570adf
|
introduce btc select command
|
btc/btc_select.py
|
btc/btc_select.py
|
Python
| 0.000002 |
@@ -0,0 +1,1385 @@
+import argparse%0Aimport fnmatch%0Aimport sys%0Aimport os%0Aimport re%0Afrom .btc import encoder, decoder, error, ordered_dict%0A%0A_description = 'select some values'%0A%0Adef main():%0A parser = argparse.ArgumentParser()%0A parser.add_argument('keys', metavar='KEY', nargs='+', default=None,%0A help='keys associated with values to be selected')%0A args = parser.parse_args()%0A%0A if sys.stdin.isatty():%0A parser.error('no input, pipe another btc command output into this command')%0A l = sys.stdin.read()%0A%0A if len(l.strip()) == 0:%0A exit(1)%0A%0A try:%0A l = decoder.decode(l)%0A except ValueError:%0A error('unexpected input: %25s' %25 l)%0A%0A if not isinstance(l, list):%0A error('input must be a list')%0A elif not all(isinstance(x, dict) for x in l):%0A error('list items must be dictionaries')%0A%0A out = %5B%5D%0A for i, e in enumerate(l):%0A e_out = %7B%7D%0A for key in args.keys:%0A try:%0A if len(args.keys) == 1:%0A e_out = e%5Bkey%5D%0A else:%0A e_out%5Bkey%5D = e%5Bkey%5D%0A except KeyError:%0A error('key not found: %7B%7D'.format(key))%0A out.append(e_out)%0A%0A if len(args.keys) %3E 1:%0A print(encoder.encode(%5Bordered_dict(d) for d in out%5D))%0A else:%0A print(encoder.encode(%5Be for e in out%5D))%0A%0Aif __name__ == '__main__':%0A main()%0A
|
|
f947e6766c77f58a6cc1bd0d97758e43d6750c7f
|
add barycentric coordinates
|
src/compas/geometry/interpolation/barycentric.py
|
src/compas/geometry/interpolation/barycentric.py
|
Python
| 0.000011 |
@@ -0,0 +1,1224 @@
+from __future__ import print_function%0Afrom __future__ import absolute_import%0Afrom __future__ import division%0A%0Afrom compas.geometry import subtract_vectors%0Afrom compas.geometry import dot_vectors%0A%0A%0A__all__ = %5B%0A 'barycentric_coordinates'%0A%5D%0A%0A%0Adef barycentric_coordinates(point, triangle):%0A %22%22%22Compute the barycentric coordinates of a point wrt to a triangle.%0A%0A Parameters%0A ----------%0A point: list%0A Point location.%0A triangle: (point, point, point)%0A A triangle defined by 3 points.%0A%0A Returns%0A -------%0A list%0A The barycentric coordinates of the point.%0A%0A %22%22%22%0A a, b, c = triangle%0A v0 = subtract_vectors(b, a)%0A v1 = subtract_vectors(c, a)%0A v2 = subtract_vectors(point, a)%0A d00 = dot_vectors(v0, v0)%0A d01 = dot_vectors(v0, v1)%0A d11 = dot_vectors(v1, v1)%0A d20 = dot_vectors(v2, v0)%0A d21 = dot_vectors(v2, v1)%0A D = d00 * d11 - d01 * d01%0A v = (d11 * d20 - d01 * d21) / D%0A w = (d00 * d21 - d01 * d20) / D%0A u = 1.0 - v - w%0A return u, v, w%0A%0A%0A# ==============================================================================%0A# Main%0A# ==============================================================================%0A%0Aif __name__ == '__main__':%0A pass%0A
|
|
ab946575b1050e67e2e6b4fdda237faa2dc342f5
|
add conversion script for BDDMPipeline
|
scripts/conversion_bddm.py
|
scripts/conversion_bddm.py
|
Python
| 0 |
@@ -0,0 +1,1266 @@
+%0Aimport argparse%0Aimport torch%0A%0Afrom diffusers.pipelines.bddm import DiffWave, BDDMPipeline%0Afrom diffusers import DDPMScheduler%0A%0A%0Adef convert_bddm_orginal(checkpoint_path, noise_scheduler_checkpoint_path, output_path):%0A sd = torch.load(checkpoint_path, map_location=%22cpu%22)%5B%22model_state_dict%22%5D%0A noise_scheduler_sd = torch.load(noise_scheduler_checkpoint_path, map_location=%22cpu%22)%0A%0A model = DiffWave()%0A model.load_state_dict(sd, strict=False)%0A%0A ts, _, betas, _ = noise_scheduler_sd%0A ts, betas = list(ts.numpy().tolist()), list(betas.numpy().tolist())%0A%0A noise_scheduler = DDPMScheduler(%0A timesteps=12,%0A trained_betas=betas,%0A timestep_values=ts,%0A clip_sample=False,%0A tensor_format=%22np%22,%0A )%0A%0A pipeline = BDDMPipeline(model, noise_scheduler)%0A pipeline.save_pretrained(output_path)%0A%0A%0Aif __name__ == %22__main__%22:%0A parser = argparse.ArgumentParser()%0A parser.add_argument(%22--checkpoint_path%22, type=str, required=True)%0A parser.add_argument(%22--noise_scheduler_checkpoint_path%22, type=str, required=True)%0A parser.add_argument(%22--output_path%22, type=str, required=True)%0A args = parser.parse_args()%0A%0A convert_bddm_orginal(args.checkpoint_path, args.noise_scheduler_checkpoint_path, args.output_path)%0A%0A%0A
|
|
271b042c4dfa2d599e1e5b6920fb996798eac631
|
Fix port picking logic in Python tests
|
src/python/grpcio_tests/tests/unit/_reconnect_test.py
|
src/python/grpcio_tests/tests/unit/_reconnect_test.py
|
# Copyright 2017 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests that a channel will reconnect if a connection is dropped"""
import socket
import unittest
import grpc
from grpc.framework.foundation import logging_pool
from tests.unit.framework.common import test_constants
_REQUEST = b'\x00\x00\x00'
_RESPONSE = b'\x00\x00\x01'
_UNARY_UNARY = '/test/UnaryUnary'
def _handle_unary_unary(unused_request, unused_servicer_context):
return _RESPONSE
class ReconnectTest(unittest.TestCase):
def test_reconnect(self):
server_pool = logging_pool.pool(test_constants.THREAD_CONCURRENCY)
handler = grpc.method_handlers_generic_handler('test', {
'UnaryUnary':
grpc.unary_unary_rpc_method_handler(_handle_unary_unary)
})
# Reserve a port, when we restart the server we want
# to hold onto the port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
opt = socket.SO_REUSEPORT
except AttributeError:
# SO_REUSEPORT is unavailable on Windows, but SO_REUSEADDR
# allows forcibly re-binding to a port
opt = socket.SO_REUSEADDR
s.setsockopt(socket.SOL_SOCKET, opt, 1)
s.bind(('localhost', 0))
port = s.getsockname()[1]
server = grpc.server(server_pool, (handler,))
server.add_insecure_port('[::]:{}'.format(port))
server.start()
channel = grpc.insecure_channel('localhost:%d' % port)
multi_callable = channel.unary_unary(_UNARY_UNARY)
self.assertEqual(_RESPONSE, multi_callable(_REQUEST))
server.stop(None)
server = grpc.server(server_pool, (handler,))
server.add_insecure_port('[::]:{}'.format(port))
server.start()
self.assertEqual(_RESPONSE, multi_callable(_REQUEST))
if __name__ == '__main__':
unittest.main(verbosity=2)
|
Python
| 0.00001 |
@@ -976,329 +976,297 @@
E%0A%0A%0A
-class ReconnectTest(unittest.TestCase
+def _get_reuse_socket_option(
):%0A
-%0A
-def test_reconnect(self):%0A server_pool = logging_pool.pool(test_constants.THREAD_CONCURRENCY)%0A handler = grpc.method_handlers_generic_handler('test', %7B%0A 'UnaryUnary':%0A grpc.unary_unary_rpc_method_handler(_handle_unary_unary)%0A %7D)%0A
+try:%0A return socket.SO_REUSEPORT%0A except AttributeError:%0A # SO_REUSEPORT is unavailable on Windows, but SO_REUSEADDR%0A # allows forcibly re-binding to a port%0A return socket.SO_REUSEADDR%0A%0A%0Adef _pick_and_bind_port(sock_opt):%0A
@@ -1318,20 +1318,16 @@
we want%0A
-
# to
@@ -1354,29 +1354,43 @@
- s = socket.socket
+port = 0%0A for address_family in
(soc
@@ -1400,16 +1400,17 @@
.AF_INET
+6
, socket
@@ -1414,20 +1414,17 @@
ket.
-SOCK_STREAM)
+AF_INET):
%0A
@@ -1449,33 +1449,61 @@
-opt = socket.SO_REUSEPORT
+s = socket.socket(address_family, socket.SOCK_STREAM)
%0A
@@ -1510,34 +1510,32 @@
except
-AttributeE
+socket.e
rror:%0A
@@ -1544,270 +1544,1128 @@
-# SO_REUSEPORT is unavailable on Windows, but SO_REUSEADDR%0A # allows forcibly re-binding to a port%0A opt = socket.SO_REUSEADDR%0A s.setsockopt(socket.SOL_SOCKET, opt, 1)%0A s.bind(('localhost', 0))%0A port = s.getsockname()%5B1%5D
+continue # this address family is unavailable%0A s.setsockopt(socket.SOL_SOCKET, sock_opt, 1)%0A try:%0A s.bind(('localhost', port))%0A # for socket.SOCK_STREAM sockets, it is necessary to call%0A # listen to get the desired behavior.%0A s.listen(1)%0A port = s.getsockname()%5B1%5D%0A except socket.error:%0A # port was not available on the current address family%0A # try again%0A port = 0%0A break%0A finally:%0A s.close()%0A if s:%0A return port if port != 0 else _pick_and_bind_port(sock_opt)%0A else:%0A return None # no address family was available%0A%0A%0Aclass ReconnectTest(unittest.TestCase):%0A%0A def test_reconnect(self):%0A server_pool = logging_pool.pool(test_constants.THREAD_CONCURRENCY)%0A handler = grpc.method_handlers_generic_handler('test', %7B%0A 'UnaryUnary':%0A grpc.unary_unary_rpc_method_handler(_handle_unary_unary)%0A %7D)%0A sock_opt = _get_reuse_socket_option()%0A port = _pick_and_bind_port(sock_opt)%0A self.assertIsNotNone(port)
%0A%0A
|
67d409b6be5f90c33e73ddf73ba2966d8f2c44f4
|
Find max function in python
|
Maths/FindMax.py
|
Maths/FindMax.py
|
Python
| 0.999997 |
@@ -0,0 +1,123 @@
+# NguyenU%0A%0Aimport math%0A%0Adef find_max(nums):%0A max = 0%0A for x in nums:%0A if x %3E max:%0A max = x%0A print max%0A
|
|
922513b2e0e26432fd4e4addfe83e2b84d631d4f
|
Create change_function_signature.py
|
change_function_signature.py
|
change_function_signature.py
|
Python
| 0.000006 |
@@ -0,0 +1,121 @@
+def foo(a):%0A print(a)%0A%0Adef bar(a, b):%0A print(a, b)%0A%0A%0Afunc = foo%0Afunc(10)%0Afunc.__code__ = bar.__code__%0Afunc(10, 20)%0A
|
|
a3b31137ac96bf3480aaecadd5faf3ca051fc4b0
|
Add bare ConnectionState
|
litecord/gateway/state.py
|
litecord/gateway/state.py
|
Python
| 0.000002 |
@@ -0,0 +1,491 @@
+%0Aclass ConnectionState:%0A %22%22%22State of a connection to the gateway over websockets%0A %0A Attributes%0A ----------%0A session_id: str%0A Session ID this state refers to.%0A%0A events: %60collections.deque%60%5Bdict%5D%0A Deque of sent events to the connection. Used for resuming%0A This is filled up when the connection receives a dispatched event%0A %22%22%22%0A def __init__(self, session_id):%0A self.session_id = session_id%0A%0A def clean(self):%0A del self.session_id%0A%0A
|
|
83f2e11d63168e022d99075d2f35c6c813c4d37d
|
add a simple linear regression model
|
gnt_model.py
|
gnt_model.py
|
Python
| 0.055082 |
@@ -0,0 +1,1511 @@
+import tensorflow as tf%0Afrom utils.gnt_record import read_and_decode, BATCH_SIZE%0A%0A%0Awith open('label_keys.list') as f:%0A labels = f.readlines()%0A%0Atfrecords_filename = %22hwdb1.1.tfrecords%22%0Afilename_queue = tf.train.string_input_producer(%0A %5Btfrecords_filename%5D, num_epochs=10)%0A%0A# Even when reading in multiple threads, share the filename%0A# queue.%0Aimages_batch, labels_batch = read_and_decode(filename_queue)%0Alabel_one_hot = tf.one_hot(labels_batch, len(labels))%0A%0Aprint(label_one_hot)%0A%0A# simple model%0Aimages_batch_normalized = images_batch / 128 - 0.5%0Aprint(images_batch)%0Aprint(images_batch_normalized)%0A%0Aimages_batch_normalized = tf.reshape(images_batch_normalized, %5BBATCH_SIZE, 128*128%5D)%0Aprint(images_batch_normalized)%0A%0Aw = tf.get_variable(%22w1%22, %5B128*128, len(labels)%5D)%0Ay_pred = tf.matmul(images_batch_normalized, w)%0A%0Aprint(%22y pred & labels batch%22)%0Aprint(y_pred)%0Aprint(label_one_hot)%0A%0Aloss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=labels_batch, logits=y_pred)%0A%0A# for monitoring%0Aloss_mean = tf.reduce_mean(loss)%0A%0Atrain_op = tf.train.AdamOptimizer().minimize(loss)%0A%0A# The op for initializing the variables.%0Ainit_op = tf.group(tf.global_variables_initializer(),%0A tf.local_variables_initializer())%0A%0Awith tf.Session() as sess:%0A sess.run(init_op)%0A%0A coord = tf.train.Coordinator()%0A threads = tf.train.start_queue_runners(coord=coord)%0A%0A while True:%0A _, loss_val = sess.run(%5Btrain_op, loss_mean%5D)%0A print(loss_val)%0A%0A coord.request_stop()%0A coord.join(threads)%0A
|
|
15970841d53e14d3739d8f512f815e8e3c19bf02
|
Create Opcao.py
|
backend/Database/Models/Opcao.py
|
backend/Database/Models/Opcao.py
|
Python
| 0 |
@@ -0,0 +1,585 @@
+from Database.Controllers.Curso import Curso%0A%0Aclass Opcao(object):%0A%0A%09def __init__(self,dados=None):%0A%09%09if dados is not None:%0A%09%09%09self.id = dados %5B'id'%5D%0A%09%09%09self.nome = dados %5B'nome'%5D%0A%09%09%09self.id_curso = dados %5B'id_curso'%5D%0A%09%09%09%0A%09def getId(self):%0A%09%09return self.id%0A%0A%09def setNome(self,nome):%0A%09%09self.nome = nome%0A%0A%09def getNome(self):%0A%09%09return self.nome%0A%09%09%0A%09def setId_curso(self,curso):%0A%09%09self.id_curso = (Curso().pegarCurso('nome = %25s',(curso))).getId()%0A%09%09%0A%09def getId_curso(self):%0A%09%09return self.id_curso%0A%09%09%0A%09def getCurso(self):%0A%09%09return (Curso().pegarCurso('id = %25s',(self.id_curso,))).getNome()%0A
|
|
3f50dcf6d91192253af320aaf72fcb13d307e137
|
add new package
|
var/spack/repos/builtin/packages/memsurfer/package.py
|
var/spack/repos/builtin/packages/memsurfer/package.py
|
Python
| 0.000001 |
@@ -0,0 +1,1875 @@
+# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other%0A# Spack Project Developers. See the top-level COPYRIGHT file for details.%0A#%0A# SPDX-License-Identifier: (Apache-2.0 OR MIT)%0A%0A%0Afrom spack import *%0A%0A%0Aclass Memsurfer(PythonPackage):%0A %22%22%22MemSurfer is a tool to compute and analyze membrane surfaces found in a%0A wide variety of large-scale molecular simulations.%22%22%22%0A%0A homepage = %22https://github.com/LLNL/MemSurfer%22%0A git = %[email protected]:LLNL/MemSurfer.git%22%0A # url = %22https://github.com/LLNL/MemSurfer/archive/1.0.tar.gz%22%0A%0A # version('1.0', sha256='06e06eba88754b0c073f1c770981f7bdd501082986e4fbe28399be23b50138de')%0A version('1.0', tag='v1.0', submodules=True)%0A version('master', branch='master', submodules=True)%0A # version('test', branch='ppoisson', submodules=True)%0A%0A variant('vtkmesa', default=False, description='Enable OSMesa support for VTK')%0A%0A extends('[email protected]')%0A depends_on('[email protected]:')%0A depends_on('[email protected]')%0A depends_on('py-cython')%0A depends_on('py-numpy')%0A depends_on('py-pip')%0A%0A depends_on('[email protected]')%0A depends_on('[email protected] +shared~core~demos~imageio')%0A%0A # vtk needs to know whether to build with mesa or opengl%0A depends_on('[email protected] +python+opengl2~mpi~haru', when='~vtkmesa')%0A depends_on('[email protected] +python+opengl2~mpi~haru +osmesa', when='+vtkmesa')%0A%0A # this is needed only to resolve the conflict between%0A # the default and netcdf's spec%0A depends_on('hdf5 +hl')%0A%0A # memsurfer's setup needs path to these deps to build extension modules%0A def setup_environment(self, spack_env, run_env):%0A spack_env.set('VTK_ROOT', self.spec%5B'vtk'%5D.prefix)%0A spack_env.set('CGAL_ROOT', self.spec%5B'cgal'%5D.prefix)%0A spack_env.set('BOOST_ROOT', self.spec%5B'boost'%5D.prefix)%0A spack_env.set('EIGEN_ROOT', self.spec%5B'eigen'%5D.prefix)%0A
|
|
5be5d2eb2ddef625963dd1f11984d1838fac5e7f
|
Fix /help command crash if a command doesn't have docstrings
|
botogram/defaults.py
|
botogram/defaults.py
|
"""
botogram.defaults
Default commands definition
Copyright (c) 2015 Pietro Albini <[email protected]>
Released under the MIT license
"""
import html
from . import syntaxes
from . import components
from . import decorators
class DefaultComponent(components.Component):
"""This component contains all the goodies botogram provides by default"""
component_name = "botogram"
def __init__(self):
self.add_command("start", self.start_command, hidden=True)
self.add_command("help", self.help_command)
self._add_no_commands_hook(self.no_commands_hook)
# /start command
def start_command(self, bot, chat):
message = []
if bot.about:
message.append(bot.about)
message.append("")
message.append(bot._("Use /help to get a list of all the commands."))
chat.send("\n".join(message), syntax="html")
@decorators.help_message_for(start_command)
def _start_command_help(bot):
return "\n".join([
bot._("Start using the bot."),
bot._("This shows a greeting message."),
])
# /help command
def help_command(self, bot, chat, args):
commands = {cmd.name: cmd for cmd in bot.available_commands()}
if len(args) > 1:
message = [bot._("<b>Error!</b> The <code>/help</code> command "
"allows up to one argument.")]
elif len(args) == 1:
if args[0] in commands:
message = self._help_command_message(bot, commands, args[0])
else:
message = [bot._("<b>Unknown command:</b> "
"<code>/%(name)s</code>",
name=args[0]),
bot._("Use /help to get a list of the commands.")]
else:
message = self._help_generic_message(bot, commands)
chat.send("\n".join(message), syntax="html")
def _help_generic_message(self, bot, commands):
"""Generate an help message"""
message = []
# Show the about text
if bot.about:
message.append(bot.about)
message.append("")
if len(bot.before_help):
message += bot.before_help
message.append("")
# Show help on commands
if len(commands) > 0:
message.append(bot._("<b>This bot supports those commands:</b>"))
for name in sorted(commands.keys()):
summary = escape_html(commands[name].summary)
if summary is None:
summary = "<i>%s</i>" % bot._("No description available.")
message.append("/%s <code>-</code> %s" % (name, summary))
message.append("")
message.append(bot._("You can also use <code>/help <command>"
"</code> to get help about a specific "
"command."))
else:
message.append(bot._("<i>This bot has no commands.</i>"))
if len(bot.after_help):
message.append("")
message += bot.after_help
# Show the owner informations
if bot.owner:
message.append("")
message.append(bot._("Please contact %(owner)s if you have "
"problems with this bot.",
owner=bot.owner))
return message
def _help_command_message(self, bot, commands, command):
"""Generate a command's help message"""
message = []
docstring = escape_html(commands[command].docstring)
if docstring is None:
docstring = "<i>%s</i>" % bot._("No description available.")
message.append("/%s <code>-</code> %s" % (command, docstring))
# Show the owner informations
if bot.owner:
message.append(" ")
message.append(bot._("Please contact %(owner)s if you have "
"problems with this bot.",
owner=bot.owner))
return message
@decorators.help_message_for(help_command)
def _help_command_help(bot):
"""Get the help message of this command"""
return "\n".join([
bot._("Show this help message."),
bot._("You can also use <code>/help <command></code> to get "
"help about a specific command."),
])
# An hook which displays "Command not found" if needed
def no_commands_hook(self, bot, chat, message):
if message.text is None:
return
# First check if a command was invoked
match = bot._commands_re.match(message.text)
if not match:
return
command = match.group(1)
splitted = message.text.split(" ")
username = bot.itself.username
mentioned = splitted[0] == "/%s@%s" % (command, username)
single_user = chat.type == "private"
if mentioned or single_user:
chat.send("\n".join([
bot._("<b>Unknown command:</b> <code>/%(name)s</code>",
name=command),
bot._("Use /help to get a list of the commands."),
]), syntax="html")
return True
def escape_html(text):
"""Escape a docstring"""
# The docstring is escaped only if it doesn't contain HTML markup
if not syntaxes.is_html(text):
return html.escape(text)
return text
|
Python
| 0.000214 |
@@ -5365,24 +5365,97 @@
ocstring%22%22%22%0A
+ # You can't escape None, right?%0A if text is None:%0A return%0A%0A
# The do
|
b5db8d8b0620491169d54eaf05bb57e5a61903e1
|
add bash8 tool (like pep8, but way hackier)
|
bash8.py
|
bash8.py
|
Python
| 0.000002 |
@@ -0,0 +1,2376 @@
+#!/usr/bin/env python%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, WITHOUT%0A# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the%0A# License for the specific language governing permissions and limitations%0A# under the License.%0A%0A# bash8 - a pep8 equivalent for bash scripts%0A#%0A# this program attempts to be an automated style checker for bash scripts%0A# to fill the same part of code review that pep8 does in most OpenStack%0A# projects. It starts from humble beginnings, and will evolve over time.%0A#%0A# Currently Supported checks%0A#%0A# Errors%0A# - E001: check that lines do not end with trailing whitespace%0A# - E002: ensure that indents are only spaces, and not hard tabs%0A# - E003: ensure all indents are a multiple of 4 spaces%0A%0Aimport argparse%0Aimport fileinput%0Aimport re%0Aimport sys%0A%0A%0AERRORS = 0%0A%0A%0Adef print_error(error, line):%0A global ERRORS%0A ERRORS = ERRORS + 1%0A print(%22%25s: '%25s'%22 %25 (error, line.rstrip('%5Cn')))%0A print(%22 - %25s: L%25s%22 %25 (fileinput.filename(), fileinput.filelineno()))%0A%0A%0Adef check_no_trailing_whitespace(line):%0A if re.search('%5B %5Ct%5D+$', line):%0A print_error('E001: Trailing Whitespace', line)%0A%0A%0Adef check_indents(line):%0A m = re.search('%5E(?P%3Cindent%3E%5B %5Ct%5D+)', line)%0A if m:%0A if re.search('%5Ct', m.group('indent')):%0A print_error('E002: Tab indents', line)%0A if (len(m.group('indent')) %25 4) != 0:%0A print_error('E003: Indent not multiple of 4', line)%0A%0A%0Adef check_files(files):%0A for line in fileinput.input(files):%0A check_no_trailing_whitespace(line)%0A check_indents(line)%0A%0A%0Adef get_options():%0A parser = argparse.ArgumentParser(%0A description='A bash script style checker')%0A parser.add_argument('files', metavar='file', nargs='+',%0A help='files to scan for errors')%0A return parser.parse_args()%0A%0A%0Adef main():%0A opts = get_options()%0A check_files(opts.files)%0A%0A if ERRORS %3E 0:%0A print(%22%25d bash8 error(s) found%22 %25 ERRORS)%0A return 1%0A else:%0A return 0%0A%0A%0Aif __name__ == %22__main__%22:%0A sys.exit(main())%0A
|
|
db4ba2ca4e0ea96c9bc3f7e9d3eb61e7c7c3bc23
|
Create softmax
|
softmax.py
|
softmax.py
|
Python
| 0.000001 |
@@ -0,0 +1,688 @@
+#! /usr/bin/env python%0A%22%22%22%0AAuthor: Umut Eser%0AProgram: softmax.py%0ADate: Friday, September 30 2016%0ADescription: Softmax applied over rows of a matrix%0A%22%22%22%0A%0Aimport numpy as np%0A%0A%0Adef softmax(X):%0A %22%22%22%0A Calculates softmax of the rows of a matrix X.%0A%0A Parameters%0A ----------%0A X : 2D numpy array%0A%0A Return%0A ------%0A 2D numpy array of positive numbers between 0 and 1%0A%0A Examples%0A --------%0A %3E%3E%3E softmax(%5B%5B0.1, 0.2%5D,%5B0.9, -10%5D%5D)%0A array(%5B%5B 0.47502081, 0.52497919%5D,%5B 9.99981542e-01, 1.84578933e-05%5D%5D)%0A %22%22%22%0A e_X = np.exp(X - np.max(X,axis=1))%0A return np.divide(e_X.T,e_X.sum(axis=1)).T%0A%0A%0Aif __name__ == %22__main__%22:%0A import doctest%0A doctest.testmod()%0A
|
|
28696b671a5f80f781c67f35ae5abb30efd6379c
|
Solve Time Conversion in python
|
solutions/uri/1019/1019.py
|
solutions/uri/1019/1019.py
|
Python
| 0.999882 |
@@ -0,0 +1,231 @@
+import sys%0A%0Ah = 0%0Am = 0%0A%0Afor t in sys.stdin:%0A t = int(t)%0A%0A if t %3E= 60 * 60:%0A h = t // (60 * 60)%0A t %25= 60 * 60%0A%0A if t %3E= 60:%0A m = t // 60%0A t %25= 60%0A%0A print(f%22%7Bh%7D:%7Bm%7D:%7Bt%7D%22)%0A%0A h = 0%0A m = 0%0A
|
|
9876f372100bbc4c272378fe9a06f7d7ddd90308
|
Add twitter daily backup script
|
twitter/daily.py
|
twitter/daily.py
|
Python
| 0.000001 |
@@ -0,0 +1,2589 @@
+#!/usr/bin/env python3%0A%0Aimport json%0Afrom datetime import datetime%0A%0Aimport pymysql%0Afrom requests_oauthlib import OAuth1Session%0A%0A%0Aclass Twitter():%0A def __init__(self):%0A self.session = OAuth1Session(%0A client_key=%22%7Bconsumer_key%7D%22,%0A client_secret=%22%7Bconsumer_secret%7D%22,%0A resource_owner_key=%22%7Baccess_token%7D%22,%0A resource_owner_secret=%22%7Baccess_secret%7D%22,%0A )%0A%0A def crawl(self, last_id):%0A ''' Crawl new tweet from user timeline.%0A :param last_id: last tweet's id in database%0A :return list:%0A '''%0A if type(last_id) != int:%0A raise TypeError(%22arg last_id expects int%22)%0A url = %22https://api.twitter.com/1.1/statuses/user_timeline.json%22%0A params = %7B%0A 'count': 200,%0A 'since_id': last_id,%0A 'max_id': None,%0A 'trim_user': True,%0A 'contributor_details': False,%0A 'exclude_replies': False,%0A 'include_rts': True,%0A %7D%0A%0A while True:%0A response = self.session.get(url, params=params)%0A tweets = json.loads(response.text)%0A if len(tweets) %3E 0:%0A yield from tweets%0A params%5B'max_id'%5D = tweets%5B-1%5D%5B'id'%5D - 1%0A else:%0A break%0A%0A%0Aclass Database():%0A def __init__(self):%0A self.connection = pymysql.connect(%0A host=%22localhost%22,%0A user=%22%7Bmysql_user%7D%22,%0A password=%22%7Bmysql_password%7D%22,%0A database=%22twitter%22,%0A charset=%22utf8mb4%22,%0A )%0A%0A def insert(self, tweet):%0A try:%0A tweet_id = tweet%5B'id'%5D%0A user_id = tweet%5B'user'%5D%5B'id'%5D%0A text = tweet%5B'text'%5D%0A time = str(datetime.strptime(%0A tweet%5B'created_at'%5D.replace(%22+0000%22, ''), %22%25c%22))%0A cursor = self.connection.cursor()%0A cursor.execute(%0A '''INSERT INTO statuses VALUES (%25s, %25s, %25s, %25s)''',%0A (tweet_id, user_id, text, time))%0A except pymysql.err.ProgrammingError as err:%0A print(%22Fail to insert tweet: %25d%22 %25 tweet_id, file=sys.stderr)%0A traceback.print_exc()%0A%0A def get_last_id(self):%0A cursor = self.connection.cursor()%0A cursor.execute(%22SELECT id FROM statuses ORDER BY id DESC LIMIT 1%22)%0A tweet = cursor.fetchone()%0A return tweet%5B0%5D%0A%0A%0Aif __name__ == '__main__':%0A twitter = Twitter()%0A database = Database()%0A%0A last_id = database.get_last_id()%0A timeline = twitter.crawl(last_id)%0A for tweet in timeline:%0A database.insert(tweet)%0A
|
|
69005d995aa0e6d291216101253197c6b2d8260a
|
Add module for command-line interface
|
husc/main.py
|
husc/main.py
|
Python
| 0.000001 |
@@ -0,0 +1,1016 @@
+import argparse%0A%0Aparser = argparse.ArgumentParser(description=%22Run the HUSC functions.%22)%0Asubpar = parser.add_subparsers()%0A%0Astitch = subpar.add_parser('stitch', %0A help=%22Stitch four quadrants into one image.%22)%0Astitch.add_argument('quadrant_image', nargs=4,%0A help=%22The images for each quadrant in order: NW, NE, %22 +%0A %22SW, SE.%22)%0Astitch.add_argument('output_image',%0A help=%22The filename for the stitched image.%22)%0A%0Aillum = subpar.add_parser('illum',%0A help=%22Estimate and correct illumination.%22)%0Aillum.add_argument('images', nargs='+',%0A help=%22The input images.%22)%0Aillum.add_argument('-o', '--output-suffix',%0A default='.illum.tif', metavar='SUFFIX',%0A help=%22What suffix to attach to the corrected images.%22)%0A%0A%0Adef main():%0A %22%22%22Fetch commands from the command line.%22%22%22%0A args = parser.parse_args()%0A print args%0A%0A%0Aif __name__ == '__main__':%0A main()%0A%0A
|
|
10440cbcde68ecf16c8b8b326ec96d1d7f8c6d6d
|
add basic PID for sial position
|
src/boat_pid_control/src/boat_pid_control/sailPID.py
|
src/boat_pid_control/src/boat_pid_control/sailPID.py
|
Python
| 0 |
@@ -0,0 +1,576 @@
+%22%22%22%0APID control for the sailing robot%0Acontroling sail position%0Abased on goal sail direction%0A%0AInputs: %0A- current heading%0A- goal heading%0A%0AOutput:%0A- Change in motor position/motor position%0A%0ATODO:%0Aconsider tack and jibe%0A%22%22%22%0A%0Aimport rospy%0A%0A%0APROPORTIONAL_GAIN = 0.1%0AINTEGRAL_GAIN = 0%0ADERIVATIVE_GAIN = 0%0A%0A%0AcurrentHeading = 23%0AgoalHeading = 35%0A%0A# with new ROS input for goal or current heading%0A%0A# Error calculation for angular error!%0Aerror = currentHeading - goalHeading%0A%0A%0Ap = error * PROPORTIONAL_GAIN%0Ai = 0%0Ad = 0%0A%0Acorrection = p + i + d%0A%0A#translate correction to servo change ...%0A%0A
|
|
ea0087970b0c0adfd8942123899ff0ec231afa03
|
Handle stealable element with utils
|
test/selenium/src/lib/page/extended_info.py
|
test/selenium/src/lib/page/extended_info.py
|
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: [email protected]
# Maintained By: [email protected]
"""A module for extended info page models (visible in LHN on hover over
object members)"""
from selenium.common import exceptions
from lib import base
from lib.constants import locator
class ExtendedInfo(base.Component):
"""Model representing an extended info box that allows the object to be
mapped"""
_locator = locator.ExtendedInfo
def __init__(self, driver):
super(ExtendedInfo, self).__init__(driver)
self.button_map = None
def _reload_contents(self):
self.button_map = base.Button(
self._driver, self._locator.BUTTON_MAP_TO)
def map_to_object(self):
try:
self.button_map = base.Button(
self._driver, self._locator.BUTTON_MAP_TO)
self.button_map.click()
except exceptions.StaleElementReferenceException:
self._reload_contents()
return self.map_to_object()
def is_already_mapped(self):
"""Checks if the object is already mapped"""
try:
self._driver.find_element(*self._locator.ALREADY_MAPPED)
return True
except exceptions.NoSuchElementException:
return False
|
Python
| 0 |
@@ -424,16 +424,53 @@
locator%0A
+from lib.utils import selenium_utils%0A
%0A%0Aclass
@@ -587,24 +587,27 @@
ed%22%22%22%0A
-_
locator
+_cls
= locat
@@ -700,16 +700,42 @@
driver)%0A
+ self.is_mapped = None%0A
self
@@ -757,88 +757,36 @@
one%0A
-%0A def _reload_contents(self):%0A self.button_map = base.Button(%0A self._
+ self.title = base.Label(
driv
@@ -798,108 +798,129 @@
elf.
-_
locator
-.BUTTON_MAP_TO)%0A%0A def map_to_object(self):%0A try:%0A self.button_map = base.Button(%0A
+_cls.TITLE)%0A%0A self._set_is_mapped()%0A%0A def map_to_object(self):%0A selenium_utils.click_on_staleable_element(%0A
@@ -940,22 +940,33 @@
ver,
+%0A
self.
-_
locator
+_cls
.BUT
@@ -985,169 +985,44 @@
-
self.
-button_map.click()%0A except exceptions.StaleElementReferenceException:%0A self._reload_contents()%0A return self.map_to_object()%0A%0A def is_already
+is_mapped = True%0A%0A def _set_is
_map
@@ -1132,16 +1132,19 @@
elf.
-_
locator
+_cls
.ALR
@@ -1162,22 +1162,32 @@
)%0A
-return
+self.is_mapped =
True%0A
@@ -1240,14 +1240,24 @@
-return
+self.is_mapped =
Fal
|
1f47c575cfd310fd4bee18673f7cbb69eb622959
|
Create block_params.py
|
block_params.py
|
block_params.py
|
Python
| 0.000004 |
@@ -0,0 +1,639 @@
+# block_params.py%0A# Demonstration of a blockchain 2 of 3 components%0A%0AGENESIS_INDEX = 0%0AGENESIS_PREVIOUS_HASH = '0'%0AGENESIS_TIMESTAMP = 1495851743%0AGENESIS_DATA = 'first block'%0A%0A%0Aclass BlockParams():%0A%0A def __init__(self, index, previous_hash, timestamp, data):%0A self.index = index%0A self.previous_hash = previous_hash%0A self.timestamp = timestamp%0A self.data = data%0A%0A def __str__(self):%0A return str(self.index) + self.previous_hash + str(self.timestamp) + self.data%0A%0A @classmethod%0A def genesis_params(cls):%0A return cls(GENESIS_INDEX, GENESIS_PREVIOUS_HASH, GENESIS_TIMESTAMP, GENESIS_DATA)%0A
|
|
65dc2f12d8540d3aa494447033e022fe3995701b
|
correct language mistake
|
btc_download.py
|
btc_download.py
|
#! /usr/bin/env python
import argparse
import sys
import os
from btc import encoder, decoder, error, warning, list_to_dict, dict_to_list, client
_description = 'download torrent file locally'
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--directory', default='.')
parser.add_argument('-o', '--output', default=None)
args = parser.parse_args()
if sys.stdin.isatty():
error('no input')
files = sys.stdin.read()
try:
files = decoder.decode(files)
except ValueError:
error('unexpected input: %s' % files)
if not os.path.exists(args.directory):
error('no such directory: %s' % args.directory)
if args.output and len(files) > 1:
if sys.stdout.isatty():
warning('multiple files: --output is ignored')
for f in files:
# FIXME: problems with \\ and /
filename = args.output or f['name']
complete = float(f['downloaded']) / float(f['size']) * 100
if sys.stdout.isatty() and complete < 100.0:
print 'skipping uncomplete file: %s' % f['name']
continue
if args.output and len(files) > 1:
filename = f['name']
if args.output and len(files) == 1:
directory = os.path.dirname(os.path.join(args.directory, args.output))
if not os.path.exists(directory):
error('no such directory: %s' % directory)
else:
directory = os.path.dirname(os.path.join(args.directory, f['name']))
if not os.path.exists(directory):
os.makedirs(directory)
if sys.stdout.isatty():
print 'downloading: %s' % os.path.join(args.directory, filename)
client.torrent_download_file(f['sid'], f['fileid'], filename, args.directory)
if not sys.stdout.isatty():
l = client.list_torrents()
print encoder.encode(l)
if __name__ == '__main__':
main()
|
Python
| 0.999994 |
@@ -1069,17 +1069,17 @@
kipping
-u
+i
ncomplet
|
7922b24882894cbc83bd4247c11d8c4a66b4b218
|
Add utility script for database setup
|
_setup_database.py
|
_setup_database.py
|
Python
| 0 |
@@ -0,0 +1,353 @@
+#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A%0Afrom setup.create_teams import migrate_teams%0Afrom setup.create_divisions import create_divisions%0A%0A%0Aif __name__ == '__main__':%0A # migrating teams from json file to database%0A migrate_teams(simulation=True)%0A # creating divisions from division configuration file%0A create_divisions(simulation=True)%0A
|
|
af436dd269a959324b495885b9406610f3737a7a
|
Create addtoindex.py
|
udacity/webcrawler/addtoindex.py
|
udacity/webcrawler/addtoindex.py
|
Python
| 0.000001 |
@@ -0,0 +1,809 @@
+# Define a procedure, add_to_index,%0A# that takes 3 inputs:%0A%0A# - an index: %5B%5B%3Ckeyword%3E,%5B%3Curl%3E,...%5D%5D,...%5D%0A# - a keyword: String%0A# - a url: String%0A%0A# If the keyword is already%0A# in the index, add the url%0A# to the list of urls associated%0A# with that keyword.%0A%0A# If the keyword is not in the index,%0A# add an entry to the index: %5Bkeyword,%5Burl%5D%5D%0A%0Aindex = %5B%5D%0A%0Adef add_to_index(index,keyword,url):%0A for entry in index:%0A if entry%5B0%5D == keyword:%0A entry%5B1%5D.append(url)%0A return%0A index.append(%5Bkeyword, %5Burl%5D%5D)%0A %0A%0A%0A%0A%0A%0Aadd_to_index(index,'udacity','http://udacity.com')%0Aadd_to_index(index,'computing','http://acm.org')%0Aadd_to_index(index,'udacity','http://npr.org')%0Aprint index%0A#%3E%3E%3E %5B%5B'udacity', %5B'http://udacity.com', 'http://npr.org'%5D%5D, %0A#%3E%3E%3E %5B'computing', %5B'http://acm.org'%5D%5D%5D%0A%0A%0A
|
|
01c4554123cbf1d37fe73fdb51ccacdedf870635
|
1. Two Sum. Brute-force
|
p001_brute_force.py
|
p001_brute_force.py
|
Python
| 0.999581 |
@@ -0,0 +1,735 @@
+import unittest%0A%0A%0Aclass Solution(object):%0A def twoSum(self, nums, target):%0A %22%22%22%0A :type nums: List%5Bint%5D%0A :type target: int%0A :rtype: List%5Bint%5D%0A %22%22%22%0A for i, a in enumerate(nums):%0A for j, b in enumerate(nums%5Bi + 1:%5D):%0A if a + b == target:%0A return %5Bi, i + 1 + j%5D%0A%0A%0Aclass Test(unittest.TestCase):%0A def test(self):%0A self._test(%5B2, 7, 11, 15%5D, 9, %5B0, 1%5D)%0A self._test(%5B11, 2, 7, 15%5D, 9, %5B1, 2%5D)%0A self._test(%5B2, 7, 11, 7, 15%5D, 14, %5B1, 3%5D)%0A%0A def _test(self, nums, target, expected):%0A actual = Solution().twoSum(nums, target)%0A self.assertItemsEqual(actual, expected)%0A%0A%0Aif __name__ == '__main__':%0A unittest.main()%0A
|
|
93621f9441af4df77c8364050d7cc3dc2b1b43b2
|
Add tests for `check` command
|
tests/functional/registration/test_check.py
|
tests/functional/registration/test_check.py
|
Python
| 0.000003 |
@@ -0,0 +1,1312 @@
+%22%22%22%0ATest check/validation command.%0A%22%22%22%0Aimport os%0Aimport subprocess%0A%0Athis_folder = os.path.abspath(os.path.dirname(__file__))%0A%0A%0Adef test_check_metamodel():%0A %22%22%22%0A Meta-model is also a model%0A %22%22%22%0A%0A metamodel_file = os.path.join(this_folder,%0A 'projects', 'flow_dsl', 'flow_dsl', 'Flow.tx')%0A output = subprocess.check_output(%5B'textx', 'check', metamodel_file%5D,%0A stderr=subprocess.STDOUT)%0A assert b'Flow.tx: OK.' in output%0A%0A%0Adef test_check_valid_model():%0A metamodel_file = os.path.join(this_folder,%0A 'projects', 'flow_dsl', 'tests',%0A 'models', 'data_flow.eflow')%0A output = subprocess.check_output(%5B'textx', 'check', metamodel_file%5D,%0A stderr=subprocess.STDOUT)%0A assert b'data_flow.eflow: OK.' in output%0A%0A%0Adef test_check_invalid_model():%0A metamodel_file = os.path.join(this_folder,%0A 'projects', 'flow_dsl', 'tests',%0A 'models', 'data_flow_including_error.eflow')%0A output = subprocess.check_output(%5B'textx', 'check', metamodel_file%5D,%0A stderr=subprocess.STDOUT)%0A assert b'error: types must be lowercase' in output%0A
|
|
720e288aba61ecc2214c8074e33d181c0d4584f5
|
Add do_datasets module
|
carto/do_datasets.py
|
carto/do_datasets.py
|
Python
| 0.000001 |
@@ -0,0 +1,1021 @@
+%22%22%22%0AModule for working with Data Observatory Datasets%0A%0A.. module:: carto.do_datasets%0A :platform: Unix, Windows%0A :synopsis: Module for working with Data Observatory Datasets%0A%0A.. moduleauthor:: Jes%C3%BAs Arroyo %[email protected]%3E%0A%0A%0A%22%22%22%0A%0Afrom pyrestcli.fields import CharField%0A%0Afrom .resources import Resource, Manager%0Afrom .exceptions import CartoException%0Afrom .paginators import CartoPaginator%0A%0A%0AAPI_VERSION = %22v4%22%0AAPI_ENDPOINT = %22api/%7Bapi_version%7D/do/datasets/%22%0A%0A%0Aclass DODatasets(Resource):%0A %22%22%22%0A Represents a Data Observatory Datasets object in CARTO.%0A%0A %22%22%22%0A datasets = CharField(many=True)%0A%0A class Meta:%0A collection_endpoint = API_ENDPOINT.format(api_version=API_VERSION)%0A name_field = %22datasets%22%0A%0Aclass DODatasetsManager(Manager):%0A %22%22%22%0A Manager for the DODatasets class.%0A%0A %22%22%22%0A resource_class = DODatasets%0A json_collection_attribute = %22result%22%0A paginator_class = CartoPaginator%0A%0A def get(self):%0A return super(DODatasetsManager, self).get(%22datasets%22)%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.