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
8deb311e6196c618f9ae3f18d18c1827407b8b96
Add a snippet.
python/pyside/pyside6/widget_QSqlTableModel_sqlite_from_file.py
python/pyside/pyside6/widget_QSqlTableModel_sqlite_from_file.py
Python
0.000002
@@ -0,0 +1,1145 @@ +#!/usr/bin/env python3%0A# -*- coding: utf-8 -*-%0A%0A# Ref: http://doc.qt.io/qt-5/modelview.html#2-1-a-read-only-table%0A%0Aimport sys%0Afrom PySide6 import QtCore, QtWidgets%0A%0Afrom PySide6.QtCore import Qt%0Afrom PySide6.QtWidgets import QApplication, QTableView%0Afrom PySide6.QtSql import QSqlDatabase, QSqlQuery, QSqlTableModel%0A%0A%0A# INIT THE DATABASE #############################%0A%0Adb = QSqlDatabase.addDatabase(%22QSQLITE%22)%0Adb.setDatabaseName(%22./employee.db%22)%0Aassert db.open()%0A%0A# INSERT VALUES%0A%0Aq = QSqlQuery()%0Aassert q.prepare(%22INSERT INTO employee(first_name, last_name) VALUES(?, ?)%22)%0A%0Aq.addBindValue(%22Jean%22)%0Aq.addBindValue(%22Dupont%22)%0Aq.exec()%0A%0Aq.addBindValue(%22Paul%22)%0Aq.addBindValue(%22Dupond%22)%0Aq.exec()%0A%0A%0A#################################################%0A%0Aapp = QApplication(sys.argv)%0A%0Atable_view = QTableView()%0A%0Amodel = QSqlTableModel()%0Amodel.setTable(%22employee%22)%0Amodel.select()%0A%0Atable_view.setModel(model)%0Atable_view.show()%0A%0A# The mainloop of the application. The event handling starts from this point.%0Aexit_code = app.exec()%0A%0A# The sys.exit() method ensures a clean exit.%0A# The environment will be informed, how the application ended.%0Asys.exit(exit_code)%0A
1fe2e3b2ed933f22ce128ca1ea8c728981009a44
Add squashed migration
billjobs/migrations/0002_service_is_available_squashed_0005_bill_issuer_address_default.py
billjobs/migrations/0002_service_is_available_squashed_0005_bill_issuer_address_default.py
Python
0.000002
@@ -0,0 +1,1157 @@ +# -*- coding: utf-8 -*-%0A# Generated by Django 1.9.4 on 2016-03-21 16:55%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations, models%0Afrom billjobs.settings import BILLJOBS_BILL_ISSUER%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A replaces = %5B('billjobs', '0002_service_is_available'), ('billjobs', '0003_billline_note'), ('billjobs', '0004_auto_20160321_1256'), ('billjobs', '0005_bill_issuer_address_default')%5D%0A%0A dependencies = %5B%0A ('billjobs', '0001_initial'),%0A %5D%0A%0A operations = %5B%0A migrations.AddField(%0A model_name='service',%0A name='is_available',%0A field=models.BooleanField(default=True, verbose_name='Is available ?'),%0A ),%0A migrations.AddField(%0A model_name='billline',%0A name='note',%0A field=models.CharField(blank=True, help_text='Write a simple note which will be added in your bill', max_length=1024, verbose_name='Note'),%0A ),%0A migrations.AddField(%0A model_name='bill',%0A name='issuer_address',%0A field=models.CharField(default=BILLJOBS_BILL_ISSUER, max_length=1024),%0A ),%0A %5D%0A
fb41c5295d867dc9ac6ec64da3646246c897e109
add running time of algorithms
src/algorithms/arrays_and_sorting/running_time_of_algorithms.py
src/algorithms/arrays_and_sorting/running_time_of_algorithms.py
Python
0.000162
@@ -0,0 +1,325 @@ +number = input()%0Anumber_array = %5B(int)(x) for x in raw_input().split()%5D%0Atotal = 0%0Afor i in range(1, number):%0A%09for j in range(i):%0A%09%09ii = number_array%5Bi%5D%0A%09%09jj = number_array%5Bj%5D%0A%09%09if ii %3C jj:%0A%09%09%09total += i - j%0A%09%09%09number_array = number_array%5B:j%5D + %5Bii%5D + %5Bjj%5D + number_array%5Bj+1:i%5D + number_array%5Bi+1:%5D%0A%09%09%09break%0Aprint total%0A%0A%0A
1f062298a68aaf6a4161279c539caed07816f1a8
Add tests for influxdb/alarm_state_history_repository.py
monasca_persister/tests/test_influxdb_alarm_state_history_repository.py
monasca_persister/tests/test_influxdb_alarm_state_history_repository.py
Python
0.000001
@@ -0,0 +1,3041 @@ +# (C) Copyright 2019 Fujitsu Limited%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%0A# implied.%0A# See the License for the specific language governing permissions and%0A# limitations under the License.%0A%0Afrom mock import Mock%0Afrom mock import patch%0A%0Afrom oslotest import base%0A%0Afrom monasca_persister.repositories.influxdb.alarm_state_history_repository %5C%0A import AlarmStateHistInfluxdbRepository%0Afrom monasca_persister.repositories.influxdb import abstract_repository%0A%0A%0Aclass TestInfluxdbAlarmStateHistoryRepo(base.BaseTestCase):%0A def setUp(self):%0A super(TestInfluxdbAlarmStateHistoryRepo, self).setUp()%0A with patch.object(abstract_repository.cfg, 'CONF', return_value=Mock()):%0A self.alarm_state_repo = AlarmStateHistInfluxdbRepository()%0A%0A def tearDown(self):%0A super(TestInfluxdbAlarmStateHistoryRepo, self).tearDown()%0A%0A def test_process_message(self):%0A message = Mock()%0A%0A message.message.value = %22%22%22%7B%0A %22alarm-transitioned%22: %7B%0A %22alarmId%22: %22dummyid%22,%0A %22metrics%22: %22dummymetrics%22,%0A %22newState%22: %22dummynewState%22,%0A %22oldState%22: %22dummyoldState%22,%0A %22link%22: %22dummylink%22,%0A %22lifecycleState%22: %22dummylifecycleState%22,%0A %22stateChangeReason%22: %22dummystateChangeReason%22,%0A %22tenantId%22: %22dummytenantId%22,%0A %22timestamp%22: %2210%22,%0A %22subAlarms%22: %7B%0A %22subAlarmExpression%22: %22dummy_sub_alarm%22,%0A %22currentValues%22: %22dummy_values%22,%0A %22metricDefinition%22: %22dummy_definition%22,%0A %22subAlarmState%22: %22dummy_state%22%0A %7D%0A %7D%0A %7D%22%22%22%0A expected_output = u'alarm_state_history,tenant_id=dummytenantId ' %5C%0A u'tenant_id=%22dummytenantId%22,alarm_id=%22dummyid%22,' %5C%0A u'metrics=%22%5C%5C%22dummymetrics%5C%5C%22%22,new_state=%22dummynewState%22' %5C%0A u',old_state=%22dummyoldState%22,link=%22dummylink%22,' %5C%0A u'lifecycle_state=%22dummylifecycleState%22,' %5C%0A u'reason=%22dummystateChangeReason%22,reason_data=%22%7B%7D%22'%0A expected_dict = %5B'%5C%5C%22sub_alarm_expression%5C%5C%22:%5C%5C%22dummy_sub_alarm%5C%5C%22',%0A '%5C%5C%22metric_definition%5C%5C%22:%5C%5C%22dummy_definition%5C%5C%22',%0A '%5C%5C%22sub_alarm_state%5C%5C%22:%5C%5C%22dummy_state%5C%5C%22',%0A '%5C%5C%22current_values%5C%5C%22:%5C%5C%22dummy_values%5C%5C%22'%5D%0A actual_output = self.alarm_state_repo.process_message(message)%0A self.assertIn(expected_output, actual_output)%0A for elem in expected_dict:%0A self.assertIn(elem, actual_output)%0A
1cd457765727a0a65d02ddc9ea164af4913448c6
Create a python file
InternetOfThings101/main.py
InternetOfThings101/main.py
Python
0
@@ -0,0 +1,270 @@ +import time%0Aimport sys%0Aimport signal%0A%0Adef interruptHandler(signal, frame):%0A sys.exit(0)%0A%0Aif __name__ == '__main__':%0A%0A signal.signal(signal.SIGINT, interruptHandler)%0A%0A while True:%0A print %22Hello Internet of Things 101%22%0A time.sleep(5)%0A%0A# End of File%0A
2e9f43d1c1679355e2d7d452137ddf7fb2bbdedf
Test Basic.Publish -> Basic.Get message passing
tests/async-send-get-test.py
tests/async-send-get-test.py
Python
0
@@ -0,0 +1,1603 @@ +#!/usr/bin/env python%0A%22%22%22%0ASend a message and confirm you can retrieve it with Basic.Get%0ATest Steps:%0A%0A1) Connect to broker - start_test%0A2) Open Channel - on_connected%0A3) Delcare Queue - on_channel_open%0A4) Send test message - on_queue_declared%0A5) Call basic get - on_queue_declared%0A6) Validate that sent message and basic get body are the same - check_message%0A%22%22%22%0Aimport utils.async as async%0A%0Aimport nose%0Afrom pika.adapters import SelectConnection%0A%0Achannel = None%0Aconfirmed = False%0Aconnection = None%0Aqueue = None%0A%0AADAPTER = SelectConnection%0AHOST = 'localhost'%0APORT = 5672%0A%0A%0A@nose.tools.timed(2)%0Adef start_test():%0A global confirmed, connection%0A confirmed = False%0A connection = async.connect(ADAPTER, HOST, PORT, on_connected)%0A connection.ioloop.start()%0A if not confirmed:%0A assert False%0A pass%0A%0A@nose.tools.nottest%0Adef on_connected(connection):%0A global connected%0A connected = connection.is_open()%0A if connected:%0A async.channel(connection, on_channel_open)%0A%0A%0A@nose.tools.nottest%0Adef on_channel_open(channel_):%0A global channel, queue%0A channel = channel_%0A queue = async.queue_name()%0A async.queue_declare(channel, queue, on_queue_declared)%0A%0A%0A@nose.tools.nottest%0Adef on_queue_declared(frame):%0A global channel, queue%0A%0A test_message = async.send_test_message(channel, queue)%0A%0A def check_message(channel_number, method, header, body):%0A global connection, confirmed%0A if body == test_message:%0A confirmed = True%0A connection.ioloop.stop()%0A%0A channel.basic_get(callback=check_message, queue=queue)%0A
2cb8f7b2df2583c9fdb545744adad2386b4ee7f3
Add test for issue #2465 - tuple subsclass subscript
tests/basics/subscr_tuple.py
tests/basics/subscr_tuple.py
Python
0
@@ -0,0 +1,87 @@ +# subscripting a subclassed tuple%0Aclass Foo(tuple):%0A pass%0A%0Afoo = Foo((1,2))%0Afoo%5B0%5D%0A%0A
7d46f6e714be4b53a800c72f800d400ef6b280c4
add tests for core functions
tests/test_core_functions.py
tests/test_core_functions.py
Python
0
@@ -0,0 +1,1113 @@ +from pygelf import gelf%0Aimport json%0Aimport zlib%0Aimport struct%0Aimport pytest%0A%0A%0A@pytest.mark.parametrize('compress', %5BTrue, False%5D)%0Adef test_pack(compress):%0A message = %7B'version': '1.1', 'short_message': 'test pack'%7D%0A packed_message = gelf.pack(message, compress)%0A unpacked_message = zlib.decompress(packed_message) if compress else packed_message%0A unpacked_message = json.loads(unpacked_message.decode('utf-8'))%0A assert message == unpacked_message%0A%0A%0Adef test_split():%0A message = b'12345'%0A header = b'%5Cx1e%5Cx0f'%0A chunks = list(gelf.split(message, 2))%0A expected = %5B%0A (struct.pack('b', 0), struct.pack('b', 3), b'12'),%0A (struct.pack('b', 1), struct.pack('b', 3), b'34'),%0A (struct.pack('b', 2), struct.pack('b', 3), b'5')%0A %5D%0A%0A assert len(chunks) == len(expected)%0A%0A for index, chunk in enumerate(chunks):%0A expected_index, expected_chunks_count, expected_chunk = expected%5Bindex%5D%0A assert chunk%5B:2%5D == header%0A assert chunk%5B10:11%5D == expected_index%0A assert chunk%5B11:12%5D == expected_chunks_count%0A assert chunk%5B12:%5D == expected_chunk%0A
2c665dbcb90785b9754f89cb6a0d3d9c3ffddc95
Add test
tests/test_proxy_nca_loss.py
tests/test_proxy_nca_loss.py
Python
0.000005
@@ -0,0 +1,2037 @@ +# -*- coding: utf-8 -*-%0A%22%22%22%0ACreated on Tue Feb 07 19:23:18 2017%0A%0A@author: sakurai%0A%22%22%22%0A%0A%0Aimport unittest%0A%0Aimport numpy as np%0A%0Aimport chainer%0Afrom chainer import cuda%0Afrom chainer import gradient_check%0Afrom chainer import testing%0Afrom chainer.testing import attr%0Aimport chainer.functions as F%0A%0Afrom deep_metric_learning.lib.functions.proxy_nca_loss import proxy_nca_loss%0A%0A%0Aclass TestProxyNcaLoss(unittest.TestCase):%0A%0A def setUp(self):%0A batch_size = 5%0A n_classes = 10%0A out_dims = 3%0A self.x_data = np.random.randn(batch_size, out_dims).astype(np.float32)%0A # x_data is assumed that each vector is L2 normalized%0A self.x_data /= np.linalg.norm(self.x_data, axis=1, keepdims=True)%0A self.proxy_data = np.random.randn(%0A n_classes, out_dims).astype(np.float32)%0A self.labels_data = np.random.choice(n_classes, batch_size)%0A%0A def check_forward(self, x_data, proxy_data, labels_data):%0A x = chainer.Variable(x_data)%0A proxy = chainer.Variable(proxy_data)%0A%0A x = F.normalize(x)%0A loss = proxy_nca_loss(x, proxy, labels_data)%0A self.assertEqual(loss.dtype, np.float32)%0A%0A def test_forward_cpu(self):%0A self.check_forward(self.x_data, self.proxy_data, self.labels_data)%0A%0A @attr.gpu%0A def test_forward_gpu(self):%0A self.check_forward(cuda.to_gpu(self.x_data),%0A cuda.to_gpu(self.proxy_data),%0A self.labels_data)%0A%0A def check_backward(self, x_data, proxy_data, labels_data):%0A gradient_check.check_backward(%0A lambda x, p: proxy_nca_loss(x, p, labels_data),%0A (x_data, proxy_data), None, atol=1.e-1)%0A%0A def test_backward_cpu(self):%0A self.check_backward(self.x_data, self.proxy_data, self.labels_data)%0A%0A @attr.gpu%0A def test_backward_gpu(self):%0A self.check_backward(cuda.to_gpu(self.x_data),%0A cuda.to_gpu(self.proxy_data),%0A self.labels_data)%0A%0A%0Atesting.run_module(__name__, __file__)%0A
703a5556174706db330c8d2e426471e490a00cef
Switch rottentomatoes to xfail rather than skip test.
tests/test_rottentomatoes.py
tests/test_rottentomatoes.py
from __future__ import unicode_literals, division, absolute_import from nose.plugins.skip import SkipTest class TestRottenTomatoesLookup(object): config = """ tasks: test: mock: # tests search - {title: 'Toy Story'} - {title: 'The Matrix'} - {title: 'Star Wars: Episode I - The Phantom Menace (3D)'} # tests direct id - {title: '[Group] Taken 720p', rt_id: 770680780} # tests title + year - {title: 'Rush.Hour[1998]1080p[Eng]-FOO'} # test short title, with repack and without year - {title: 'Up.REPACK.720p.Bluray.x264-FlexGet'} rottentomatoes_lookup: yes """ def test_rottentomatoes_lookup(self, execute_task, use_vcr): raise SkipTest('This plugin seems to be broken') task = execute_task('test') # check that these were created assert task.find_entry(rt_name='Toy Story', rt_year=1995, rt_id=9559, imdb_id='tt0114709'), \ 'Didn\'t populate RT info for Toy Story' assert task.find_entry(imdb_id='tt0114709'), \ 'Didn\'t populate imdb_id info for Toy Story' assert task.find_entry(rt_name='The Matrix', rt_year=1999, rt_id=12897, imdb_id='tt0133093'), \ 'Didn\'t populate RT info for The Matrix' assert task.find_entry(rt_name='Star Wars: Episode I - The Phantom Menace', rt_year=1999, rt_id=10008), \ 'Didn\'t populate RT info for Star Wars: Episode I - The Phantom Menace (in 3D)' assert task.find_entry(rt_name='Taken', rt_year=2008, rt_id=770680780), \ 'Didn\'t populate RT info for Taken' assert task.find_entry(rt_name='Rush Hour', rt_year=1998, rt_id=10201), \ 'Didn\'t populate RT info for Rush Hour' assert task.find_entry(rt_name='Up', rt_year=2009, rt_id=770671912), \ 'Didn\'t populate RT info for Up'
Python
0
@@ -65,50 +65,24 @@ rt%0A%0A -from nose.plugins.skip import -SkipT +pyt est%0A%0A%0A -%0A clas @@ -723,16 +723,80 @@ %22%22%22%0A%0A + @pytest.mark.xfail(reason='This plugin seems to be broken')%0A def @@ -856,65 +856,8 @@ r):%0A - raise SkipTest('This plugin seems to be broken')%0A
ecdda7cf81cb3feb353a1d62441eff92aed082af
Add aggregationtypes to routes
iatidataquality/aggregationtypes.py
iatidataquality/aggregationtypes.py
Python
0.000001
@@ -0,0 +1,3204 @@ +%0A# IATI Data Quality, tools for Data QA on IATI-formatted publications%0A# by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith%0A#%0A# Copyright (C) 2013 Publish What You Fund%0A#%0A# This programme is free software; you may redistribute and/or modify%0A# it under the terms of the GNU Affero General Public License v3.0%0A%0Afrom flask import Flask, render_template, flash, request, Markup, %5C%0A session, redirect, url_for, escape, Response, abort, send_file%0Aimport StringIO%0Afrom flask.ext.sqlalchemy import SQLAlchemy%0Afrom flask.ext.login import (LoginManager, current_user, login_required,%0A login_user, logout_user, UserMixin, AnonymousUser,%0A confirm_login, fresh_login_required)%0Afrom sqlalchemy import func%0Afrom datetime import datetime%0A%0Afrom iatidataquality import app%0Afrom iatidataquality import db%0A%0Aimport os%0Aimport sys%0Aimport json%0A%0Acurrent = os.path.dirname(os.path.abspath(__file__))%0Aparent = os.path.dirname(current)%0Asys.path.append(parent)%0A%0Afrom iatidq import dqtests, dqaggregationtypes%0A%0Aimport StringIO%0Aimport unicodecsv%0A%0A@app.route(%22/aggregationtypes/%22)%0A@app.route(%22/aggregationtypes/%3Caggregationtype_id%3E/%22)%0Adef aggregationtypes(aggregationtype_id=None):%0A ats=dqaggregationtypes.aggregationTypes()%0A return render_template(%22aggregation_types.html%22, aggregationtypes=ats)%0A%0A@app.route(%22/aggregationtypes/new/%22, methods=%5B'POST', 'GET'%5D)%0A@app.route(%22/aggregationtypes/%3Caggregationtype_id%3E/edit/%22, methods=%5B'POST', 'GET'%5D)%0Adef aggregationtypes_edit(aggregationtype_id=None):%0A if aggregationtype_id:%0A if request.method=='POST':%0A data = %7B%0A 'name': request.form%5B'name'%5D,%0A 'description': request.form%5B'description'%5D,%0A 'test_id': request.form%5B'test_id'%5D,%0A 'test_result': request.form%5B'test_result'%5D%0A %7D%0A if data%5B'test_id'%5D==%22%22:%0A data%5B'test_id'%5D = None%0A aggregationtype = dqaggregationtypes.updateAggregationType(aggregationtype_id, data)%0A if aggregationtype:%0A flash('Successfully updated your aggregation type.', 'success')%0A else:%0A aggregationtype = %7B%7D%0A flash('Could not update your aggregation type.', 'error')%0A else:%0A aggregationtype=dqaggregationtypes.aggregationTypes(aggregationtype_id)%0A else:%0A aggregationtype = %7B%7D%0A if request.method=='POST':%0A data = %7B%0A 'name': request.form%5B'name'%5D,%0A 'description': request.form%5B'description'%5D,%0A 'test_id': request.form%5B'test_id'%5D,%0A 'test_result': request.form%5B'test_result'%5D%0A %7D%0A if data%5B'test_id'%5D==%22%22:%0A data%5B'test_id'%5D = None%0A aggregationtype = dqaggregationtypes.addAggregationType(data)%0A if aggregationtype:%0A flash('Successfully added your aggregation type.', 'success')%0A else:%0A aggregationtype = %7B%7D%0A flash('Could not add your aggregation type.', 'error')%0A tests = dqtests.tests()%0A return render_template(%22aggregation_types_edit.html%22, aggregationtype=aggregationtype, tests=tests)%0A
e7e51333133dd561e8a746144c29c6635d8a982a
Add migration to add column for proposal image filename
migrations/versions/320f4eb0698b_add_proposal_image.py
migrations/versions/320f4eb0698b_add_proposal_image.py
Python
0
@@ -0,0 +1,622 @@ +%22%22%22add proposal image%0A%0ARevision ID: 320f4eb0698b%0ARevises: 26ef95fc6f2c%0ACreate Date: 2015-03-31 15:55:20.062624%0A%0A%22%22%22%0A%0A# revision identifiers, used by Alembic.%0Arevision = '320f4eb0698b'%0Adown_revision = '26ef95fc6f2c'%0A%0Afrom alembic import op%0Aimport sqlalchemy as sa%0A%0A%0Adef upgrade():%0A ### commands auto generated by Alembic - please adjust! ###%0A op.add_column('proposal', sa.Column('image', sa.String(length=150), nullable=False))%0A ### end Alembic commands ###%0A%0A%0Adef downgrade():%0A ### commands auto generated by Alembic - please adjust! ###%0A op.drop_column('proposal', 'image')%0A ### end Alembic commands ###%0A
4990f7c761382654c7577e8c23527ea3c1f8a773
Patch for saving the pose
models/tridimensional/docking_validation/mutate_pdb.py
models/tridimensional/docking_validation/mutate_pdb.py
import os from rosetta import * from toolbox import mutate_residue def mutate_pose(pose, mutations): """Applies list of mutations to the given template pose and returns a mutated version Args: pose: PyRosetta Pose() object representing a loaded pdb structure mutations: list of amino acid swaps to apply, format is: [(int, char), ..., (int, char)] where char is a string of length 1 in "ACDEFGHIKLMNPQRSTVWY" Returns: mutant_pose containing the specified amino acid swaps Notes: - this procedure doesn't modify the input pose """ mutant_pose = Pose() mutant_pose.assign(pose) for aa_num, aa_replacement in mutations: # ensure mutation is valid and apply it assert isinstance(aa_num, int) assert isinstance(aa_replacement, str) and len(aa_replacement) == 1 mutant_pose = mutate_residue(mutant_pose, aa_num, aa_replacement) # specify a pose packer to repack the mutation region pose_packer = standard_packer_task(mutant_pose) pose_packer.restrict_to_repacking() # ================================= # mark's hack segment # ================================= # This is a hack, but I want to test. Can't set a movemap, resfiles # might be the way to go. Freeze all residues. pose_packer.temporarily_fix_everything() # Let's release the PI domain for i in range(1110, 1388): pose_packer.temporarily_set_pack_residue(i, True) # ================================= # specify the rotamer mover and apply repacking packmover = PackRotamersMover(get_fa_scorefxn(), pose_packer) packmover.apply(mutant_pose) return mutant_pose def mutate_pdb(input_pdb_path, mutations, output_directory, output_id): """Create a new pdb (<output_filename>.pdb) in the output directory containing specified mutations Args: input_pdb_path: [string] pdb file for template pose (apply mutations to the template) mutations: list of amino acid swaps to apply, format is: [(int, char), ..., (int, char)] where str is a character in "ACDEFGHIKLMNPQRSTVWY" output_directory: [string] directory to store output pdb file in (e.g. "mutants/some_category/") output_id: [string] filename of mutant, do not include ".pdb" (e.g. "some_mutant_id") Returns: full filepath to the output pdb with the specified mutations """ assert os.path.isfile(input_pdb_path) pose_template = pose_from_pdb(input_pdb_path) pose_mutant = mutate_pose(pose_template, mutations) if not os.path.exists(output_directory): os.makedirs(output_directory) output_pdb_path = os.path.join(output_directory, output_id + ".pdb") pose_mutant.dump(output_pdb_path) return output_pdb_path if __name__ == '__main__': print "main behaviour not yet implemented"
Python
0
@@ -2756,16 +2756,20 @@ ant.dump +_pdb (output_
2233b8cb2e59e4304492b60eb9842962130e14c2
Create NoisyNeighborsClosedForm.py
NoisyNeighborsClosedForm.py
NoisyNeighborsClosedForm.py
Python
0
@@ -0,0 +1,2180 @@ +# Google Code Jam%0A# Google Code Jam 2015%0A# Round 1B%0A# Problem B. Noisy Neighbors%0A%0A# Closed form solution O(1)%0A%0Afrom math import ceil%0A%0AtestCaseFile = open(%22NoisyNeighbors_B-large-practice.in%22, %22r%22)%0Alines = testCaseFile.read().split('%5Cn')%0An = int(lines%5B0%5D)%0AtestCases = %5B0 for x in range(n)%5D%0A%0Aclass TestCase:%0A def __init__(self, r, c, n):%0A self.row = r%0A self.column = c%0A self.tenant = n%0A %0A def compute_min_unhappiness(self):%0A r = self.row%0A c = self.column%0A n = self.tenant%0A width = int(min(r,c))%0A %0A unhappinessAtFull = (r-1)*c+(c-1)*r%0A maxNAtZero = ceil(r*c/2)%0A %0A if (width == 1): %0A if ((r*c)%252==0): %0A if (n%3C=maxNAtZero): return 0%0A else: return 2*(n-maxNAtZero)-1%0A else: %0A if (n%3C=maxNAtZero): return 0%0A else: return 2*(n-maxNAtZero)%0A else: %0A minNAtMinusFour = r*c - ceil((r-2)*(c-2)/2)%0A if ((r*c)%252==0): %0A if (n%3C=maxNAtZero): return 0%0A elif (n%3C=maxNAtZero+2): return 2*(n-maxNAtZero)%0A elif (n%3CminNAtMinusFour): return 3*(n-maxNAtZero)-2%0A else: return unhappinessAtFull - 4*(r*c-n)%0A else:%0A minNAtMinusThree = minNAtMinusFour - (r+c-6)%0A if (n%3C=maxNAtZero): return 0%0A elif (n%3CminNAtMinusThree): return 3*(n-maxNAtZero)%0A elif (n%3CminNAtMinusFour): return unhappinessAtFull - 4*(r*c-minNAtMinusFour) - 3*(minNAtMinusFour-n)%0A else: return unhappinessAtFull - 4*(r*c-n)%0A%0Adef initialize_test_cases(lines):%0A global testCases%0A for index, item in enumerate(lines):%0A if index %3E 0: %0A items = item.split(' ')%0A if (len(items) %3E 1): %0A r = int(items%5B0%5D)%0A c = int(items%5B1%5D)%0A n = int(items%5B2%5D)%0A testCases%5Bindex - 1%5D = TestCase(r, c, n)%0A %0Adef print_all_results():%0A for x in range(len(testCases)):%0A print('Case #' + str(x+1) + ': ' + str(testCases%5Bx%5D.compute_min_unhappiness()))%0A%0Ainitialize_test_cases(lines)%0Aprint_all_results()%0A
f39947677bc2eaf15a0a9d5ef976a29905b23339
Add AirQuality notification
PushAirQuality.py
PushAirQuality.py
Python
0
@@ -0,0 +1,644 @@ +from twitter import *%0Afrom pushbullet import PushBullet%0Aimport config%0A%0ACONSUMER_KEY = config.twitter_consumer_key%0ACONSUMER_SECRET = config.twitter_consumer_secret%0AOAUTH_TOKEN = config.twitter_oauth_token%0AOAUTH_SECRET = config.twitter_oauth_secret%0Apb_api_key = config.pb_api_key%0A%0A%0Atwitter = Twitter(auth=OAuth(%0AOAUTH_TOKEN, OAUTH_SECRET, CONSUMER_KEY, CONSUMER_SECRET))%0Atweets = twitter.statuses.user_timeline(screen_name=%22CGShanghaiAir%22, count=1)%0Atext = tweets%5B0%5D%5B'text'%5D%0Apm25 = text.split(%22;%22)%5B3%5D%0Aif pm25 %3E 90:%0A%09pb = PushBullet(pb_api_key)%0A%09nexus6p = pb.get_device('Huawei Nexus 6P')%0A%09nexus6p.push_note('Shanghai Air Quality', text)%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A
d4b86bc3b4440d665eb8119828a9ffe241b321a6
Update 24-game.py
Python/24-game.py
Python/24-game.py
# Time: O(n^3 * 4^n) # Space: O(n^2) from fractions import Fraction from operator import * class Solution(object): def judgePoint24(self, nums): """ :type nums: List[int] :rtype: bool """ def dfs(nums): if len(nums) == 1: return nums[0] == 24 ops = [add, sub, mul, div] for i in xrange(len(nums)): for j in xrange(len(nums)): if i == j: continue for op in ops: if op == div and nums[j] == 0: continue next_nums = [nums[k] for k in xrange(len(nums)) if k not in [i, j]] next_nums.append(op(nums[i], nums[j])) if dfs(next_nums): return True return False return dfs(map(lambda x: Fraction(x, 1), nums))
Python
0
@@ -14,16 +14,23 @@ 3 * 4%5En) +, n = 4 %0A# Space
fcf0ed3c4e2deb9ce1d6a758dc18e6a03542eb59
Add a script to find parties with multiple emblems (logos) from the EC
candidates/management/commands/candidates_parties_with_multiple_emblems.py
candidates/management/commands/candidates_parties_with_multiple_emblems.py
Python
0
@@ -0,0 +1,842 @@ +from django.core.management.base import BaseCommand%0A%0Afrom candidates.popit import create_popit_api_object, popit_unwrap_pagination%0A%0Aclass Command(BaseCommand):%0A%0A def handle(self, *args, **options):%0A api = create_popit_api_object()%0A%0A for org in popit_unwrap_pagination(%0A api.organizations,%0A per_page=100%0A ):%0A org.pop('versions', None)%0A org.pop('memberships', None)%0A images = org.get('images', %5B%5D)%0A if len(images) %3C 2:%0A continue%0A print %22=====================================================%22%0A print len(images), org%5B'id'%5D, org%5B'name'%5D.encode('utf-8')%0A for image in images:%0A print ' --'%0A print ' ' + image%5B'notes'%5D.encode('utf-8')%0A print ' ' + image%5B'url'%5D%0A
0f6e065a70bcd1f9dd64dfa04c13cb0065e33c13
Add basic test for navigator
src/autobot/src/navigator_test.py
src/autobot/src/navigator_test.py
Python
0.000002
@@ -0,0 +1,1033 @@ +#!/usr/bin/env python%0Aimport unittest%0Aimport mock%0Afrom autobot.msg import detected_object%0Afrom navigator import *%0A%0A%0Adef fake_stopCar():%0A return True%0A%0A%0Adef fake_srvTogglePathFinder(state):%0A return%0A%0A%0Adef fake_setWallDist(dist, wall):%0A return%0A%0A%0Aclass NavigatorTest(unittest.TestCase):%0A @mock.patch('navigator.setWallDist',%0A side_effect=fake_setWallDist)%0A @mock.patch('navigator.srvTogglePathFinder',%0A side_effect=fake_srvTogglePathFinder)%0A @mock.patch('navigator.stopCar', side_effect=fake_stopCar)%0A def testPersonInFront(self, fake_stopCar,%0A fake_srvTogglePathFinder,%0A fake_setWallDist):%0A global OBJECT_MAP%0A global PATH_STATE%0A OBJECT_MAP.addToMap('person', 10, 50, 1.2)%0A OBJECT_MAP.addToMap('cat', 10, 50, 60)%0A OBJECT_MAP.addToMap('bat', 10, 50, 65)%0A PATH_STATE.enabled = True%0A onDecisionInterval(None)%0A fake_setWallDist.assert_not_called()%0A fake_stopCar.assert_called()%0A
bebe5ba7bddd0facf0f5d64d1123d1139fab789e
Remove line overwritting history
axelrod/tests/unit/test_player.py
axelrod/tests/unit/test_player.py
import copy import random import unittest import axelrod C, D = 'C', 'D' def cooperate(self): return 'C' def defect(self): return 'D' class TestPlayerClass(unittest.TestCase): name = "Player" player = axelrod.Player stochastic = False def test_add_noise(self): random.seed(1) noise = 0.2 s1, s2 = 'C', 'C' noisy_s1, noisy_s2 = self.player()._add_noise(noise, s1, s2) self.assertEqual(noisy_s1, 'D') self.assertEqual(noisy_s2, 'C') def test_play(self): p1, p2 = self.player(), self.player() p1.strategy = cooperate p2.strategy = defect p1.play(p2) self.assertEqual(p1.history[0], 'C') self.assertEqual(p2.history[0], 'D') def test_noisy_play(self): random.seed(1) noise = 0.2 p1, p2 = self.player(), self.player() p1.strategy = cooperate p2.strategy = defect p1.play(p2, noise) self.assertEqual(p1.history[0], 'D') self.assertEqual(p2.history[0], 'D') class MockPlayer(axelrod.Player): """Creates a mock player that enforces a particular next move for a given player.""" def __init__(self, player, move): # Need to retain history for opponents that examine opponents history # Do a deep copy just to be safe self.history = copy.copy(player.history) self.history = player.history self.move = move def strategy(self, opponent): # Just return the saved move return self.move def test_four_vector(test_class, expected_dictionary): """ Checks that two dictionaries match -- the four-vector defining a memory-one strategy and the given expected dictionary. """ P1 = test_class.player() for key in sorted(expected_dictionary.keys()): test_class.assertAlmostEqual( P1._four_vector[key], expected_dictionary[key]) def test_responses(test_class, P1, P2, history_1, history_2, responses, random_seed=None): """Test responses to arbitrary histories. Used for the the following tests in TestPlayer: first_play_test, markov_test, and responses_test. Works for arbitrary players as well. Input response_lists is a list of lists, each of which consists of a list for the history of player 1, a list for the history of player 2, and a list for the subsequent moves by player one to test.""" if random_seed: random.seed(random_seed) # Force the histories, In case either history is impossible or if some # internal state needs to be set, actually submit to moves to the strategy # method. Still need to append history manually. for h1, h2 in zip(history_1, history_2): P1.strategy(MockPlayer(P2, h2)) P2.strategy(MockPlayer(P1, h1)) P1.history.append(h1) P2.history.append(h2) # Run the tests for response in responses: test_class.assertEqual(P1.strategy(P2), response) class TestPlayer(unittest.TestCase): "A Test class from which other player test classes are inherited" name = "Player" player = axelrod.Player stochastic = False def test_initialisation(self): """Test that the player initiates correctly.""" self.assertEqual(self.player().history, []) self.assertEqual(self.player().stochastic, self.stochastic) def test_repr(self): """Test that the representation is correct.""" self.assertEquals(str(self.player()), self.name) def test_reset(self): """Make sure reseting works correctly.""" p = self.player() p.history = [C, C] p.reset() self.assertEquals(p.history, []) def test_strategy(self): """Test that strategy method.""" self.assertEquals(self.player().strategy(self.player()), None) def first_play_test(self, play, random_seed=None): """Tests first move of a strategy.""" P1 = self.player() P2 = axelrod.Player() test_responses( self, P1, P2, [], [], [play], random_seed=random_seed) def markov_test(self, responses, random_seed=None): """Test responses to the four possible one round histories. Input responses is simply the four responses to CC, CD, DC, and DD.""" # Construct the test lists histories = [ [[C], [C]], [[C], [D]], [[D], [C]], [[D], [D]]] for i, history in enumerate(histories): # Needs to be in the inner loop in case player retains some state P1 = self.player() P2 = axelrod.Player() test_responses(self, P1, P2, history[0], history[1], responses[i], random_seed=random_seed) def responses_test(self, history_1, history_2, responses, random_seed=None): """Test responses to arbitrary histories. Input response_list is a list of lists, each of which consists of a list for the history of player 1, a list for the history of player 2, and a list for the subsequent moves by player one to test.""" P1 = self.player() P2 = axelrod.Player() test_responses( self, P1, P2, history_1, history_2, responses, random_seed=random_seed) class TestHeadsUp(unittest.TestCase): """Test class for heads up play between two given players.""" def versus_test(self, player_1_class, player_2_class, outcomes, player_1_history=None, player_2_history=None, random_seed=None): """Tests a sequence of outcomes for two given players.""" if random_seed: random.seed(random_seed) player_1 = player_1_class() player_2 = player_2_class() # Set histories if player_1_history is None: player_1_history = [] player_1.history = player_1_history if player_2_history is None: player_2_history = [] player_2.history = player_2_history # Test sequence of play for outcome_1, outcome_2 in outcomes: player_1.play(player_2) self.assertEqual(player_1_history[-1], outcome_1) self.assertEqual(player_2_history[-1], outcome_2)
Python
0.000002
@@ -1387,46 +1387,8 @@ ry)%0A - self.history = player.history%0A
dc72a321311f213132ef448afecbe7a0797aede8
Fix for GLUT
vispy/app/tests/test_context.py
vispy/app/tests/test_context.py
import os from nose.tools import assert_equal, assert_raises from vispy.util.testing import requires_application, has_backend from vispy.app import Canvas from vispy.app.backends import BACKEND_NAMES from vispy.gloo import (get_gl_configuration, VertexShader, FragmentShader, Program, check_error) @requires_application() def test_context_properties(): """Test setting context properties""" contexts = (dict(double_buffer=False), # stereo won't work on every sys dict(samples=4), dict(stencil_size=8), dict(double_buffer=False, samples=4)) for context in contexts: n_items = len(context) with Canvas(context=context): if os.getenv('TRAVIS', 'false') == 'true': # Travis cannot handle obtaining these values props = context else: props = get_gl_configuration() assert_equal(len(context), n_items) for key, val in context.items(): assert_equal(val, props[key], key) assert_raises(TypeError, Canvas, context='foo') assert_raises(KeyError, Canvas, context=dict(foo=True)) assert_raises(TypeError, Canvas, context=dict(double_buffer='foo')) def test_context_sharing(): """Test context sharing""" can = list() cannot = list() for backend in BACKEND_NAMES: if has_backend(backend): if has_backend(backend, capable=['context']): can.append(backend) else: cannot.append(backend) for backend in can: with Canvas(app=backend) as c1: vert = VertexShader("uniform vec4 pos;" "void main (void) {gl_Position = pos;}") frag = FragmentShader("uniform vec4 pos;" "void main (void) {gl_FragColor = pos;}") program = Program(vert, frag) program['pos'] = [1, 2, 3, 4] program.activate() # should print def check(): program.activate() check_error() with Canvas(app=backend): if backend.lower() != 'pyglet': # pyglet always shares assert_raises(RuntimeError, check) with Canvas(app=backend, context=c1.context): check() for backend in cannot: with Canvas(app=backend) as c1: assert_raises(RuntimeError, Canvas, app=backend, context=c1.context)
Python
0.000001
@@ -1323,28 +1323,8 @@ t()%0A - cannot = list()%0A @@ -1357,45 +1357,8 @@ ES:%0A - if has_backend(backend):%0A @@ -1407,20 +1407,16 @@ ext'%5D):%0A - @@ -1447,60 +1447,119 @@ - else:%0A cannot.append(backend) +# We could also test backends that can't share contexts, but that's only%0A # GLUT and it doesn't test well :( %0A @@ -2348,178 +2348,4 @@ k()%0A - for backend in cannot:%0A with Canvas(app=backend) as c1:%0A assert_raises(RuntimeError, Canvas, app=backend,%0A context=c1.context)%0A
d11d7c38edef63e50dbd1da78a8829905a86c2a5
Add forgotten file
bluebottle/assignments/states.py
bluebottle/assignments/states.py
Python
0.000001
@@ -0,0 +1,309 @@ +from bluebottle.activities.states import ActivityStateMachine, ContributionStateMachine%0A%0Afrom bluebottle.assignments.models import Assignment, Applicant%0A%0A%0Aclass AssignmentStateMachine(ActivityStateMachine):%0A model = Assignment%0A%0A%0Aclass ApplicantStateMachine(ContributionStateMachine):%0A model = Applicant%0A
98f26afc012b1ab25360738776c36b58229d0b3a
Add CLI interface.
fulltext/__main__.py
fulltext/__main__.py
Python
0
@@ -0,0 +1,725 @@ +%22%22%22%0AFulltext CLI interface.%0A%22%22%22%0A%0Afrom __future__ import absolute_import%0A%0Aimport sys%0Aimport logging%0A%0Afrom docopt import docopt%0A%0Aimport fulltext%0A%0A%0Adef _handle_open(path):%0A with open(path, 'rb') as f:%0A return fulltext.get(f)%0A%0A%0Adef main(args=sys.argv%5B1:%5D):%0A %22%22%22%0A Extract text from a file.%0A%0A Usage:%0A fulltext %5B-f%5D %3Cpath%3E...%0A%0A Options:%0A -f Open file first.%0A %22%22%22%0A opt = docopt(main.__doc__.strip(), args, options_first=True)%0A%0A logger = logging.getLogger()%0A logger.addHandler(logging.StreamHandler())%0A%0A handler = fulltext.get%0A%0A if opt%5B'-f'%5D:%0A handler = _handle_open%0A%0A for path in opt%5B'%3Cpath%3E'%5D:%0A print(handler(path))%0A%0A%0Aif __name__ == '__main__':%0A main()%0A
5666161f59a8c3efa5b3f884912f9777c9a12edd
Add the ability to get template variables from the CLI
saliere/main.py
saliere/main.py
#!/usr/bin/python3 """Creates a skeleton for various projects based on Jinja2 templates. Example: $ main.py mysql -t salt-formula $ main.py mysql-django -t django $ main.py mysql -t salt-formula -o my-formula-directory $ main.py mysql -t ~/my/custom/template -o my-template-directory """ import argparse import os from saliere.config import Config from saliere.templatizer import Templatizer # Define a list of valid paths to look for the templates template_path_list = ['templates', '../templates', '/usr/local/share/saliere/templates'] def main(): # Create the parser. parser = argparse.ArgumentParser(description="Create a skeleton for your formula.") # Create the options. parser.add_argument("-n", "--name", help="the name of your project", type=str) parser.add_argument("-t", "--type", help="the type of your template or the path of a jinja template", type=str) parser.add_argument("-o", "--output", default=os.getcwd(), help="output directory (default is the current directory)", type=str) parser.add_argument("-l", "--list", action="store_true", help="list the available templates") parser.add_argument("-c", "--configfile", default='config.yml', help="file containing the template information (default: config.yml)", type=str) # Parse the arguments. args = parser.parse_args() # Create the templatizer object. t = Templatizer(template_path_list) # List the templates if asked to. if args.list: print("Available templates: \n\t" + "\n\t".join(t.list_templates())) exit(0) # Ensure the project name and project type are specified. if not args.name or not args.type: print("The template type and project name are required: -t type -n name.") exit(1) # Retrieve the template path. template_path = t.locate_template(args.type) if not template_path: print("The template name you specified does not exist.") exit(1) # Get the project type t.template_type = args.type # Load the template variables, if any, from the configuration file. config = Config() config.load_from_file(args.configfile) template_vars = config.get_value(args.type) # Call the copy function. t.copy(args.name, args.output, template_vars) if __name__ == '__main__': main()
Python
0
@@ -1332,16 +1332,97 @@ ype=str) +%0A parser.add_argument(%22--var%22, default=None, help=%22template values%22, type=str) %0A%0A # @@ -2154,16 +2154,251 @@ s.type%0A%0A + # Load the template variables, if any, from the command line.%0A if args.var:%0A vars_split = args.var.split('%7C')%0A vars_list = %5Bv.split('=', 1) for v in vars_split if '=' in v%5D%0A template_vars = dict(vars_list)%0A%0A # Lo @@ -2461,16 +2461,30 @@ n file.%0A + else:%0A conf @@ -2497,16 +2497,20 @@ onfig()%0A + conf @@ -2544,16 +2544,20 @@ igfile)%0A + temp
1dc11286b21d8a84e3d1d9a194cc49275be4d97d
Add core models example factories
apps/core/factories.py
apps/core/factories.py
Python
0
@@ -0,0 +1,1335 @@ +from factory import Faker, Iterator, SubFactory%0Afrom factory.django import DjangoModelFactory%0A%0Afrom apps.data.factories import EntryFactory, RepositoryFactory%0Afrom . import models%0A%0A%0Aclass SpeciesFactory(DjangoModelFactory):%0A%0A name = Faker('word')%0A reference = SubFactory(EntryFactory)%0A repository = SubFactory(RepositoryFactory)%0A description = Faker('text', max_nb_chars=300)%0A%0A class Meta:%0A model = 'core.Species'%0A django_get_or_create = ('name', )%0A%0A%0Aclass StrainFactory(DjangoModelFactory):%0A%0A name = Faker('word')%0A description = Faker('text', max_nb_chars=300)%0A species = SubFactory(SpeciesFactory)%0A reference = SubFactory(EntryFactory)%0A%0A class Meta:%0A model = 'core.Strain'%0A django_get_or_create = ('name', )%0A%0A%0Aclass OmicsUnitTypeFactory(DjangoModelFactory):%0A%0A name = Faker('word')%0A description = Faker('text', max_nb_chars=300)%0A%0A class Meta:%0A model = 'core.OmicsUnitType'%0A django_get_or_create = ('name', )%0A%0A%0Aclass OmicsUnitFactory(DjangoModelFactory):%0A%0A reference = SubFactory(EntryFactory)%0A strain = SubFactory(StrainFactory)%0A type = SubFactory(OmicsUnitTypeFactory)%0A status = Iterator(s%5B0%5D for s in models.OmicsUnit.STATUS_CHOICES)%0A%0A class Meta:%0A model = 'core.OmicsUnit'%0A django_get_or_create = ('reference', 'strain')%0A
38e231076209f0d71ee64bd4d60e1769aac8ce93
add raspberry pi receiver script
power_monitor_rf24.py
power_monitor_rf24.py
Python
0
@@ -0,0 +1,1909 @@ +#!/usr/bin/env python%0A%0A# receive values from CS5460A power monitor via NRF24L01%0A# may need to run as sudo%0A# see https://github.com/zerog2k/power_meter_cs5460a for arduino transmitter code%0A%0Aimport time as time%0Afrom RF24 import *%0Aimport RPi.GPIO as GPIO%0Aimport binascii%0Aimport struct%0Afrom datetime import datetime, date%0A%0AMSGTYPES = %5B %22MSG_POWER_METER%22 %5D%0A%0Airq_gpio_pin = None%0A%0A########### USER CONFIGURATION ###########%0A# See https://github.com/TMRh20/RF24/blob/master/RPi/pyRF24/readme.md%0A%0A# CE Pin, CSN Pin, SPI Speed%0A%0A#RPi B+%0A# Setup for GPIO 22 CE and CE0 CSN for RPi B+ with SPI Speed @ 8Mhz%0Aradio = RF24(RPI_BPLUS_GPIO_J8_15, RPI_BPLUS_GPIO_J8_24, BCM2835_SPI_SPEED_1MHZ)%0A%0A# Setup for connected IRQ pin, GPIO 24 on RPi B+; uncomment to activate%0A#irq_gpio_pin = RPI_BPLUS_GPIO_J8_18%0A#irq_gpio_pin = 24%0A%0Apipes = %5B0x4A454E5300%5D%0A%0Aradio.begin()%0A%0Aradio.setChannel( 1 )%0A# set datarate %0Aradio.setDataRate( RF24_250KBPS )%0A#radio.setPALevel(RF24_PA_MAX)%0Aradio.enableDynamicPayloads()%0A%0Aradio.printDetails()%0A%0Aradio.openReadingPipe(0, pipes%5B0%5D)%0Aradio.startListening()%0A%0Adt = datetime%0A%0Apipenum = -1%0A%0A# forever loop%0Awhile True:%0A try:%0A have_data, pipenum = radio.available_pipe()%0A if have_data:%0A len = radio.getDynamicPayloadSize()%0A if len %3E 0:%0A msgtype = radio.read(1);%0A receive_payload = radio.read(len)%0A%0A if msgtype%5B0%5D == MSGTYPES.index(%22MSG_POWER_METER%22):%0A (voltage, current, true_power, power_factor) = struct.unpack_from(%22ffff%22, receive_payload, 1)%0A print %22%25s pipe: %25d, msgtype: %25s, voltage: %250.1f, current: %250.2f, true_power: %250.1f, PF: %250.2f%22 %5C%0A %25 (dt.now(), pipenum, MSGTYPES%5Bmsgtype%5B0%5D%5D, voltage, current, true_power, power_factor)%0A else:%0A print %22%25s got: pipe=%25d size=%25s raw=%25s%22 %25 (dt.now(), pipenum, len, binascii.hexlify(receive_payload))%0A time.sleep(1)%0A except Exception as e:%0A print e.strerror%0A%0A%0A
3b33a9410bac5b710a52e603fd40ed88765b7414
Create colecoes.py
colecoes/colecoes.py
colecoes/colecoes.py
Python
0
@@ -0,0 +1,360 @@ +from aula5.pessoa import import Pessoa%0Afrom aula6.pessoas_tipos import Homem, Mulher%0A%0Aif __name__=='__main__':%0A gomes = Homem('Gomes')%0A gomes_igual = Homem('Gomes')%0A gomes_identico=gomes%0A selina=Mulher('Selina')%0A print(gomes is gomes_igual)%0A print(gomes is gomes_identico)%0A print(gomes == gomes_igual)%0A print(gomes == gomes_identico)%0A
0f06b139ecfbdb05dee86b4cbda5b23c9af4379a
test private name
chap5/test_private_name_coven.py
chap5/test_private_name_coven.py
Python
0.000011
@@ -0,0 +1,255 @@ +#!/usr/bin/python%0A# -*- indent-tabs-mode: nil; tab-width: 4 -*-%0A# vi: et ts=4 sts=4 sw=4%0Aclass Foo:%0A def __priv(self):%0A print %22I'm private%22%0A%0Adef main():%0A foo = Foo()%0A getattr(Foo, '_Foo__priv')(foo)%0A%0Aif __name__ == '__main__':%0A main()%0A%0A
c48bf268ec7e077443ad347f007d7477d841cc04
Add ds_binary_heap.py
ds_binary_heap.py
ds_binary_heap.py
Python
0.000853
@@ -0,0 +1,237 @@ +from __future__ import absolute_import%0Afrom __future__ import division%0Afrom __future__ import print_function%0A%0Aclass BinaryHeap(object):%0A def __init__(self):%0A pass%0A%0A%0Adef main():%0A pass%0A%0A%0Aif __name__ == '__main__':%0A main()%0A%0A
cd1c67c34768bdef0cc4649573e2541558e648ad
Add : Basic client implementation
elevator/client.py
elevator/client.py
Python
0
@@ -0,0 +1,1308 @@ +#!/usr/bin/env python%0A#Copyright (c) 2011 Fabula Solutions. All rights reserved.%0A#Use of this source code is governed by a BSD-style license that can be%0A#found in the license.txt file.%0A%0A# leveldb client%0Aimport zmq%0Aimport threading%0Aimport time%0Aimport ujson as json%0A%0Aclass Elevator(object):%0A def __init__(self, host=%22tcp://127.0.0.1:4141%22, timeout=10*1000):%0A self.host = host%0A self.timeout = timeout%0A self.connect()%0A%0A%0A def __del__(self):%0A self.close()%0A%0A%0A def connect(self):%0A self.context = zmq.Context()%0A self.socket = self.context.socket(zmq.XREQ)%0A self.socket.connect(self.host)%0A%0A%0A def Get(self, key):%0A self.socket.send_multipart(%5B'GET', json.dumps(%5Bkey%5D)%5D)%0A return self.socket.recv_multipart()%5B0%5D%0A%0A%0A def Put(self, key, value):%0A self.socket.send_multipart(%5B'PUT', json.dumps(%5Bkey, value%5D)%5D)%0A return self.socket.recv_multipart()%5B0%5D%0A%0A%0A def Delete(self, key):%0A self.socket.send_multipart(%5B'DELETE', json.dumps(%5Bkey%5D)%5D)%0A return self.socket.recv_multipart()%5B0%5D%0A%0A%0A def Range(self, start=None, end=None):%0A self.socket.send_multipart(%5B'RANGE', json.dumps(%5Bstart, end%5D)%5D)%0A return self.socket.recv_multipart()%5B0%5D%0A%0A%0A def close(self):%0A self.socket.close()%0A self.context.term()%0A
fc40c3f740f9f5dedbcddd4dcbd274c76aaba529
Add ToS script
output/tos.py
output/tos.py
Python
0
@@ -0,0 +1,961 @@ +#!/usr/bin/python%0D%0A# -*- coding: utf-8 -*-%0D%0A%0D%0A%22%22%22tos.py - Accept PokemonGo ToS for multiple accounts using file.%22%22%22%0D%0A%0D%0Afrom pgoapi import PGoApi%0D%0Afrom pgoapi.utilities import f2i%0D%0Afrom pgoapi import utilities as util%0D%0Afrom pgoapi.exceptions import AuthException%0D%0Aimport pprint%0D%0Aimport time%0D%0Aimport threading%0D%0Aimport sys, getopt%0D%0A%0D%0Adef accept_tos(username, password):%0D%0A api = PGoApi()%0D%0A api.set_position(40.7127837, -74.005941, 0.0)%0D%0A api.login('ptc', username, password)%0D%0A time.sleep(2)%0D%0A req = api.create_request()%0D%0A req.mark_tutorial_complete(tutorials_completed = 0, send_marketing_emails = False, send_push_notifications = False)%0D%0A response = req.call()%0D%0A print('Accepted Terms of Service for %7B%7D'.format(username))%0D%0A%0D%0Awith open(str(sys.argv%5B1%5D)) as f:%0D%0A credentials = %5Bx.strip().split(' ') for x in f.readlines()%5D%0D%0A%0D%0Afor username,password in credentials:%0D%0A accept_tos(username, password)
db4f449be99d7b66bd7c46a1a3af8b46424421c6
Add tests for DummyCurrentPlaylistController.get_by_{id,uri}
tests/backends/get_test.py
tests/backends/get_test.py
Python
0
@@ -0,0 +1,1739 @@ +import unittest%0A%0Afrom mopidy.backends.dummy import DummyBackend, DummyCurrentPlaylistController%0Afrom mopidy.models import Playlist, Track%0A%0Aclass CurrentPlaylistGetTest(unittest.TestCase):%0A def setUp(self):%0A self.b = DummyBackend()%0A self.c = self.b.current_playlist%0A%0A def test_get_by_id_returns_unique_match(self):%0A track = Track(id=1)%0A self.c.playlist = Playlist(tracks=%5BTrack(id=13), track, Track(id=17)%5D)%0A self.assertEqual(track, self.c.get_by_id(1))%0A%0A def test_get_by_id_returns_first_of_multiple_matches(self):%0A track = Track(id=1)%0A self.c.playlist = Playlist(tracks=%5BTrack(id=13), track, track%5D)%0A self.assertEqual(track, self.c.get_by_id(1))%0A%0A def test_get_by_id_raises_keyerror_if_no_match(self):%0A self.c.playlist = Playlist(tracks=%5BTrack(id=13), Track(id=17)%5D)%0A try:%0A self.c.get_by_id(1)%0A self.fail(u'Should raise KeyError if no match')%0A except KeyError:%0A pass%0A%0A def test_get_by_uri_returns_unique_match(self):%0A track = Track(uri='a')%0A self.c.playlist = Playlist(%0A tracks=%5BTrack(uri='z'), track, Track(uri='y')%5D)%0A self.assertEqual(track, self.c.get_by_uri('a'))%0A%0A def test_get_by_uri_returns_first_of_multiple_matches(self):%0A track = Track(uri='a')%0A self.c.playlist = Playlist(tracks=%5BTrack(uri='z'), track, track%5D)%0A self.assertEqual(track, self.c.get_by_uri('a'))%0A%0A def test_get_by_uri_raises_keyerror_if_no_match(self):%0A self.c.playlist = Playlist(tracks=%5BTrack(uri='z'), Track(uri='y')%5D)%0A try:%0A self.c.get_by_uri('a')%0A self.fail(u'Should raise KeyError if no match')%0A except KeyError:%0A pass%0A
069a031ce871125fb727a5ec43f406539be0150f
add .mdown ext in check_ext
simiki/utils.py
simiki/utils.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function from os import path as osp RESET_COLOR = "\033[0m" COLOR_CODES = { "debug" : "\033[1;34m", # blue "info" : "\033[1;32m", # green "warning" : "\033[1;33m", # yellow "error" : "\033[1;31m", # red "critical" : "\033[1;41m", # background red } def color_msg(level, msg): return COLOR_CODES[level] + msg + RESET_COLOR def check_path_exists(path): """Check if the path(include file and directory) exists""" if osp.exists(path): return True return False def check_extension(filename): """Filter file by suffix If the file suffix not in the allowed suffixes, the return true and filter. The `fnmatch` module can also get the suffix: patterns = ["*.md", "*.mkd", "*.markdown"] fnmatch.filter(files, pattern) """ # Allowed suffixes ( aka "extensions" ) exts = {".md", ".mkd", ".markdown"} return osp.splitext(filename)[1] in exts if __name__ == "__main__": print(color_msg("debug", "DEBUG")) print(color_msg("info", "DEBUG")) print(color_msg("warning", "WARNING")) print(color_msg("error", "ERROR")) print(color_msg("critical", "CRITICAL"))
Python
0.000001
@@ -934,16 +934,26 @@ %22.mkd%22, + %22.mdown%22, %22.markd
f68c673273acbc62259213ceb47bb34e7d3f87fd
Create combination_test.py
test/combination_test.py
test/combination_test.py
Python
0.000004
@@ -0,0 +1,779 @@ +%0Adef loop(array_input, com_len, head, array_output):%0A n= com_len-1;sign=range(head+1,head+com_len)%0A while(sign%5Bn-1%5D%3C=len(array_input)-n):%0A core(head,sign, n,array_input,array_output)%0A sign=%5Bx + 1 for x in sign%5D %0A%0A %0Adef core(head, sign, n, array_input,array_output): %0A fetch=sign%5Bn-1%5D%0A array_child=%5Barray_input%5Bhead%5D%5D.extend(array_input%5Bsign%5B0%5D:fetch%5D) %0A while fetch %3C len(array_input):%0A i=0%0A array_child%5Bn-1%5D=array_input%5Bfetch%5D%0A array_output.append(array_child)%0A fetch+=1%0A i+=1 %0A%0Aif __name__ == %22__main__%22:%0A array_input=%5B1,2,3,4,5%5D; com_len=3; array_output=%5B%5D%0A for head in range(0,len(array_input)-com_len+2):%0A loop(array_input, com_len, head,array_output)%0A %0A print array_output%0A
cc7ff0ef2ce94b0ac39af4c03d08f8a82bc2ff53
Print installation instruction
tests/sync_test_megacli.py
tests/sync_test_megacli.py
""" Application for testing syncing algorithm (c) 2013-2014 by Mega Limited, Wellsford, New Zealand This file is part of the MEGA SDK - Client Access Engine. Applications using the MEGA API must present a valid application key and comply with the the rules set forth in the Terms of Service. The MEGA SDK is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. @copyright Simplified (2-clause) BSD License. You should have received a copy of the license along with this program. """ import sys import os import time import shutil import unittest import xmlrunner import subprocess import re from sync_test_app import SyncTestApp from sync_test import SyncTest import logging import argparse class SyncTestMegaCliApp(SyncTestApp): """ operates with megacli application """ def __init__(self, local_mount_in, local_mount_out, delete_tmp_files=True, use_large_files=True, check_if_alive=True): """ local_mount_in: local upsync folder local_mount_out: local downsync folder """ self.work_dir = os.path.join(".", "work_dir") SyncTestApp.__init__(self, local_mount_in, local_mount_out, self.work_dir, delete_tmp_files, use_large_files) self.check_if_alive = check_if_alive def sync(self): time.sleep(5) def start(self): # try to create work dir return True def finish(self): try: shutil.rmtree(self.work_dir) except OSError, e: logging.error("Failed to remove dir: %s (%s)" % (self.work_dir, e)) def is_alive(self): """ return True if application instance is running """ if not self.check_if_alive: return True s = subprocess.Popen(["ps", "axw"], stdout=subprocess.PIPE) for x in s.stdout: if re.search("megacli", x): return True return False def pause(self): """ pause application """ # TODO: implement this ! raise NotImplementedError("Not Implemented !") def unpause(self): """ unpause application """ # TODO: implement this ! raise NotImplementedError("Not Implemented !") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--test1", help="test_create_delete_files", action="store_true") parser.add_argument("--test2", help="test_create_rename_delete_files", action="store_true") parser.add_argument("--test3", help="test_create_delete_dirs", action="store_true") parser.add_argument("--test4", help="test_create_rename_delete_dirs", action="store_true") parser.add_argument("--test5", help="test_sync_files_write", action="store_true") parser.add_argument("--test6", help="test_local_operations", action="store_true") parser.add_argument("--test7", help="test_update_mtime", action="store_true") parser.add_argument("--test8", help="test_create_rename_delete_unicode_files_dirs", action="store_true") parser.add_argument("-a", "--all", help="run all tests", action="store_true") parser.add_argument("-b", "--basic", help="run basic, stable tests", action="store_true") parser.add_argument("-d", "--debug", help="use debug output", action="store_true") parser.add_argument("-l", "--large", help="use large files for testing", action="store_true") parser.add_argument("-n", "--nodelete", help="Do not delete work files", action="store_false") parser.add_argument("-c", "--check", help="Do not check if megacli is running (useful, if other application is used for testing)", action="store_false") parser.add_argument("upsync_dir", help="local upsync directory") parser.add_argument("downsync_dir", help="local downsync directory") args = parser.parse_args() if args.debug: lvl = logging.DEBUG else: lvl = logging.INFO if args.all: args.test1 = args.test2 = args.test3 = args.test4 = args.test5 = args.test6 = args.test7 = args.test8 = True if args.basic: args.test1 = args.test2 = args.test3 = args.test4 = True logging.StreamHandler(sys.stdout) logging.basicConfig(format='[%(asctime)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=lvl) logging.info("") logging.info("1) Start the first [megacli] and run the following command: sync " + args.upsync_dir + " [remote folder]") logging.info("2) Start the second [megacli] and run the following command: sync " + args.downsync_dir + " [remote folder]") logging.info("3) Wait for both folders get fully synced") logging.info("4) Run: python %s", sys.argv[0]) logging.info("") time.sleep(5) with SyncTestMegaCliApp(args.upsync_dir, args.downsync_dir, args.nodelete, args.large, args.check) as app: suite = unittest.TestSuite() if args.test1: suite.addTest(SyncTest("test_create_delete_files", app)) if args.test2: suite.addTest(SyncTest("test_create_rename_delete_files", app)) if args.test3: suite.addTest(SyncTest("test_create_delete_dirs", app, )) if args.test4: suite.addTest(SyncTest("test_create_rename_delete_dirs", app)) if args.test5: suite.addTest(SyncTest("test_sync_files_write", app)) if args.test6: suite.addTest(SyncTest("test_local_operations", app)) if args.test7: suite.addTest(SyncTest("test_update_mtime", app)) if args.test8: suite.addTest(SyncTest("test_create_rename_delete_unicode_files_dirs", app)) testRunner = xmlrunner.XMLTestRunner(output='test-reports') testRunner.run(suite)
Python
0
@@ -4777,24 +4777,151 @@ ng.info(%22%22)%0A + logging.info(%22 Make sure you have unittest module installed: pip install unittest-xml-reporting%22)%0A logging.info(%22%22)%0A time.sle
c9b61a3f2599826d17f8a667837b0663be0ce6d0
Revert "TEST: isposinf and isneginf is now also tested with complex values"
numpy/lib/tests/test_ufunclike.py
numpy/lib/tests/test_ufunclike.py
from __future__ import division, absolute_import, print_function import numpy as np import numpy.core as nx import numpy.lib.ufunclike as ufl from numpy.testing import ( assert_, assert_equal, assert_array_equal, assert_warns ) class TestUfunclike(object): def test_isposinf(self): for dtype in [np.float, np.complex]: a = nx.array([nx.inf, -nx.inf, nx.nan, 0.0, 3.0, -3.0], dtype=dtype) out = nx.zeros(a.shape, bool) tgt = nx.array([True, False, False, False, False, False]) res = ufl.isposinf(a) assert_equal(res, tgt) res = ufl.isposinf(a, out) assert_equal(res, tgt) assert_equal(out, tgt) def test_isneginf(self): for dtype in [np.float, np.complex]: a = nx.array([nx.inf, -nx.inf, nx.nan, 0.0, 3.0, -3.0], dtype=dtype) out = nx.zeros(a.shape, bool) tgt = nx.array([False, True, False, False, False, False]) res = ufl.isneginf(a) assert_equal(res, tgt) res = ufl.isneginf(a, out) assert_equal(res, tgt) assert_equal(out, tgt) def test_fix(self): a = nx.array([[1.0, 1.1, 1.5, 1.8], [-1.0, -1.1, -1.5, -1.8]]) out = nx.zeros(a.shape, float) tgt = nx.array([[1., 1., 1., 1.], [-1., -1., -1., -1.]]) res = ufl.fix(a) assert_equal(res, tgt) res = ufl.fix(a, out) assert_equal(res, tgt) assert_equal(out, tgt) assert_equal(ufl.fix(3.14), 3) def test_fix_with_subclass(self): class MyArray(nx.ndarray): def __new__(cls, data, metadata=None): res = nx.array(data, copy=True).view(cls) res.metadata = metadata return res def __array_wrap__(self, obj, context=None): obj.metadata = self.metadata return obj def __array_finalize__(self, obj): self.metadata = getattr(obj, 'metadata', None) return self a = nx.array([1.1, -1.1]) m = MyArray(a, metadata='foo') f = ufl.fix(m) assert_array_equal(f, nx.array([1, -1])) assert_(isinstance(f, MyArray)) assert_equal(f.metadata, 'foo') # check 0d arrays don't decay to scalars m0d = m[0,...] m0d.metadata = 'bar' f0d = ufl.fix(m0d) assert_(isinstance(f0d, MyArray)) assert_equal(f0d.metadata, 'bar') def test_deprecated(self): # NumPy 1.13.0, 2017-04-26 assert_warns(DeprecationWarning, ufl.fix, [1, 2], y=nx.empty(2)) assert_warns(DeprecationWarning, ufl.isposinf, [1, 2], y=nx.empty(2)) assert_warns(DeprecationWarning, ufl.isneginf, [1, 2], y=nx.empty(2)) def test_scalar(self): x = np.inf actual = np.isposinf(x) expected = np.True_ assert_equal(actual, expected) assert_equal(type(actual), type(expected)) x = -3.4 actual = np.fix(x) expected = np.float64(-3.0) assert_equal(actual, expected) assert_equal(type(actual), type(expected)) out = np.array(0.0) actual = np.fix(x, out=out) assert_(actual is out)
Python
0
@@ -295,57 +295,8 @@ f):%0A - for dtype in %5Bnp.float, np.complex%5D:%0A @@ -353,35 +353,18 @@ 0, -3.0%5D -, dtype=dtype)%0A +)%0A @@ -393,36 +393,32 @@ , bool)%0A - - tgt = nx.array(%5B @@ -460,36 +460,32 @@ alse%5D)%0A%0A - res = ufl.isposi @@ -486,28 +486,24 @@ isposinf(a)%0A - asse @@ -521,36 +521,32 @@ s, tgt)%0A - - res = ufl.isposi @@ -556,36 +556,32 @@ a, out)%0A - assert_equal(res @@ -579,36 +579,32 @@ equal(res, tgt)%0A - assert_e @@ -652,57 +652,8 @@ f):%0A - for dtype in %5Bnp.float, np.complex%5D:%0A @@ -714,27 +714,10 @@ 3.0%5D -, dtype=dtype)%0A +)%0A @@ -754,28 +754,24 @@ ol)%0A - - tgt = nx.arr @@ -817,36 +817,32 @@ alse%5D)%0A%0A - res = ufl.isnegi @@ -843,28 +843,24 @@ isneginf(a)%0A - asse @@ -882,28 +882,24 @@ gt)%0A - - res = ufl.is @@ -913,36 +913,32 @@ a, out)%0A - assert_equal(res @@ -940,28 +940,24 @@ l(res, tgt)%0A - asse
d4d5ef52cf7ac9f40bb8ada199b6c035690eacfa
Add tests for transmission
rpihelper/transmission/tests.py
rpihelper/transmission/tests.py
Python
0
@@ -0,0 +1,1456 @@ +# -*- coding: utf-8 -*-%0A%0Aimport transmissionrpc%0A%0Afrom unittest import TestCase%0Afrom unittest.mock import patch, MagicMock%0A%0Afrom rpihelper.transmission.logic import (%0A transmissionrpc_client, transmissionrpc_add_torrent,%0A)%0A%0A__all__ = (%0A 'TransmissionrpcClientLogicTests',%0A 'TransmissionrpcAddTorrentLogicTests',%0A)%0A%0A%0Adef raise_exception(*args, **kwargs):%0A raise transmissionrpc.error.TransmissionError%0A%0A%0Aclass TransmissionrpcClientLogicTests(TestCase):%0A @patch('rpihelper.transmission.logic.transmissionrpc.Client')%0A def test_ok(self, mock_client):%0A tc = transmissionrpc_client()%0A%0A mock_client.assert_called_once()%0A self.assertTrue(isinstance(tc, MagicMock))%0A%0A @patch('rpihelper.transmission.logic.transmissionrpc.Client', new=raise_exception)%0A def test_transmission_error(self):%0A tc = transmissionrpc_client()%0A self.assertIsNone(tc)%0A%0A%0Aclass TransmissionrpcAddTorrentLogicTests(TestCase):%0A def test_ok(self):%0A tc = MagicMock()%0A tc_add_torrent = MagicMock()%0A tc.add_torrent = tc_add_torrent%0A%0A success = transmissionrpc_add_torrent(tc, 'fake_file')%0A tc_add_torrent.assert_called_once()%0A self.assertTrue(success)%0A%0A def test_transmission_error(self):%0A tc = MagicMock()%0A tc_add_torrent = raise_exception%0A tc.add_torrent = tc_add_torrent%0A%0A success = transmissionrpc_add_torrent(tc, 'fake_file')%0A self.assertFalse(success)%0A
cb1e797c6039a1677024a563852b117b581faaf2
Add solution of problem 1 in Python
problem1/rumen.py
problem1/rumen.py
Python
0.998909
@@ -0,0 +1,64 @@ +sum(filter(lambda x: x %25 3 == 0 or x %25 5 == 0, range(1, 1000)))%0A
cb82fd05c02b97bfc82668164fe3f3bb22faaade
Add fair and square
2013/qualification_round/fair_and_square.py
2013/qualification_round/fair_and_square.py
Python
0.002189
@@ -0,0 +1,2063 @@ +#!/usr/bin/env python%0A# Need solve time complexity%0A%0Afrom __future__ import print_function%0Afrom collections import deque%0A%0Adef count_fair_and_square_numbers(a, b):%0A count = 0%0A n = a%0A while n %3C= b:%0A if is_fair_and_square(n):%0A count += 1%0A n += 1%0A return count%0A%0Adef is_fair_and_square(n):%0A assert isinstance(n, int) or isinstance(n, long)%0A if is_palindrome(n):%0A if is_square(n):%0A return is_palindrome(int(n ** 0.5))%0A else:%0A return False%0A else:%0A return False%0A%0Adef is_square(n):%0A assert isinstance(n, int) or isinstance(n, long)%0A%0A if 0 %3C= n %3C= 1:%0A return True%0A%0A x = n // 2%0A seen = set(%5Bx%5D)%0A while x ** 2 != n:%0A x = (x + (n // x)) // 2%0A if x in seen:%0A return False%0A seen.add(x)%0A return True%0A%0Adef is_palindrome(n):%0A assert isinstance(n, int) or isinstance(n, long)%0A dq = deque(str(n))%0A dq.reverse()%0A n_ = int(''.join(dq))%0A return n == n_%0A%0Aif __name__ == '__main__':%0A import os%0A%0A print(is_square(152415789666209426002111556165263283035677489))%0A%0A samples = %5B%0A (1, 4),%0A (10, 120),%0A (100, 1000)%0A %5D%0A%0A for sample in samples:%0A print(count_fair_and_square_numbers(*sample))%0A%0A data_files = %5B'C-small-practice', 'C-large-practice-1', 'C-large-practice-2'%5D%0A for f in data_files:%0A with open(os.path.join(os.path.dirname(os.path.realpath(__file__)),%0A '%7B0%7D.in'.format(f)), 'r') as input_file:%0A lines = input_file.readlines()%0A input_count = int(lines%5B0%5D.replace('%5Cn' ,''))%0A inputs = %5Bline.replace('%5Cn', '') for line in lines%5B1:%5D%5D%0A%0A i = 1%0A with open(os.path.join(os.path.dirname(os.path.realpath(__file__)),%0A '%7B0%7D.out'.format(f)), 'w') as output_file:%0A for in_ in inputs:%0A a, b = tuple(%5Bint(_) for _ in in_.split(' ')%5D)%0A print(a, b)%0A output_file.write('Case #%7B0%7D: %7B1%7D%5Cn'.format(i, count_fair_and_square_numbers(a, b)))%0A i += 1%0A
8a245ab951e1c5a72e8a14a8bb95d3f1d3a549ee
Hello World
pyexamples/conditions.py
pyexamples/conditions.py
Python
0.99998
@@ -0,0 +1,22 @@ +print ('Hello World')%0A
463b20a1fa6740e6db2c8abac3861fa9a30f9a2e
Add Django 1.4.1 as a support version to suppress warning.
src/reversion/__init__.py
src/reversion/__init__.py
""" Transactional version control for Django models. Developed by Dave Hall. <http://www.etianen.com/> """ import django, warnings from reversion.revisions import default_revision_manager, revision_context_manager, VersionAdapter from reversion.admin import VersionAdmin from reversion.models import pre_revision_commit, post_revision_commit from reversion.version import __version__ VERSION = __version__ SUPPORTED_DJANGO_VERSIONS = ( (1, 4, 0), ) def check_django_version(): """Checks the version of django being used, and issues a warning if incorrect.""" if django.VERSION[:3] not in SUPPORTED_DJANGO_VERSIONS: format_version = lambda v: u".".join(unicode(n) for n in v) warnings.warn( ( u"django-reversion %(reversion_version)s is intended for use with django %(supported_django_version)s. " u"You are running django %(django_version)s, so some features, such as admin integration, may not work. " u"Please see https://github.com/etianen/django-reversion/wiki/Compatible-Django-Versions" ) % { "reversion_version": format_version(VERSION), "supported_django_version": ' or '.join(format_version(v) for v in SUPPORTED_DJANGO_VERSIONS), "django_version": format_version(django.VERSION[:3]), } ) check_django_version() # Legacy revision reference. revision = default_revision_manager # TODO: Deprecate eventually. # Easy registration methods. register = default_revision_manager.register is_registered = default_revision_manager.is_registered unregister = default_revision_manager.unregister get_adapter = default_revision_manager.get_adapter get_registered_models = default_revision_manager.get_registered_models # Context management. create_revision = revision_context_manager.create_revision # Revision meta data. get_db = revision_context_manager.get_db set_db = revision_context_manager.set_db get_user = revision_context_manager.get_user set_user = revision_context_manager.set_user get_comment = revision_context_manager.get_comment set_comment = revision_context_manager.set_comment add_meta = revision_context_manager.add_meta get_ignore_duplicates = revision_context_manager.get_ignore_duplicates set_ignore_duplicates = revision_context_manager.set_ignore_duplicates # Low level API. get_for_object_reference = default_revision_manager.get_for_object_reference get_for_object = default_revision_manager.get_for_object get_unique_for_object = default_revision_manager.get_unique_for_object get_for_date = default_revision_manager.get_for_date get_deleted = default_revision_manager.get_deleted
Python
0
@@ -453,16 +453,31 @@ 4, 0),%0A + (1, 4, 1),%0A )%0A%0Adef c
0b445c9606d30f31a6df1d99ef4d564f931014f2
use unittest
python/calc/calc_test.py
python/calc/calc_test.py
Python
0.000001
@@ -0,0 +1,384 @@ +import unittest%0Afrom calc import Calc%0A%0Aclass CalcTest(unittest.TestCase):%0A def setUp(self):%0A print %22Calc Test%22%0A def test_add(self):%0A c = Calc()%0A x = 100%0A y = 200%0A result = 0%0A result = c.add(x,y)%0A print '%7B0%7D + %7B1%7D = %7B2%7D'.format(x, y, result)%0A self.assertEqual(x + y, result)%0A%0Aif __name__ == '__main__':%0A unittest.main()%0A
4972930bb42ed6d7ebc1bad2909ede1a3c213cec
Add preprocessing functions.
preprocess.py
preprocess.py
Python
0.000001
@@ -0,0 +1,529 @@ +import numpy as np%0A%0A%22%22%22This file contains some functions related to preprocessing.%22%22%22%0A%0Adef get_output_array_from_labels(output_labels, labels_encoding=None):%0A%09labels = np.unique(output_labels)%0A%09labels = labels.reshape(len(labels), 1)%0A%09outputs = np.zeros((output_labels.shape%5B0%5D, labels.shape%5B0%5D))%0A%0A%09if not labels_encoding:%0A%09%09labels_encoding = np.concatenate(%0A%09%09%09%5Blabels, np.eye(labels.shape%5B0%5D)%5D, axis=1)%0A%0A%09for enc in labels_encoding:%0A%09%09indices = np.where(output_labels == enc%5B0%5D)%0A%09%09outputs%5Bindices%5B0%5D%5D = enc%5B1:%5D%0A%09return outputs%0A
c1d66909a6ce9903aa0a856d80721c756bc54806
test for neo4j
test/test_neo4j_graph.py
test/test_neo4j_graph.py
Python
0.000001
@@ -0,0 +1,762 @@ +#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A%0A# from py2neo import neo4j, node, rel%0Afrom bulbs.config import DEBUG%0Afrom bulbs.neo4jserver import Graph, Config, NEO4J_URI%0Afrom message import Message, IsRetweet # models%0Afrom datetime import datetime%0A%0A# setup %0Aconfig = Config(NEO4J_URI, %22james%22, %22secret%22)%0Ag = Graph(config)%0A# g.config.set_logger(DEBUG)%0A%0A# g.add_proxy(%22message%22, Message)%0Ag.add_proxy(%22tweet%22, Message)%0Ag.add_proxy(%22isRT%22, IsRetweet)%0A%0A# create node%0Am1= g.tweet.create(text=%22salut%22,created_at=datetime.now())%0Am2= g.tweet.create(text=%22re-salut%22,created_at=datetime.now())%0A%0A# nodes = g.tweet.index.lookup(text=%22salut%22)%0A%0A# create edge%0Art=g.isRT.create(m2,m1)%0A%0A# Connect to neo4j%0A# graph_db = neo4j.GraphDatabaseService(%22http://localhost:7474/db/data/%22%0A
9ff3b324a2ca82378e0b9d51515941d62d00109c
fix handling of missing collections in API
aleph/views/entities_api.py
aleph/views/entities_api.py
from flask import Blueprint, request from apikit import obj_or_404, jsonify, request_data, arg_bool from apikit import get_limit, get_offset, Pager from sqlalchemy import func, not_ from aleph import authz from aleph.model import Entity, Collection, db from aleph.logic import update_entity from aleph.views.cache import enable_cache from aleph.search import entities_query, execute_entities_query from aleph.search import suggest_entities, similar_entities from aleph.text import latinize_text blueprint = Blueprint('entities_api', __name__) def check_authz(entity, permission): permissions = authz.collections(permission) for collection in entity.collections: if collection.id in permissions: return authz.require(False) def get_collections(data): collections = [] for coll_id in data.get('collection_id'): if isinstance(coll_id, dict): coll_id = coll_id.get('id') collections.append(coll_id) return Collection.all_by_ids(collections).all() @blueprint.route('/api/1/entities', methods=['GET']) def index(): q = entities_query(request.args) q['size'] = get_limit(default=50) q['from'] = get_offset() doc_counts = arg_bool('doc_counts') res = execute_entities_query(request.args, q, doc_counts=doc_counts) return jsonify(res) @blueprint.route('/api/1/entities/_all', methods=['GET']) def all(): q = Entity.all() q = q.filter(Entity.state == Entity.STATE_ACTIVE) clause = Collection.id.in_(authz.collections(authz.READ)) q = q.filter(Entity.collections.any(clause)) q = q.order_by(Entity.id.asc()) return jsonify(Pager(q, limit=100)) @blueprint.route('/api/1/entities', methods=['POST', 'PUT']) def create(): data = request_data() data.pop('id', None) data['collections'] = get_collections(data) for collection in data['collections']: authz.require(authz.collection_write(collection.id)) entity = Entity.save(data) for collection in entity.collections: collection.touch() db.session.commit() update_entity(entity) return view(entity.id) @blueprint.route('/api/1/entities/_suggest', methods=['GET']) def suggest(): collections = authz.collections(authz.READ) enable_cache(vary=collections, server_side=False) return jsonify(suggest_entities(request.args)) @blueprint.route('/api/1/entities/_pending', methods=['GET']) def pending(): q = db.session.query(Entity) skip_entities = request.args.getlist('skip') if len(skip_entities): q = q.filter(not_(Entity.id.in_(skip_entities))) q = q.filter(Entity.state == Entity.STATE_PENDING) clause = Collection.id.in_(authz.collections(authz.READ)) q = q.filter(Entity.collections.any(clause)) # this was too slow to actually work: # ref = aliased(Reference) # q = q.join(ref) # q = q.group_by(Entity) # q = q.order_by(func.count(ref.id).desc()) q = q.order_by(func.random()) q = q.limit(30) entities = [] for entity in q.all(): data = entity.to_dict() data['name_latin'] = latinize_text(entity.name, lowercase=False) entities.append(data) return jsonify({'results': entities, 'total': len(entities)}) @blueprint.route('/api/1/entities/<id>', methods=['GET']) def view(id): entity = obj_or_404(Entity.by_id(id)) check_authz(entity, authz.READ) return jsonify(entity) @blueprint.route('/api/1/entities/<id>/similar', methods=['GET']) def similar(id): entity = obj_or_404(Entity.by_id(id)) check_authz(entity, authz.READ) return jsonify(similar_entities(entity, request.args)) @blueprint.route('/api/1/entities/_lookup', methods=['GET']) def lookup(): entity = obj_or_404(Entity.by_identifier(request.args.get('scheme'), request.args.get('identifier'))) check_authz(entity, authz.READ) return jsonify(entity) @blueprint.route('/api/1/entities/<id>', methods=['POST', 'PUT']) def update(id): entity = obj_or_404(Entity.by_id(id)) check_authz(entity, authz.WRITE) data = request_data() data['id'] = entity.id possible_collections = authz.collections(authz.WRITE) possible_collections.extend([c.id for c in entity.collections]) data['collections'] = [c for c in get_collections(data) if c.id in possible_collections] entity = Entity.save(data, merge=arg_bool('merge')) for collection in entity.collections: collection.touch() db.session.commit() update_entity(entity) return view(entity.id) @blueprint.route('/api/1/entities/<id>/merge/<other_id>', methods=['DELETE']) def merge(id, other_id): entity = obj_or_404(Entity.by_id(id)) check_authz(entity, authz.WRITE) other = obj_or_404(Entity.by_id(other_id)) check_authz(other, authz.WRITE) entity.merge(other) db.session.commit() update_entity(entity) update_entity(other) return view(entity.id) @blueprint.route('/api/1/entities/<id>', methods=['DELETE']) def delete(id): entity = obj_or_404(Entity.by_id(id)) check_authz(entity, authz.WRITE) entity.delete() db.session.commit() update_entity(entity) return jsonify({'status': 'ok'})
Python
0.000001
@@ -810,22 +810,23 @@ -for coll +ection _id -in += dat @@ -847,16 +847,55 @@ ion_id') + or %5B%5D%0A for coll_id in collection_id :%0A
09f1cf984a456a4a452f1a1c0a0ff6fd09b7b415
add code.py
code.py
code.py
Python
0.000008
@@ -0,0 +1,20 @@ +print 'Hello GitHub'
a5012c9fb81768e85b555b52264baa11efc17ba1
Add unittest for select_taxa that runs main and selects a single genome
test/test_select_taxa.py
test/test_select_taxa.py
Python
0
@@ -0,0 +1,814 @@ +import logging%0Aimport os%0Aimport tempfile%0Aimport unittest%0A%0Aimport select_taxa%0A%0A%0Aclass Test(unittest.TestCase):%0A%0A def setUp(self):%0A self.longMessage = True%0A logging.root.setLevel(logging.DEBUG)%0A%0A def test_main(self):%0A '''%0A Select a single genome and assert the download log file contains the correct output for it.%0A '''%0A # Setup arguments%0A target = tempfile.mktemp()%5B1%5D%0A try:%0A args = ('--genomes=13960 --genomes-file=' + target).split()%0A%0A # Write to argument file%0A select_taxa.main(args)%0A%0A # Assert contents%0A with open(target) as reader:%0A contents = reader.read()%0A self.assertIn('17745.1%5CtEscherichia coli E24377A', contents)%0A finally:%0A os.remove(target)%0A
b5207cfcee8bd3f1a41fc87f3e9afcfe94646314
Add example of how to list of codecs.
src/swig/python/codecs.py
src/swig/python/codecs.py
Python
0
@@ -0,0 +1,475 @@ +#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A%0A# Import required modules%0Aimport mlt%0A%0A# Start the mlt system%0Amlt.Factory().init( )%0A%0A# Create the consumer%0Ac = mlt.Consumer( mlt.Profile(), %22avformat%22 )%0A%0A# Ask for video codecs supports%0Ac.set( 'vcodec', 'list' )%0A%0A# Start the consumer to generate the list%0Ac.start()%0A%0A# Get the vcodec property%0Acodecs = mlt.Properties( c.get_data( 'vcodec' ) )%0A%0A# Print the list of codecs%0Afor i in range( 0, codecs.count()):%0A%09print codecs.get( i )%0A
872e2a38845d8a9d321435092f808e2eb79a26e3
test case for issue #9
tests/test_formatters.py
tests/test_formatters.py
Python
0
@@ -0,0 +1,1567 @@ +import os%0Afrom unittest import TestCase%0Afrom textwrap import dedent%0A%0Aimport pyexcel as pe%0A%0A%0Aclass TestAutoDetectInt(TestCase):%0A def setUp(self):%0A self.content = %5B%5B1,2,3.1%5D%5D%0A self.test_file = %22test_auto_detect_init.ods%22%0A pe.save_as(array=self.content, dest_file_name=self.test_file)%0A%0A def test_auto_detect_int(self):%0A sheet = pe.get_sheet(file_name=self.test_file)%0A expected = dedent(%22%22%22%0A pyexcel_sheet1:%0A +---+---+-----+%0A %7C 1 %7C 2 %7C 3.1 %7C%0A +---+---+-----+%22%22%22).strip()%0A self.assertEqual(str(sheet), expected)%0A%0A def test_get_book_auto_detect_int(self):%0A book = pe.get_book(file_name=self.test_file)%0A expected = dedent(%22%22%22%0A pyexcel_sheet1:%0A +---+---+-----+%0A %7C 1 %7C 2 %7C 3.1 %7C%0A +---+---+-----+%22%22%22).strip()%0A self.assertEqual(str(book), expected)%0A%0A def test_auto_detect_int_false(self):%0A sheet = pe.get_sheet(file_name=self.test_file, auto_detect_int=False)%0A expected = dedent(%22%22%22%0A pyexcel_sheet1:%0A +-----+-----+-----+%0A %7C 1.0 %7C 2.0 %7C 3.1 %7C%0A +-----+-----+-----+%22%22%22).strip()%0A self.assertEqual(str(sheet), expected)%0A%0A def test_get_book_auto_detect_int_false(self):%0A book = pe.get_book(file_name=self.test_file, auto_detect_int=False)%0A expected = dedent(%22%22%22%0A pyexcel_sheet1:%0A +-----+-----+-----+%0A %7C 1.0 %7C 2.0 %7C 3.1 %7C%0A +-----+-----+-----+%22%22%22).strip()%0A self.assertEqual(str(book), expected)%0A%0A def tearDown(self):%0A os.unlink(self.test_file)%0A
5692f64619bf009cf92bf0a8c6f77bf82f0e3d02
Add a new regression testing module
tests/test_regression.py
tests/test_regression.py
Python
0.000001
@@ -0,0 +1,1134 @@ +# Copyright: See the LICENSE file.%0A%0A%0A%22%22%22Regression tests related to issues found with the project%22%22%22%0A%0Aimport datetime%0Aimport typing as T%0Aimport unittest%0A%0Aimport factory%0A%0A# Example objects%0A# ===============%0A%0A%0Aclass Author(T.NamedTuple):%0A fullname: str%0A pseudonym: T.Optional%5Bstr%5D = None%0A%0A%0Aclass Book(T.NamedTuple):%0A title: str%0A author: Author%0A%0A%0Aclass PublishedBook(T.NamedTuple):%0A book: Book%0A published_on: datetime.date%0A countries: T.List%5Bstr%5D%0A%0A%0Aclass FakerRegressionTests(unittest.TestCase):%0A def test_locale_issue(self):%0A %22%22%22Regression test for %60KeyError: 'locale'%60%0A%0A See #785 #786 #787 #788 #790 #796.%0A %22%22%22%0A class AuthorFactory(factory.Factory):%0A class Meta:%0A model = Author%0A%0A class Params:%0A unknown = factory.Trait(%0A fullname=%22%22,%0A )%0A%0A fullname = factory.Faker(%22name%22)%0A%0A public_author = AuthorFactory(unknown=False)%0A self.assertIsNone(public_author.pseudonym)%0A%0A unknown_author = AuthorFactory(unknown=True)%0A self.assertEqual(%22%22, unknown_author.fullname)%0A
58354f477decff942a3063a12fb72684beca8233
Add singleton tests
tests/test_singletons.py
tests/test_singletons.py
Python
0.000001
@@ -0,0 +1,1132 @@ +# coding=utf-8%0Afrom __future__ import absolute_import%0Afrom __future__ import division%0Afrom __future__ import print_function%0Afrom __future__ import unicode_literals%0A%0Aimport unittest%0A%0Aimport properties%0Afrom properties.extras import Singleton%0A%0A%0Aclass TestSingleton(unittest.TestCase):%0A%0A def test_singleton(self):%0A%0A a = Singleton('a')%0A b = Singleton('a')%0A c = Singleton('c')%0A%0A assert a is b%0A assert a is not c%0A%0A d = properties.copy(c)%0A%0A assert d is c%0A%0A e = Singleton.deserialize(d.serialize())%0A assert e is d%0A%0A class AnotherSingleton(Singleton):%0A pass%0A%0A with self.assertRaises(ValueError):%0A AnotherSingleton('a')%0A%0A def test_hassingleton(self):%0A%0A class HasSingleton(properties.HasProperties):%0A%0A s = properties.Instance('', Singleton)%0A%0A hs1 = HasSingleton()%0A hs2 = HasSingleton()%0A hs3 = HasSingleton()%0A%0A hs1.s = 'a'%0A hs2.s = Singleton('a')%0A hs3.s = %7B'name': 'a'%7D%0A%0A assert hs1.s is hs2.s%0A assert hs1.s is hs3.s%0A%0A%0Aif __name__ == '__main__':%0A unittest.main()%0A
b93b8d96114338809e6a082f819291144eedd4af
add an utils to reduce the original dataset to a choosen class samples size
reduce_dataset.py
reduce_dataset.py
Python
0.000002
@@ -0,0 +1,1728 @@ +import sys, os%0Afrom shutil import copyfile%0A%0Asupplied_args = sys.argv%5B1:%5D%0A%0ADATA_DIRECTORY = %22data_dir%22%0ANEW_DATA_DIRECTORY = supplied_args%5B0%5D if supplied_args else sys.exit(%22You need to supplied a new data directory name : $python reduce_dataset.py %3Cnew data directory name%3E %3Cmax sample by class%3E%22)%0AMAX_SAMPLE_BY_CLASS = int(supplied_args%5B1%5D) if len(supplied_args) %3E 1 else sys.exit(%22You need to supplied the max sample number by class you want : $python reduce_dataset.py %3Cnew data directory name%3E %3Cmax sample by class%3E%22)%0A%0Aif not os.path.exists(DATA_DIRECTORY):%0A sys.exist(%22The default data directory %25s doesn't exist, please create it and store in it your default dataset.%22 %25 DATA_DIRECTORY)%0A%0Aif not os.path.exists(NEW_DATA_DIRECTORY):%0A os.makedirs(NEW_DATA_DIRECTORY)%0Aclasses = %7B%7D%0A%0Adirectories_it = os.scandir(DATA_DIRECTORY)%0Afor entry in directories_it: %0A if entry.is_file():%0A continue%0A %0A subdir_new_path = os.path.join(NEW_DATA_DIRECTORY, entry.name)%0A subdir_path = os.path.join(DATA_DIRECTORY, entry.name)%0A%0A if not os.path.exists(subdir_new_path):%0A os.makedirs(subdir_new_path)%0A %0A classes%5Bentry.name%5D = 0%0A%0A files_it = os.scandir(subdir_path) %0A for file in files_it:%0A if MAX_SAMPLE_BY_CLASS %3E classes%5Bentry.name%5D:%0A file_src = os.path.join(subdir_path, file.name)%0A file_dest = os.path.join(subdir_new_path, file.name)%0A copyfile(file_src, file_dest)%0A classes%5Bentry.name%5D += 1%0A else:%0A break%0A%0Aclasses_count = len(classes)%0Aprint( %22%25d classes with a maximum of %25d samples were successfuly copied from %25s directory to %25s directory.%22 %25 (classes_count, MAX_SAMPLE_BY_CLASS, DATA_DIRECTORY, NEW_DATA_DIRECTORY))%0A
ab164307310474625926bbc9ea7fae03b99c99cf
Create architecture core models
opps/core/models/__init__.py
opps/core/models/__init__.py
Python
0.000001
@@ -0,0 +1,104 @@ +# -*- coding: utf-8 -*-%0Afrom opps.core.models.channel import *%0Afrom opps.core.models.publisher import *%0A
9fde684095ba34300fcade827dfb17eae99f4daa
add advanced.py
renew/advanced.py
renew/advanced.py
Python
0.000001
@@ -0,0 +1,133 @@ +%0Adef fib(max):%0A%09a, b, n = 0, 1, 0%0A%09while n %3C max:%0A%09%09yield b%0A%09%09a, b = b, a + b%0A%09%09n += 1%0A%0A%09print('done')%0A%0Afor i in fib(20):%0A%09print(i)%0A%0A
fab91baa976693f89c6001a0e09e0f351d30ccfe
add decorator timeout test
test/test_decorator.py
test/test_decorator.py
Python
0.000001
@@ -0,0 +1,575 @@ +# coding=utf-8%0Aimport unittest%0Afrom decorators.decorator import *%0Aimport time%0A%0A%0Aclass TestDecorator(unittest.TestCase):%0A def test_timeout(self):%0A @timeout(1)%0A def test_timeout_no_params():%0A time.sleep(2)%0A self.assertTrue()%0A%0A test_timeout_no_params()%0A%0A @timeout(1)%0A def test_timeout_with_params(*args, **kwargs):%0A self.assertEqual(args, (1, 2, 3))%0A self.assertEqual(kwargs, %7B'a': 1, 'b': 2%7D)%0A%0A test_timeout_with_params(1, 2, 3, a=1, b=2)%0A%0A%0Aif __name__ == '__main__':%0A unittest.main()%0A
db85c1a9aca124ef4cf45c61244c6cf556138d77
Add cmd.py script
python/cmd.py
python/cmd.py
Python
0.000002
@@ -0,0 +1,1011 @@ +#!/usr/bin/env python3%0A%0A# Copyright (c) 2014, Ruslan Baratov%0A# All rights reserved.%0A%0Aimport argparse%0Aimport os%0Aimport stat%0Aimport subprocess%0Aimport sys%0A%0Aimport detail.os%0Aimport detail.command%0A%0Aassert(sys.version_info.major == 3)%0A%0Aparser = argparse.ArgumentParser(description='Start windows cmd')%0Aargs = parser.parse_args()%0A%0Aexplorer_cygpath = detail.command.get_absolute_path('explorer')%0Aexplorer_winpath = detail.os.cygwin_to_win(explorer_cygpath)%0A%0Acwd_winpath = detail.os.cygwin_to_win(os.getcwd())%0A%0A%22%22%22Temporary %60.bat%60 script%22%22%22%0Atmp_path = '/tmp/configs.python.cmd.py-temp.bat'%0Atmp_winpath = detail.os.cygwin_to_win(tmp_path)%0A%0Atemp = open(tmp_path, 'w')%0Atemp.write('%7B%7D:%5Cn'.format(cwd_winpath%5B0%5D))%0Atemp.write('cd %22%7B%7D%22%5Cn'.format(cwd_winpath))%0Atemp.write('cmd%5Cn')%0A%0Aos.chmod(%0A tmp_path,%0A stat.S_IXOTH %7C stat.S_IXGRP %7C stat.S_IXUSR %7C%0A stat.S_IROTH %7C stat.S_IRGRP %7C stat.S_IRUSR%0A)%0A%0Asubprocess.Popen(%5B%0A 'cmd',%0A '/C',%0A 'start',%0A 'clean shell',%0A '/I',%0A explorer_winpath,%0A tmp_winpath%0A%5D)%0A
6d80008e2d14621943830ba6ca4a533f1bdc1da3
add test which is checking answer after user input
quiz/tests.py
quiz/tests.py
# coding=utf-8 from django.core.urlresolvers import resolve from django.test import TestCase from django.http import HttpRequest from django.template.loader import render_to_string from django.shortcuts import render from quiz.views import home_page from quiz.models import Phrase from quiz.models import PlayerRecord class HomePageTest(TestCase): def setUp(self): phrase = Phrase() phrase.url = "http://www.stackoverflow.com" phrase.english = "I have a question" phrase.korean = "질문이 있어요" phrase.category = "QnA" phrase.save() def test_root_url_resolves_to_home_page_view(self): found = resolve('/') self.assertEqual(found.func, home_page) def test_home_page_returns_correct_html(self): request = HttpRequest() response = home_page(request) expected_html = render_to_string( 'home.html', { 'quiz': '질문이 있어요', }) self.assertEqual(response.content.decode('utf-8'), expected_html) def test_home_page_can_save_a_POST_request(self): request = HttpRequest() request.method = 'POST' request.POST['user_text'] = 'I have question' response = home_page(request) self.assertEqual(PlayerRecord.objects.count(), 1) player_record = PlayerRecord.objects.first() self.assertEqual(player_record.answer, "I have question") def test_home_page_only_saves_items_when_necessary(self): request = HttpRequest() home_page(request) self.assertEqual(PlayerRecord.objects.count(), 0) class PhraseModelTest(TestCase): def test_saving_and_retreiving_phrases(self): first_phrase = Phrase() first_phrase.url = "http://www.stackoverflow.com" first_phrase.english = "I have a question" first_phrase.korean = "질문이 있어요" first_phrase.category = "QnA" first_phrase.save() second_phrase = Phrase() second_phrase.url = "http://www.github.com" second_phrase.english = "Is it possible to transfer Wiki content to another's repository?" second_phrase.korean = "위키를 다른 사람의 저장소로 옮길 수 있을까요?" second_phrase.category = "Issue" second_phrase.save() saved_phrases = Phrase.objects.all() self.assertEqual(saved_phrases.count(), 2) first_saved_phrase = saved_phrases[0] second_saved_phrase = saved_phrases[1] self.assertEqual(first_saved_phrase.category, "QnA") self.assertEqual(second_saved_phrase.category, "Issue") class PlayerRecordTest(TestCase): def test_saving_and_retreiving_player_record(self): phrase = Phrase() phrase.url = "http://www.stackoverflow.com" phrase.english = "I have a question" phrase.korean = "질문이 있어요" phrase.category = "QnA" phrase.save() player_record = PlayerRecord() player_record.phrase = phrase player_record.answer = "I have question" player_record.save() saved_player_records = PlayerRecord.objects.all() self.assertEqual(saved_player_records.count(), 1) saved_player_record = saved_player_records[0] self.assertEqual(saved_player_record.answer, "I have question")
Python
0.000008
@@ -1596,16 +1596,444 @@ (), 0)%0A%0A + def test_home_page_can_show_a_answer_after_user_input(self):%0A request = HttpRequest()%0A request.method = 'POST'%0A request.POST%5B'user_text'%5D = 'I have question'%0A response = home_page(request)%0A%0A expected_html = render_to_string(%22home.html%22, %7B%0A 'quiz': '%EC%A7%88%EB%AC%B8%EC%9D%B4 %EC%9E%88%EC%96%B4%EC%9A%94',%0A 'answer': 'I have a question'%7D)%0A self.assertEqual(response.content.decode('utf-8'), expected_html)%0A%0A %0Aclass P
48faf04cfcd40739e2a0ddfc593f2320f1aeef65
Create re_install.py
re_install.py
re_install.py
Python
0.000001
@@ -0,0 +1,1718 @@ +# -*- coding: utf-8 -*-%0A%0A#-----------------------------------------------------------------------------#%0A# #%0A# import libs #%0A# #%0A#-----------------------------------------------------------------------------#%0Aimport os%0A#-----------------------------------------------------------------------------#%0A%0A#-----------------------------------------------------------------------------#%0A# #%0A# main dev #%0A# #%0A#-----------------------------------------------------------------------------#%0A#when i need to re install all the program in case of loss%0A#we can get them back from the run of that python program%0A%0A#os.system(%22sudo modprobe w1-gpio%22)%0A#os.system(%22sudo modprobe w1-therm%22)%0A#os.system(%22cd /sys/bus/w1/devices/28*%22)%0A%0Aos.system(%22sudo apt-get update%22)%0Aos.system(%22sudo apt-get upgrade%22)%0Aos.system(%22sudo apt-get install python-pip%22)%0Aos.system(%22sudo apt-get install python-dev%22)%0Aos.system(%22sudo apt-get install python-rpi.gpio%22)%0A%0A#we install the lib to get the temperature of the temp sensors DS18B20%0A#se more here : https://github.com/timofurrer/w1thermsensor%0Aos.system(%22sudo pip install w1thermsensor%22)%0A#install mysqldb lib for python used in code%0Aos.system(%22sudo apt-get install python-mysqldb%22)%0A#os.system(%22sudo apt-get install tightvncserver%22)%0Aos.system(%22sudo reboot%22)%0A%0Aprint %22the end%22%0A
4411c676426fb580d33ae09682444c093ab2c204
Add multi-processing tests
test/test_mp.py
test/test_mp.py
Python
0.000001
@@ -0,0 +1,2152 @@ +import unittest%0Aimport time%0A%0Afrom clopure.core import ClopureRunner%0Afrom clopure.parser import ClopureParser%0A%0A%0Aclass TestMultiprocessing(unittest.TestCase):%0A%0A def setUp(self):%0A self.parser = ClopureParser()%0A self.runner = ClopureRunner(procs=4)%0A%0A def test_pmap(self):%0A code = %22(defimport time sleep) (list (pmap #(do (sleep %25) %25) %5B1.0 0.8 0.5 0.1 0.1 0.3%5D))%22%0A tree = self.parser.parse_line(code)%0A result = self.runner.evaluate(tree%5B0%5D)%0A start_time = time.time()%0A result = self.runner.evaluate(tree%5B1%5D)%0A end_time = time.time()%0A self.assertEqual(result, %5B1.0, 0.8, 0.5, 0.1, 0.1, 0.3%5D)%0A self.assertTrue(0.95 %3C end_time - start_time %3C 1.05)%0A%0A def test_pmap_unord(self):%0A code = %22(defimport time sleep) (list (pmap-unord #(do (sleep %25) %25) %5B1.0 0.8 0.5 0.1 0.1 0.3%5D))%22%0A tree = self.parser.parse_line(code)%0A result = self.runner.evaluate(tree%5B0%5D)%0A start_time = time.time()%0A result = self.runner.evaluate(tree%5B1%5D)%0A end_time = time.time()%0A self.assertEqual(result, %5B0.1, 0.1, 0.5, 0.3, 0.8, 1.0%5D)%0A self.assertTrue(0.95 %3C end_time - start_time %3C 1.05)%0A%0A def test_iter_mp_split(self):%0A code = %22(defimport time sleep) (list ((iter-mp-split #(map #(do (sleep %25) %25) %25)) %5B1.0 0.8 0.5 0.1 0.1 0.3%5D))%22%0A tree = self.parser.parse_line(code)%0A result = self.runner.evaluate(tree%5B0%5D)%0A start_time = time.time()%0A result = self.runner.evaluate(tree%5B1%5D)%0A end_time = time.time()%0A self.assertEqual(result, %5B1.0, 0.8, 0.5, 0.1, 0.1, 0.3%5D)%0A self.assertTrue(0.95 %3C end_time - start_time %3C 1.05)%0A%0A def test_iter_mp_split_unord(self):%0A code = %22(defimport time sleep) (list ((iter-mp-split-unord #(map #(do (sleep %25) %25) %25)) %5B1.0 0.8 0.5 0.1 0.1 0.3%5D))%22%0A tree = self.parser.parse_line(code)%0A result = self.runner.evaluate(tree%5B0%5D)%0A start_time = time.time()%0A result = self.runner.evaluate(tree%5B1%5D)%0A end_time = time.time()%0A self.assertEqual(result, %5B0.1, 0.1, 0.5, 0.3, 0.8, 1.0%5D)%0A self.assertTrue(0.95 %3C end_time - start_time %3C 1.05)%0A
122eb3c6eb9f8467fc5d3325f0e5c58cc285cb50
Add a script to convert hex formatted key to token using random partitioner
token-hexkey.py
token-hexkey.py
Python
0
@@ -0,0 +1,1336 @@ +#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A# Licensed to the Apache Software Foundation (ASF) under one%0A# or more contributor license agreements. See the NOTICE file%0A# distributed with this work for additional information%0A# regarding copyright ownership. The ASF licenses this file%0A# to you under the Apache License, Version 2.0 (the%0A# %22License%22); you may not use this file except in compliance%0A# with the License. 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 specif%0A%0A%0A# a script to convert a given key in hex format to token using RandomPartitioner%0A%0Aimport hashlib%0Aimport binascii%0Aimport sys%0A%0Aif len(sys.argv) %3C 2:%0A print %22usage: python token.py %3Ckey in hex format%3E%22%0A sys.exit(1)%0A%0Akey = binascii.unhexlify(sys.argv%5B1%5D)%0A%0A# Calculate MD5 digest and convert it to hex format%0Adigest = hashlib.md5(key).hexdigest()%0A%0A# Convert the hash digest to 2's complement form%0Atoken = long(digest, 16)%0Abits = 128%0Aif ((token & (1 %3C%3C (bits - 1))) != 0):%0A token = token - (1 %3C%3C bits)%0A%0A# Convert the resulting number to unsigned form%0Aprint abs(token)%0A
b35a0d2415cfc8d8d5d4060f1cf411a42c90a9a0
add leetcode Pascal's Triangle.
leetcode/PascalTriangle/solution.py
leetcode/PascalTriangle/solution.py
Python
0
@@ -0,0 +1,681 @@ +# -*- coding:utf-8 -*-%0Aclass Solution:%0A # @return a list of lists of integers%0A def generate(self, numRows):%0A ret = %5B%5D%0A if numRows == 0:%0A return %5B%5D%0A if numRows == 1:%0A ret.append(%5B1%5D)%0A return ret%0A if numRows == 2:%0A ret.extend(%5B%5B1%5D, %5B1,1%5D%5D)%0A return ret%0A ret.extend(%5B%5B1%5D, %5B1,1%5D%5D)%0A prev = %5B1,1%5D%0A for x in xrange(numRows - 2):%0A row = %5B1%5D%0A row_prev = prev%5B0%5D%0A for v in prev%5B1:%5D:%0A row.append(row_prev + v)%0A row_prev = v%0A row.append(1)%0A prev = row%0A ret.append(row)%0A return ret%0A
8b5f09708eb79abdcde730727f6788881a3a68a3
Initialize P4_textToExcel
books/AutomateTheBoringStuffWithPython/Chapter12/PracticeProjects/P4_textToExcel.py
books/AutomateTheBoringStuffWithPython/Chapter12/PracticeProjects/P4_textToExcel.py
Python
0.00127
@@ -0,0 +1,334 @@ +# Write a program to read in the contents of several text files (you can make%0A# the text files yourself) and insert those contents into a spreadsheet, with%0A# one line of text per row. The lines of the first text file will be in the%0A# cells of column A, the lines of the second text file will be in the cells of%0A# column B, and so on.%0A
c50e072c5e79083ec3ec4104789a64223c2f63f8
Create tao.py
tao.py
tao.py
Python
0.000028
@@ -0,0 +1,515 @@ +#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0Afrom apscheduler.schedulers.blocking import BlockingScheduler%0Aimport itchat, time%0A%0Aitchat.auto_login()%0A%0Adef task():%0A chatroomList = itchat.get_chatrooms(False);%0A for m in chatroomList:%0A NickName = m%5B'NickName'%5D.encode('utf-8')%0A if NickName == u'%E6%B5%8B%E8%AF%95'.encode('utf-8'):%0A text = u'%E4%B8%AD%E6%96%87%E7%BE%A4%E5%8F%91%E6%B5%8B%E8%AF%95'.encode('utf-8')%0A itchat.send(text, m%5B'UserName'%5D)%0A%0Asched = BlockingScheduler()%0Asched.add_job(task, 'cron', month='1-12', day='1-31', hour=14, minute=32)%0Asched.start()%0A
7e757d24bff5758350dd2bc92b9e2b1e2f919c12
Add compute synth (#3830)
java-compute/google-cloud-compute/synth.py
java-compute/google-cloud-compute/synth.py
Python
0
@@ -0,0 +1,934 @@ +# Copyright 2018 Google LLC%0A#%0A# Licensed under the Apache License, Version 2.0 (the %22License%22);%0A# you may not use this file except in compliance with the License.%0A# You may obtain a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS,%0A# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A# See the License for the specific language governing permissions and%0A# limitations under the License.%0A%0A%22%22%22This script is used to synthesize generated parts of this library.%22%22%22%0A%0Aimport synthtool as s%0Aimport synthtool.gcp as gcp%0A%0Agapic = gcp.DiscoGAPICGenerator()%0A%0Alibrary = gapic.java_library(%0A service='compute',%0A version='v1',%0A config_path='artman_compute.yaml',%0A artman_output_name='')%0A%0As.copy(library / 'gapic-google-cloud-compute-v1/src', 'src')%0A
2d88daf10d11033bfd597112fb6484783c5a852a
Create xyz.py
xyz.py
xyz.py
Python
0.000768
@@ -0,0 +1,5 @@ +#...%0A
e61840020820af4e7a625e472c060e8396b24055
add migrations
gem/migrations/0013_gemsettings_moderator_name.py
gem/migrations/0013_gemsettings_moderator_name.py
Python
0.000001
@@ -0,0 +1,523 @@ +# -*- coding: utf-8 -*-%0A# Generated by Django 1.9.12 on 2017-03-09 13:45%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations, models%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('gem', '0012_partner_credit'),%0A %5D%0A%0A operations = %5B%0A migrations.AddField(%0A model_name='gemsettings',%0A name='moderator_name',%0A field=models.TextField(blank=True, help_text=b'Moderator name', null=True, verbose_name=b'Moderator Name'),%0A ),%0A %5D%0A
955ae619a6502a68f9a8d34022a4a8b1ebeb5ce2
Create 20.py
E/20.py
E/20.py
Python
0.000015
@@ -0,0 +1,333 @@ +# Problem 20 - Factorial digit sum%0A# n! means n %C3%97 (n %E2%88%92 1) %C3%97 ... %C3%97 3 %C3%97 2 %C3%97 1%0A# For example, 10! = 10 %C3%97 9 %C3%97 ... %C3%97 3 %C3%97 2 %C3%97 1 = 3628800,%0A# and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27%0A# Find the sum of the digits in the number 100!%0Afrom math import factorial as f%0Aprint(sum(int(c) for c in str(f(100))))%0A
81f983c833d9858ad23f589367bf601babddf858
Add some useful activation functions.
elements/activation_functions.py
elements/activation_functions.py
Python
0
@@ -0,0 +1,1155 @@ +import theano%0Aimport theano.tensor as T%0A%0A%22%22%22%0AA set of activation functions for Neural Network layers.%0AThey're in the form of class so we can take advantage of constructor%0Ato set initial value for some parameters.%0A%22%22%22%0A%0Adef tanh(x):%0A%09%22%22%22%0A%09tanh function (-1 to 1)%0A%0A%09@input: x, theano shared variable.%0A%09@output: element-wise tanh of x%0A%09%22%22%22%0A%09return T.tanh(x)%0A%0Adef sigmoid(x):%0A%09%22%22%22%0A%09sigmoid function (0 to 1, (tanh(x)+1)/2).%0A%0A%09@input: x, theano shared variable.%0A%09@output: element-wise sigmoid of x%0A%09%22%22%22%0A%09return (T.tanh(x)+1)/2%0A%0Adef linier(x):%0A%09%22%22%22%0A%09linier function.%0A%0A%09@input: x, theano shared variable.%0A%09@output: x%0A%09%22%22%22%0A%09return x%0A%0Adef relu_generator(alpha=0):%0A%09%22%22%22%0A%09this function returns a relu function with proper alpha value.%0A%0A%09@input: alpha, slope of negative side of ReLU.%0A%09@output: ReLU function%0A%09%22%22%22%0A%09def relu(x):%0A%09%09%22%22%22%0A%09%09rectified linier function (-alpha*x if x%3C0, x if x%3E0).%0A%0A%09%09@input: x, theano shared variable.%0A%09%09@output: x%3C0?-alpha*x:x%0A%09%09%22%22%22%0A%09%09return T.nnet.relu(x, alpha)%0A%0A%09return relu%0A%0A# TODO:%0A# add RBF activation function%0A#%0A# def RBF(x):%0A# %09%22%22%22%0A# %09radial basis function.%0A%0A# %09@input: x, theano shared variable.%0A# %09@output: Not Implimented%0A# %09%22%22%22%0A
b8e7f5381abcf15d07cac07c20c671ec7cc64c90
Add missing migration.
ideascube/mediacenter/migrations/0013_auto_20170323_1525.py
ideascube/mediacenter/migrations/0013_auto_20170323_1525.py
Python
0
@@ -0,0 +1,668 @@ +# -*- coding: utf-8 -*-%0A# Generated by Django 1.10.6 on 2017-03-23 15:25%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations, models%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('mediacenter', '0012_auto_20170210_0940'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterField(%0A model_name='document',%0A name='kind',%0A field=models.CharField(choices=%5B('image', 'image'), ('audio', 'sound'), ('video', 'video'), ('pdf', 'pdf'), ('text', 'text'), ('epub', 'epub'), ('mobi', 'mobi'), ('app', 'app'), ('other', 'other')%5D, default='other', max_length=5, verbose_name='type'),%0A ),%0A %5D%0A
6585ca91a399a06094636a505fe813a0425c1a35
add auth module (split from server mod.)
auth.py
auth.py
Python
0
@@ -0,0 +1,950 @@ +from urllib import urlencode%0Afrom requests import post%0A%0Aauth_url = 'https://github.com/login/oauth/authorize'%0Aaccess_token_url = 'https://github.com/login/oauth/access_token'%0A%0A%0Adef generate_auth_link(client_id, scopes):%0A%0A # append the client_id and scopes list to the url query string%0A return auth_url + '?' + urlencode(%7B%0A 'client_id': client_id,%0A 'scope': ','.join(scopes)%0A %7D)%0A%0A%0Adef get_auth_token(client_id, client_secret, code):%0A%0A # request a token%0A response = post(%0A access_token_url,%0A data=%7B%0A 'client_id': client_id,%0A 'client_secret': client_secret,%0A 'code': code%0A %7D,%0A headers=%7B%0A 'Accept': 'application/json'%0A %7D%0A )%0A%0A # decode the response%0A json = response.json()%0A%0A # check if response contains the token%0A if 'access_token' in json:%0A return json%5B'access_token'%5D%0A else:%0A return None # token request failed%0A
dbc20f37c7fb1dd00c90ac54d2021fb1ba3b5eda
Add some end-to-end functional tests
exam.py
exam.py
Python
0.000003
@@ -0,0 +1,2666 @@ +import time%0Aimport sys%0A%0Afrom groupy.client import Client%0A%0A%0Adef read_token_from_file(filename):%0A with open(filename) as f:%0A return f.read().strip()%0A%0A%0Adef test_groups(groups):%0A for group in groups:%0A print(group)%0A%0A print('Members:')%0A for member in group.members%5B:5%5D:%0A print(member)%0A%0A print('Recent messages:')%0A for message in group.messages.list()%5B:5%5D:%0A print(message)%0A%0A print('Leaderboard (day):')%0A for message in group.leaderboard.list_day()%5B:5%5D:%0A print(message.favorited_by)%0A%0A print('Gallery:')%0A for message in group.gallery.list()%5B:5%5D:%0A print(message.attachments)%0A%0A print()%0A%0A%0Adef test_messages(messages):%0A for message in messages:%0A print(message)%0A print(message.attachments)%0A print('Liking...', message.like())%0A time.sleep(1) # you get rate limited by liking/unliking too fast%0A print('Unliking...', message.unlike())%0A%0A%0Adef test_chats(chats):%0A for chat in chats:%0A print(chat)%0A print('Recent messages:')%0A for message in chat.messages.list():%0A print(message)%0A%0A%0Adef main(*args):%0A token_file = args%5B0%5D%0A token = read_token_from_file(token_file)%0A client = Client.from_token(token)%0A%0A groups = list(client.groups.list().autopage())%0A test_group_ids = ('12268264', '27205597', '27205784', '35799100')%0A target_groups = %5B%5D%0A for group in groups:%0A if group.id in test_group_ids:%0A print('Found %7B0%7D (id=%7B0.group_id%7D)'.format(group))%0A target_groups.append(group)%0A if len(target_groups) %3C len(test_group_ids):%0A raise Exception('could not find group test groups')%0A%0A chats = list(client.chats.list())%0A test_chat_ids = ('14529712+14612048',)%0A target_chats = %5B%5D%0A for chat in chats:%0A if chat.last_message%5B'conversation_id'%5D in test_chat_ids:%0A print('Found %7B%7D'.format(chat))%0A target_chats.append(group)%0A if len(target_chats) %3C len(test_chat_ids):%0A raise Exception('could not find group test chats')%0A%0A target_messages = %5B%5D%0A for group in target_groups:%0A target_messages.append(group.messages.list()%5B0%5D)%0A for chat in target_chats:%0A target_messages.append(chat.messages.list()%5B0%5D)%0A%0A print_header('test groups')%0A test_groups(target_groups)%0A%0A print_header('test chats')%0A test_chats(target_chats)%0A%0A print_header('test messages')%0A test_messages(target_messages)%0A%0A%0Adef print_header(header):%0A print('%5Cn')%0A print('=' * 50)%0A print('%7C %7B%7D'.format(header))%0A print('=' * 50)%0A print()%0A%0A%0Aif __name__ == '__main__':%0A main(*sys.argv%5B1:%5D)%0A
64139e0a41c1b1da81e9b5e244b2d7095c4a7a2b
Add delete old sessions command
core/management/commands/delete_old_sessions.py
core/management/commands/delete_old_sessions.py
Python
0.000001
@@ -0,0 +1,1078 @@ +from datetime import datetime%0A%0Afrom django.core.management.base import BaseCommand%0Afrom django.contrib.sessions.models import Session%0A%0A%22%22%22%0A%3E%3E%3E def clean(count):%0A... for idx, s in enumerate(Session.objects.filter(expire_date__lt=now)%5B:count+1%5D):%0A... s.delete()%0A... if str(idx).endswith('000'): print idx%0A... print %22%7B0%7D records left%22.format(Session.objects.filter(expire_date__lt=now).count())%0A... %0A%22%22%22%0A%0Aclass Command(NoArgsCommand):%0A%0A args = '%3Ccount count ...%3E'%0A help = %22Delete old sessions%22%0A%0A def handle(self, *args, **options):%0A old_sessions = Session.objects.filter(expire_date__lt=datetime.now())%0A%0A self.stdout.write(%22Deleting %7B0%7D expired sessions%22.format(%0A old_sessions.count()%0A )%0A%0A for index, session in enumerate(old_sessions):%0A session.delete()%0A if str(idx).endswith('000'):%0A self.stdout.write(%22%7B0%7D records deleted%22.format(index)%0A%0A self.stdout.write(%22%7B0%7D expired sessions remaining%22.format(%0A Session.objects.filter(expire_date__lt=datetime.now())%0A )
53add23b6dcb19251a41c7a99347ef6592b2898f
Add tests for serving precompressed files
tests/sentry/web/frontend/generic/test_static_media.py
tests/sentry/web/frontend/generic/test_static_media.py
from __future__ import absolute_import from django.test.utils import override_settings from sentry.testutils import TestCase from sentry.web.frontend.generic import FOREVER_CACHE, NEVER_CACHE class StaticMediaTest(TestCase): @override_settings(DEBUG=False) def test_basic(self): url = '/_static/sentry/app/index.js' response = self.client.get(url) assert response.status_code == 200, response assert response['Cache-Control'] == NEVER_CACHE assert 'Vary' not in response assert response['Access-Control-Allow-Origin'] == '*' @override_settings(DEBUG=False) def test_versioned(self): url = '/_static/1234567890/sentry/app/index.js' response = self.client.get(url) assert response.status_code == 200, response assert response['Cache-Control'] == FOREVER_CACHE assert 'Vary' not in response assert response['Access-Control-Allow-Origin'] == '*' url = '/_static/a43db3b08ddd4918972f80739f15344b/sentry/app/index.js' response = self.client.get(url) assert response.status_code == 200, response assert response['Cache-Control'] == FOREVER_CACHE assert 'Vary' not in response assert response['Access-Control-Allow-Origin'] == '*' with override_settings(DEBUG=True): response = self.client.get(url) assert response.status_code == 200, response assert response['Cache-Control'] == NEVER_CACHE assert 'Vary' not in response assert response['Access-Control-Allow-Origin'] == '*' @override_settings(DEBUG=False) def test_no_cors(self): url = '/_static/sentry/images/favicon.ico' response = self.client.get(url) assert response.status_code == 200, response assert response['Cache-Control'] == NEVER_CACHE assert 'Vary' not in response assert 'Access-Control-Allow-Origin' not in response
Python
0
@@ -33,16 +33,26 @@ import%0A%0A +import os%0A from dja @@ -502,38 +502,53 @@ assert -'Vary' not in response +response%5B'Vary'%5D == 'Accept-Encoding' %0A @@ -593,32 +593,75 @@ -Origin'%5D == '*' +%0A 'Content-Encoding' not in response %0A%0A @override_ @@ -934,38 +934,53 @@ assert -'Vary' not in response +response%5B'Vary'%5D == 'Accept-Encoding' %0A @@ -1025,32 +1025,75 @@ -Origin'%5D == '*' +%0A 'Content-Encoding' not in response %0A%0A url = @@ -1322,38 +1322,53 @@ assert -'Vary' not in response +response%5B'Vary'%5D == 'Accept-Encoding' %0A @@ -1417,24 +1417,67 @@ gin'%5D == '*' +%0A 'Content-Encoding' not in response %0A%0A wi @@ -1690,38 +1690,53 @@ assert -'Vary' not in response +response%5B'Vary'%5D == 'Accept-Encoding' %0A @@ -2078,74 +2078,1006 @@ ert -'Vary' not in response%0A assert 'Access-Control-Allow-Orig +response%5B'Vary'%5D == 'Accept-Encoding'%0A assert 'Access-Control-Allow-Origin' not in response%0A 'Content-Encoding' not in response%0A%0A def test_404(self):%0A url = '/_static/sentry/app/thisfiledoesnotexistlol.js'%0A response = self.client.get(url)%0A assert response.status_code == 404, response%0A%0A def test_gzip(self):%0A url = '/_static/sentry/app/index.js'%0A response = self.client.get(url, HTTP_ACCEPT_ENCODING='gzip,deflate')%0A assert response.status_code == 200, response%0A assert response%5B'Vary'%5D == 'Accept-Encoding'%0A 'Content-Encoding' not in response%0A%0A try:%0A open('src/sentry/static/sentry/app/index.js.gz', 'a').close()%0A%0A # Not a gzip Accept-Encoding, so shouldn't serve gzipped file%0A response = self.client.get(url, HTTP_ACCEPT_ENCODING='lol')%0A assert response.status_code == 200, response%0A assert response%5B'Vary'%5D == 'Accept-Encoding'%0A 'Content-Encod in +g ' no @@ -3070,28 +3070,437 @@ t-Encoding' not in response%0A +%0A response = self.client.get(url, HTTP_ACCEPT_ENCODING='gzip,deflate')%0A assert response.status_code == 200, response%0A assert response%5B'Vary'%5D == 'Accept-Encoding'%0A assert response%5B'Content-Encoding'%5D == 'gzip'%0A finally:%0A try:%0A os.unlink('src/sentry/static/sentry/app/index.js.gz')%0A except Exception:%0A pass%0A
bb0cff292f1931b52bf05a3a0630dda9a508023f
Add basic wrapper for gym env
packages/syft/src/syft/lib/gym/env.py
packages/syft/src/syft/lib/gym/env.py
Python
0
@@ -0,0 +1,516 @@ +# third party%0Aimport gym%0A%0A# syft relative%0Afrom ...generate_wrapper import GenerateWrapper%0Afrom ...proto.lib.gym.env_pb2 import Env as Env_PB%0A%0Agym_env_type = type(gym.Env())%0A%0A%0Adef object2proto(obj: gym.Env) -%3E Env_PB:%0A return Env_PB(id=obj.unwrapped.spec.id)%0A%0A%0Adef proto2object(proto: Env_PB) -%3E gym.Env:%0A return gym.make(proto.id)%0A%0A%0AGenerateWrapper(%0A wrapped_type=gym_env_type,%0A import_path=%22gym.Env%22,%0A protobuf_scheme=Env_PB,%0A type_object2proto=object2proto,%0A type_proto2object=proto2object,%0A)%0A
05bf0cd188d4666c9c0aeb56a95d7867f25952c2
Add a script for dqn continuous task demo
demo_dqn_continuous.py
demo_dqn_continuous.py
Python
0
@@ -0,0 +1,1847 @@ +import argparse%0A%0Aimport chainer%0Afrom chainer import serializers%0Aimport gym%0Aimport numpy as np%0A%0Aimport random_seed%0Aimport env_modifiers%0Aimport q_function%0A%0A%0Adef eval_single_run(env, model, phi):%0A test_r = 0%0A obs = env.reset()%0A done = False%0A while not done:%0A s = chainer.Variable(np.expand_dims(phi(obs), 0))%0A qout = model(s)%0A a = qout.greedy_actions.data%5B0%5D%0A obs, r, done, info = env.step(a)%0A test_r += r%0A return test_r%0A%0A%0Adef main():%0A import logging%0A logging.basicConfig(level=logging.DEBUG)%0A%0A parser = argparse.ArgumentParser()%0A parser.add_argument('model', type=str)%0A parser.add_argument('--env', type=str, default='Pendulum-v0')%0A parser.add_argument('--seed', type=int, default=0)%0A parser.add_argument('--n-runs', type=int, default=10)%0A parser.add_argument('--window-visible', action='store_true')%0A parser.add_argument('--render', action='store_true')%0A parser.set_defaults(render=False)%0A args = parser.parse_args()%0A%0A random_seed.set_random_seed(args.seed)%0A%0A env = gym.make(args.env)%0A timestep_limit = env.spec.timestep_limit%0A env_modifiers.make_timestep_limited(env, timestep_limit)%0A if args.render:%0A env_modifiers.make_rendered(env)%0A%0A obs_size = np.asarray(env.observation_space.shape).prod()%0A action_size = np.asarray(env.action_space.shape).prod()%0A%0A q_func = q_function.FCSIContinuousQFunction(%0A obs_size, action_size, 100, 2, env.action_space)%0A serializers.load_hdf5(args.model, q_func)%0A%0A scores = %5B%5D%0A%0A def phi(obs):%0A return obs.astype(np.float32)%0A%0A for i in range(args.n_runs):%0A score = eval_single_run(env, q_func, phi)%0A print('Run %7B%7D: %7B%7D'.format(i, score))%0A scores.append(score)%0A print('Average: %7B%7D'.format(sum(scores) / args.n_runs))%0A%0A%0Aif __name__ == '__main__':%0A main()%0A
a2cb69b40daa7ab7b222e7d670dd1022571395a1
add aiohttp demon
demos/aiohttp_demon.py
demos/aiohttp_demon.py
Python
0
@@ -0,0 +1,857 @@ +# -*- coding: utf-8 -*-%0A# 18/5/22%0A# create by: snower%0A%0Aimport datetime%0Afrom torpeewee import *%0Afrom aiohttp import web%0A%0Adb = MySQLDatabase(%22test%22, host=%22127.0.0.1%22, user=%22root%22, passwd=%22123456%22)%0A%0Aclass BaseModel(Model):%0A class Meta:%0A database = db%0A%0Aclass Test(BaseModel):%0A id = IntegerField(primary_key= True)%0A data = CharField(max_length=64, null=False)%0A created_at = DateTimeField()%0A%0Aasync def show_handle(request):%0A datas = %5Bt.data for t in await Test.select()%5D%0A return web.Response(text = u%22%3Cbr /%3E%22.join(datas))%0A%0Aasync def create_handle(request):%0A data = await request.post()%0A data = data%5B%22data%22%5D%0A await Test.create(data=data, created_at=datetime.datetime.now())%0A return web.HTTPFound('/')%0A%0Aapp = web.Application()%0Aapp.add_routes(%5B%0A web.get('/', show_handle),%0A web.post('/', create_handle)%0A%5D)%0A%0Aweb.run_app(app)
f61570297ef56e94b104aff42c822ea82a66030b
Add tests for database
tests/test_database.py
tests/test_database.py
Python
0.000001
@@ -0,0 +1,2195 @@ +import unittest%0A%0Afrom rcblog import db%0A%0A%0Aclass TestDataBase(unittest.TestCase):%0A @classmethod%0A def setUpClass(cls):%0A db.DB_NAME = 'test'%0A date_base = db.DataBase()%0A try:%0A db.r.table_drop('languages').run(date_base.connection)%0A except Exception as e:%0A print(e)%0A try:%0A db.r.table_drop('posts').run(date_base.connection)%0A except Exception as e:%0A print(e)%0A try:%0A date_base.init()%0A except Exception as e:%0A print(e)%0A try:%0A db.r.table('languages').delete().run(date_base.connection)%0A except Exception as e:%0A print(e)%0A try:%0A db.r.table('posts').delete().run(date_base.connection)%0A except Exception as e:%0A print(e)%0A%0A def setUp(self):%0A self.date_base = db.DataBase()%0A%0A def tearDown(self):%0A db.r.table('languages').delete().run(self.date_base.connection)%0A db.r.table('posts').delete().run(self.date_base.connection)%0A%0A def test_add_translation(self):%0A self.date_base.add_post(%7B'eng': 'post1_eng.md', 'rus': 'post1_rus.md'%7D, %5B'tag1', 'tag2'%5D)%0A posts = self.date_base.get_all_posts()%0A self.assertEqual(len(posts), 1)%0A post = posts%5B0%5D%0A id_ = post%5B'id'%5D%0A self.date_base.add_translation(id_, %7B'jbo': 'post1_jbo.md'%7D)%0A posts = self.date_base.get_all_posts()%0A self.assertEqual(len(posts), 1)%0A post = posts%5B0%5D%0A self.assertEqual(post%5B'translations'%5D%5B'eng'%5D, 'post1_eng.md')%0A self.assertEqual(post%5B'translations'%5D%5B'rus'%5D, 'post1_rus.md')%0A self.assertEqual(post%5B'translations'%5D%5B'jbo'%5D, 'post1_jbo.md')%0A%0A def test_add_tag(self):%0A self.date_base.add_post(%7B'eng': 'post1_eng.md', 'rus': 'post1_rus.md'%7D, %5B'tag1', 'tag2'%5D)%0A posts = self.date_base.get_all_posts()%0A self.assertEqual(len(posts), 1)%0A post = posts%5B0%5D%0A id_ = post%5B'id'%5D%0A self.date_base.add_tags(id_, %5B'tag3', 'tag4'%5D)%0A posts = self.date_base.get_all_posts()%0A self.assertEqual(len(posts), 1)%0A post = posts%5B0%5D%0A self.assertEqual(post%5B'tags'%5D, %5B'tag1', 'tag2', 'tag3', 'tag4'%5D)%0A
054c71e88a5fb278ffcdac2ce85a59843f5e3ac0
add new tests for oop
tests/scripts/oop/ex1.py
tests/scripts/oop/ex1.py
Python
0
@@ -0,0 +1,482 @@ +# coding: utf-8%0A%0A#$ header class Point(public)%0A#$ header method __init__(Point, double, double)%0A#$ header method __del__(Point)%0A#$ header method translate(Point, double, double)%0A%0Aclass Point(object):%0A def __init__(self, x, y):%0A self.x = x%0A self.y = y%0A%0A def __del__(self):%0A pass%0A%0A def translate(self, a, b):%0A self.x = self.x + a%0A self.y = self.y + b%0A%0Ap = Point (0.0, 0.0)%0A%0Ap.translate(1.0, 2.0)%0A%0A#print(p.x, p.y)%0A#a = p.x%0A#print(a)%0A%0Adel p%0A
8d280e5a464a9ca75ac7c35e02d8de6bddbaaa7e
Add reaction tests
tests/test_reaction.py
tests/test_reaction.py
Python
0.000051
@@ -0,0 +1,998 @@ +import pytest%0Aimport linkatos.reaction as react%0A%0Adef test_positive_reaction():%0A reaction = '+1'%0A assert react.positive_reaction(reaction) is True%0A%0A%0Adef test_not_positive_reaction():%0A reaction = '-1'%0A assert react.positive_reaction(reaction) is False%0A%0A%0Adef test_known_reaction_neg():%0A reaction = '-1'%0A assert react.known_reaction(reaction) is True%0A%0A%0Adef test_known_reaction_pos():%0A reaction = '+1'%0A assert react.known_reaction(reaction) is True%0A%0A%0Adef test_unknown_reaction():%0A reaction = 'worried'%0A assert react.known_reaction(reaction) is False%0A%0A%0Adef test_equal_ids():%0A id_one = 'id'%0A id_two = 'id'%0A assert react.reacting_to_url(id_one, id_two) is True%0A%0A%0Adef test_different_ids():%0A id_one = 'id1'%0A id_two = 'id2'%0A assert react.reacting_to_url(id_one, id_two) is False%0A%0A%0Adef test_confirmation():%0A reaction = '+1'%0A url_message_id = 'id'%0A reaction_to_id = 'id'%0A assert react.is_confirmation(reaction, url_message_id, reaction_to_id) is True%0A
c0f7be02fb1dc294a9bac2867fc695e353ea3445
Test Resource.
tests/test_resource.py
tests/test_resource.py
Python
0
@@ -0,0 +1,887 @@ +# -*- coding: utf-8 -*-%0A%0Afrom unittest import TestCase%0Afrom electro.resource import Resource%0A%0Aclass TestResource(TestCase):%0A%0A def assert_parser(self, assert_value, values):%0A resource = Resource()%0A value = resource._parse_response(values)%0A self.assertEqual(value, assert_value)%0A%0A def test_empty_content_will_return_204(self):%0A self.assert_parser(('', 204, %7B%7D), '')%0A%0A def test_dict_will_return_200(self):%0A self.assert_parser(('%7B%7D', 200, %7B%7D), %7B%7D)%0A%0A def test_list_will_return_200(self):%0A self.assert_parser(('%5B%5D', 200, %7B%7D), %5B%5D)%0A%0A def test_str_will_return_200(self):%0A self.assert_parser(('%22test%22', 200, %7B%7D), 'test')%0A%0A def test_data_with_code(self):%0A self.assert_parser(('%7B%7D', 201, %7B%7D), (%7B%7D, 201))%0A%0A def test_data_with_code_and_headers(self):%0A self.assert_parser(('%7B%7D', 201, %7B'k':'v'%7D), (%7B%7D, 201, %7B'k':'v'%7D))%0A
5adf35b9131ea6c0a16f6765cf44c50767ddc3f3
add testanalyzing
tests/testanalyzing.py
tests/testanalyzing.py
Python
0.998693
@@ -0,0 +1,907 @@ +from timeside.decoder import *%0Afrom timeside.analyzer import *%0Afrom unit_timeside import *%0A%0Aimport os.path%0A%0A__all__ = %5B'TestAnalyzing'%5D%0A%0Aclass TestAnalyzing(TestCase):%0A %22Test all analyzers%22%0A%0A def setUp(self):%0A self.source = os.path.join (os.path.dirname(__file__), %22samples/sweep.wav%22)%0A%0A def testDC(self):%0A %22Test mean DC shift%22%0A self.analyzer = MeanDCShift()%0A self.value = -0%0A%0A def testMeanLevel(self):%0A %22Test mean level%22%0A self.analyzer = MeanLevel()%0A self.value = -9.856%0A%0A def testMaxLevel(self):%0A %22Test max level%22%0A self.analyzer = MaxLevel()%0A self.value = -6.0209999999999999%0A%0A def tearDown(self):%0A decoder = FileDecoder(self.source)%0A (decoder %7C self.analyzer).run()%0A self.assertEquals(self.analyzer.result(), self.value)%0A%0A%0Aif __name__ == '__main__':%0A unittest.main(testRunner=TestRunner())%0A%0A
b2a083e1531134ec82a70ca581fca31db7867566
add test for data with no coincidences
tests/test_singletons.py
tests/test_singletons.py
Python
0.000009
@@ -0,0 +1,1215 @@ +# -*- coding: utf-8 -*-%0A# pylint: disable=missing-docstring%0A# pylint: disable=redefined-outer-name%0A%22%22%22Test ref results for data with no coincidences.%22%22%22%0Aimport numpy%0Aimport pytest%0Afrom pytest import approx%0A%0Afrom ndd.estimators import NSB, AsymptoticNSB, Plugin%0Afrom ndd.exceptions import NddError%0A%0AN = (10, 10)%0AK = (10, 1000)%0A%0A%0A@pytest.fixture(params=zip(N, K))%0Adef data(request):%0A n, k = request.param%0A return %7B'nk': numpy.array(%5B1%5D * n), 'k': k%7D%0A%0A%0Adef test_NSB(data):%0A %22%22%22The NSB estimate should be somewhat close to log(k)%22%22%22%0A estimator = NSB()%0A relative_error = 1 - estimator(**data) / numpy.log(data%5B'k'%5D)%0A assert 0 %3C relative_error %3C 0.2%0A%0A%0Adef test_Asymptotic(data):%0A %22%22%22Should raise an exception%22%22%22%0A estimator = AsymptoticNSB()%0A with pytest.raises(NddError):%0A estimator(**data)%0A%0A%0Adef test_Plugin(data):%0A %22%22%22Should be close to the log of #visited bins with frequency %3E 0%22%22%22%0A estimator = Plugin(alpha=None)%0A k = sum(data%5B'nk'%5D %3E 0)%0A assert estimator(**data) == approx(numpy.log(k))%0A%0A%0Adef test_Plugin_pseudo(data):%0A %22%22%22Should be close to log(cardinality)%22%22%22%0A estimator = Plugin(alpha=1)%0A assert estimator(**data) == approx(numpy.log(data%5B'k'%5D), rel=1.e-3)%0A
ad54db707004dd2b6e445c72462c1e937417d046
test viz lib on fibonacci numbers
algopy/fib_gcd.py
algopy/fib_gcd.py
Python
0
@@ -0,0 +1,623 @@ +from rcviz import viz, callgraph%0A%0A%0A@viz%0Adef fib1(num):%0A assert num %3E= 0%0A if num %3C= 1:%0A return num%0A%0A fb1 = fib1(num - 1)%0A fb2 = fib1(num - 2)%0A res = fb1 + fb2%0A%0A return res%0A%0A%0A@viz%0Adef fib2(num):%0A assert num %3E= 0%0A return num if num %3C= 1 else fib2(num - 1) + fib2(num - 2)%0A%0A%0Adef gcd(a, b):%0A print %22a = %25d, b = %25d%22 %25 (a, b)%0A if a == 0 or b == 0:%0A return max(a, b)%0A%0A res = gcd(b %25 a, a)%0A return res%0A%0A%0Adef main():%0A a, b = 24, 9%0A d = gcd(a, b)%0A%0A print(d)%0A%0Aif __name__ == %22__main__%22:%0A # main()%0A%0A print fib1(6)%0A # callgraph.reset()%0A callgraph.render(%22test.png%22)%0A
8510352580ac6f39d706b6a4ace8426f9b45ca6c
Add unit tests for security_group_rules_client
tempest/tests/services/compute/test_security_group_rules_client.py
tempest/tests/services/compute/test_security_group_rules_client.py
Python
0.000001
@@ -0,0 +1,2571 @@ +# Copyright 2015 NEC Corporation. All rights reserved.%0A#%0A# Licensed under the Apache License, Version 2.0 (the %22License%22); you may%0A# not use this file except in compliance with the License. You may obtain%0A# 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%0Afrom tempest.services.compute.json import security_group_rules_client%0Afrom tempest.tests import fake_auth_provider%0Afrom tempest.tests.services.compute import base%0A%0A%0Aclass TestSecurityGroupRulesClient(base.BaseComputeServiceTest):%0A%0A FAKE_SECURITY_GROUP_RULE = %7B%0A %22security_group_rule%22: %7B%0A %22id%22: %222d021cf1-ce4b-4292-994f-7a785d62a144%22,%0A %22ip_range%22: %7B%0A %22cidr%22: %220.0.0.0/0%22%0A %7D,%0A %22parent_group_id%22: %2248700ff3-30b8-4e63-845f-a79c9633e9fb%22,%0A %22to_port%22: 443,%0A %22ip_protocol%22: %22tcp%22,%0A %22group%22: %7B%7D,%0A %22from_port%22: 443%0A %7D%0A %7D%0A%0A def setUp(self):%0A super(TestSecurityGroupRulesClient, self).setUp()%0A fake_auth = fake_auth_provider.FakeAuthProvider()%0A self.client = security_group_rules_client.SecurityGroupRulesClient(%0A fake_auth, 'compute', 'regionOne')%0A%0A def _test_create_security_group_rule(self, bytes_body=False):%0A req_body = %7B%0A %22from_port%22: %22443%22,%0A %22ip_protocol%22: %22tcp%22,%0A %22to_port%22: %22443%22,%0A %22cidr%22: %220.0.0.0/0%22,%0A %22parent_group_id%22: %2248700ff3-30b8-4e63-845f-a79c9633e9fb%22%0A %7D%0A self.check_service_client_function(%0A self.client.create_security_group_rule,%0A 'tempest.common.service_client.ServiceClient.post',%0A self.FAKE_SECURITY_GROUP_RULE,%0A to_utf=bytes_body, **req_body)%0A%0A def test_create_security_group_rule_with_str_body(self):%0A self._test_create_security_group_rule()%0A%0A def test_create_security_group_rule_with_bytes_body(self):%0A self._test_create_security_group_rule(bytes_body=True)%0A%0A def test_delete_security_group_rule(self):%0A self.check_service_client_function(%0A self.client.delete_security_group_rule,%0A 'tempest.common.service_client.ServiceClient.delete',%0A %7B%7D, status=202, group_rule_id='group-id')%0A
0d32be58f5145c067e012a9d314be3f688bcbc2a
Add tests for view
go/scheduler/tests/test_views.py
go/scheduler/tests/test_views.py
Python
0
@@ -0,0 +1,3221 @@ +import datetime%0Afrom go.vumitools.tests.helpers import djangotest_imports%0A%0Awith djangotest_imports(globals()):%0A from django.core.urlresolvers import reverse%0A from django.template import defaultfilters%0A from django.conf import settings%0A from go.base.tests.helpers import GoDjangoTestCase, DjangoVumiApiHelper%0A from go.scheduler.models import Task%0A from go.scheduler.views import SchedulerListView%0A%0Aclass TestSchedulerListView(GoDjangoTestCase):%0A def setUp(self):%0A self.vumi_helper = self.add_helper(%0A DjangoVumiApiHelper())%0A self.user_helper = self.vumi_helper.make_django_user()%0A self.client = self.vumi_helper.get_client()%0A%0A def create_task(self, label, account_id=None, delta=7):%0A now = datetime.datetime.now()%0A scheduled_time = now + datetime.timedelta(days=delta)%0A if account_id is None:%0A account_id = self.user_helper.account_key%0A return Task.objects.create(%0A account_id=account_id, label=label, scheduled_for=scheduled_time)%0A%0A def test_no_tasks(self):%0A r = self.client.get(reverse('scheduler:tasks'))%0A self.assertContains(r, '%3EScheduled Tasks%3C/a%3E')%0A self.assertContains(r, '%3ENo scheduled tasks%3C')%0A%0A def assert_contains_task(self, response, task):%0A self.assertContains(response, task.label)%0A self.assertContains(response, task.get_task_type_display())%0A self.assertContains(response, task.get_status_display())%0A formatted_date = defaultfilters.date(%0A task.scheduled_for, settings.DATETIME_FORMAT)%0A self.assertContains(response, formatted_date)%0A timezone = defaultfilters.date(%0A task.scheduled_for, 'T')%0A self.assertContains(response, timezone)%0A time_remaining = defaultfilters.timeuntil(task.scheduled_for)%0A self.assertContains(response, time_remaining)%0A%0A def test_single_task(self):%0A task = self.create_task('Test task') %0A r = self.client.get(reverse('scheduler:tasks'))%0A self.assert_contains_task(r, task)%0A%0A def test_multiple_pages(self):%0A tasks = %5B%5D%0A for i in range(SchedulerListView.paginate_by + 1):%0A task = self.create_task('Test task %25d' %25 i)%0A tasks.append(task)%0A%0A r = self.client.get(reverse('scheduler:tasks'))%0A excluded_task = tasks.pop()%0A for task in tasks:%0A self.assert_contains_task(r, task)%0A self.assertNotContains(r, excluded_task.label)%0A%0A self.assertContains(r, '&larr;%3C/a%3E')%0A self.assertContains(r, '&rarr;%3C/a%3E')%0A%0A def test_task_past(self):%0A task = self.create_task('Test task', delta=-7)%0A r = self.client.get(reverse('scheduler:tasks'))%0A self.assertNotContains(r, task.label)%0A%0A def test_task_different_user(self):%0A user2 = self.vumi_helper.make_django_user(email='user2@domain.com')%0A task = self.create_task('Test task', account_id=user2.account_key)%0A r = self.client.get(reverse('scheduler:tasks'))%0A self.assertNotContains(r, task.label)%0A%0A def test_scheduled_tasks_in_header(self):%0A r = self.client.get(reverse('scheduler:tasks'))%0A self.assertContains(r, '%3EScheduled Tasks%3C/a%3E%3C/li%3E')%0A
c39b95eebb402d1d0137448b3f0efd9b6d7ec169
Test if repository manager if retrieving a repository when we lookup after one
tests/managers/test_repository.py
tests/managers/test_repository.py
Python
0
@@ -0,0 +1,1005 @@ +from unittest import TestCase%0A%0Afrom mock import MagicMock, patch%0Afrom nose.tools import eq_%0A%0Afrom pyolite.managers.repository import RepositoryManager%0A%0A%0Aclass TestRepositoryManager(TestCase):%0A def test_get_repository(self):%0A mocked_repository = MagicMock()%0A mocked_repository.get_by_name.return_value = 'my_repo'%0A%0A mocked_path = MagicMock()%0A mocked_git = MagicMock()%0A%0A with patch.multiple('pyolite.managers.manager',%0A Path=MagicMock(return_value=mocked_path),%0A Git=MagicMock(return_value=mocked_git)):%0A with patch.multiple('pyolite.managers.repository',%0A Repository=mocked_repository):%0A%0A repos = RepositoryManager('/path/to/admin/repo/')%0A%0A eq_(repos.get('my_repo'), 'my_repo')%0A mocked_repository.get_by_name.assert_called_once_with('my_repo',%0A mocked_path,%0A mocked_git)%0A
d124b7f51f0719f58e629d615c51522884515656
delete commented code
bihar/reports/indicators/reports.py
bihar/reports/indicators/reports.py
from bihar.reports.supervisor import BiharNavReport, MockEmptyReport, \ url_and_params, BiharSummaryReport, \ ConvenientBaseMixIn, GroupReferenceMixIn, list_prompt, shared_bihar_context,\ team_member_context from copy import copy from corehq.apps.reports.generic import GenericTabularReport, summary_context from corehq.apps.reports.standard import CustomProjectReport from dimagi.utils.decorators.memoized import memoized from dimagi.utils.html import format_html from django.utils.translation import ugettext as _, ugettext_noop from bihar.reports.indicators.mixins import IndicatorSetMixIn, IndicatorMixIn DEFAULT_EMPTY = "?" class IndicatorNav(GroupReferenceMixIn, BiharNavReport): name = ugettext_noop("Indicator Options") slug = "indicatornav" description = ugettext_noop("Indicator navigation") preserve_url_params = True report_template_path = "bihar/team_listing_tabular.html" extra_context_providers = [shared_bihar_context, summary_context, team_member_context] @property def reports(self): return [IndicatorClientSelectNav, IndicatorSummaryReport] @property def rendered_report_title(self): return self.group_display class IndicatorSummaryReport(GroupReferenceMixIn, BiharSummaryReport, IndicatorSetMixIn): name = ugettext_noop("Indicators") slug = "indicatorsummary" description = "Indicator details report" base_template_mobile = "bihar/indicator_summary.html" @property def rendered_report_title(self): return _(self.indicator_set.name) @property def summary_indicators(self): return [i for i in self.indicator_set.get_indicators() if i.show_in_indicators] @property def _headers(self): return [_("Team Name")] + [_(i.name) for i in self.summary_indicators] @property @memoized def data(self): def _nav_link(indicator): params = copy(self.request_params) params['indicator'] = indicator.slug del params['next_report'] return format_html(u'<a href="{next}">{chart}{val}</a>', val=self.get_indicator_value(indicator), chart=self.get_chart(indicator), next=url_and_params( IndicatorClientList.get_url(self.domain, render_as=self.render_next), params )) return [self.group.name] + \ [_nav_link(i) for i in self.summary_indicators] def get_indicator_value(self, indicator): return indicator.display(self.cases) def get_chart(self, indicator): # this is a serious hack for now piecls = 'sparkpie' split = self.get_indicator_value(indicator).split("/") chart_template = '<span data-numerator="{num}" ' \ 'data-denominator="{denom}" class="{piecls}"></span>' if len(split) == 2: return format_html(chart_template, num=split[0], denom=int(split[1]) - int(split[0]), piecls=piecls) return '' # no chart class IndicatorCharts(MockEmptyReport): name = ugettext_noop("Charts") slug = "indicatorcharts" class IndicatorClientSelectNav(GroupReferenceMixIn, BiharSummaryReport, IndicatorSetMixIn): name = ugettext_noop("Select Client List") slug = "clients" _indicator_type = "client_list" @property def rendered_report_title(self): return self.group_display @property def indicators(self): return [i for i in self.indicator_set.get_indicators() if i.show_in_client_list] @property def _headers(self): return [list_prompt(i, iset.name) for i, iset in enumerate(self.indicators)] @property def data(self): def _nav_link(indicator): params = copy(self.request_params) params["indicators"] = self.indicator_set.slug params["indicator"] = indicator.slug # params["next_report"] = IndicatorNav.slug return format_html(u'<a href="{next}">{val}</a>', val=self.count(indicator), next=url_and_params( IndicatorClientList.get_url(self.domain, render_as=self.render_next), params )) return [_nav_link(i) for i in self.indicators] def count(self, indicator): return len([c for c in self.cases if indicator.filter(c)]) class IndicatorClientList(GroupReferenceMixIn, ConvenientBaseMixIn, GenericTabularReport, CustomProjectReport, IndicatorMixIn): slug = "indicatorclientlist" name = ugettext_noop("Client List") @property def _name(self): # NOTE: this isn't currently used, but is how things should work # once we have a workaround for name needing to be available at # the class level. try: return self.indicator.name except AttributeError: return self.name @property def _headers(self): return [_(c) for c in self.indicator.get_columns()] @property def sorted_cases(self): return sorted(self.cases, key=self.indicator.sortkey) def _filter(self, case): if self.indicator: return self.indicator.filter(case) else: return True def _get_clients(self): for c in self.sorted_cases: if self._filter(c): yield c @property def rows(self): return [self.indicator.as_row(c) for c in self._get_clients()]
Python
0
@@ -4040,77 +4040,8 @@ lug%0A - %0A # params%5B%22next_report%22%5D = IndicatorNav.slug%0A
9ad755263fe12fa16c0b27381893c380626c85d8
Add unittest for string_view conversion
bindings/pyroot/test/conversions.py
bindings/pyroot/test/conversions.py
Python
0
@@ -0,0 +1,346 @@ +import unittest%0Aimport ROOT%0A%0Acppcode = %22%22%22%0Avoid stringViewConv(std::string_view) %7B%7D;%0A%22%22%22%0A%0Aclass ListInitialization(unittest.TestCase):%0A @classmethod%0A def setUpClass(cls):%0A ROOT.gInterpreter.Declare(cppcode)%0A%0A def test_string_view_conv(self):%0A ROOT.stringViewConv(%22pyString%22)%0A%0Aif __name__ == '__main__':%0A unittest.main()%0A
6cfca819bbefab1f38904fc73b46dae80e03b32e
Create __init__.py
knockoutpy/__init__.py
knockoutpy/__init__.py
Python
0.000429
@@ -0,0 +1 @@ +%0A
9eb5f67a954888c4e14789b5b8acc785c789a77c
Add a command for creating rsa key.
oidc_provider/management/commands/creatersakey.py
oidc_provider/management/commands/creatersakey.py
Python
0
@@ -0,0 +1,653 @@ +from Crypto.PublicKey import RSA%0A%0Afrom django.conf import settings%0Afrom django.core.management.base import BaseCommand, CommandError%0A%0A%0Aclass Command(BaseCommand):%0A help = 'Randomly generate a new RSA key for the OpenID server'%0A%0A def handle(self, *args, **options):%0A try:%0A key = RSA.generate(1024)%0A file_path = settings.BASE_DIR + '/OIDC_RSA_KEY.pem'%0A with open(file_path, 'w') as f:%0A f.write(key.exportKey('PEM'))%0A self.stdout.write('RSA key successfully created at: ' + file_path)%0A except Exception as e:%0A self.stdout.write('Something goes wrong: ' + e.message)%0A
aaddd474b8e17164c59f445d14b75b9f20a95948
add post install
setup_post_install.py
setup_post_install.py
Python
0
@@ -0,0 +1,1606 @@ +import urllib2%0Aimport zipfile%0Aimport re%0Aimport sys%0Afrom glob import glob%0Afrom os import chdir, mkdir, rename, getcwd%0Afrom os.path import exists%0A%0Afrom resample_all import resample_all%0A%0Adef run_post_install():%0A%0A%09# Double check modules%0A%0A%09modules = set(%5B'numpy', 'scipy', 'librosa', 'sklearn'%5D)%0A%09for module in modules:%0A%09%09try:%0A%09%09%09__import__(module)%0A%09%09except ImportError:%0A%09%09%09print('module %5C'' + str(module) + '%5C' is not installed')%0A%09%09%09sys.exit()%0A%0A%09# Download dataset%0A%0A%09url = 'http://c4dm.eecs.qmul.ac.uk/rdr/bitstream/handle/123456789/29/scenes_stereo.zip'%0A%0A%09file_name = url.split('/')%5B-1%5D%0A%09u = urllib2.urlopen(url)%0A%09f = open(file_name, 'wb')%0A%09meta = u.info()%0A%09file_size = int(meta.getheaders(%22Content-Length%22)%5B0%5D)%0A%09print 'Downloading: %25s Bytes: %25s' %25 (file_name, file_size)%0A%0A%09file_size_dl = 0%0A%09block_sz = 8192%0A%09while True:%0A%09%09buffer = u.read(block_sz)%0A%09%09if not buffer:%0A%09%09%09break%0A%0A%09%09file_size_dl += len(buffer)%0A%09%09f.write(buffer)%0A%09%09status = r'%2510d %5B%253.2f%25%25%5D' %25 (file_size_dl, file_size_dl * 100. / file_size)%0A%09%09status = status + chr(8)*(len(status)+1)%0A%09%09print status,%0A%0A%09f.close()%0A%0A%09# Extract zip%0A%0A%09print('%5CnExtracting zip file')%0A%09with zipfile.ZipFile('scenes_stereo.zip', %22r%22) as z:%0A%09%09z.extractall('./')%0A%0A%09# Reorganize folders%0A%09%0A%09print('Moving files to class folders')%0A%09audio_folder = 'scenes_stereo/'%0A%09home_folder = getcwd()%0A%09chdir(audio_folder)%0A%0A%09for filename in glob('*'):%0A%0A%09%09y = re.split('0%7C1', filename)%5B0%5D%0A%09%09if not exists(y):%0A%09%09%09mkdir(y)%0A%09%09rename(filename, y + '/' + filename)%0A%0A%0A%09# Resample%0A%0A%09print('Resampling all files to 8kHz')%0A%09chdir(home_folder)%0A%09resample_all()%0A%0A%09print('Setup finished with no errors')%0A
768b0ec7afa92156f35663d45b2ef3e091f35da5
Allow helpers to return None
smore/apispec/core.py
smore/apispec/core.py
# -*- coding: utf-8 -*- from .exceptions import APISpecError, PluginError class Path(object): """Represents a Swagger Path object. https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#pathsObject :param str path: The path template, e.g. ``"/pet/{petId}"`` :param str method: The HTTP method. :param dict operation: The operation object, as a `dict`. See https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#operationObject """ def __init__(self, path=None, operations=None, **kwargs): self.path = path self.operations = operations or {} def to_dict(self): if not self.path: raise APISpecError('Path template is not specified') return { self.path: self.operations } def update(self, path): if path.path: self.path = path.path self.operations.update(path.operations) class APISpec(object): """Stores metadata that describes a RESTful API using the Swagger 2.0 specification. """ def __init__(self, plugins=(), default_content_types=None, *args, **kwargs): # Metadata self._definitions = {} self._paths = {} # Plugin and helpers self._plugins = {} self._definition_helpers = [] self._path_helpers = [] for plugin_path in plugins: self.setup_plugin(plugin_path) def to_dict(self): return { 'definitions': self._definitions, 'paths': self._paths, } def add_path(self, path=None, operations=None, **kwargs): """Add a new path object to the spec. https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#paths-object- """ path = Path(path=path, operations=operations) # Execute plugins' helpers for func in self._path_helpers: ret = func( path=path, operations=operations, **kwargs ) path.update(ret) self._paths.update(path.to_dict()) def definition(self, name, properties=None, enum=None, **kwargs): """Add a new definition to the spec. https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#definitionsObject """ ret = {} # Execute all helpers from plugins for func in self._definition_helpers: ret.update(func(name, **kwargs)) if properties: ret['properties'] = properties if enum: ret['enum'] = enum self._definitions[name] = ret # PLUGIN INTERFACE # adapted from Sphinx def setup_plugin(self, path): """Import and setup a plugin. No-op if called twice for the same plugin. :param str name: Import path to the plugin. :raise: PluginError if the given plugin is invalid. """ if path in self._plugins: return try: mod = __import__( path, globals=None, locals=None, fromlist=('setup', ) ) except ImportError as err: raise PluginError( 'Could not import plugin "{0}"\n\n{1}'.format(path, err) ) if not hasattr(mod, 'setup'): raise PluginError('Plugin "{0}" has no setup() function.') else: mod.setup(self) self._plugins[path] = mod return None def register_definition_helper(self, func): """Register a new definition helper. The helper **must** meet the following conditions: - Receive the definition `name` as the first argument. - Include ``**kwargs`` in its signature. - Return a `dict` representation of the definition's Schema object. The helper may define any named arguments after the `name` argument. https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#definitionsObject :param callable func: The definition helper function. """ self._definition_helpers.append(func) def register_path_helper(self, func): """Register a new path helper. The helper **must** meet the following conditions: - Include ``**kwargs`` in signature. - Return a `smore.apispec.core.Path` object. The helper may define any named arguments in its signature. """ self._path_helpers.append(func)
Python
0.999319
@@ -1990,32 +1990,74 @@ s%0A )%0A + if isinstance(ret, Path):%0A path
45140f281ac8df0a8f325e99d2cc17385eabbcf4
Create fizzbuzz.py
solutions/fizzbuzz.py
solutions/fizzbuzz.py
Python
0.00001
@@ -0,0 +1,232 @@ +def fizzbuzz(number):%0A%09for i in range(number):%0A%09%09if i%2515 == 0:%0A%09%09%09print %22FizzBuzz%22%0A%09%09elif i%255 == 0:%0A%09%09%09print %22Buzz%22%0A%09%09elif i%253 == 0:%0A%09%09%09print %22Fizz%22%0A%09%09else:%0A%09%09%09print i%0A%0Adef main():%0A%09fizzbuzz(101)%0A%0Aif __name__ == '__main__':%0A%09main()%0A
feb7b6c627c05412176fd070abd8d5116d30f227
:sparkles:find smallest letter greater than target
python/problems/find_smallest_letter_greater_than_target.py
python/problems/find_smallest_letter_greater_than_target.py
Python
0.999505
@@ -0,0 +1,1251 @@ +%22%22%22%0Ahttps://leetcode.com/problems/find-smallest-letter-greater-than-target/description/%0A%0Ahttps://leetcode.com/submissions/detail/131676021/%0A%22%22%22%0A%0A%0Aclass Solution:%0A def nextGreatestLetter(self, letters, target):%0A %22%22%22%0A :type letters: List%5Bstr%5D%0A :type target: str%0A :rtype: str%0A %22%22%22%0A dic = 'abcdefghijklmnopqrstuvwxyz'%0A targetIndex = dic.index(target)%0A resultIndex = 0%0A found = False%0A for i in range(len(letters)):%0A letter = letters%5Bi%5D%0A letterIndex = dic.index(letter)%0A if letterIndex %3C= targetIndex:%0A resultIndex = i%0A else:%0A found = True%0A resultIndex = i%0A break%0A if found:%0A return letters%5BresultIndex%5D%0A return letters%5B0%5D%0A%0A%0Aimport unittest%0A%0A%0Aclass Test(unittest.TestCase):%0A def test(self):%0A solution = Solution()%0A self.assertEqual(solution.nextGreatestLetter(%0A %5B'c', 'f', 'j'%5D, 'a'), 'c')%0A self.assertEqual(solution.nextGreatestLetter(%0A %5B'c', 'f', 'j'%5D, 'c'), 'f')%0A self.assertEqual(solution.nextGreatestLetter(%0A %5B'c', 'f', 'j'%5D, 'k'), 'c')%0A%0A%0Aif __name__ == '__main__':%0A unittest.main()%0A
2ea891fd99eb50f58abb6cf1dba55950916742ab
Clear solution for roman-numerals.
roman-numerals.py
roman-numerals.py
Python
0
@@ -0,0 +1,961 @@ +# I 1 (unus)%0A# V 5 (quinque)%0A# X 10 (decem)%0A# L 50 (quinquaginta)%0A# C 100 (centum)%0A# D 500 (quingenti)%0A# M 1,000 (mille)%0A%0Aplace2symbol = %7B%0A 0: %22I%22,%0A 1: %22X%22,%0A 2: %22C%22,%0A 3: %22M%22,%0A%7D%0A%0Areplacements = %5B%0A (%22I%22 * 9, %22IX%22),%0A (%22I%22 * 5, %22V%22),%0A (%22I%22 * 4, %22IV%22),%0A (%22X%22 * 9, %22XC%22),%0A (%22X%22 * 5, %22L%22),%0A (%22X%22 * 4, %22XL%22),%0A (%22C%22 * 9, %22CM%22),%0A (%22C%22 * 5, %22D%22),%0A (%22C%22 * 4, %22CD%22),%0A%5D%0A%0A%0Adef checkio(number):%0A snumber = str(number)%0A replaceable = %22%22.join(%5B%0A place2symbol%5Blen(snumber) - invp - 1%5D * int(d)%0A for invp, d%0A in enumerate(snumber)%0A if d != %220%22 # There is no zero in the roman number system.%0A %5D)%0A for old, new in replacements:%0A replaceable = replaceable.replace(old, new)%0A return replaceable%0A%0Aif __name__ == '__main__':%0A assert checkio(6) == 'VI', '6'%0A assert checkio(76) == 'LXXVI', '76'%0A assert checkio(499) == 'CDXCIX', '499'%0A assert checkio(3888) == 'MMMDCCCLXXXVIII', '3888'%0A
d0c4ff9461144e9608c30c8d5a43381282912cc0
Add builtin/github/writer.py
anchorhub/builtin/github/writer.py
anchorhub/builtin/github/writer.py
Python
0
@@ -0,0 +1,986 @@ +%22%22%22%0AFile that initializes a Writer object designed for GitHub style markdown files.%0A%22%22%22%0A%0Afrom anchorhub.writer import Writer%0Afrom anchorhub.builtin.github.wstrategies import MarkdownATXWriterStrategy, %5C%0A MarkdownSetextWriterStrategy, MarkdownInlineLinkWriterStrategy%0Aimport anchorhub.builtin.github.switches as ghswitches%0A%0A%0Adef make_github_markdown_writer(opts):%0A %22%22%22%0A Creates a Writer object used for parsing and writing Markdown files with%0A a GitHub style anchor transformation%0A%0A :param opts:%0A :return: A Writer object designed for parsing, modifying, and writing%0A AnchorHub tags to converted anchors in Markdown files using GitHub style%0A anchors%0A %22%22%22%0A assert hasattr(opts, 'wrapper_regex')%0A atx = MarkdownATXWriterStrategy(opts)%0A inline = MarkdownInlineLinkWriterStrategy(opts)%0A code_block_switch = ghswitches.code_block_switch%0A%0A strategies = %5Batx, inline%5D%0A switches = %5Bcode_block_switch%5D%0A%0A return Writer(strategies, switches=switches)
ed19693800bbe50121fead603a3c645fdc1ed81a
Add migration
services/migrations/0059_add_unit_count_related_name.py
services/migrations/0059_add_unit_count_related_name.py
Python
0.000002
@@ -0,0 +1,598 @@ +# -*- coding: utf-8 -*-%0A# Generated by Django 1.11.11 on 2018-05-17 11:34%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations, models%0Aimport django.db.models.deletion%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('services', '0058_add_servicenodeunitcount'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterField(%0A model_name='servicenodeunitcount',%0A name='service_node',%0A field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='unit_counts', to='services.ServiceNode'),%0A ),%0A %5D%0A
c83cc4a60c719cf07d5ee3fe14556f8bb9542d22
check zmq version in ProxyDevice
zmq/devices/proxydevice.py
zmq/devices/proxydevice.py
"""Proxy classes and functions. Authors ------- * MinRK * Brian Granger """ #----------------------------------------------------------------------------- # Copyright (c) 2013 Brian Granger, Min Ragan-Kelley # # This file is part of pyzmq # # Distributed under the terms of the New BSD License. The full license is in # the file COPYING.BSD, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- import time from zmq import ZMQError, PUB from zmq.devices.basedevice import Device, ThreadDevice, ProcessDevice #----------------------------------------------------------------------------- # Classes #----------------------------------------------------------------------------- class ProxyBase(object): """Base class for overriding methods.""" def __init__(self, in_type, out_type, mon_type=PUB): Device.__init__(self, in_type=in_type, out_type=out_type) self.mon_type = mon_type self._mon_binds = [] self._mon_connects = [] self._mon_sockopts = [] def bind_mon(self, addr): """Enqueue ZMQ address for binding on mon_socket. See zmq.Socket.bind for details. """ self._mon_binds.append(addr) def connect_mon(self, addr): """Enqueue ZMQ address for connecting on mon_socket. See zmq.Socket.bind for details. """ self._mon_connects.append(addr) def setsockopt_mon(self, opt, value): """Enqueue setsockopt(opt, value) for mon_socket See zmq.Socket.setsockopt for details. """ self._mon_sockopts.append((opt, value)) def _setup_sockets(self): ins,outs = Device._setup_sockets(self) ctx = self._context mons = ctx.socket(self.mon_type) # set sockopts (must be done first, in case of zmq.IDENTITY) for opt,value in self._mon_sockopts: mons.setsockopt(opt, value) for iface in self._mon_binds: mons.bind(iface) for iface in self._mon_connects: mons.connect(iface) return ins,outs,mons def run(self): ins,outs,mons = self._setup_sockets() rc = zmq.proxy(ins, outs, mons) self.done = True return rc class Proxy(ProxyBase, Device): """Threadsafe Proxy object. *Warning* as with most 'threadsafe' Python objects, this is only threadsafe as long as you do not use private methods or attributes. Private names are prefixed with '_', such as 'self._setup_socket()'. See zmq.devices.Device for most of the spec. This subclass adds a <method>_mon version of each <method>_{in|out} method, for configuring the monitor socket. A Proxy is a 3-socket ZMQ Device that functions just like a QUEUE, except each message is also sent out on the monitor socket. If a message comes from in_sock, it will be prefixed with 'in'. If it comes from out_sock, it will be prefixed with 'out' A PUB socket is perhaps the most logical for the mon_socket, but it is not restricted. """ pass class ThreadProxy(ProxyBase, ThreadDevice): """Proxy in a Thread. See Proxy for more.""" pass class ProcessProxy(ProxyBase, ProcessDevice): """Proxy in a Process. See Proxy for more.""" pass __all__ = [ 'Proxy', 'ThreadProxy', 'ProcessProxy', ]
Python
0
@@ -647,37 +647,18 @@ me%0A%0A -from zmq import ZMQError, PUB +import zmq %0Afro @@ -1022,16 +1022,20 @@ on_type= +zmq. PUB):%0A @@ -1107,32 +1107,172 @@ t_type)%0A +if zmq.zmq_version_info() %3C (3,2):%0A raise RuntimeError(%22zmq.proxy only available with libzmq %3E= 3.2, not %25s%22 %25 zmq.zmq_version()) %0A self.mo
d46374388596fee83be8aa850afc961579b71a22
add basic settings.py
uiautomator2/settings.py
uiautomator2/settings.py
Python
0.000001
@@ -0,0 +1,1189 @@ +# coding: utf-8%0A#%0A%0Afrom typing import Any%0Aimport uiautomator2 as u2%0A%0A%0Aclass Settings(object):%0A def __init__(self, d: u2.Device = None):%0A self._d = d%0A self._defaults = %7B%0A %22post_delay%22: 0,%0A %22implicitly_wait%22: 20.0,%0A %7D%0A self._props = %7B%0A %22post_delay%22: %5Bfloat, int%5D,%0A %22implicitly_wait%22: %5Bfloat, int%5D,%0A %7D%0A for k, v in self._defaults.items():%0A if k not in self._props:%0A self._props%5Bk%5D = type(v)%0A%0A def get(self, key: str) -%3E Any:%0A return self._defaults.get(key)%0A %0A def set(self, key: str, val: Any):%0A if key not in self._props:%0A raise AttributeError(%22invalid attribute%22, key)%0A if not isinstance(val, self._props%5Bkey%5D):%0A raise TypeError(%22invalid type, only accept: %25s%22 %25 self._props%5Bkey%5D)%0A self._defaults%5Bkey%5D = val%0A%0A def __setitem__(self, key: str, val: Any):%0A self.set(key, val)%0A%0A def __getitem__(self, key: str) -%3E Any:%0A return self.get(key)%0A%0A%0A%0Aif __name__ == %22__main__%22:%0A settings = Settings()%0A settings.set(%22pre_delay%22, 10)%0A print(settings%5B'pre_delay'%5D)%0A settings%5B%22post_delay%22%5D = 10%0A
c2470e9710d29cc4bfe38f1598eb2025d52507d2
Use internal class variable for resolving templates in makefiles
tools/export/makefile/__init__.py
tools/export/makefile/__init__.py
""" mbed SDK Copyright (c) 2011-2016 ARM Limited 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 os.path import splitext, basename, relpath, join, abspath, dirname,\ exists from os import curdir, getcwd from jinja2.exceptions import TemplateNotFound from tools.export.exporters import Exporter from tools.utils import NotSupportedException from tools.targets import TARGET_MAP class Makefile(Exporter): """Generic Makefile template that mimics the behavior of the python build system """ DOT_IN_RELATIVE_PATH = True MBED_CONFIG_HEADER_SUPPORTED = True def generate(self): """Generate the makefile Note: subclasses should not need to override this method """ self.resources.win_to_unix() to_be_compiled = [splitext(src)[0] + ".o" for src in self.resources.s_sources + self.resources.c_sources + self.resources.cpp_sources] libraries = [self.prepare_lib(basename(lib)) for lib in self.resources.libraries] ctx = { 'name': self.project_name, 'to_be_compiled': to_be_compiled, 'object_files': self.resources.objects, 'include_paths': list(set(self.resources.inc_dirs)), 'library_paths': self.resources.lib_dirs, 'linker_script': self.resources.linker_script, 'libraries': libraries, 'hex_files': self.resources.hex_files, 'vpath': (["../../.."] if (basename(dirname(dirname(self.export_dir))) == "projectfiles") else [".."]), 'cc_cmd': " ".join(["\'" + part + "\'" for part in self.toolchain.cc]), 'cppc_cmd': " ".join(["\'" + part + "\'" for part in self.toolchain.cppc]), 'asm_cmd': " ".join(["\'" + part + "\'" for part in self.toolchain.asm]), 'ld_cmd': " ".join(["\'" + part + "\'" for part in self.toolchain.ld]), 'elf2bin_cmd': "\'" + self.toolchain.elf2bin + "\'", 'link_script_ext': self.toolchain.LINKER_EXT, 'link_script_option': self.LINK_SCRIPT_OPTION, 'user_library_flag': self.USER_LIBRARY_FLAG, } for key in ['include_paths', 'library_paths', 'linker_script', 'hex_files']: if isinstance(ctx[key], list): ctx[key] = [ctx['vpath'][0] + "/" + t for t in ctx[key]] else: ctx[key] = ctx['vpath'][0] + "/" + ctx[key] if "../." not in ctx["include_paths"]: ctx["include_paths"] += ['../.'] for key in ['include_paths', 'library_paths', 'hex_files', 'to_be_compiled']: ctx[key] = sorted(ctx[key]) ctx.update(self.flags) for templatefile in \ ['makefile/%s_%s.tmpl' % (self.NAME.lower(), self.target.lower())] + \ ['makefile/%s_%s.tmpl' % (self.NAME.lower(), label.lower()) for label in self.toolchain.target.extra_labels] +\ ['makefile/%s.tmpl' % self.NAME.lower()]: try: self.gen_file(templatefile, ctx, 'Makefile') break except TemplateNotFound: pass else: raise NotSupportedException("This make tool is in development") class GccArm(Makefile): """GCC ARM specific makefile target""" TARGETS = [target for target, obj in TARGET_MAP.iteritems() if "GCC_ARM" in obj.supported_toolchains] NAME = 'Make-GCC-ARM' TOOLCHAIN = "GCC_ARM" LINK_SCRIPT_OPTION = "-T" USER_LIBRARY_FLAG = "-L" @staticmethod def prepare_lib(libname): return "-l:" + libname class Armc5(Makefile): """ARM Compiler 5 specific makefile target""" TARGETS = [target for target, obj in TARGET_MAP.iteritems() if "ARM" in obj.supported_toolchains] NAME = 'Make-ARMc5' TOOLCHAIN = "ARM" LINK_SCRIPT_OPTION = "--scatter" USER_LIBRARY_FLAG = "--userlibpath " @staticmethod def prepare_lib(libname): return libname class IAR(Makefile): """IAR specific makefile target""" TARGETS = [target for target, obj in TARGET_MAP.iteritems() if "IAR" in obj.supported_toolchains] NAME = 'Make-IAR' TOOLCHAIN = "IAR" LINK_SCRIPT_OPTION = "--config" USER_LIBRARY_FLAG = "-L" @staticmethod def prepare_lib(libname): if "lib" == libname[:3]: libname = libname[3:] return "-l" + splitext(libname)[0]
Python
0
@@ -3532,36 +3532,32 @@ pl' %25 (self. -NAME.lower() +TEMPLATE ,%0A @@ -3653,28 +3653,24 @@ %25 (self. -NAME.lower() +TEMPLATE ,%0A @@ -3824,20 +3824,16 @@ elf. -NAME.lower() +TEMPLATE %5D:%0A @@ -4295,16 +4295,46 @@ CC-ARM'%0A + TEMPLATE = 'make-gcc-arm'%0A TOOL @@ -4706,16 +4706,44 @@ -ARMc5'%0A + TEMPLATE = 'make-armc5'%0A TOOL @@ -5077,32 +5077,32 @@ ted_toolchains%5D%0A - NAME = 'Make @@ -5107,16 +5107,42 @@ ke-IAR'%0A + TEMPLATE = 'make-iar'%0A TOOL
9327b5f0836652c4225af2c4e10cda592ce15a09
Distinct subsequence
DP/distinct_subsequences.py
DP/distinct_subsequences.py
Python
0.99897
@@ -0,0 +1,1272 @@ +import unittest%0A%22%22%22%0AGiven two sequences A and B, find out number of distinct subsequences in A which are equal to B.%0AInput: A: rabbbit, B: rabbit%0AOutput: 2 %5BOne subsequence which includes first b and one excludes first b%5D%0A%22%22%22%0A%0A%22%22%22%0AApproach:%0A1. Following optimal substructure exists:%0A If A%5Bi%5D != B%5Bj%5D:%0A distinct(A,B,i,j) = distinct(A,B,i-1,j)%0A else:%0A distinct(A,B,i,j) = distinct(A,B,i-1,j-1) + distinct(A,B,i-1,j)%0AThat is, even when characters match, we may include the match or exlclude the match while looking for subsequence.%0A%22%22%22%0A%0A%0Adef distinct_subsequences(A, B, i, j, table=%7B%7D):%0A if j == 0:%0A return 1%0A if j %3E i:%0A return 0%0A key = A%5B:i%5D + B%5B:j%5D%0A if key in table:%0A return table%5Bkey%5D%0A if A%5Bi-1%5D == B%5Bj-1%5D:%0A result = distinct_subsequences(A, B, i-1, j-1) + distinct_subsequences(A, B, i-1, j)%0A else:%0A result = distinct_subsequences(A, B, i-1, j)%0A table%5Bkey%5D = result%0A return result%0A%0A%0Aclass TestDistinctSubsequences(unittest.TestCase):%0A%0A def test_distinct_subsequences(self):%0A A = 'rabbbit'%0A B = 'rabbit'%0A self.assertEqual(distinct_subsequences(A, B, len(A), len(B)), 3)%0A A = 'uwnny'%0A B = 'uwnny'%0A self.assertEqual(distinct_subsequences(A, B, len(A), len(B)), 1)%0A