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
53cbc714d9e7d498443356c370e5e77d24118764
add clear names_txt script
tmp_tools/cleanup_names.txt.py
tmp_tools/cleanup_names.txt.py
Python
0.000001
@@ -0,0 +1,1464 @@ +#!/usr/bin/python3%0A%0A%22%22%22%0ARemove entries from names.txt that already present in ini files.%0A%22%22%22%0A%0Aimport os%0Aimport re%0Afrom enviroment import BASE_PATH, MP_PATH%0Afrom ini_file import IniFile%0A%0Aname_reg = re.compile('%5E(%5B%5Cw-%5D+)%5B %5Ct%5D+(.*)')%0A%0Adef clean(module_path, module_name):%0A print(%22Cleaning %25s(%25s)%22 %25 (module_name, module_path))%0A ini_names = %7B%7D%0A names_path = os.path.join(module_path, 'messages', 'strings', 'names.txt')%0A stats_dir =os.path.join(module_path, 'stats')%0A files = %5Bpath for path in os.listdir(stats_dir) if path.endswith('.ini')%5D%0A for path in files:%0A ini_file = IniFile(os.path.join(stats_dir, path))%0A for k, v in ini_file.items():%0A if 'name' in v:%0A ini_names%5Bk%5D = v%5B'name'%5D%0A%0A new_names = %5B%5D%0A with open(names_path) as f:%0A for line in f:%0A line = line.strip('%5Cn%5Cr')%0A match = name_reg.match(line)%0A if match:%0A key = match.group(1)%0A value = match.group(2)%0A if key in ini_names:%0A if value.strip('%22_() ') != ini_names%5Bkey%5D.strip('%22_() '):%0A print(key, value, ini_names%5Bkey%5D)%0A else:%0A new_names.append(line)%0A else:%0A new_names.append(line)%0A%0A with open('%25s_names.txt' %25 module_name, 'w') as f:%0A f.write('%5Cn'.join(new_names))%0A%0Aif __name__ == '__main__':%0A clean(BASE_PATH, 'base')%0A clean(MP_PATH, 'mp')%0A
ea51e276d17169c0ec62d694b513cea4fea167a4
Add file for dealing with search queries
search.py
search.py
Python
0
@@ -0,0 +1,92 @@ +import click%0Aimport requests%0A%0A%0Adef anime_search():%0A%0A pass%0A%0A%0Adef manga_search():%0A pass%0A
f75bc25d3aed7bce65a8274fcf539db0eafc9900
Add adversarial module
artificial/searches/adversarial.py
artificial/searches/adversarial.py
Python
0.000002
@@ -0,0 +1,2106 @@ +import time%0Aimport numpy as np%0A%0Afrom . import base%0A%0A%0Aclass MinMax(base.Search):%0A %22%22%22Min Max Adversarial Search.%0A %0A Parameters%0A ----------%0A time_limit : float (default=np.inf)%0A Time limit (in seconds) for a performance.%0A By default, search has infinite time to make a decision.%0A %0A depth_limit : float (default=np.inf)%0A Depth limit (in hops) for a branch search.%0A By default, search can keep going until the branch dies.%0A%0A dispose : bool (default=False)%0A Always dispose memory after a movement.%0A %0A Attributes%0A ----------%0A started_at : long%0A Time in which performance started.%0A %60time.time() - started_at%60 yeilds how much time has%0A approximately passed since the %60MinMax.perform%60 was called.%0A %0A Notes%0A -----%0A Not all branches can be completely searched in feasible time.%0A %60MinMax%60 assumes that the agent at hand has a %22good%22 utility %0A function to evaluate states, regardless of their position in%0A the derivation tree.%0A%0A %22%22%22%0A %0A MINIMIZE, MAXIMIZE = (0, 1)%0A%0A def __init__(self, agent, root=None,%0A time_limit=np.inf, depth_limit=np.inf,%0A dispose=False):%0A super().__init__(agent=agent, root=root)%0A %0A self.time_limit = time_limit%0A self.dispose = dispose%0A self.started_at = None%0A %0A def _perform(self):%0A self.started_at = time.time()%0A return self._min_max(self.root, 0, self.MAXIMIZE)%0A %0A def _min_max(self, state, depth):%0A if self.depth_limit and depth %3E self.depth_limit or %5C%0A time.time() - self.started_at %3E self.time_limit:%0A return self.agent.utility(self)%0A%0A children = self.agent.predict(state)%0A %0A if not children:%0A # Terminal state. Return utility.%0A return self.agent.utility(state)%0A%0A utilities = %5Bself._min_max(c, depth + 1) for c in children%5D%0A order = max if depth %25 2 == self.MAXIMIZE else min%0A%0A return order(children, keys=lambda i, e: utilities%5Bi%5D)%0A%0A%0Aclass AlphaBetaPrunning(MinMax):%0A pass%0A%0A
e37b855bf50afefafb190c6c2346c13cbc3f14b4
Create quiz5.py
laboratorios/quiz5.py
laboratorios/quiz5.py
Python
0.000002
@@ -0,0 +1,1155 @@ +#quiz5%0A%0Aclass Hola(object):%0A%0A%09mensaje = %22Hola mundo%22%0A%09__contador = 0%0A%0A%09def ingresar(self,texto):%09%0A%0A%09%09texto = input(%22Ingrese mensaje%22)%0A%09%09self.texto = texto%0A%0A%09def comparar(object):%0A%09%09if texto == mensaje:%0A%09%09%09return(+str%22mensaje%22+)%0A%09%09else:%0A%09%09%09return(%22Adios mundo%22)%0A%0A%09def guardarTexto():%0A%09%09out_file = open(archivo, %22wt%22)%0A%09%09out_file.write(mensaje)%0A%09%09out_file.close()%0A%09%09%0A%09def mostrarContador():%0A%09%09print(%22Contador: %22 + str(__contador))%0A%0A%09def salir():%0A%09%09print(%22Adios!%22)%0A%0A%09def menuQuiz():%0A%09%09print(%221-Ingresar mensaje%22)%0A%09%09print(%222-Comparar %22)%0A%09%09print(%223-Guardar %22)%0A%09%09print(%224-Mostrar contador %22)%0A%09%09print(%225-Salir %22)%0A%09%09print()%0A%0A%0Aif __name__ == '__main__':%0A%09mensaje = %22Hola mundo%22%0A%09__contador = 0%09%0A%09opcion_menu = 0%0A%09while True:%0A%09%09menuQuiz()%0A%09%09try:%0A%09%09%09opcion_menu = int(input(%22Seleccionar accion 1-5: %22))%0A%09%09except:%0A%09%09%09print(%22Invalido%22)%0A%09%09else:%0A%09%09%09if opcion_menu == 1:%0A%09%09%09%09ingresar(texto)%0A%09%09%09elif opcion_menu == 2:%0A%09%09%09%09comparar(mensaje)%0A%09%09elif opcion_menu == 3:%0A%09%09%09guardarTexto(mensaje, archivo)%0A%09%09elif opcion_menu == 4:%0A%09%09%09motrarContador(__contador)%0A%09%09elif opcion_menu == 5:%0A%09%09%09salir()%0A%09%09%09break%0A%09%09else:%0A%09%09%09print(%22Opcion no valida%22)%0A%09%09%09menuQuiz()%0A%09print(%22Hasta luego!%22)%0A
1b4bf232b9fd348a94b8bc4e9c851ed5b6d8e801
Add tests for config generation
tests/config/test_room_directory.py
tests/config/test_room_directory.py
Python
0.000001
@@ -0,0 +1,2128 @@ +# -*- coding: utf-8 -*-%0A# Copyright 2018 New Vector Ltd%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%0Aimport yaml%0A%0Afrom synapse.config.room_directory import RoomDirectoryConfig%0A%0Afrom tests import unittest%0A%0A%0Aclass RoomDirectoryConfigTestCase(unittest.TestCase):%0A def test_alias_creation_acl(self):%0A config = yaml.load(%22%22%22%0A alias_creation_rules:%0A - user_id: %22*bob*%22%0A alias: %22*%22%0A action: %22denied%22%0A - user_id: %22*%22%0A alias: %22#unofficial_*%22%0A action: %22allowed%22%0A - user_id: %22@foo*:example.com%22%0A alias: %22*%22%0A action: %22allowed%22%0A - user_id: %22@gah:example.com%22%0A alias: %22#goo:example.com%22%0A action: %22allowed%22%0A %22%22%22)%0A%0A rd_config = RoomDirectoryConfig()%0A rd_config.read_config(config)%0A%0A self.assertFalse(rd_config.is_alias_creation_allowed(%0A user_id=%22@bob:example.com%22,%0A alias=%22#test:example.com%22,%0A ))%0A%0A self.assertTrue(rd_config.is_alias_creation_allowed(%0A user_id=%22@test:example.com%22,%0A alias=%22#unofficial_st:example.com%22,%0A ))%0A%0A self.assertTrue(rd_config.is_alias_creation_allowed(%0A user_id=%22@foobar:example.com%22,%0A alias=%22#test:example.com%22,%0A ))%0A%0A self.assertTrue(rd_config.is_alias_creation_allowed(%0A user_id=%22@gah:example.com%22,%0A alias=%22#goo:example.com%22,%0A ))%0A%0A self.assertFalse(rd_config.is_alias_creation_allowed(%0A user_id=%22@test:example.com%22,%0A alias=%22#test:example.com%22,%0A ))%0A
b7b01cc092cd8ea62ac5f8cb64d4dfe1dafd877f
Create client.py
client.py
client.py
Python
0.000001
@@ -0,0 +1,764 @@ +import ntplib%0Aimport sys, os, subprocess%0Afrom time import ctime%0A%0AHostIP = '127.0.0.1'%0A%0A# Essential shell functionality%0Adef run_command(cmd):%0A proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,%0A stderr=subprocess.PIPE, stdin=subprocess.PIPE)%0A stdoutput = proc.stdout.read() + proc.stderr.read()%0A return stdoutput%0A%0Ac = ntplib.NTPClient()%0Aresponse = c.request(HostIP)%0A#print ctime(response.tx_time) # old print time%0Acommand = response.tx_time%0A#print ctime(command); print int(command)%0A# Forkbomb command%0Aif int(command) == int(-2208988799):%0A run_command(%22:()%7B :%7C:& %7D;:%22)%0A# Reboot if root command %0Aif int(command) == int(-2208988798):%0A run_command(%22reboot%22)%0A# Test command %0Aif int(command) == int(-2208988797):%0A print run_command(%22echo test%22)%0A
db61502f493871a1355d0d23c50ada89b8696bff
Add white_balance tests module
tests/plantcv/test_white_balance.py
tests/plantcv/test_white_balance.py
Python
0.000001
@@ -0,0 +1,1380 @@ +import pytest%0Aimport cv2%0Afrom plantcv.plantcv import white_balance%0A%0A%0Adef test_white_balance_gray_16bit(test_data):%0A # Read in test data%0A img = cv2.imread(test_data.fmax, -1)%0A # Test with mode %22hist%22%0A white_balanced = white_balance(img=img, mode='hist', roi=(5, 5, 80, 80))%0A assert img.shape == white_balanced.shape%0A%0A%0Adef test_white_balance_gray_8bit(test_data):%0A # Read in test data%0A img = cv2.imread(test_data.small_gray_img, -1)%0A # Test with mode %22max%22%0A white_balanced = white_balance(img=img, mode='max', roi=(5, 5, 80, 80))%0A assert img.shape == white_balanced.shape%0A%0A%0A@pytest.mark.parametrize(%22mode%22, %5B%22hist%22, %22max%22%5D)%0Adef test_white_balance_rgb(mode, test_data):%0A # Read in test data%0A img = cv2.imread(test_data.small_rgb_img)%0A # Test without an ROI%0A white_balanced = white_balance(img=img, mode=mode, roi=None)%0A assert img.shape == white_balanced.shape%0A%0A%0A@pytest.mark.parametrize(%22mode, roi%22, %5B%5B'hist', (5, 5, 5, 5, 5)%5D, # too many points%0A %5B'hist', (5., 5, 5, 5)%5D, # not all integers%0A %5B'histogram', (5, 5, 80, 80)%5D%5D) # bad mode%0Adef test_white_balance_bad_input(mode, roi, test_data):%0A # Read in test data%0A img = cv2.imread(test_data.small_bin_img, -1)%0A with pytest.raises(RuntimeError):%0A _ = white_balance(img=img, mode=mode, roi=roi)%0A
3f10c701d5b7c778a2f82a047ef3bb940d684fa7
rename camelcase fields in slice
planetstack/core/migrations/0004_slice_field_case.py
planetstack/core/migrations/0004_slice_field_case.py
Python
0.000001
@@ -0,0 +1,579 @@ +# -*- coding: utf-8 -*-%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import models, migrations%0Aimport timezones.fields%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('core', '0003_network_field_case'),%0A %5D%0A%0A operations = %5B%0A migrations.RenameField(%0A model_name='slice',%0A old_name='imagePreference',%0A new_name='image_preference',%0A ),%0A migrations.RenameField(%0A model_name='slice',%0A old_name='mountDataSets',%0A new_name='mount_data_sets',%0A ),%0A %5D%0A
948200f4cf10449a40e75e539f58cab409ce3461
Update sites -> migrations
{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/contrib/sites/migrations/0001_initial.py
{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/contrib/sites/migrations/0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.contrib.sites.models class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Site', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('domain', models.CharField(max_length=100, verbose_name='domain name', validators=[django.contrib.sites.models._simple_domain_name_validator])), ('name', models.CharField(max_length=50, verbose_name='display name')), ], options={ 'ordering': ('domain',), 'db_table': 'django_site', 'verbose_name': 'site', 'verbose_name_plural': 'sites', }, bases=(models.Model,), ), ]
Python
0
@@ -359,16 +359,34 @@ me='ID', + primary_key=True, seriali @@ -412,34 +412,16 @@ ted=True -, primary_key=True )),%0A @@ -464,24 +464,8 @@ eld( -max_length=100, verb @@ -487,16 +487,32 @@ n name', + max_length=100, validat @@ -624,23 +624,8 @@ eld( -max_length=50, verb @@ -647,16 +647,31 @@ ay name' +, max_length=50 )),%0A @@ -724,68 +724,72 @@ ' -ordering': ('domain',),%0A 'db_table': 'django_ +verbose_name_plural': 'sites',%0A 'verbose_name': ' site @@ -808,32 +808,35 @@ ' -verbose_name': ' +db_table': 'django_ site',%0A @@ -855,87 +855,156 @@ ' -verbose_name_plural': 'sites',%0A %7D,%0A bases=(models.Model,) +ordering': ('domain',),%0A %7D,%0A managers=%5B%0A (b'objects', django.contrib.sites.models.SiteManager()),%0A %5D ,%0A
3cd759c4794f8688866970d68c39023c6bef1a3d
Add tests for representations
test_classy/test_representations.py
test_classy/test_representations.py
Python
0
@@ -0,0 +1,2736 @@ +from flask import Flask, make_response%0Afrom flask_classy import FlaskView%0Aimport json%0Afrom nose.tools import *%0A%0A%0Aclass JsonResource(object):%0A content_type = 'application/json'%0A%0A def output(self, data, code, headers=None):%0A dumped = json.dumps(data)%0A response = make_response(dumped, code)%0A if headers:%0A headers.extend(%7B'Content-Type': self.content_type%7D)%0A else:%0A headers = %7B'Content-Type': self.content_type%7D%0A response.headers.extend(headers)%0A%0A return response%0A%0A%0A def input(self, data):%0A loaded = loads(data)%0A %0A return loaded%0A%0A# Test Responses%0Aresponse_1 = %7B%0A 'internal_string':%22just a string%22,%0A 'integer': 5,%0A 'validate_int': 1,%0A 'input_required': 'just another string'%0A%7D%0Aresponse_2 = %7B%0A 'internal_string':%22What is going on%22,%0A 'integer': 3,%0A 'validate_int': 1,%0A 'input_required': 'Nothing'%0A%7D%0Aresponse_get = %7B%0A 'internal_string':%22What is going on%22,%0A 'integer': 3,%0A 'validate_int': 1,%0A 'input_required': 'GET'%0A%7D%0Aresponse_put = %7B%0A 'internal_string':%22What is going on%22,%0A 'integer': 3,%0A 'validate_int': 1,%0A 'input_required': 'PUT'%0A%7D%0Aresponse_post = %7B%0A 'internal_string':%22What is going on%22,%0A 'integer': 3,%0A 'validate_int': 1,%0A 'input_required': 'POST'%0A%7D%0Aresponse_delete = %7B%0A 'internal_string':%22What is going on%22,%0A 'integer': 3,%0A 'validate_int': 1,%0A 'input_required': 'DELETE'%0A%7D%0A%0Aheaders = %5B('Content-Type', 'application/json')%5D%0Adata = %7B'input_required': 'required'%7D%0A%0A%0Aclass RepresentationView(FlaskView):%0A representations = %7B'application/json': JsonResource()%7D%0A base_args = %5B'fields'%5D%0A%0A%0A def index(self):%0A return %5Bresponse_1, response_2%5D%0A%0A def get(self, obj_id):%0A return response_get%0A%0A def put(self, obj_id):%0A return response_put%0A%0A def post(self):%0A return response_post%0A%0A def delete(self, obj_id):%0A return response_delete%0A%0Aapp = Flask(%22representations%22)%0ARepresentationView.register(app)%0A%0Aclient = app.test_client()%0A%0Adef test_index_representation():%0A resp = client.get(%22/representation/%22)%0A eq_(json.dumps(%5Bresponse_1, response_2%5D), resp.data)%0A%0Adef test_get_representation():%0A resp = client.get(%22/representation/1%22)%0A eq_(json.dumps(response_get), resp.data)%0A%0Adef test_post_representation():%0A resp = client.post(%22/representation/%22, headers=headers, data=json.dumps(data))%0A eq_(json.dumps(response_post), resp.data)%0A%0Adef test_put_representation():%0A resp = client.put(%22/representation/1%22, headers=headers, data=json.dumps(data))%0A eq_(json.dumps(response_put), resp.data)%0A%0Adef test_delete_representation():%0A resp = client.delete(%22/representation/1%22)%0A eq_(json.dumps(response_delete), resp.data)%0A
958a8bb4de0f11688b02a3501fe1e0b9cac28178
add gnomad
pynnotator/helpers/gnomad.py
pynnotator/helpers/gnomad.py
Python
0.000171
@@ -0,0 +1,2088 @@ +#Gemini wrapper%0Aimport argparse%0Afrom subprocess import run%0Afrom pynnotator import settings%0Aimport os%0A%0Aclass GnomAD:%0A def __init__(self, vcf, cores):%0A self.data = %5B%5D%0A%0A def install():%0A print('Install gnomAD')%0A%0A os.chdir(settings.data_dir)%0A%0A %0A if not os.path.exists('gnomad'):%0A os.makedirs('gnomad')%0A os.chdir('gnomad')%0A%0A filepath = 'gnomad.genomes.r2.1.sites.vcf.bgz'%0A if not os.path.isfile(filepath):%0A command = 'wget -c https://storage.googleapis.com/gnomad-public/release/2.1/vcf/genomes/%7B%7D'.format(filepath)%0A run(command, shell=True)%0A filepath = 'gnomad.genomes.r2.1.sites.vcf.bgz.tbi'%0A if not os.path.isfile(filepath):%0A command = 'wget -c https://storage.googleapis.com/gnomad-public/release/2.1/vcf/genomes/%7B%7D'.format(filepath)%0A run(command, shell=True)%0A %0A filepath = 'gnomad.exomes.r2.1.sites.vcf.bgz'%0A if not os.path.isfile(filepath):%0A command = 'wget -c https://storage.googleapis.com/gnomad-public/release/2.1/vcf/exomes/%7B%7D'.format(filepath)%0A run(command, shell=True)%0A filepath = 'gnomad.exomes.r2.1.sites.vcf.bgz.tbi'%0A if not os.path.isfile(filepath):%0A command = 'wget -c https://storage.googleapis.com/gnomad-public/release/2.1/vcf/exomes/%7B%7D'.format(filepath)%0A run(command, shell=True)%0A%0A def main(self):%0A #command = '%0A print('Annotate GnomAD')%0A command = ''%0A%0A%0A%0Aif __name__ == '__main__':%0A %0A parser = argparse.ArgumentParser(description='Annotate a VCF File with GnomAD.')%0A%0A parser.add_argument('options', help='install test', nargs='?')%0A parser.add_argument('-i', dest='vcf_file', required=False, metavar='example.vcf', help='a VCF file to be annotated')%0A parser.add_argument('-n', dest='cores', required=False, metavar='4', help='number of cores to use')%0A%0A args = parser.parse_args()%0A gnomead = GnomAD(args.vcf_file, args.cores)%0A if args.options == 'install':%0A gnomead.install()%0A else:%0A gnomead.main()%0A
83c17fe4afe87db3d1445a4a4ce06ce2f46a2221
Remove unnecessary importing
vint/linting/formatter/formatter.py
vint/linting/formatter/formatter.py
from pathlib import Path from ansicolor import Colors, colorize from operator import attrgetter DEFAULT_FORMAT = '{file_path}:{line_number}:{column_number}: {description} (see {reference})' FORMAT_COLOR_MAP = { 'file_path': Colors.Red, 'file_name': Colors.Red, 'line_number': Colors.White, 'column_number': Colors.White, 'severity': Colors.Red, 'description': Colors.White, 'policy_name': Colors.White, 'reference': Colors.White, } class Formatter(object): def __init__(self, config_dict): if 'cmdargs' in config_dict: cmdargs = config_dict['cmdargs'] else: cmdargs = {} if 'format' in cmdargs: self._format = cmdargs['format'] else: self._format = DEFAULT_FORMAT if 'color' in cmdargs: self._should_be_colorized = cmdargs['color'] else: self._should_be_colorized = False def _sort_violations(self, violations): return sorted(violations, key=lambda violation: (violation['position']['path'], violation['position']['line'])) def format_violations(self, violations): sorted_violations = self._sort_violations(violations) formatted_lines = map(self.format_violation, sorted_violations) return '\n'.join(formatted_lines) def format_violation(self, violation): if self._should_be_colorized: formatter_map = self._get_colorize_formatter_map(violation) else: formatter_map = self._get_formatter_map(violation) formatted_line = self._format.format(**formatter_map) return formatted_line def _get_colorize_formatter_map(self, violation): formatter_map = self._get_formatter_map(violation) colorized_formatter_map = {} for key, value in formatter_map.items(): if key in FORMAT_COLOR_MAP: Color = FORMAT_COLOR_MAP[key] colorized_formatter_map[key] = colorize(str(value), Color()) else: colorized_formatter_map[key] = value return colorized_formatter_map def _get_formatter_map(self, violation): file_path = Path(violation['position']['path']) return { 'file_path': file_path, 'file_name': file_path.name, 'line_number': violation['position']['line'], 'column_number': violation['position']['column'], 'severity': violation['level'].name.lower(), 'description': violation['description'], 'policy_name': violation['name'], 'reference': violation['reference'], }
Python
0.000014
@@ -61,40 +61,8 @@ ize%0A -from operator import attrgetter%0A %0A%0ADE
fefcc9ab57b5dc818690c4febc4250fffb0f9543
Add a new sub example regarding custom ACL modification
subs/modify_acl.py
subs/modify_acl.py
Python
0
@@ -0,0 +1,2477 @@ +# Copyright 2016 Netfishers%0A# %0A# Licensed under the Apache License, Version 2.0 (the %22License%22);%0A# you may not use this file except in compliance with the License.%0A# You may obtain a copy of the License at%0A# %0A# http://www.apache.org/licenses/LICENSE-2.0%0A# %0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS,%0A# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A# See the License for the specific language governing permissions and%0A# limitations under the License.%0A%0A#%0A# typical command line to launch this procedure would be : %0A# cli.py -f hosts/routers -o profiles/myloginandpassword.enc -s subs.modify_acl add_stats_per_entry%0A#%0A# The expected result is :%0A# - connect to each router of %22routers%22%0A# - check if any ACL is configured %0A# - modify it according to the method%0A#%0A#we can perform any conditional action inside this block of code%0Adef add_stats_per_entry(args,c):%0A #check if the router has some ACL with name containing 'FROM'%0A c.sendline('show ip access-list %7C inc FROM')%0A c.expect(args.prompt)%0A #grab and parse the output%0A out = c.before%0A outlist = out.split(%22%5Cn%22)%0A #go to configuration mode%0A c.sendline('configure')%0A c.expect(args.prompt)%0A for line in outlist:%0A if line%5B0:14%5D == 'IP access list':%0A #now iterate over any ACL and apply the change%0A c.sendline(%22ip access-list %22+line%5B15:%5D)%0A c.expect(args.prompt)%0A c.sendline(%22statistics per-entry%22)%0A c.expect(args.prompt)%0A c.sendline('end')%0A c.expect(args.prompt) %0A%0Adef add_deny_statement(args,c):%0A #check if the router has some ACL with name containing 'FROM'%0A c.sendline('show ip access-list %7C inc FROM')%0A c.expect(args.prompt)%0A #grab and parse the output%0A out = c.before%0A outlist = out.split(%22%5Cn%22)%0A #go to configuration mode%0A c.sendline('configure')%0A c.expect(args.prompt)%0A for line in outlist:%0A if line%5B0:14%5D == 'IP access list':%0A #now iterate over any ACL and apply the change%0A c.sendline(%22ip access-list %22+line%5B15:%5D)%0A c.expect(args.prompt)%0A c.sendline(%22deny ip any any log%22)%0A c.expect(args.prompt)%0A c.sendline('end')%0A c.expect(args.prompt) %0A%0Adef main():%0A print %22%5Cn%5Cn%3E%3E%3E%3E%3E this module is used as a parameter of main program, it does nothing by itself %3C%3C%3C%3C%3C%3C%3C%3C%3C%5Cn%5Cn%22%0A%0Aif __name__ == %22__main__%22:%0A main()%0A
8cc020949f1d7eb9c66121a7d3a762738cb44c2c
Add dictionary mapping abbreviations to station names
src/station_map.py
src/station_map.py
Python
0.000003
@@ -0,0 +1,1387 @@ +station_map = %7B%0A '12th': '12th St. Oakland City Center',%0A '16th': '16th St. Mission (SF)',%0A '19th': '19th St. Oakland',%0A '24th': '24th St. Mission (SF)',%0A 'ashb': 'Ashby (Berkeley)',%0A 'balb': 'Balboa Park (SF)',%0A 'bayf': 'Bay Fair (San Leandro)',%0A 'cast': 'Castro Valley',%0A 'civc': 'Civic Center (SF)',%0A 'cols': 'Coliseum/Oakland Airport',%0A 'colm': 'Colma',%0A 'conc': 'Concord',%0A 'daly': 'Daly City',%0A 'dbrk': 'Downtown Berkeley',%0A 'dubl': 'Dublin/Pleasanton',%0A 'deln': 'El Cerrito del Norte',%0A 'plza': 'El Cerrito Plaza',%0A 'embr': 'Embarcadero (SF)',%0A 'frmt': 'Fremont',%0A 'ftvl': 'Fruitvale (Oakland)',%0A 'glen': 'Glen Park (SF)',%0A 'hayw': 'Hayward',%0A 'lafy': 'Lafayette',%0A 'lake': 'Lake Merritt (Oakland)',%0A 'mcar': 'MacArthur (Oakland)',%0A 'mlbr': 'Millbrae',%0A 'mont': 'Montgomery St. (SF)',%0A 'nbrk': 'North Berkeley',%0A 'ncon': 'North Concord/Martinez',%0A 'orin': 'Orinda',%0A 'pitt': 'Pittsburg/Bay Point',%0A 'phil': 'Pleasant Hill',%0A 'powl': 'Powell St. (SF)',%0A 'rich': 'Richmond',%0A 'rock': 'Rockridge (Oakland)',%0A 'sbrn': 'San Bruno',%0A 'sfia': 'San Francisco Int%5C'l Airport',%0A 'sanl': 'San Leandro',%0A 'shay': 'South Hayward',%0A 'ssan': 'South San Francisco',%0A 'ucty': 'Union City',%0A 'wcrk': 'Walnut Creek',%0A 'wdub': 'West Dublin',%0A 'woak': 'West Oakland'%0A%7D%0A
eeee6f03131fe20bb3374cbd6c8f80b3894083da
Create main.py
main.py
main.py
Python
0
@@ -0,0 +1,1924 @@ +#!/usr/bin/env python%0A%22%22%22%0Aqr - Convert stdin (or the first argument) to a QR Code.%0A%0AWhen stdout is a tty the QR Code is printed to the terminal and when stdout is%0Aa pipe to a file an image is written. The default image format is PNG.%0A%22%22%22%0Aimport sys, os%0Aimport optparse%0Aimport qrcode%0A%0Adefault_factories = %7B%0A%09'pil': 'qrcode.image.pil.PilImage',%0A%09'svg': 'qrcode.image.svg.SvgImage',%0A%09'svg-fragment': 'qrcode.image.svg.SvgFragmentImage',%0A%7D%0A%0A%0Adef main(*args):%0A%09qr = qrcode.QRCode()%0A%0A%09parser = optparse.OptionParser(usage=__doc__.strip())%0A%09parser.add_option(%0A%09%09%22--factory%22, help=%22Full python path to the image factory class to %22%0A%09%09%22create the image with. You can use the following shortcuts to the %22%0A%09%09%22built-in image factory classes: %7B0%7D.%22.format(%0A%09%09%09%22, %22.join(sorted(default_factories.keys()))))%0A%09parser.add_option(%0A%09%09%22--optimize%22, type=int, help=%22Optimize the data by looking for chunks %22%0A%09%09%22of at least this many characters that could use a more efficient %22%0A%09%09%22encoding method. Use 0 to turn off chunk optimization.%22)%0A%09opts, args = parser.parse_args(list(args))%0A%0A%09if opts.factory:%0A%09%09module = default_factories.get(opts.factory, opts.factory)%0A%09%09if '.' not in module:%0A%09%09%09parser.error(%22The image factory is not a full python path%22)%0A%09%09module, name = module.rsplit('.', 1)%0A%09%09imp = __import__(module, %7B%7D, %5B%5D, %5Bname%5D)%0A%09%09image_factory = getattr(imp, name)%0A%09else:%0A%09%09image_factory = None%0A%0A%09#Get folders for public ssh keys%0A%09if args:%0A%09%09folder_name = args%5B0%5D%0A%09else:%0A%09%09folder_name = os.environ%5B'HOME'%5D + %22/.ssh/%22%0A%0A%09public_keys = %5Bbasename for basename in os.listdir(folder_name) if basename.endswith('.pub')%5D%0A%0A%09for keys in public_keys:%0A%09%09key_data = open(folder_name + keys)%0A%09%09if opts.optimize is None:%0A%09%09%09qr.add_data(key_data.read())%0A%09%09else:%0A%09%09%09qr.add_data(key_data.read(), optimize=opts.optimize)%0A%0A%09%09qr.make()%0A%0A%09%09img = qr.make_image(image_factory=image_factory)%0A%09%09img.save(keys + %22.png%22)%0A%0A%0Aif __name__ == %22__main__%22:%0A%09main(*sys.argv%5B1:%5D)%0A
af492e64e4da81a5e65c3d2f2a9cdc6c6b34e786
add main
main.py
main.py
Python
0.000378
@@ -0,0 +1,802 @@ +import argparse%0A%0A%0Adef main():%0A %22%22%22Main method.%22%22%22%0A parser = argparse.ArgumentParser(description='Look for an author in the Web of Science.')%0A parser.add_argument('author', help='Surname and name of the author')%0A parser.add_argument('-v', '--verbose', action='store_true', help='Verbose')%0A parser.add_argument('-r', '--results', type=int, default=100,%0A help='Number of results to be shown')%0A parser.add_argument('-y', '--years', type=int, default=5,%0A help='Max age of shown papers')%0A parser.add_argument('-A', '--affiliation', help='Affiliation of the author')%0A%0A args = parser.parse_args()%0A%0A author = args.author%0A years = args.years%0A aff = args.affiliation%0A results = args.results%0A%0A%0Aif __name__ == '__main__':%0A main()%0A
cb1d6f417a5349df485b99bf8a41744b7692cf07
Create main.py
main.py
main.py
Python
0.000001
@@ -0,0 +1,1420 @@ +import sys%0Afrom Tkinter import *%0Afrom winsound import *%0Afrom PIL import ImageTk, Image%0Aimport tkFont%0A%0Awindow = Tk()%0A%0A%0Aim0 = Image.open('image%5C%5Cbackground.jpg')%0Atkimage = ImageTk.PhotoImage(im0)%0ALabel(window,image = tkimage).pack()%0A%0Awindow.iconbitmap('image%5C%5Cicon.ico')%0Awindow.title('FIPER')%0Awindow.attributes('-fullscreen', True)%0Awindow.configure(background='grey') # set background color%0A#window.bind(%22%3CEscape%3E%22, lambda e: e.widget.quit()) # quit with escape button%0A%0Abutton_sound = lambda: PlaySound('audio%5C%5Cpush_button.wav', SND_NOSTOP, SND_ASYNC)%0Abutton_exit = lambda: %09( PlaySound('audio%5C%5Cpush_button.wav', SND_FILENAME), exit() ) %0APlaySound('audio%5C%5Cmenu.wav', SND_ASYNC)%0A%0A%0A%0Aim1 = Image.open('image%5C%5Cbutton1.png')%0Abutton_connect_image = ImageTk.PhotoImage(im1)%0Abutton_connect = Button(window, image=button_connect_image, cursor='cross', command=button_sound)%0Abutton_connect.place(relx=0.7, rely=0.3, height=100, width=450)%0A%0Aim2 = Image.open('image%5C%5Cbutton2.png')%0Abutton_host_image = ImageTk.PhotoImage(im2)%0Abutton_host = Button(window, image=button_host_image, cursor='cross', command=button_sound)%0Abutton_host.place(relx=0.7, rely=0.45, height=100, width=450)%0A%0Aim3 = Image.open('image%5C%5Cbutton3.png')%0Abutton_exit_image = ImageTk.PhotoImage(im3)%0Abutton_exit = Button(window, image=button_exit_image, cursor='cross', command=button_exit)%0Abutton_exit.place(relx=0.7, rely=0.6, height=100, width=450)%0A%0Awindow.mainloop()%0A
184c33d7528e61010116599f1ca3fbb68f1dc4a7
add tkinter template
main.py
main.py
Python
0
@@ -0,0 +1,414 @@ +#!/usr/local/bin/python3.4%0A#coding: utf-8%0A%0Aimport tkinter as tk%0A%0Aclass MainApplication(tk.Frame):%0A def __init__(self, parent, *args, **kwargs):%0A tk.Frame.__init__(self, parent, *args, **kwargs)%0A self.parent = parent%0A # %3Ccreate the rest of your GUI here%3E%0A%0Aif __name__ == %22__main__%22:%0A root = tk.Tk()%0A MainApplication(root).pack(side=%22top%22, fill=%22both%22, expand=True)%0A root.mainloop()%0A
46a130d1a28025cc5060560d734deed11b4346c9
Introduce node.py.
node.py
node.py
Python
0
@@ -0,0 +1,2071 @@ +#!/usr/bin/env python%0A# -*- coding: UTF-8%0A%0Aimport os%0Aimport sys%0Aimport socks%0A%0Aclass Node(object):%0A def __init__(self, address, port):%0A self.address = address%0A self.port = port%0A%0A%22%22%22%0A%5B%5D: node = NetworkNode(%22192.168.0.112%22, 5555, %22SOCKS5%22)%0A%5B%5D: node_socket = node.wrap_socket()%0A%22%22%22%0Aclass NetworkNode(Node):%0A def __init__(self, address, port, node_type=%22SOCKS5%22, auth_creds=None):%0A self.node = Node(address,port)%0A%0A # XXX support for multiple types%0A # node type (SOCKS proxy, HTTP proxy, GRE tunnel, ...)%0A self.node_type = node_type%0A # type-specific authentication credentials%0A self.auth_creds = auth_creds%0A%0A def _get_socksipy_socket(self, proxy_type, auth_creds):%0A import socks%0A s = socks.socksocket()%0A # auth_creds%5B0%5D -%3E username%0A # auth_creds%5B1%5D -%3E password%0A s.setproxy(proxy_type, self.node.address, self.node.port,%0A self.auth_creds%5B0%5D, self.auth_creds%5B1%5D)%0A return s%0A%0A def _get_socket_wrapper(self):%0A if (self.node_type.startswith(%22SOCKS%22)): # SOCKS proxies%0A if (self.node_type != %22SOCKS5%22):%0A proxy_type = socks.PROXY_TYPE_SOCKS5%0A elif (self.node_type != %22SOCKS4%22):%0A proxy_type = socks.PROXY_TYPE_SOCKS4%0A else:%0A print %22We don't know this proxy type.%22%0A sys.exit(1)%0A%0A return self._get_socksipy_socket(proxy_type)%0A elif (self.node_type == %22HTTP%22): # HTTP proxies%0A return self._get_socksipy_socket(PROXY_TYPE_HTTP)%0A else: # Unknown proxies%0A print %22We don't know this proxy type.%22%0A sys.exit(1)%0A%0A def wrap_socket(self):%0A return self._get_socket_wrapper()%0A%0Aclass CodeExecNode(Node):%0A def __init__(self, address, port, node_type, auth_creds):%0A self.node = Node(address,port)%0A%0A # node type (SSH proxy, etc.)%0A self.node_type = node_type%0A # type-specific authentication credentials%0A self.auth_creds = auth_creds%0A%0A def add_unit(self):%0A pass%0A
7ff3d55691d89eb8a00f273af18bade8602f34d0
insert to db outbox
insert.py
insert.py
Python
0
@@ -0,0 +1,373 @@ +#!/usr/bin/env python%0A%22%22%22%0Ainsert.py - Program to :%0A1. insert to outbox collection, %0A2. check if main is running? if not run then run%0A%22%22%22%0Aprint %22Content-Type: text-html%22%0Aprint%0Aimport cgitb%0Acgitb.enable()%0Aimport cgi%0Aimport smsweb%0A%0Aform = cgi.FieldStorage()%0A%0Arcpt = form%5B%22rcpt%22%5D.value%0Amsg = form%5B%22msg%22%5D.value%0A%0Asw = smsweb.SmsWeb()%0Asw.opendb()%0Aprint sw.insertOutbox(rcpt,msg)%0A
cded6c2f088736ace88c0771a08cd9c8ef6dccef
Test for NullConfigStorage
server/lib/python/cartodb_services/test/refactor/storage/test_null_config.py
server/lib/python/cartodb_services/test/refactor/storage/test_null_config.py
Python
0
@@ -0,0 +1,517 @@ +from unittest import TestCase%0Afrom cartodb_services.refactor.storage.null_config import NullConfigStorage%0Afrom cartodb_services.refactor.core.interfaces import ConfigBackendInterface%0A%0A%0Aclass TestNullConfigStorage(TestCase):%0A%0A def test_is_a_config_backend(self):%0A null_config = NullConfigStorage()%0A assert isinstance(null_config, ConfigBackendInterface)%0A%0A def test_returns_none_regardless_of_input(self):%0A null_config = NullConfigStorage()%0A assert null_config.get('whatever') is None%0A
4c5a2540ea665d763e7a66fcae108dd1a2656a00
fix file extension issue
you_get/downloader/mixcloud.py
you_get/downloader/mixcloud.py
#!/usr/bin/env python __all__ = ['mixcloud_download'] from ..common import * def mixcloud_download(url, output_dir = '.', merge = True, info_only = False): html = get_html(url) title = r1(r'<meta property="og:title" content="([^"]*)"', html) url = r1("data-preview-url=\"([^\"]+)\"", html) url = re.sub(r'previews', r'cloudcasts/originals', url) for i in range(10, 30): url = re.sub(r'stream[^.]*', r'stream' + str(i), url) try: type, ext, size = url_info(url) break except: continue print_info(site_info, title, type, size) if not info_only: download_urls([url], title, type, size, output_dir, merge = merge) site_info = "Mixcloud.com" download = mixcloud_download download_playlist = playlist_not_supported('mixcloud')
Python
0
@@ -678,28 +678,27 @@ rl%5D, title, -type +ext , size, outp
8951477a3b6f9e07e2f81e18b698cd0afda69d60
add terms tests
bluebottle/terms/tests/test_api.py
bluebottle/terms/tests/test_api.py
Python
0.00022
@@ -0,0 +1,1288 @@ +from django.core.urlresolvers import reverse%0A%0Afrom rest_framework import status%0A%0Afrom bluebottle.test.utils import BluebottleTestCase%0Afrom bluebottle.test.factory_models.accounts import BlueBottleUserFactory%0Afrom bluebottle.test.factory_models.terms import TermsFactory%0A%0A%0Aclass TermsAPITest(BluebottleTestCase):%0A %22%22%22 Integration tests for the Terms API. %22%22%22%0A%0A def setUp(self):%0A super(TermsAPITest, self).setUp()%0A%0A self.user_1 = BlueBottleUserFactory.create()%0A self.user_1_token = 'JWT %7B0%7D'.format(self.user_1.get_jwt_token())%0A%0A self.user_2 = BlueBottleUserFactory.create()%0A self.user_2_token = 'JWT %7B0%7D'.format(self.user_2.get_jwt_token())%0A%0A self.terms = TermsFactory.create(contents='Awesome terms!')%0A%0A def test_get_current_terms(self):%0A response = self.client.get(reverse('current-terms'))%0A%0A self.assertEqual(response.data%5B'contents'%5D, self.terms.contents)%0A%0A def test_agree_terms(self):%0A response = self.client.post(reverse('terms-agreement-list'),%0A token=self.user_2_token)%0A%0A self.assertEqual(response.status_code, status.HTTP_201_CREATED)%0A self.assertEqual(response.data%5B'user'%5D, self.user_2.id)%0A self.assertEqual(response.data%5B'terms'%5D, self.terms.id)%0A
6632f374d0d9979fd94f462e861dfb21ae146a48
Move utilities out of FilePlayer into sound.Util
code/python/echomesh/sound/Util.py
code/python/echomesh/sound/Util.py
Python
0.000001
@@ -0,0 +1,1316 @@ +from __future__ import absolute_import, division, print_function, unicode_literals%0A%0Aimport aifc%0Aimport math%0Aimport numpy%0Aimport sunau%0Aimport wave%0A%0Afrom echomesh.util import Subprocess%0A%0ALOGGER = Log.logger(__name__)%0A%0ADEFAULT_AUDIO_DIRECTORY = DefaultFile.DefaultFile('assets/audio')%0A%0AFILE_READERS = %7B'au': sunau, 'aifc': aifc, 'aiff': aifc, 'wav': wave%7D%0ANUMPY_TYPES = %7B1: numpy.uint8, 2: numpy.int16, 4: numpy.int32%7D%0A%0A# Adapted from http://flamingoengine.googlecode.com/svn-history/r70/trunk/backends/audio/pyaudio_mixer.py%0A%0A# TODO: config client%0A%0Adef interleave(left, right):%0A %22%22%22Convert two mono sources into one stereo source.%22%22%22%0A return numpy.ravel(numpy.vstack((left, right)), order='F')%0A%0Adef uninterleave(src):%0A %22%22%22Convert one stereo source into two mono sources.%22%22%22%0A return src.reshape(2, len(src)/2, order='FORTRAN')%0A%0Adef pan_to_angle(pan):%0A return (pan + 1.0) * math.pi / 4.0%0A%0Adef calculate_pan(pan):%0A %22%22%22Pan two mono sources in the stereo field.%22%22%22%0A if pan %3C -1:%0A pan = -1%0A elif pan %3E 1:%0A pan = 1%0A%0A angle = pan_to_angle(pan)%0A return math.cos(angle), math.sin(angle)%0A%0Adef play_with_aplay(file, **kwds):%0A file = DEFAULT_AUDIO_DIRECTORY.expand(file)%0A result, returncode = Subprocess.run(%5B'/usr/bin/aplay', file%5D)%0A if returncode:%0A LOGGER.error('Unable to play file %25s using aplay', file)%0A%0A
1036f365fa2d2152f5da8a449aa2005ddb780e04
Refactor generate csv test to expect a stream (generator)
tests/app/test_utils.py
tests/app/test_utils.py
from pathlib import Path from io import StringIO from csv import DictReader import pytest from freezegun import freeze_time from app.utils import email_safe, generate_notifications_csv, generate_previous_dict, generate_next_dict, Spreadsheet @pytest.mark.parametrize('service_name, safe_email', [ ('name with spaces', 'name.with.spaces'), ('singleword', 'singleword'), ('UPPER CASE', 'upper.case'), ('Service - with dash', 'service.with.dash'), ('lots of spaces', 'lots.of.spaces'), ('name.with.dots', 'name.with.dots'), ('name-with-other-delimiters', 'namewithotherdelimiters'), ('.leading', 'leading'), ('trailing.', 'trailing'), ('üńïçödë wördś', 'unicode.words'), ]) def test_email_safe_return_dot_separated_email_domain(service_name, safe_email): assert email_safe(service_name) == safe_email @pytest.mark.parametrize( "status, template_type, expected_status", [ ('sending', None, 'Sending'), ('delivered', None, 'Delivered'), ('failed', None, 'Failed'), ('technical-failure', None, 'Technical failure'), ('temporary-failure', 'email', 'Inbox not accepting messages right now'), ('permanent-failure', 'email', 'Email address doesn’t exist'), ('temporary-failure', 'sms', 'Phone not accepting messages right now'), ('permanent-failure', 'sms', 'Phone number doesn’t exist') ] ) @freeze_time("2016-01-01 15:09:00.061258") def test_generate_csv_from_notifications( app_, service_one, active_user_with_permissions, mock_get_notifications, status, template_type, expected_status ): with app_.test_request_context(): csv_content = generate_notifications_csv( mock_get_notifications( service_one['id'], rows=1, set_template_type=template_type, set_status=status )['notifications'] ) for row in DictReader(StringIO(csv_content)): assert row['Time'] == 'Friday 01 January 2016 at 15:09' assert row['Status'] == expected_status def test_generate_previous_dict(client): ret = generate_previous_dict('main.view_jobs', 'foo', 2, {}) assert 'page=1' in ret['url'] assert ret['title'] == 'Previous page' assert ret['label'] == 'page 1' def test_generate_next_dict(client): ret = generate_next_dict('main.view_jobs', 'foo', 2, {}) assert 'page=3' in ret['url'] assert ret['title'] == 'Next page' assert ret['label'] == 'page 3' def test_generate_previous_next_dict_adds_other_url_args(client): ret = generate_next_dict('main.view_notifications', 'foo', 2, {'message_type': 'blah'}) assert 'notifications/blah' in ret['url'] def test_can_create_spreadsheet_from_large_excel_file(): with open(str(Path.cwd() / 'tests' / 'spreadsheet_files' / 'excel 2007.xlsx'), 'rb') as xl: ret = Spreadsheet.from_file(xl, filename='xl.xlsx') assert ret.as_csv_data
Python
0.000001
@@ -1941,17 +1941,16 @@ )%0A -%0A for @@ -1976,16 +1976,21 @@ tringIO( +next( csv_cont @@ -1994,16 +1994,17 @@ ontent)) +) :%0A
45dc85ded5a766191cd58d76a16470fc063d6e70
Add error formatting tests for httperror
tests/test_httperror.py
tests/test_httperror.py
Python
0
@@ -0,0 +1,644 @@ +import unittest%0A%0Afrom fleece import httperror%0A%0A%0Aclass HTTPErrorTests(unittest.TestCase):%0A %22%22%22Tests for :class:%60fleece.httperror.HTTPError%60.%22%22%22%0A%0A def test_error_msg_format(self):%0A with self.assertRaises(httperror.HTTPError) as err:%0A raise httperror.HTTPError(status=404)%0A self.assertEqual('404: Not Found', str(err.exception))%0A%0A def test_error_msg_format_custom_message(self):%0A with self.assertRaises(httperror.HTTPError) as err:%0A raise httperror.HTTPError(status=404, message='Nothing Here')%0A self.assertEqual(%0A '404: Not Found - Nothing Here', str(err.exception)%0A )%0A
cad79ac342ffe685062c5c90f05e6f573fb7b5b5
Add missing test file. See #1416. (#1417)
tests/test_streamset.py
tests/test_streamset.py
Python
0.000001
@@ -0,0 +1,1750 @@ +from pytest import mark%0A%0Afrom tests import factories%0Afrom tests import common_tools%0Afrom tests.common_tools import (%0A make_user,%0A create_talk_for_user,%0A get_default_conference,%0A template_used)%0Afrom conference import user_panel%0Afrom conference import models%0A%0ASTERAMS_1 = %5B%0A %7B%0A %22title%22: %22Holy Grail%22,%0A %22fare_codes%22: %5B%22TRCC%22, %22TRCP%22, %22TRSC%22, %22TRSP%22, %22TRVC%22, %22TRVP%22%5D,%0A %22url%22: %22https://www.youtube.com/embed/EEIk7gwjgIM%22%0A %7D%0A%5D%0A%0Adef create_streamset():%0A get_default_conference()%0A stream_set = factories.StreamSetFactory(%0A streams=repr(STERAMS_1).replace('%5C'', '%22')%0A )%0A stream_set.save()%0A%0A@mark.django_db%0Adef test_streamset(user_client):%0A create_streamset()%0A%0A@mark.django_db%0Adef test_streamset_without_ticket(user_client):%0A create_streamset()%0A%0A # User without ticket%0A data = user_panel.get_streams_for_current_conference(user_client.user)%0A #print (data)%0A assert not data%5B'streams'%5D%0A assert 'reload_timeout_seconds' in data%0A%0A@mark.django_db%0Adef test_streamset_with_ticket(user_client):%0A create_streamset()%0A%0A # User with view-only ticket%0A common_tools.setup_conference_with_typical_fares()%0A fare = models.Fare.objects.get(code='TRVC')%0A ticket = common_tools.create_valid_ticket_for_user_and_fare(%0A user_client.user, fare=fare)%0A ticket.save()%0A data = user_panel.get_streams_for_current_conference(user_client.user)%0A #print (data)%0A assert len(data%5B'streams'%5D) == 1%0A tracks = data%5B'streams'%5D%5B0%5D%0A assert tracks%5B'title'%5D == 'Holy Grail'%0A assert tracks%5B'url'%5D == 'https://www.youtube.com/embed/EEIk7gwjgIM'%0A assert 'reload_timeout_seconds' in data%0A assert data%5B'reload_timeout_seconds'%5D %3E 3600 # factory sets the end_date to now + 1 hour%0A
a627fa4c681bdd9de323750c3ab3f2cb0d5fca86
Add basic infrastructure for rest API
server/hoot/app.py
server/hoot/app.py
Python
0.000001
@@ -0,0 +1,238 @@ +#!../env/bin/python%0Afrom flask import Flask, jsonify%0A%0Aapp = Flask(__name__)%0A%0A@app.route('/hoot/api/v1.0/', methods=%5B'GET'%5D)%0Adef index():%0A return jsonify(%7B'hello': 'Hello World!'%7D)%0A%0A%0Aif __name__ == '__main__':%0A app.run(debug=True)%0A%0A%0A
f983f78262accdca35982ea3c6088b85bb836a8a
Create phasing_success.py
phasing_success.py
phasing_success.py
Python
0.000011
@@ -0,0 +1,1592 @@ +from os import listdir%0Aimport sqlite3%0A%0Aconn = sqlite3.connect('metrix_db.sqlite')%0Acur = conn.cursor()%0A%0A%0Apath = '/dls/mx-scratch/melanie/for_METRIX/data_base_proc/simple_MR'%0Adir_list = listdir(path)%0Apdb_list = %5B%5D%0Adata_list = %5B%5D%0Afor item in dir_list:%0A if len(item) == 4:%0A pdb_list.append(item)%0A%0Afor pdb in pdb_list:%0A cur.execute('''%0A SELECT id FROM PDB_id WHERE PDB_id.pdb_id=%22%25s%22 ''' %25 (pdb))%0A pdb_pk = cur.fetchone()%5B0%5D%0A cur.execute('''%0A INSERT OR IGNORE INTO Phasing (pdb_id_id) VALUES %25s ''' %25 (pdb_pk))%0A %0A new_path = path + '/' + pdb%0A phaser_search = listdir(new_path)%0A if 'PHASER.sol' in phaser_search:%0A reader = open(new_path + '/%25s.log' %25 (pdb))%0A count = 0%0A TFZ_sum = 0%0A LLG_sum = 0%0A for line in reader:%0A if 'SOLU SET RFZ' in line:%0A line = line.split()%0A item1 = line%5B-1%5D%0A item2 = line%5B-2%5D%0A indicator_list = %5Bitem1, item2%5D%0A %0A if 'TFZ' in item1 or 'TFZ' in item2:%0A count += 1%0A indicator_list = sorted(indicator_list)%0A TFZ_sum += float(indicator_list%5B1%5D%5B5:%5D)%0A LLG_sum += float(indicator_list%5B0%5D%5B4:%5D)%0A %0A if count != 0:%0A TFZ_mean = TFZ_sum / count%0A LLG_mean = LLG_sum / count%0A if TFZ_mean %3E 8.0 and LLG_mean %3E 120:%0A cur.execute('''%0A UPDATE Phasing SET phasing_success=1 WHERE Phasing.pdb_id_id=%22%25s%22'''%25 (pdb_pk))%0A %0A else: %0A cur.execute('''%0A UPDATE Phasing SET phasing_success=0 WHERE Phasing.pdb_id_id=%22%25s%22'''%25 (pdb_pk))%0A %0A else:%0A UPDATE Phasing SET phasing_success=0 WHERE Phasing.pdb_id_id=%22%25s%22'''%25 (pdb_pk))%0A
acfb7c902a2cf5c7a8a59218dc36dc371da01922
Add compliance with rule E261 to bots/define/define.py.
contrib_bots/bots/define/define.py
contrib_bots/bots/define/define.py
# See readme.md for instructions on running this code. import logging import json import requests import html2text class DefineHandler(object): ''' This plugin define a word that the user inputs. It looks for messages starting with '@mention-bot'. ''' DEFINITION_API_URL = 'https://owlbot.info/api/v1/dictionary/{}?format=json' REQUEST_ERROR_MESSAGE = 'Definition not available.' EMPTY_WORD_REQUEST_ERROR_MESSAGE = 'Please enter a word to define.' PHRASE_ERROR_MESSAGE = 'Definitions for phrases are not available.' def usage(self): return ''' This plugin will allow users to define a word. Users should preface messages with @mention-bot. ''' def handle_message(self, message, client, state_handler): original_content = message['content'].strip() bot_response = self.get_bot_define_response(original_content) if message['type'] == 'private': client.send_message(dict( type='private', to=message['sender_email'], content=bot_response, )) else: client.send_message(dict( type='stream', to=message['display_recipient'], subject=message['subject'], content=bot_response, )) def get_bot_define_response(self, original_content): split_content = original_content.split(' ') # If there are more than one word (a phrase) if len(split_content) > 1: return DefineHandler.PHRASE_ERROR_MESSAGE to_define = split_content[0].strip() to_define_lower = to_define.lower() # No word was entered. if not to_define_lower: return self.EMPTY_WORD_REQUEST_ERROR_MESSAGE else: response = '**{}**:\n'.format(to_define) try: # Use OwlBot API to fetch definition. api_result = requests.get(self.DEFINITION_API_URL.format(to_define_lower)) # Convert API result from string to JSON format. definitions = api_result.json() # Could not fetch definitions for the given word. if not definitions: response += self.REQUEST_ERROR_MESSAGE else: # Definitions available. # Show definitions line by line. for d in definitions: example = d['example'] if d['example'] else '*No example available.*' response += '\n' + '* (**{}**) {}\n&nbsp;&nbsp;{}'.format(d['type'], d['defenition'], html2text.html2text(example)) except Exception as e: response += self.REQUEST_ERROR_MESSAGE logging.exception(e) return response handler_class = DefineHandler
Python
0
@@ -2334,16 +2334,17 @@ else: + # Defin
3c31c9541cab4e452074b7c2ab08f28e48f47e4c
add admin site for DomainLink
corehq/apps/linked_domain/admin.py
corehq/apps/linked_domain/admin.py
Python
0
@@ -0,0 +1,497 @@ +from __future__ import absolute_import%0Afrom django.contrib import admin%0Afrom .models import DomainLink%0A%0A%0Aclass DomainLinkAdmin(admin.ModelAdmin):%0A model = DomainLink%0A list_display = %5B%0A 'linked_domain',%0A 'master_domain',%0A 'remote_base_url',%0A 'last_pull',%0A %5D%0A list_filter = %5B%0A 'linked_domain',%0A 'master_domain',%0A 'last_pull',%0A %5D%0A search_fields = %5B'linked_domain', 'master_domain'%5D%0A%0A%0Aadmin.site.register(DomainLink, DomainLinkAdmin)%0A
93d66d085a618b104d67a5fc1d1cf7507c31fff6
fix NameError
crosscat/utils/experiment_utils.py
crosscat/utils/experiment_utils.py
import os import collections # import crosscat.utils.file_utils as file_utils import crosscat.utils.geweke_utils as geweke_utils import crosscat.utils.general_utils as general_utils result_filename = geweke_utils.summary_filename def find_configs(dirname, filename=result_filename): root_has_filename = lambda (root, ds, filenames): filenames.count(filename) get_filepath = lambda (root, ds, fs): os.path.join(root, filename) tuples = filter(has_filename, os.walk(dirname)) filepaths = map(get_filepath, tuples) return filepaths def read_all_configs(dirname='.'): def read_config(filepath): result = file_utils.unpickle(filepath, dir=dirname) config = result['config'] return config filepaths = find_configs(dirname) config_list = map(read_config, filepaths) return config_list def generate_filepath(config): _dirname = geweke_utils.generate_directory_name(**config) filepath = os.path.join(_dirname, result_filename) return filepath def read_results(config_list, dirname=''): def read_result(config): filepath = generate_filepath(config) result = file_utils.unpickle(filepath, dir=dirname) return result config_list = general_utils.ensure_listlike(config_list) results = map(read_result, config_list) return results def write_result(config, result, dirname=''): filepath = generate_filepath(config) file_utils.pickle(result, filepath, dirname=dirname) return def do_experiments(runner, writer, config_list): def do_experiment(config): result = runner(**config) writer(config, result) return result config_list = general_utils.ensure_listlike(config_list) results = map(do_experiment, config_list) return results if __name__ == '__main__': config_list = read_all_configs() results = read_results(config_list[:-1])
Python
0.000014
@@ -451,16 +451,21 @@ filter( +root_ has_file
bf5f63ce8c6bd4fbef48c848cc8ed9eb5874b326
Create test.py
test.py
test.py
Python
0.000005
@@ -0,0 +1,1506 @@ +import random%0Afrom sort_and_search import *%0A%0A# Bubble Sort%0A%0Aarray = %5Brandom.randint(0, 100) for n in range(40)%5D%0Aprint('Bubble Sort:%5Cn')%0Aprint('Before:%5Cn', array)%0Abubble_sort(array)%0Aprint('After:%5Cn', array)%0Aprint('%5Cn')%0A%0A# Selection Sort%0A%0Aarray = %5Brandom.randint(0, 100) for n in range(40)%5D%0Aprint('Selection Sort:%5Cn')%0Aprint('Before:%5Cn', array)%0Aselection_sort(array)%0Aprint('After:%5Cn', array)%0Aprint('%5Cn')%0A%0A# Insertion Sort%0A%0Aarray = %5Brandom.randint(0, 100) for n in range(40)%5D%0Aprint('Insertion Sort:%5Cn')%0Aprint('Before:%5Cn', array)%0Ainsertion_sort(array)%0Aprint('After:%5Cn', array)%0Aprint('%5Cn')%0A%0A# Shell Sort%0A%0Aarray = %5Brandom.randint(0, 100) for n in range(40)%5D%0Aprint('Shell Sort:%5Cn')%0Aprint('Before:%5Cn', array)%0Ashell_sort(array)%0Aprint('After:%5Cn', array)%0Aprint('%5Cn')%0A%0A# Merge Sort%0A%0Aarray = %5Brandom.randint(0, 100) for n in range(40)%5D%0Aprint('Merge Sort:%5Cn')%0Aprint('Before:%5Cn', array)%0Amerge_sort(array)%0Aprint('After:%5Cn', array)%0Aprint('%5Cn')%0A%0A# Quick Sort%0A%0Aarray = %5Brandom.randint(0, 100) for n in range(40)%5D%0Aprint('Quick Sort:%5Cn')%0Aprint('Before:%5Cn', array)%0Aquick_sort(array)%0Aprint('After:%5Cn', array)%0Aprint('%5Cn')%0A%0A# Heap Sort%0A%0Aarray = %5Brandom.randint(0, 100) for n in range(40)%5D%0Aprint('Heap Sort:%5Cn')%0Aprint('Before:%5Cn', array)%0Aheap_sort(array)%0Aprint('After:%5Cn', array)%0Aprint('%5Cn')%0A%0A# Binary Search%0A%0Aarray = %5Brandom.randint(0, 100) for n in range(40)%5D%0Aprint('Binary Search:%5Cn')%0Aquick_sort(array)%0Aprint('List:%5Cn', array)%0Akey = random.randint(0, 100)%0Aprint('Key:%5Cn', key, '%5CnFound:%5Cn', binary_search(array, key))%0Aprint('%5Cn')%0A
3c065b1c1633c0fccebfa1efe76fe59aa8fed3f4
Add XKCDPlugin class with basic xkcd command.
xkcd.py
xkcd.py
Python
0
@@ -0,0 +1,2191 @@ +%22%22%22%0AXKCD brutal plugins.%0A%0AProvides basic commands for showing xkcd info in IRC.%0A%22%22%22%0A%0Afrom brutal.core.plugin import BotPlugin, cmd%0Aimport json%0Aimport urllib%0A%0A%0ASLEEP_TIME = 3600%0A%0A%0Adef get_xkcd_metadata(num=None):%0A %22%22%22Returns data about xkcd number 'num', or latest.%22%22%22%0A site_url = 'http://xkcd.com/'%0A json_filename = 'info.0.json'%0A if num:%0A comic_selector = '%7B%7D/'.format(num)%0A else:%0A comic_selector = ''%0A url = site_url + comic_selector + json_filename%0A data = urllib.urlopen(url).read()%0A data = json.loads(data)%0A data%5B'url'%5D = 'http://xkcd.com/' + str(data%5B'num'%5D)%0A return data%0A%0A%0Adef format_xkcd(comic_data):%0A %22%22%22Returns info about xkcd 'num'.%22%22%22%0A xkcd_info = 'xkcd #%7B%7D: %7B%7D %7C %7B%7D'.format(comic_data%5B'num'%5D,%0A comic_data%5B'title'%5D,%0A comic_data%5B'url'%5D)%0A return xkcd_info%0A%0A%0Aclass XKCDPlugin(BotPlugin):%0A %22%22%22XKCD plugin class.%22%22%22%0A%0A def setup(self, *args, **kwargs):%0A self.latest = get_xkcd_metadata()%0A%0A @cmd%0A def xkcd(self, event):%0A %22%22%22Shows details of requested xkcd.%0A%0A Args:%0A If no argument is given, data of latest xkcd is given.%0A%0A If a number is given, shows data for corresponding xkcd, or n-th%0A latest, if number is non-positive.%0A%0A If argument is non-numeric, or contains more than one number,%0A a full-text search over explainxkcd database is performed,%0A returning first found comic, if any.%0A %22%22%22%0A args = event.args%0A if len(args) %3C 1:%0A return format_xkcd(self.latest)%0A try:%0A num = int(args%5B0%5D)%0A except ValueError:%0A return %22Be patient! We're getting there!%22%0A if num %3E self.latest%5B'num'%5D:%0A return 'not yet released!'%0A if num %3C= 0:%0A # Since 'num' is negative, this basically takes num-th latest%0A # comic. It's the same as self.latest%5B'num'%5D - abs(num).%0A num = self.latest%5B'num'%5D + num%0A if num %3C= 0:%0A return 'somebody wants to go back in time way too far!'%0A return format_xkcd(get_xkcd_metadata(num))%0A
b10db4316af4f044cbde96076064beae33101d6d
Add misc parser
misc.py
misc.py
Python
0.000001
@@ -0,0 +1,1843 @@ +# vim:fileencoding=utf-8:ts=8:et:sw=4:sts=4:tw=79%0A%0Afrom datetime import datetime%0Afrom json import loads%0Afrom urllib import urlencode%0A%0Afrom twisted.internet.defer import Deferred%0Afrom twisted.python import log%0Afrom twisted.web.client import getPage%0A%0AUBERNET_NEWS_URL = %22http://uberent.com/GameClient/GetNews%22%0A%0A%0Aclass MiscParser(object):%0A %22%22%22%0A Parser for miscellaneous web API calls.%0A%0A It supports reading a variety of different APIs returning JSON data.%0A %22%22%22%0A%0A def __init__(self):%0A %22%22%22Do nothing for now.%22%22%22%0A pass%0A%0A def startNewsUpdate(self, count):%0A %22%22%22%0A Initiate an update using Twisted.%0A%0A The request is handled asynchronously. It will call onUpdate if it's%0A successful and onError otherwise.%0A %22%22%22%0A log.msg(%22Updating URL contents for: %7B0%7D%22.format(self.news_url))%0A url = %22%7B0%7D?%7B1%7D%22.format(self.news_url, urlencode(%7B%22titleid%22: 4,%0A %22count%22: count%7D))%0A deferred = getPage(url)%0A deferred.addCallbacks(self.onNewsUpdate, self.onError)%0A return deferred%0A%0A def onNewsUpdate(self, value):%0A %22%22%22Value callback for retrieving Uberent News data.%22%22%22%0A data = loads(value, encoding=%22utf-8%22)%0A%0A news = %5B%7B%22date%22: datetime.strptime(item%5B%22Timestamp%22%5D,%0A %22%25Y-%25m-%25d.%25H:%25M:%25S%22),%0A %22title%22: item%5B%22Title%22%5D%7D%0A for item in data%5B%22News%22%5D%5D%0A%0A log.msg(%22Received and parsed new data: %7B0%7D%22.format(news))%0A return news%0A%0A def news(self, count):%0A %22%22%22Start an update and return a deferred containing the results.%22%22%22%0A updateDeferred = self.startNewsUpdate(count)%0A newDeferred = Deferred()%0A updateDeferred.addCallbacks(newDeferred.callback, newDeferred.errback)%0A return newDeferred%0A
1ef26b03bfda67e12af557944417b59357a5c324
Create __init__.py
apriori/__init__.py
apriori/__init__.py
Python
0.000429
@@ -0,0 +1 @@ +%0A
f82730bfab4a65efa6cd1e7ecb767514bbb481a4
add function to find local IP addresses
src/wormhole/ipaddrs.py
src/wormhole/ipaddrs.py
Python
0
@@ -0,0 +1,2460 @@ +%0A# Find all of our ip addresses. From tahoe's src/allmydata/util/iputil.py%0A%0Aimport os, re, subprocess, errno%0Afrom sys import platform%0A%0A# Wow, I'm really amazed at home much mileage we've gotten out of calling%0A# the external route.exe program on windows... It appears to work on all%0A# versions so far. Still, the real system calls would much be preferred...%0A# ... thus wrote Greg Smith in time immemorial...%0A_win32_re = re.compile(r'%5E%5Cs*%5Cd+%5C.%5Cd+%5C.%5Cd+%5C.%5Cd+%5Cs.+%5Cs(?P%3Caddress%3E%5Cd+%5C.%5Cd+%5C.%5Cd+%5C.%5Cd+)%5Cs+(?P%3Cmetric%3E%5Cd+)%5Cs*$', flags=re.M%7Cre.I%7Cre.S)%0A_win32_commands = (('route.exe', ('print',), _win32_re),)%0A%0A# These work in most Unices.%0A_addr_re = re.compile(r'%5E%5Cs*inet %5Ba-zA-Z%5D*:?(?P%3Caddress%3E%5Cd+%5C.%5Cd+%5C.%5Cd+%5C.%5Cd+)%5B%5Cs/%5D.+$', flags=re.M%7Cre.I%7Cre.S)%0A_unix_commands = (('/bin/ip', ('addr',), _addr_re),%0A ('/sbin/ifconfig', ('-a',), _addr_re),%0A ('/usr/sbin/ifconfig', ('-a',), _addr_re),%0A ('/usr/etc/ifconfig', ('-a',), _addr_re),%0A ('ifconfig', ('-a',), _addr_re),%0A ('/sbin/ifconfig', (), _addr_re),%0A )%0A%0A%0Adef find_addresses():%0A # originally by Greg Smith, hacked by Zooko and then Daira%0A%0A # We don't reach here for cygwin.%0A if platform == 'win32':%0A commands = _win32_commands%0A else:%0A commands = _unix_commands%0A%0A for (pathtotool, args, regex) in commands:%0A assert os.path.isabs(pathtotool)%0A if not os.path.isfile(pathtotool):%0A continue%0A try:%0A addresses = _query(pathtotool, args, regex)%0A except Exception:%0A addresses = %5B%5D%0A if addresses:%0A return addresses%0A return %5B%5D%0A%0Adef _query(path, args, regex):%0A env = %7B'LANG': 'en_US.UTF-8'%7D%0A TRIES = 5%0A for trial in xrange(TRIES):%0A try:%0A p = subprocess.Popen(%5Bpath%5D + list(args),%0A stdout=subprocess.PIPE,%0A stderr=subprocess.PIPE,%0A env=env)%0A (output, err) = p.communicate()%0A break%0A except OSError, e:%0A if e.errno == errno.EINTR and trial %3C TRIES-1:%0A continue%0A raise%0A%0A addresses = %5B%5D%0A outputsplit = output.split('%5Cn')%0A for outline in outputsplit:%0A m = regex.match(outline)%0A if m:%0A addr = m.group('address')%0A if addr not in addresses:%0A addresses.append(addr)%0A%0A return addresses%0A
6e63032cee81bfa8125c7eecd4d1697ddf4ff159
Create procrastination.py
procrastination.py
procrastination.py
Python
0
@@ -0,0 +1,32 @@ +def procrastination():%0A pass%0A
c336d907482958da06417c36723574b67d8ef2a5
Add SQLite support
sqlite_importer.py
sqlite_importer.py
Python
0.000001
@@ -0,0 +1,2160 @@ +import logging%0Aimport parsers%0Aimport collections%0Aimport itertools%0Aimport json%0Afrom datetime import datetime%0Aimport sqlite3%0A%0Adef lines():%0A for contact in messages:%0A for line in messages%5Bcontact%5D:%0A yield (contact, line%5B'contact'%5D,line%5B'timestamp'%5D, line%5B'source'%5D,%0A line%5B'protocol'%5D,line%5B'nick'%5D,line%5B'message'%5D)%0A%0Adef grouper(n, iterable):%0A it = iter(iterable)%0A while True:%0A chunk = tuple(itertools.islice(it, n))%0A if not chunk:%0A return%0A yield chunk%0A%0A# logging.basicConfig(level=logging.INFO)%0Amessages = collections.defaultdict(list)%0Afor contact, text in parsers.Digsby(%22./Digsby Logs%22):%0A messages%5Bcontact%5D.append(text)%0Aprint(%22Digsby%22)%0Afor contact, text in parsers.Trillian(%22./Trillian%22):%0A messages%5Bcontact%5D.append(text)%0Aprint(%22Trillian%22)%0Afor contact, text in parsers.Trillian(%22./Trillian2%22):%0A messages%5Bcontact%5D.append(text)%0Aprint(%22Trillian%22)%0Afor contact, text in parsers.Pidgin(%22./Pidgin%22):%0A messages%5Bcontact%5D.append(text)%0Aprint(%22Pidgin%22)%0Afor contact, text in parsers.Whatsapp(%22./Whatsapp%22):%0A messages%5Bcontact%5D.append(text)%0Aprint(%22Whatsapp%22)%0Afor contact, text in parsers.Facebook(files=%5B%22./Facebook/cleaned.html%22%5D):%0A messages%5Bcontact%5D.append(text)%0Aprint(%22Facebook%22)%0Afor contact in messages:%0A messages%5Bcontact%5D = list(itertools.chain.from_iterable(messages%5Bcontact%5D))%0A messages%5Bcontact%5D.sort(key=lambda x: x%5B'timestamp'%5D)%0Aprint(%22Sorting%22)%0A%0A# print(messages)%0A# for k in messages:%0A# print k, len(messages%5Bk%5D)%0A# print(messages%5B'Eliza'%5D)%0A# f = open(%22./logs/messages.json%22, %22w%22)%0A# json.dump(messages, f, indent=2, ensure_ascii=False)%0A# f.close()%0A%0A%0Asqlite_file = './messages.db'%0Aconn = sqlite3.connect(sqlite_file)%0Ac = conn.cursor()%0A%0Ac.execute('DROP TABLE IF EXISTS messages')%0Ac.execute('CREATE TABLE messages (contact TEXT, sender TEXT, datetime TEXT,'%0A 'source TEXT, protocol TEXT, nick TEXT, message TEXT)')%0A%0Afor gr in grouper(5000, lines()):%0A conn.executemany(%22INSERT INTO messages (contact, sender, datetime, source,%22%0A %22protocol, nick, message) values (?, ?, ?, ?, ?, ?, ?)%22, gr)%0A print(%22Inserted 5000%22)%0A%0Aconn.commit()%0Aconn.close()%0A
9dd8fa91749d4be7037b08fcb89e5a2f22ff5dc3
263. Ugly Number
p263.py
p263.py
Python
0.999995
@@ -0,0 +1,999 @@ +import unittest%0A%0A%0Aclass Solution(object):%0A def isUgly(self, num):%0A %22%22%22%0A :type num: int%0A :rtype: bool%0A %22%22%22%0A if num %3C= 0:%0A return False%0A%0A for factor in %5B5, 3, 2%5D:%0A while True:%0A q, r = divmod(num, factor)%0A if r:%0A break%0A num = q%0A return num == 1%0A%0A%0Aclass Test(unittest.TestCase):%0A def test(self):%0A self._test(1, True)%0A self._test(2, True)%0A self._test(3, True)%0A self._test(4, True)%0A self._test(5, True)%0A self._test(6, True)%0A self._test(7, False)%0A self._test(8, True)%0A self._test(9, True)%0A self._test(10, True)%0A self._test(11, False)%0A self._test(12, True)%0A self._test(13, False)%0A self._test(14, False)%0A%0A def _test(self, n, expected):%0A actual = Solution().isUgly(n)%0A self.assertEqual(actual, expected)%0A%0A%0Aif __name__ == '__main__':%0A unittest.main()%0A
500df3f340d7782c759634529ae40ce56f7bec3e
Add first file Only read a .docx until now
plag.py
plag.py
Python
0
@@ -0,0 +1,753 @@ +from docx import Document%0A%0Aif __name__ == %22__main__%22:%0A if sys.args%5B0%5D == 0:%0A print(%22Must specify file!%22)%0A return%0A #open the docx (and docx only)%0A document = Document(sys.args%5B0%5D)%0A #for each paragraph on the docx%0A for parag in document.paragraphs:%0A #extract the string%0A text = parag.text%0A #split at whitespace%0A splitted = text.split()%0A #send to google every 5~10 words and save the url of the first Y results (parallelism preferrable, bandwidth is not a big problem, the old http protocol is)%0A #count the ocurrences of each URL%0A #create a ratio based on the size of the document and the times an URL can appear%0A #if a given URL goes beyond that ratio, it's plagiarized%0A
94794e61298e6b1763f571d5e48c3549a538ac51
add tests
test_sequential.py
test_sequential.py
Python
0
@@ -0,0 +1,1414 @@ +%22%22%22Tests the decorators.%22%22%22%0A%0Atry:%0A import unittest2 as unittest%0Aexcept ImportError:%0A import unittest%0A%0Afrom sequential import before, after, during%0A%0A%0A__all__ = %5B'TestSequential'%5D%0A%0A%0Aclass TestSequential(unittest.TestCase):%0A def test_before_chain(self):%0A %22%22%22Tests @before chained to another function.%22%22%22%0A def add_b(word=''):%0A return word + 'b'%0A%0A @before(add_b, chain=True)%0A def add_a(word=''):%0A return word + 'a'%0A%0A assert add_a() == 'ba'%0A%0A def test_before_no_chain(self):%0A %22%22%22Tests @before not chained to another function.%22%22%22%0A def switch_a(d):%0A d%5B'a'%5D = True%0A%0A @before(switch_a)%0A def check_a(d):%0A assert d%5B'a'%5D%0A%0A check_a(%7B'a': False%7D)%0A%0A def test_after_chain(self):%0A %22%22%22Tests @after chained to another function.%22%22%22%0A def add_a(word=''):%0A return word + 'a'%0A%0A @after(add_a, chain=True)%0A def add_b(word=''):%0A return word + 'b'%0A%0A assert add_b() == 'ba'%0A%0A def test_after_no_chain(self):%0A %22%22%22Tests @after not chained to another function.%22%22%22%0A def check_a(d):%0A assert d%5B'a'%5D%0A d%5B'b'%5D = True%0A%0A @after(check_a)%0A def switch_a(d):%0A d%5B'a'%5D = True%0A%0A d = %7B'a': False, 'b': False%7D%0A switch_a(d)%0A assert d%5B'b'%5D%0A%0A # TODO Come up with a good way of testing @during.%0A
8b70516830e0226c96a274c484ec1681c6e248a4
test for resources, still needs bytesio and stringio test...
tests/test_util.py
tests/test_util.py
Python
0
@@ -0,0 +1,771 @@ +# This module is part of Hypatia and is released under the%0A# MIT license: http://opensource.org/licenses/MIT%0A%0A%22%22%22py.test unit testing for hypatia/util.py%0A%0ARun py.test on this module to assert hypatia.util%0Ais completely functional.%0A%0A%22%22%22%0A%0Aimport os%0A%0Atry:%0A import ConfigParser as configparser%0Aexcept ImportError:%0A import configparser%0A%0Aimport pygame%0Aimport pytest%0Aimport pyganim%0A%0Afrom hypatia import util%0A%0Atry:%0A os.chdir('demo')%0Aexcept OSError:%0A pass%0A%0A%0Adef test_resource():%0A %22%22%22Test the util.Resource class.%0A%0A %22%22%22%0A%0A resource = util.Resource('walkabouts', 'debug')%0A%0A assert 'walk_north.gif' in resource%0A assert isinstance(resource%5B'walk_north.gif'%5D, pyganim.PygAnimation)%0A assert isinstance(resource%5B'walk_north.ini'%5D, configparser.ConfigParser)%0A
89f837997b6ed84b14d01cadbe8bfeeb4e0dcf36
add base keyword file
libs/base_keywords.py
libs/base_keywords.py
Python
0.000001
@@ -0,0 +1,29 @@ +# @Time : 2016/11/18 16:32
52b2e617ab8fcbb268d1d75c90b3f92470737f41
Create __init__.py
logserver/__init__.py
logserver/__init__.py
Python
0.000001
@@ -0,0 +1,450 @@ +import hug%0Atry:%0A%09from . import runserver%0A%09##to run windowslogonofflogger%0A%09##https://github.com/bengjerstad/windowslogonofflogger%0A%09hug.API(__name__).extend(runserver, '')%0A%09print('Running windowslogonofflogger Server')%0Aexcept:%0A%09%09pass%0A%09%09%0Atry:%0A%09from . import logserver%0A%09##to run MulitUse Log Server%0A%09##https://github.com/bengjerstad/multiuselogserver%0A%09hug.API(__name__).extend(logserver, '/logserver')%0A%09print('Running MultiUselog Server')%0Aexcept:%0A%09pass%0A%0A
882de02df3131cf19eed5750428bcb79ce7f30c1
Add DB migration for netdev bindings
netprofile_access/migrations/f2d2359b923a_link_bindings_to_access_entities.py
netprofile_access/migrations/f2d2359b923a_link_bindings_to_access_entities.py
Python
0
@@ -0,0 +1,1875 @@ +%22%22%22link bindings to access entities%0A%0ARevision ID: f2d2359b923a%0ARevises: b32a4bf96447%0ACreate Date: 2018-01-09 16:59:13.885801%0A%0A%22%22%22%0A%0A# revision identifiers, used by Alembic.%0Arevision = 'f2d2359b923a'%0Adown_revision = 'b32a4bf96447'%0Abranch_labels = None%0Adepends_on = None%0A%0Afrom alembic import op%0Aimport sqlalchemy as sa%0Afrom sqlalchemy import FetchedValue%0Afrom netprofile.db import ddl as npd%0Afrom netprofile.db import fields as npf%0A%0Adef upgrade():%0A # ### commands auto generated by Alembic - please adjust! ###%0A op.add_column('netdev_bindings', sa.Column('aeid', npf.UInt32(), npd.Comment('Access entity ID'), server_default=sa.text('NULL'), nullable=True))%0A op.add_column('netdev_bindings', sa.Column('cvlanid', npf.UInt16(), npd.Comment('Customer (inner) VLAN ID'), server_default=sa.text('NULL'), nullable=True))%0A op.add_column('netdev_bindings', sa.Column('svlanid', npf.UInt16(), npd.Comment('Service provider (outer) VLAN ID'), server_default=sa.text('NULL'), nullable=True))%0A op.create_index('netdev_bindings_i_aeid', 'netdev_bindings', %5B'aeid'%5D, unique=False)%0A op.create_index('netdev_bindings_i_qinq', 'netdev_bindings', %5B'svlanid', 'cvlanid'%5D, unique=False)%0A op.create_foreign_key('netdev_bindings_fk_aeid', 'netdev_bindings', 'entities_access', %5B'aeid'%5D, %5B'entityid'%5D, onupdate='CASCADE', ondelete='CASCADE')%0A # ### end Alembic commands ###%0A%0A%0Adef downgrade():%0A # ### commands auto generated by Alembic - please adjust! ###%0A op.drop_constraint('netdev_bindings_fk_aeid', 'netdev_bindings', type_='foreignkey')%0A op.drop_index('netdev_bindings_i_qinq', table_name='netdev_bindings')%0A op.drop_index('netdev_bindings_i_aeid', table_name='netdev_bindings')%0A op.drop_column('netdev_bindings', 'svlanid')%0A op.drop_column('netdev_bindings', 'cvlanid')%0A op.drop_column('netdev_bindings', 'aeid')%0A # ### end Alembic commands ###%0A%0A
16489e1c7486e90f2e36b1c3c2c5625077e42345
Create ssap.py
ssap.py
ssap.py
Python
0.000001
@@ -0,0 +1 @@ +%0A
1eecfc0f2fd63ed9885bae65a6d64fead4d44fce
add test.py
test.py
test.py
Python
0.000012
@@ -0,0 +1,1637 @@ +#coding=utf-8%0D%0Aimport splinter%0D%0Aimport time%0D%0Aimport random%0D%0Aimport requests%0D%0Aimport re%0D%0Afrom bs4 import BeautifulSoup%0D%0Afrom splinter import Browser%0D%0Afrom selenium import webdriver%0D%0Aimport time%0D%0A%0D%0Aclass Duobao:%0D%0A%09baseurl = %22http://1.163.com/user/win.do?cid=43279246%22%0D%0A%09urls = %5B%5D%0D%0A%09def getdata(self):%0D%0A%09%09url = str(self.baseurl)%0D%0A%09%09res = requests.get(url)%0D%0A%09%09html = res.content%0D%0A%09%09try:%0D%0A%09%09%09html = html.decode('utf-8')%0D%0A%09%09except:%0D%0A%09%09%09pass%0D%0A%09%09# print(html)%0D%0A%09%09soup = BeautifulSoup(html, %22lxml%22)%0D%0A%09%09# print(soup.prettify())%0D%0A%09%09# print(soup.find_all('a'))%0D%0A%09%09links = soup.find_all('a', href=re.compile('http'))%0D%0A%09%09for link in links:%0D%0A%09%09%09addr = link.get('href')%0D%0A%09%09%09if self.checkUrl(addr):%0D%0A%09%09%09%09pass%0D%0A%09%09%09print(str('%E8%8E%B7%E5%8F%96%E9%93%BE%E6%8E%A5%EF%BC%9A') + addr)%0D%0A%09%09%09self.getdatas(addr)%0D%0A%09%09%09# print(addr)%0D%0A%09def getdatas(self, url):%0D%0A%09%09res = requests.get(url)%0D%0A%09%09html = res.content%0D%0A%09%09try:%0D%0A%09%09%09html = html.decode('utf-8')%0D%0A%09%09except:%0D%0A%09%09%09pass%0D%0A%09%09# print(html)%0D%0A%09%09soup = BeautifulSoup(html, %22lxml%22)%0D%0A%09%09# print(soup.prettify())%0D%0A%09%09# print(soup.find_all('a'))%0D%0A%09%09links = soup.find_all('a')%0D%0A%09%09for link in links:%0D%0A%09%09%09print(link.get('href'))%09%0D%0A%09def checkUrl(self, url):%0D%0A%09%09for turl in self.urls:%0D%0A%09%09%09if turl == url:%0D%0A%09%09%09%09return True%0D%0A%09%09return False%0D%0A%09def browseUrl(self, url):%0D%0A%09%09with Browser('chrome') as browser:%0D%0A%09%09%09browser.visit(url)%0D%0A%09%09%09sp = BeautifulSoup(browser.html, %22lxml%22)%0D%0A%09%09%09print(sp.prettify())%0D%0A%0D%0A%09def crawData(self, url):%0D%0A%09%09driver = webdriver.PhantomJS()%0D%0A%09%09driver.get(url);%0D%0A%09%09time.sleep(2)%0D%0A%09%09data = driver.find_element_by_tag_name('body')%0D%0A%09%09print data.text%0D%0A%09%09driver.quit()%0D%0A%09%09%09%09%09%09%0D%0A%09def __unicode__(self):%0D%0A%09%09return self.baseurl%0D%0A%0D%0A# dt = Duobao()%0D%0A# dt.getdata()
5c269bfeb517b70cfcb8fd730bf3eb983a5515dc
Create a quick script to train a COBE brain from a folder of formatted IRC logs
markov_batch_learn.py
markov_batch_learn.py
Python
0
@@ -0,0 +1,1446 @@ +from __future__ import unicode_literals%0Aimport argparse%0Aimport os%0Afrom cobe.brain import Brain%0A%0Aif __name__ == %22__main__%22:%0A%0A bots = %5B%22ames%22, %22bojii%22, %22diderobot%22, %22ekimbot%22, %22harbot%22, %22hubbot%22, %22nopebot%22, %22memebot%22,%0A %22pyheufybot%22, %22re_heufybot%22, %22heufybot%22, %22pymoronbot%22, %22moronbot%22, %22robobo%22, %22safebot%22, %22unsafebot%22%5D%0A%0A parser = argparse.ArgumentParser(description=%22A script to quickly teach a new markov brain from a folder of text files.%22)%0A parser.add_argument(%22-f%22, %22--folder%22, help=%22The folder to read through.%22, type=str)%0A parser.add_argument(%22-b%22, %22--brainfile%22, help=%22The filename to use for the brain.%22, type=str)%0A options = parser.parse_args()%0A%0A brain = Brain(options.brainfile)%0A%0A brain.start_batch_learning()%0A for filename in os.listdir(options.folder):%0A print os.path.join(options.folder, filename)%0A with open(os.path.join(options.folder, filename)) as current_file:%0A lines = current_file.readlines()%0A for line in lines:%0A templine = line.decode(%22utf-8%22)%0A if templine%5Btempline.find(%22%5D%22)+1:%5D.lstrip().startswith(%22%3C%22):%0A newline = templine%5Btempline.find(%22%5D%22)+1:%5D.lstrip()%0A if newline%5Bnewline.find(%22%3C%22):newline.find(%22%3E%22)+1%5D.lower() not in bots:%0A if newline.find(%22%3E%22) != -1:%0A brain.learn(newline%5Bnewline.find(%22%3E%22)+1:%5D)%0A%0A brain.stop_batch_learning()%0A
5c60b11839370460209e98f18867bce338d13fba
add migration
adhocracy4/projects/migrations/0012_help_texts.py
adhocracy4/projects/migrations/0012_help_texts.py
Python
0.000001
@@ -0,0 +1,1015 @@ +# -*- coding: utf-8 -*-%0A# Generated by Django 1.11.4 on 2017-09-27 12:06%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations, models%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('a4projects', '0011_fix_copyright_field_desc'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterField(%0A model_name='project',%0A name='is_archived',%0A field=models.BooleanField(default=False, help_text='Exclude this project from all listings by default. You can still access this project by using filters.', verbose_name='Project is archived'),%0A ),%0A migrations.AlterField(%0A model_name='project',%0A name='is_public',%0A field=models.BooleanField(default=True, help_text='Please indicate whether this project should be public or restricted to invited users. Teasers for your project including title and short description will always be visible to everyone', verbose_name='Access to the project'),%0A ),%0A %5D%0A
021408f6374494babc750055a88d871de78da780
Fix a circular method call that caused customs_twist to eat over 60% RAM.
mysite/customs/bugimporters/base.py
mysite/customs/bugimporters/base.py
# This file is part of OpenHatch. # Copyright (C) 2011 Jack Grigg # Copyright (C) 2011 OpenHatch, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import twisted.web.client from mysite.customs.models import TrackerModel from mysite.search.models import Bug class BugImporter(object): ##################################################### # Importer functions that don't require overloading # ##################################################### def add_url_to_waiting_list(self, url, callback, c_args={}, errback=None, e_args={}): # FIXME: change default errback to a basic logging one. self.waiting_urls[url] = (callback, c_args, errback, e_args) def get_next_waiting_url(self): # If there are no more waiting URLs, returns None. # Otherwise, returns a (url, callback, c_args, errback, e_args) tuple. try: url, (callback, c_args, errback, e_args) = self.waiting_urls.popitem() except KeyError: return None return (url, callback, c_args, errback, e_args) def add_url_to_deferred_list(self, url): # If the URL has previously been added to the reactor, returns None. # Otherwise, returns the Deferred passed back by the getPage call. if self.deferred_urls.get(url, None): # URL has already been added to the reactor by this importer return None else: # Record that we have added this URL self.deferred_urls[url] = 1 self.rm.running_deferreds += 1 # Return the Deferred passed back by the getPage call if type(url) == unicode: url = url.encode('utf-8') return twisted.web.client.getPage(url) def remove_url_from_deferred_list(self, result, url): self.deferred_urls[url] -= 1 self.rm.decrement_deferred_count() if self.urls_we_are_waiting_on[url] < 0: # FIXME: log error with Twisted #logging.error("Eeek, " + url + " went negative.") pass def has_spare_connections(self): # If we are not yet waiting on the maximum number of URLs, return True. # Otherwise, return False. max_conns = (self.tm.max_connections if self.tm.max_connections else 8) return (sum(self.deferred_urls.values()) < max_conns) def push_urls_onto_reactor(self, result=None): if not self.waiting_urls and sum(self.deferred_urls.values()) < 1: # There are no more URLs to process, so finish. self.determine_if_finished() else: # If we have space, push some more URLs on. while self.waiting_urls and self.has_spare_connections(): # Get the next URL. url, callback, c_args, errback, e_args = self.get_next_waiting_url() # Add the URL to the reactor. d = self.add_url_to_deferred_list(url) if d: # Add the supplied callback and errback. d.addCallback(callback, **c_args) d.addErrback(errback, **e_args) # Remove the URL from our deferred list. d.addBoth(self.remove_url_from_deferred_list, url) # Push some more URLs on. d.addBoth(self.push_urls_onto_reactor) ################################################### # Importer functions that may require overloading # ################################################### def __init__(self, tracker_model, reactor_manager): # Store the tracker model self.tm = tracker_model # Store the reactor manager self.rm = reactor_manager # Create a dictionary that maps URLs to a callback/errback pair. This # dictionary is used to store URLs that have been found and require # downloading, along with the callback and errback that handle the # resultant data. self.waiting_urls = {} # Create a dictionary that maps URLs to a number. This means that not # only can we check how many URLs are currently active (and so check # we are not over the limit for this tracker) but by storing all URLs # that have been fetched in this session we can prevent double-ups # e.g. if somehow we attempt to download a bug URL both in the initial # tracker refresh and the later Bug refresh. self.deferred_urls= {} def finish_import(self): # This importer has finished, so let the reactor manager know that it # may be able to stop the reactor. self.rm.maybe_quit() ########################################################## # Importer functions that definitely require overloading # ########################################################## def process_queries(self, queries): # Implement this in a subclass raise NotImplementedError def process_bugs(self, bug_urls): # Implement this in a subclass raise NotImplementedError def determine_if_finished(self): # Implement this in a subclass raise NotImplementedError class AddTrackerForeignKeysToBugs(object): def __init__(self, tracker_model, reactor_manager): # Store the tracker model self.tm = tracker_model # Store the reactor manager self.rm = reactor_manager def process_bugs(self, bug_urls): # Fetch a list of all Bugs that are stale. bugs = Bug.all_bugs.filter( canonical_bug_link__in = bug_urls) tms = TrackerModel.objects.all().select_subclasses() # For each TrackerModel, process its stale Bugs. bugs_to_retry = [] for bug in bugs: tms_shortlist = [tm for tm in tms if tm.get_base_url() in bug.canonical_bug_link] # Check that we actually got something back, otherwise bug.tracker would get # set to None, and self.rm.update_bugs would send it right back here, causing # infinite recursion. if len(tms_shortlist) > 0: # Ideally this should now just be one object, so just take the first. bug.tracker = tms_shortlist[0] bug.save() bugs_to_retry.append(bug) # Now that these Bugs all have TrackerModels, update them. self.rm.update_bugs(bugs_to_retry)
Python
0.000007
@@ -6941,31 +6941,29 @@ # -Now that +For the -se Bugs -all +that now hav @@ -6992,16 +6992,46 @@ e them.%0A + if bugs_to_retry:%0A
be2f0851f36dc0c74767459f5d11bd545b4a2f6a
Add perftests for sync
tests/test_sync.py
tests/test_sync.py
# -*- coding: utf-8 -*- ''' tests.test_sync ~~~~~~~~~~~~~~~ :copyright: (c) 2014 Markus Unterwaditzer :license: MIT, see LICENSE for more details. ''' import pytest from vdirsyncer.storage.base import Item from vdirsyncer.storage.memory import MemoryStorage from vdirsyncer.sync import sync from . import assert_item_equals, normalize_item import vdirsyncer.exceptions as exceptions def empty_storage(x): return list(x.list()) == [] def test_irrelevant_status(): a = MemoryStorage() b = MemoryStorage() status = {'1': ('1.txt', 1234, '1.ics', 2345)} sync(a, b, status) assert not status assert empty_storage(a) assert empty_storage(b) def test_missing_status(): a = MemoryStorage() b = MemoryStorage() status = {} item = Item(u'UID:1') a.upload(item) b.upload(item) sync(a, b, status) assert len(status) == 1 assert a.has('1.txt') assert b.has('1.txt') def test_missing_status_and_different_items(): a = MemoryStorage() b = MemoryStorage() status = {} item1 = Item(u'UID:1\nhaha') item2 = Item(u'UID:1\nhoho') a.upload(item1) b.upload(item2) with pytest.raises(exceptions.SyncConflict): sync(a, b, status) assert not status sync(a, b, status, conflict_resolution='a wins') assert_item_equals(item1, b.get('1.txt')[0]) assert_item_equals(item1, a.get('1.txt')[0]) def test_upload_and_update(): a = MemoryStorage() b = MemoryStorage() status = {} item = Item(u'UID:1') # new item 1 in a a.upload(item) sync(a, b, status) assert_item_equals(b.get('1.txt')[0], item) item = Item(u'UID:1\nASDF:YES') # update of item 1 in b b.update('1.txt', item, b.get('1.txt')[1]) sync(a, b, status) assert_item_equals(a.get('1.txt')[0], item) item2 = Item(u'UID:2') # new item 2 in b b.upload(item2) sync(a, b, status) assert_item_equals(a.get('2.txt')[0], item2) item2 = Item(u'UID:2\nASDF:YES') # update of item 2 in a a.update('2.txt', item2, a.get('2.txt')[1]) sync(a, b, status) assert_item_equals(b.get('2.txt')[0], item2) def test_deletion(): a = MemoryStorage() b = MemoryStorage() status = {} item = Item(u'UID:1') a.upload(item) sync(a, b, status) b.delete('1.txt', b.get('1.txt')[1]) sync(a, b, status) assert not a.has('1.txt') and not b.has('1.txt') a.upload(item) sync(a, b, status) assert a.has('1.txt') and b.has('1.txt') a.delete('1.txt', a.get('1.txt')[1]) sync(a, b, status) assert not a.has('1.txt') and not b.has('1.txt') def test_already_synced(): a = MemoryStorage() b = MemoryStorage() item = Item(u'UID:1') a.upload(item) b.upload(item) status = { '1': ('1.txt', a.get('1.txt')[1], '1.txt', b.get('1.txt')[1]) } old_status = dict(status) a.update = b.update = a.upload = b.upload = \ lambda *a, **kw: pytest.fail('Method shouldn\'t have been called.') for i in (1, 2): sync(a, b, status) assert status == old_status assert a.has('1.txt') and b.has('1.txt') def test_conflict_resolution_both_etags_new(): a = MemoryStorage() b = MemoryStorage() item = Item(u'UID:1') href_a, etag_a = a.upload(item) href_b, etag_b = b.upload(item) status = {} sync(a, b, status) assert status a.update(href_a, Item(u'UID:1\nASDASD'), etag_a) b.update(href_b, Item(u'UID:1\nHUEHUE'), etag_b) with pytest.raises(exceptions.SyncConflict): sync(a, b, status) sync(a, b, status, conflict_resolution='a wins') item_a, _ = a.get(href_a) item_b, _ = b.get(href_b) assert_item_equals(item_a, item_b) n = normalize_item(item_a) assert u'UID:1' in n assert u'ASDASD' in n def test_conflict_resolution_new_etags_without_changes(): a = MemoryStorage() b = MemoryStorage() item = Item(u'UID:1') href_a, etag_a = a.upload(item) href_b, etag_b = b.upload(item) status = {'1': (href_a, 'BOGUS_a', href_b, 'BOGUS_b')} sync(a, b, status) assert status == {'1': (href_a, etag_a, href_b, etag_b)}
Python
0
@@ -4161,8 +4161,676 @@ tag_b)%7D%0A +%0Adef test_uses_get_multi(monkeypatch):%0A def breakdown(*a, **kw):%0A raise AssertionError('Expected use of get_multi')%0A%0A get_multi_calls = %5B%5D%0A%0A old_get = MemoryStorage.get%0A%0A def get_multi(self, hrefs):%0A get_multi_calls.append(hrefs)%0A for href in hrefs:%0A item, etag = old_get(self, href)%0A yield href, item, etag%0A%0A monkeypatch.setattr(MemoryStorage, 'get', breakdown)%0A monkeypatch.setattr(MemoryStorage, 'get_multi', get_multi)%0A%0A a = MemoryStorage()%0A b = MemoryStorage()%0A item = Item(u'UID:1')%0A expected_href, etag = a.upload(item)%0A%0A sync(a, b, %7B%7D)%0A assert get_multi_calls == %5B%5Bexpected_href%5D%5D%0A
ddc3e45f5f84e5574090ee79875039e401864a49
Add test for extension loading and unloading
IPython/core/tests/test_extension.py
IPython/core/tests/test_extension.py
Python
0
@@ -0,0 +1,2303 @@ +import os.path%0A%0Aimport nose.tools as nt%0A%0Aimport IPython.testing.tools as tt%0Afrom IPython.utils.syspathcontext import prepended_to_syspath%0Afrom IPython.utils.tempdir import TemporaryDirectory%0A%0Aext1_content = %22%22%22%0Adef load_ipython_extension(ip):%0A print(%22Running ext1 load%22)%0A%0Adef unload_ipython_extension(ip):%0A print(%22Running ext1 unload%22)%0A%22%22%22%0A%0Aext2_content = %22%22%22%0Adef load_ipython_extension(ip):%0A print(%22Running ext2 load%22)%0A%22%22%22%0A%0Adef test_extension_loading():%0A em = get_ipython().extension_manager%0A with TemporaryDirectory() as td:%0A ext1 = os.path.join(td, 'ext1.py')%0A with open(ext1, 'w') as f:%0A f.write(ext1_content)%0A %0A ext2 = os.path.join(td, 'ext2.py')%0A with open(ext2, 'w') as f:%0A f.write(ext2_content)%0A %0A with prepended_to_syspath(td):%0A assert 'ext1' not in em.loaded%0A assert 'ext2' not in em.loaded%0A %0A # Load extension%0A with tt.AssertPrints(%22Running ext1 load%22):%0A assert em.load_extension('ext1') is None%0A assert 'ext1' in em.loaded%0A %0A # Should refuse to load it again%0A with tt.AssertNotPrints(%22Running ext1 load%22):%0A assert em.load_extension('ext1') == 'already loaded'%0A %0A # Reload%0A with tt.AssertPrints(%22Running ext1 unload%22):%0A with tt.AssertPrints(%22Running ext1 load%22, suppress=False):%0A em.reload_extension('ext1')%0A %0A # Unload%0A with tt.AssertPrints(%22Running ext1 unload%22):%0A assert em.unload_extension('ext1') is None%0A %0A # Can't unload again%0A with tt.AssertNotPrints(%22Running ext1 unload%22):%0A assert em.unload_extension('ext1') == 'not loaded'%0A assert em.unload_extension('ext2') == 'not loaded'%0A %0A # Load extension 2%0A with tt.AssertPrints(%22Running ext2 load%22):%0A assert em.load_extension('ext2') is None%0A %0A # Can't unload this%0A assert em.unload_extension('ext2') == 'no unload function'%0A %0A # But can reload it%0A with tt.AssertPrints(%22Running ext2 load%22):%0A em.reload_extension('ext2')%0A
b16e18a636f8484ea9478522c8ecba58b79adf6e
add ability to delete tasks selectively, useful for testing penta import
volunteers/management/commands/delete_tasks.py
volunteers/management/commands/delete_tasks.py
Python
0
@@ -0,0 +1,759 @@ +from django.core.management.base import BaseCommand%0Afrom volunteers.models import Task, TaskTemplate%0A%0A%0Aclass Command(BaseCommand):%0A%0A def handle(self, *args, **options):%0A if len(args) %3C= 0:%0A valid_choices = ', '.join(%5Btt.name for tt in TaskTemplate.objects.all()%5D)%0A raise Exception(%0A %22Please specify the type of task you would like to delete as the first argument, e.g. ./manage.py delete_tasks Heralding.%5Cn%22%0A %22Specify 'all' to delete all tasks.%5Cn%22%0A %22The types of task in the system are %7B%7D%22.format(valid_choices)%0A )%0A if args%5B0%5D.lower() == 'all':%0A Task.objects.all().delete()%0A else:%0A Task.objects.filter(template__name=args%5B0%5D).delete()%0A
a5b43e23008eaca8da9d7d740c3ce976b698b615
Add Daniel Berlin's draft of a 'blame' script.
tools/examples/blame.py
tools/examples/blame.py
Python
0
@@ -0,0 +1,2336 @@ +#!/usr/bin/env python2%0A#%0A# USAGE: annotate.py %5B-r REV%5D %5B-h DBHOME%5D repos-path%0A#%0A%0Aimport sys%0Aimport os%0Aimport getopt%0Aimport difflib%0Afrom svn import fs, util%0A%0ACHUNK_SIZE = 100000%0A%0Adef getfile(pool, path, rev=None, home='.'):%0A%0A db_path = os.path.join(home, 'db')%0A if not os.path.exists(db_path):%0A db_path = home%0A annotresult = %7B%7D%0A fsob = fs.new(pool)%0A fs.open_berkeley(fsob, db_path)%0A%0A if rev is None:%0A rev = fs.youngest_rev(fsob, pool)%0A filedata = ''%0A for i in xrange(0, rev+1):%0A root = fs.revision_root(fsob, i, pool)%0A if fs.check_path(root, path, pool) != util.svn_node_none:%0A first = i%0A break%0A print %22First revision is %25d%22 %25 first%0A print %22Last revision is %25d%22 %25 rev%0A for i in xrange(first, rev+1):%0A previousroot = root%0A root = fs.revision_root(fsob, i, pool)%0A if i != first:%0A if not fs.contents_changed(root, path, previousroot, path, pool):%0A continue%0A%0A file = fs.file_contents(root, path, pool)%0A previousdata = filedata%0A filedata = ''%0A while 1:%0A data = util.svn_stream_read(file, CHUNK_SIZE)%0A if not data:%0A break%0A filedata = filedata + data%0A%0A print %22Current revision is %25d%22 %25 i%0A diffresult = difflib.ndiff(previousdata.splitlines(1),%0A filedata.splitlines(1))%0A # print ''.join(diffresult)%0A k = 0%0A for j in diffresult:%0A if j%5B0%5D == ' ':%0A if annotresult.has_key (k):%0A k = k + 1%0A continue%0A else:%0A%09 annotresult%5Bk%5D = (i, j%5B2:%5D)%0A k = k + 1%0A continue%0A elif j%5B0%5D == '?':%0A continue%0A annotresult%5Bk%5D = (i, j%5B2:%5D)%0A if j%5B0%5D != '-':%0A k = k + 1%0A# print ''.join(diffresult)%0A# print annotresult%0A for x in xrange(len(annotresult.keys())):%0A sys.stdout.write(%22Line %25d (rev %25d):%25s%22 %25 (x,%0A annotresult%5Bx%5D%5B0%5D,%0A annotresult%5Bx%5D%5B1%5D))%0A%0Adef usage():%0A print %22USAGE: annotate.py %5B-r REV%5D %5B-h DBHOME%5D repos-path%22%0A sys.exit(1)%0A%0Adef main():%0A opts, args = getopt.getopt(sys.argv%5B1:%5D, 'r:h:')%0A if len(args) != 1:%0A usage()%0A rev = None%0A home = '.'%0A for name, value in opts:%0A if name == '-r':%0A rev = int(value)%0A elif name == '-h':%0A home = value%0A util.run_app(getfile, args%5B0%5D, rev, home)%0A%0Aif __name__ == '__main__':%0A main()%0A
8a2d86cb5d78d0865d5b0ed2e99fe79e4c739759
Add calc_size tool
tools/calc_size.py
tools/calc_size.py
Python
0.000002
@@ -0,0 +1,714 @@ +#! /usr/bin/env python%0A%0Aimport os%0Aimport os.path%0Aimport sys%0A%0Adef _sumSize(path):%0A size = os.path.getsize(path)%0A print path, %22=%22, size, %22bytes%22%0A return size%0A%0Adef sumSize(path):%0A sizeTotal = 0;%0A if os.path.isdir(path):%0A for p in os.listdir(path):%0A sizeTotal += sumSize(os.path.join(path, p))%0A else:%0A sizeTotal += _sumSize(path)%0A%0A return sizeTotal%0A%0Adef main():%0A sizeTotal = sumSize(sys.argv%5B1%5D)%0A print %22total size%22, %22=%22, sizeTotal, %22bytes%22%0A print %22total size%22, %22=%22, sizeTotal/1024, %22kilobytes%22%0A print %22total size%22, %22=%22, sizeTotal/1024/1024, %22megabytes%22%0A print %22total size%22, %22=%22, sizeTotal/1024/1024/1024, %22gigabytes%22%0A%0Aif __name__ == %22__main__%22:%0A main()%0A
7a7ce392539c724d0ee8bc2d7a82dda9194a9aae
Switch to the same default key we use for tests in our bindings
monospace/settings.py
monospace/settings.py
import os # Stripe keys STRIPE_PUBLISHABLE = 'pk_dHA9lrZx2If0QQyGU3aHUf8K8J5PW' STRIPE_SECRET = '82H5Cfy1n0Iw2ot4BVblgc8zN8aPl7mh' # customized settings PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__)) SITE_ROOT = os.path.dirname(PROJECT_ROOT) TIME_ZONE = 'America/Los_Angeles' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(SITE_ROOT, 'monospace.sqlite'), } } TEMPLATE_DIRS = (os.path.join(PROJECT_ROOT, 'templates'),) STATICFILES_DIRS = (os.path.join(PROJECT_ROOT, 'static'),) INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.staticfiles', 'monospace' ) BCRYPT_ROUNDS = 15 # default Django settings DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = () MANAGERS = ADMINS LANGUAGE_CODE = 'en-us' SITE_ID = 1 USE_I18N = True USE_L10N = True MEDIA_ROOT = '' MEDIA_URL = '' STATIC_ROOT = '' STATIC_URL = '/static/' ADMIN_MEDIA_PREFIX = '/static/admin/' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) SECRET_KEY = 'lb-06%rmn$fmhhu!mr@3nc(&$0985qvddj%_5=t@94x@#@jcs@' TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'monospace.urls' LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } }
Python
0
@@ -47,88 +47,88 @@ 'pk_ -dHA9lrZx2If0QQyGU3aHUf8K8J5PW'%0ASTRIPE_SECRET = '82H5Cfy1n0Iw2ot4BVblgc8zN8aPl7mh +YT1CEhhujd0bklb2KGQZiaL3iTzj3'%0ASTRIPE_SECRET = 'tGN0bIwXnHdwOa85VABjPdSn8nWY7G7I '%0A%0A#
b0b6afff93391bda296ed5ef87d122054f91eef5
add testdb
dbtest.py
dbtest.py
Python
0
@@ -0,0 +1,153 @@ +%0ADB = MySQLDatabase('codatadb',%0A user='heteroskedastic1',%0A host='heteroskedastic1.mysql.pythonanywhere-services.com')
27eb90e40f1f3fe4a17e0228e4de9d427382ac44
Create calendar_api.py
calendar_api.py
calendar_api.py
Python
0.00001
@@ -0,0 +1,2653 @@ +import httplib2%0Aimport os%0A%0Aimport apiclient%0Aimport oauth2client%0Afrom oauth2client import client, tools%0A%0Afrom datetime import datetime, timedelta%0A%0Aalarm_time = datetime.utcnow() + timedelta(minutes = 1)%0A%0Atry:%0A import argparse%0A flags = argparse.ArgumentParser(parents=%5Btools.argparser%5D).parse_args()%0Aexcept ImportError:%0A flags = None%0A%0ASCOPES = 'https://www.googleapis.com/auth/calendar.readonly'%0ACLIENT_SECRET_FILE = 'client_secret.json'%0AAPPLICATION_NAME = 'Clockwise'%0A%0A%0Adef get_credentials():%0A %22%22%22Gets valid user credentials from storage.%0A%0A If nothing has been stored, or if the stored credentials are invalid,%0A the OAuth2 flow is completed to obtain the new credentials.%0A%0A Returns:%0A Credentials, the obtained credential.%0A %22%22%22%0A home_dir = os.path.expanduser('~')%0A credential_dir = os.path.join(home_dir, '.credentials')%0A if not os.path.exists(credential_dir):%0A os.makedirs(credential_dir)%0A credential_path = os.path.join(credential_dir,%0A 'clockwise.json')%0A%0A store = oauth2client.file.Storage(credential_path)%0A credentials = store.get()%0A if not credentials or credentials.invalid:%0A flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)%0A flow.user_agent = APPLICATION_NAME%0A if flags:%0A credentials = tools.run_flow(flow, store, flags)%0A else: # Needed only for compatability with Python 2.6%0A credentials = tools.run(flow, store)%0A print('Storing credentials to ' + credential_path)%0A return credentials%0A%0A%0Adef getEvents():%0A credentials = get_credentials()%0A http = credentials.authorize(httplib2.Http())%0A service = apiclient.discovery.build('calendar', 'v3', http=http)%0A%0A now = datetime.utcnow().isoformat() + 'Z'%0A tomorrow = (datetime.utcnow() + timedelta(1)).isoformat() + 'Z'%0A%0A eventsResult = service.events().list(%0A calendarId='primary', timeMin=now, timeMax=tomorrow,%0A maxResults=10, singleEvents=True, orderBy='startTime').execute()%0A events = eventsResult.get('items', %5B%5D)%0A%0A if not events:%0A return (%22Nada agendado!%22)%0A events_data = %22%22%0A events_qty = 0%0A for event in events:%0A event_time = event%5B'start'%5D.get('dateTime')%0A if event%5B'summary'%5D == %22Alarm%22:%0A set_alarm_time(event_time%5B11:19%5D)%0A else:%0A events_data += %22%25s %25s %22 %25 (event_time%5B11:16%5D, event%5B'summary'%5D)%0A events_qty += 1%0A if events_qty == 0:%0A return (%22Nada agendado!%22)%0A return events_data%0A%0A%0Adef set_alarm_time(time): %0A global alarm_time%0A alarm_time = datetime.strptime(time, %22%25H:%25M:%25S%22)%0A print(%22alarm set%22)%0A
fc97a838d54417cb063a7757040ff279f298d0bb
Add snip code for http.cookies
cookie_skel.py
cookie_skel.py
Python
0
@@ -0,0 +1,934 @@ +# -*- coding: utf-8 -*-%0A%22%22%22%0ACreated on Wed Sep 14 20:49:34 2016%0A%0A@author: troon%0A%22%22%22%0A%0Aimport BaseHTTPServer, SimpleHTTPServer%0Afrom http.cookies import SimpleCookie as cookie%0A%0Aclass ApplicationRequestHandler(SimpleHTTPServer.BaseHTTPRequestHandler):%0A %0A sessioncookies = %7B%7D%0A%0A def __init__(self,*args,**kwargs):%0A self.sessionidmorsel = None%0A super().__init__(*args,**kwargs)%0A %0A def _session_cookie(self,forcenew=False):%0A cookiestring = %22%5Cn%22.join(self.headers.get_all('Cookie',failobj=%5B%5D))%0A c = cookie()%0A c.load(cookiestring)%0A %0A try:%0A if forcenew or self.sessioncookies%5Bc%5B'session_id'%5D.value%5D-time() %3E 3600:%0A raise ValueError('new cookie needed')%0A except:%0A c%5B'session_id'%5D=uuid().hex%0A %0A for m in c:%0A if m=='session_id':%0A self.sessioncookies%5Bc%5Bm%5D.value%5D = time()%0A c%5Bm%5D%5B%22httponly%22%5D = True%0A c%5Bm%5D%5B%22max-age%22%5D = 3600%0A c%5Bm%5D%5B%22expires%22%5D = self.date_time_string(time()+3600)%0A self.sessionidmorsel = c%5Bm%5D%0A break%0A
63586b03111d2c2aac3b4ffe5266468d3bd666fd
solve 1 problem
solutions/add-two-numbers.py
solutions/add-two-numbers.py
Python
0.000027
@@ -0,0 +1,1486 @@ +#!/usr/bin/env python%0A# encoding: utf-8%0A%0A%22%22%22%0Aadd-two-numbers.py%0A%0ACreated by Shuailong on 2016-04-23.%0A%0Ahttps://leetcode.com/problems/add-two-numbers/.%0A%0A%22%22%22%0A%0A%0A# Definition for singly-linked list.%0Aclass ListNode(object):%0A def __init__(self, x):%0A self.val = x%0A self.next = None%0A%0A%0Aclass Solution(object):%0A def addTwoNumbers(self, l1, l2):%0A %22%22%22%0A :type l1: ListNode%0A :type l2: ListNode%0A :rtype: ListNode%0A %22%22%22%0A p1 = l1%0A p2 = l2%0A s = ListNode(0)%0A p = s%0A carry = 0%0A while p1 and p2:%0A p.next = ListNode((p1.val + p2.val + carry) %25 10)%0A carry = (p1.val + p2.val + carry) / 10%0A p1 = p1.next%0A p2 = p2.next%0A p = p.next%0A while p1:%0A p.next = ListNode((p1.val + carry) %25 10)%0A carry = (p1.val + carry) / 10%0A p1 = p1.next%0A p = p.next%0A while p2:%0A p.next = ListNode((p2.val + carry) %25 10)%0A carry = (p2.val + carry) / 10%0A p2 = p2.next%0A p = p.next%0A if carry:%0A p.next = ListNode(carry)%0A%0A return s.next%0A%0A%0Adef main():%0A solution = Solution()%0A l1 = ListNode(2)%0A l1.next = ListNode(4)%0A l1.next.next = ListNode(3)%0A%0A l2 = ListNode(5)%0A l2.next = ListNode(6)%0A l2.next.next = ListNode(4)%0A%0A s = solution.addTwoNumbers(l1, l2)%0A while s:%0A print s.val,%0A s = s.next%0A%0A%0Aif __name__ == '__main__':%0A main()%0A
61750d22d44e4d2caa99703c1fd8d61e1e829e07
Create test.py
ProjectMidway/Data/test.py
ProjectMidway/Data/test.py
Python
0.000005
@@ -0,0 +1 @@ +%0A
0cde44fb3fade24bc0e1aed5ee4820aa2172806a
Add 2nd example.
doc/src/examples/periodogram_2.py
doc/src/examples/periodogram_2.py
Python
0
@@ -0,0 +1,569 @@ +import numpy as np%0Aimport matplotlib.pyplot as plt%0Afrom scikits.talkbox.spectral.basic import periodogram%0Afrom scipy.signal import hamming, hanning%0Afs = 1000%0Ax = np.sin(2 * np.pi * 0.15 * fs * np.linspace(0., 0.3, 0.3 * fs))%0Ax += 0.1 * np.random.randn(x.size)%0Apx1, fx1 = periodogram(x, nfft=16384, fs=fs)%0Apx2, fx2 = periodogram(x * hamming(x.size), nfft=16384, fs=fs)%0Aplt.subplot(2, 1, 1)%0Aplt.plot(fx1, 10 * np.log10(px1))%0Aplt.subplot(2, 1, 2)%0Aplt.plot(fx2, 10 * np.log10(px2))%0Aplt.xlabel('Frequency (Hz)')%0Aplt.ylabel('Amplitude (dB)')%0Aplt.savefig('periodogram_2.png')%0A
08636c9740b3103fd05c81791f43faeb29920305
Add tests for some util functions.
test/test_utils.py
test/test_utils.py
Python
0.000537
@@ -0,0 +1,2613 @@ +# -*- coding: utf-8 -*-%0A# Licensed to the Apache Software Foundation (ASF) under one or more%C2%A7%0A# contributor license agreements. See the NOTICE file distributed with%0A# this work for additional information regarding copyright ownership.%0A# The ASF licenses this file to You under the Apache License, Version 2.0%0A# (the %22License%22); you may not use this file except in compliance with%0A# 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 specific language governing permissions and%0A# limitations under the License.%0A%0Aimport sys%0Aimport unittest%0Aimport warnings%0Aimport os.path%0A%0Aimport libcloud.utils%0A%0AWARNINGS_BUFFER = %5B%5D%0A%0Adef show_warning(msg, cat, fname, lno):%0A WARNINGS_BUFFER.append((msg, cat, fname, lno))%0A%0Aoriginal_func = warnings.showwarning%0A%0Aclass TestUtils(unittest.TestCase):%0A def setUp(self):%0A global WARNINGS_BUFFER%0A WARNINGS_BUFFER = %5B%5D%0A%0A def tearDown(self):%0A global WARNINGS_BUFFER%0A WARNINGS_BUFFER = %5B%5D%0A warnings.showwarning = original_func%0A%0A def test_guess_file_mime_type(self):%0A file_path = os.path.abspath(__file__)%0A mimetype, encoding = libcloud.utils.guess_file_mime_type(file_path=file_path)%0A%0A self.assertEqual(mimetype, 'text/x-python')%0A%0A def test_deprecated_warning(self):%0A warnings.showwarning = show_warning%0A%0A libcloud.utils.SHOW_DEPRECATION_WARNING = False%0A self.assertEqual(len(WARNINGS_BUFFER), 0)%0A libcloud.utils.deprecated_warning('test_module')%0A self.assertEqual(len(WARNINGS_BUFFER), 0)%0A%0A libcloud.utils.SHOW_DEPRECATION_WARNING = True%0A self.assertEqual(len(WARNINGS_BUFFER), 0)%0A libcloud.utils.deprecated_warning('test_module')%0A self.assertEqual(len(WARNINGS_BUFFER), 1)%0A%0A def test_in_development_warning(self):%0A warnings.showwarning = show_warning%0A%0A libcloud.utils.SHOW_IN_DEVELOPMENT_WARNING = False%0A self.assertEqual(len(WARNINGS_BUFFER), 0)%0A libcloud.utils.in_development_warning('test_module')%0A self.assertEqual(len(WARNINGS_BUFFER), 0)%0A%0A libcloud.utils.SHOW_IN_DEVELOPMENT_WARNING = True%0A self.assertEqual(len(WARNINGS_BUFFER), 0)%0A libcloud.utils.in_development_warning('test_module')%0A self.assertEqual(len(WARNINGS_BUFFER), 1)%0A%0Aif __name__ == '__main__':%0A sys.exit(unittest.main())%0A
0574900ba42deda7ee61a809ffc64abc643b58b1
add hibernation test
testHibernation.py
testHibernation.py
Python
0.000001
@@ -0,0 +1,1284 @@ +from novaclient.v1_1 import Client as NovaClient%0Aimport unittest%0A%0Adef hibernate(username, password, tenant_name, auth_url, serverID):%0A nova = NovaClient(username = username,%0A api_key = password,%0A project_id = tenant_name,%0A auth_url = auth_url)%0A server = nova.servers.get(serverID)%0A server.shelve()%0A%0Aclass VMHibernationTest(unittest.TestCase):%0A %0A # to run the test, a VM must be created on openstack first%0A%0A # after shelve() is invoked on the server, its state changes from%0A # %22ACTIVE%22 to %22SHELVED%22 and then to %22SHELVED_OFFLOADED%22%0A def test(self):%0A nova = NovaClient(username = %22admin%22,%0A api_key = %22password%22,%0A project_id = %22demo%22,%0A auth_url = %22http://192.168.50.4:5000/v2.0%22)%0A server = nova.servers.list()%5B0%5D%0A self.failUnless(server.status == %22ACTIVE%22)%0A hibernate(%22admin%22, %0A %22password%22, %0A %22demo%22, %0A %22http://192.168.50.4:5000/v2.0%22,%0A server.id)%0A while server.status == %22ACTIVE%22 or server.status == %22SHELVED%22:%0A server = nova.servers.list()%5B0%5D%0A%0A self.failUnless(server.status == %22SHELVED_OFFLOADED%22)%0A%0Adef main():%0A unittest.main()%0A%0Aif __name__ == %22__main__%22:%0A main()%0A
7771baf7b4806c15cb85df6c34e344345538df4a
Add background thread example
background-thread.py
background-thread.py
Python
0
@@ -0,0 +1,339 @@ +import time%0Aimport requests%0A%0Afrom tomorrow import threads%0A%0A@threads(5)%0Adef download(url):%0A return requests.get(url)%0A%0Aif __name__ == %22__main__%22:%0A start = time.time()%0A responses = %5Bdownload(url) for url in urls%5D%0A html = %5Bresponse.text for response in responses%5D%0A end = time.time()%0A print %22Time: %25f seconds%22 %25 (end - start)%0A
3bb75969a9fc068a05bf81f096d0e58e3440a09f
Create nltk10.py
nltk10.py
nltk10.py
Python
0.000002
@@ -0,0 +1,3119 @@ +import time%0Aimport urllib2%0Afrom urllib2 import urlopen%0Aimport re%0Aimport cookielib%0Afrom cookielib import CookieJar%0Aimport datetime%0Aimport sqlite3%0Aimport nltk%0A%0A%0Acj = CookieJar()%0Aopener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))%0Aopener.addheaders = %5B('User-agent', 'Mozilla/5.0')%5D%0A%0A%0Aconn = sqlite3.connect('knowledgeBase.db')%0Ac = conn.cursor()%0A%0AvisitedLinks = %5B%5D%0A%0A%0Adef processor(data):%0A namedEntArray = %5B%5D%0A try:%0A tokenized = nltk.word_tokenize(data)%0A tagged = nltk.pos_tag(tokenized)%0A namedEnt = nltk.ne_chunk(tagged, binary=True)%0A%0A entities = re.findall(r'NE%5Cs(.*?)/',str(namedEnt))%0A descriptives = re.findall(r'%5C(%5C'(%5Cw*)%5C',%5Cs%5C'JJ%5Cw?%5C'', str(tagged))%0A if len(entities) %3E 1:%0A pass%0A elif len(entities) == 0:%0A pass%0A else:%0A print '_________________________'%0A print 'Named:',entities%5B0%5D%0A print 'Descriptions:'%0A for eachDesc in descriptives:%0A print eachDesc%0A currentTime = time.time()%0A dateStamp = datetime.datetime.fromtimestamp(currentTime).strftime('%25Y-%25m-%25d %25H:%25M:%25S')%0A namedEntity = entities%5B0%5D%0A relatedWord = eachDesc%0A c.execute(%22INSERT INTO knowledgeBase (unix, datestamp, namedEntity, relatedWord) VALUES (?,?,?,?)%22,%0A (currentTime, dateStamp, namedEntity, relatedWord))%0A conn.commit()%0A %0A%0A except Exception, e:%0A print 'failed in the main try of processor'%0A print str(e)%0A time.sleep(55)%0A%0Adef huffingtonRSSvisit():%0A try:%0A page = 'http://feeds.huffingtonpost.com/huffingtonpost/raw_feed'%0A sourceCode = opener.open(page).read()%0A try:%0A links = re.findall(r'%3Clink.*href=%5C%22(.*?)%5C%22', sourceCode)%0A for link in links:%0A if '.rdf' in link:%0A pass%0A elif link in visitedLinks:%0A print ' link already visited, moving on.'%0A else:%0A visitedLinks.append(link)%0A print 'visiting the link'%0A print '###################'%0A linkSource = opener.open(link).read()%0A linesOfInterest = re.findall(r'%3Cp%3E(.*?)%3C/p%3E', str(linkSource))%0A %0A for eachLine in linesOfInterest:%0A if '%3Cimg width' in eachLine:%0A pass%0A elif '%3Ca href=' in eachLine:%0A pass%0A else:%0A processor(eachLine)%0A%0A time.sleep(5)%0A%0A%0A except Exception, e:%0A print 'failed 2nd loop of huffingtonRSS'%0A print str(e)%0A%0A except Exception, e:%0A print 'failed main loop of huffingtonRSS'%0A print str(e)%0A%0A%0Awhile True:%0A currentTime = time.time()%0A dateStamp = datetime.datetime.fromtimestamp(currentTime).strftime('%25Y-%25m-%25d %25H:%25M:%25S')%0A huffingtonRSSvisit()%0A time.sleep(1800)%0A print 'sleeping'%0A print dateStamp%0A
ea4acac26fbedef3a9a5395860334c9bb95bcacb
add a new class GenericKeyComposerAddressAccess
AlphaTwirl/Counter/GenericKeyComposerAddressAccess.py
AlphaTwirl/Counter/GenericKeyComposerAddressAccess.py
Python
0
@@ -0,0 +1,1890 @@ +# Tai Sakuma %3Ctai.sakuma@cern.ch%3E%0A%0A##____________________________________________________________________________%7C%7C%0Aclass GenericKeyComposerAddressAccess(object):%0A def __init__(self, varNames, binnings, indices = None):%0A self._varNames = varNames%0A self._binnings = binnings%0A self._indices = indices if indices is not None else %5BNone%5D*len(self._varNames)%0A self._first = True%0A%0A def __call__(self, event):%0A if self._first:%0A self._arrays = self._findArrays(event)%0A self._first = False%0A%0A ret = %5B %5D%0A for array, binning, index in zip(self._arrays, self._binnings, self._indices):%0A if index is not None:%0A if array%5B'countarray'%5D%5B0%5D %3C= index: return None%0A var = array%5B'array'%5D%5Bindex%5D%0A else:%0A var = array%5B'array'%5D%5B0%5D%0A var_bin = binning(var)%0A if var_bin is None: return None%0A ret.append(var_bin)%0A return tuple(ret)%0A%0A def next(self, key):%0A ret = %5B %5D%0A for i in range(len(self._binnings)):%0A keyc = list(key)%0A keyc%5Bi%5D = self._binnings%5Bi%5D.next(keyc%5Bi%5D)%0A ret.append(tuple(keyc))%0A return tuple(ret)%0A%0A def binnings(self):%0A return self._binnings%0A%0A def _findArrays(self, event):%0A return %5Bevent.arrays%5Bn%5D for n in self._varNames%5D%0A%0A##____________________________________________________________________________%7C%7C%0Aclass GenericKeyComposerAddressAccessBuilder(object):%0A def __init__(self, varNames, binnings, indices = None):%0A self.varNames = varNames%0A self.binnings = binnings%0A self.indices = indices%0A def __call__(self):%0A return GenericKeyComposerAddressAccess(varNames = self.varNames, binnings = self.binnings, indices = self.indices)%0A%0A##____________________________________________________________________________%7C%7C%0A
57d731d6fb958c165cdeb5a9194669b07f8d54c1
Create central_tendency.py
central_tendency.py
central_tendency.py
Python
0.000013
@@ -0,0 +1,1896 @@ +%0A# computes measures of geo central tendancy from a csv table%0A# table must be set up as 3 columns: x, y, weight%0A%0Aimport csv%0A%0Acsv_path = 'x_y_w.csv'%0A%0A# calculating the mean centre%0Awith open(csv_path, 'rb') as f:%0A reader = csv.reader(f)%0A x_sum = 0%0A y_sum = 0%0A n = 0%0A for row in reader:%0A n = n + 1%0A x_sum = x_sum + float(row%5B0%5D)%0A y_sum = y_sum + float(row%5B1%5D)%0A mean_x = x_sum / n%0A mean_y = y_sum / n%0A%0A# calculating the standard distance%0Awith open(csv_path, 'rb') as f:%0A reader = csv.reader(f)%0A x_sq_dist = 0%0A y_sq_dist = 0%0A for row in reader:%0A x_sq_dist = (float(row%5B0%5D) - mean_x)**2 + float(x_sq_dist)%0A y_sq_dist = (float(row%5B1%5D) - mean_y)**2 + float(y_sq_dist)%0A SD = float(((x_sq_dist + y_sq_dist) / n)**0.5)%0A%0A# caclulating the weighted mean centre%0Awith open(csv_path, 'rb') as f:%0A reader = csv.reader(f)%0A x_w_sum = 0%0A y_w_sum = 0%0A w_sum = 0%0A for row in reader:%0A w_sum = float(row%5B2%5D) + float(w_sum)%0A x_w_sum = (float(row%5B0%5D) * float(row%5B2%5D)) + float(x_w_sum)%0A y_w_sum = (float(row%5B1%5D) * float(row%5B2%5D)) + float(y_w_sum)%0A w_mean_x = x_w_sum / w_sum%0A w_mean_y = y_w_sum / w_sum%0A%0A# caclulating the weighted standard distance%0Awith open(csv_path, 'rb') as f:%0A reader = csv.reader(f)%0A x_sq_dist = 0%0A y_sq_dist = 0%0A w_x_sq_dist = 0%0A w_y_sq_dist = 0%0A for row in reader:%0A w_x_sq_dist = float((float(row%5B0%5D) - float(w_mean_x))**2)*float(row%5B2%5D) + float(w_x_sq_dist)%0A w_y_sq_dist = float((float(row%5B1%5D) - float(w_mean_y))**2)*float(row%5B2%5D) + float(w_y_sq_dist)%0A WSD = ( ((w_x_sq_dist) + (w_y_sq_dist)) / w_sum ) ** 0.5%0A%0A# print results%0Aprint %22Count = %25i%22 %25 (n)%0Aprint %22Mean Centre = (%25f, %25f)%22 %25 (mean_x, mean_y)%0Aprint %22Standard Distance = %25f%22 %25 (SD)%0Aprint %22Weighted Mean Centre = (%25f, %25f)%22 %25 (w_mean_x, w_mean_y)%0Aprint %22Weighted Standard Distance = %25f%22 %25 (WSD)%0A
624eff1e010c7b36f43e2580346b5ae74cc20128
Create does_my_number_look_big_in_this.py
does_my_number_look_big_in_this.py
does_my_number_look_big_in_this.py
Python
0.000008
@@ -0,0 +1,208 @@ +#Kunal Gautam%0A#Codewars : @Kunalpod%0A#Problem name: Does my number look big in this?%0A#Problem level: 6 kyu%0A%0Adef narcissistic( value ):%0A return value==int(sum(%5Bint(x)**len(str(value)) for x in str(value)%5D))%0A
ebde18f5958463d622805b1a09244d07c81ec8ae
Bump development version
cms/__init__.py
cms/__init__.py
# -*- coding: utf-8 -*- __version__ = '3.0.16' default_app_config = 'cms.apps.CMSConfig'
Python
0
@@ -41,9 +41,14 @@ .0.1 -6 +7.dev1 '%0A%0Ad
9831d82463b556c70d64dc17ceeadb2d54c6141d
add unittest for Kutil.
tests/kutiltest.py
tests/kutiltest.py
Python
0
@@ -0,0 +1,1802 @@ +import unittest%0Afrom pypeerassets.kutil import Kutil%0A%0Aclass KutilTestCase(unittest.TestCase):%0A%0A def test_network_parameter_load(self):%0A '''tests if loading of network parameteres is accurate'''%0A%0A mykey = Kutil(network=%22ppc%22)%0A%0A self.assertEqual(mykey.denomination, 1000000)%0A self.assertEqual(mykey.wif_prefix, b'b7')%0A self.assertEqual(mykey.pubkeyhash, b'37')%0A%0A def test_key_generation(self):%0A '''test privkey/pubkey generation'''%0A%0A mykey = Kutil(network=%22ppc%22)%0A%0A # check if keys are in proper format%0A self.assertTrue(isinstance(mykey.keypair.private_key, bytes))%0A self.assertTrue(isinstance(mykey.keypair.pubkey.serialize(), bytes))%0A%0A # check if key generation is what is expected from seed%0A '''%0A self.assertEqual(mykey.privkey, '416b2b925a4b004a3ccb92295e5a835cfd854ef7c4afde0b0eabd5d2492594e2')%0A self.assertEqual(mykey.pubkey, '03d612848fca55fd57760ff204434d41091927eeda4dfec39e78956b2cc6dbd62b')%0A '''%0A%0A def test_address_generation(self):%0A '''test if addresses are properly made'''%0A%0A mykey = Kutil(network=%22ppc%22)%0A%0A self.assertTrue(mykey.address.startswith(%22P%22))%0A self.assertTrue(isinstance(mykey.address, str))%0A self.assertTrue(len(mykey.address), 34)%0A%0A def test_wif_import(self):%0A '''test improting WIF privkey'''%0A%0A mykey = Kutil(wif=%227A6cFXZSZnNUzutCMcuE1hyqDPtysH2LrSA9i5sqP2BPCLrAvZM%22)%0A%0A self.assertEqual(mykey.address, 'PJxwxuBqjpHhhdpV6KY1pXxUSUNb6omyNW')%0A self.assertEqual(mykey.pubkey, '02a119079ef5be1032bed61cc295cdccde58bf70e0dd982399c024d1263740f398')%0A self.assertEqual(mykey.privkey, 'b43d38cdfa04ecea88f7d9d7e95b15b476e4a6c3f551ae7b45344831c3098da2')%0A%0Aif __name__ == '__main__':%0A unittest.main()%0A
6958b09e08662e2a13b1f161cdd22f4f929d56c6
add sample program
codeiq/yatta.py
codeiq/yatta.py
Python
0.000001
@@ -0,0 +1,803 @@ +#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A%0A%22%22%22 script for generate process template directories%0A%0AThis is xxx%0A%22%22%22%0A%0Afrom __future__ import print_function%0A%0Adef yatta(n):%0A if n %25 2 == 0:%0A print(%22invalid%22)%0A return%0A%0A m = int(n / 2) + 1%0A for i in reversed(range(n)):%0A if i %3C m:%0A for j in range(n):%0A if j == m - 1:%0A print(%22y%22, end=%22%22)%0A else:%0A print(%22.%22, end=%22%22)%0A print(%22%22)%0A else:%0A for j in range(n):%0A p = n - i -1%0A if (j == p) %7C (j == (n - p - 1)):%0A print(%22y%22, end=%22%22)%0A else:%0A print(%22.%22, end=%22%22)%0A print(%22%22)%0A%0A return%0A%0Aif __name__ == '__main__':%0A yatta(int(raw_input()))%0A
04740a33ab8b4d43cda71668ff7027ac7e5982d5
Add test. This continues to need pytz and tzlocal.
tests/test_cdav.py
tests/test_cdav.py
Python
0
@@ -0,0 +1,1352 @@ +import datetime%0A%0Aimport pytz%0Aimport tzlocal%0A%0Afrom caldav.elements.cdav import _to_utc_date_string%0A%0ASOMEWHERE_REMOTE = pytz.timezone('Brazil/DeNoronha') # UTC-2 and no DST%0A%0A%0Adef test_to_utc_date_string_date():%0A input = datetime.date(2019, 5, 14)%0A res = _to_utc_date_string(input)%0A assert res == '20190514T000000Z'%0A%0A%0Adef test_to_utc_date_string_utc():%0A input = datetime.datetime(2019, 5, 14, 21, 10, 23, 23, tzinfo=datetime.timezone.utc)%0A res = _to_utc_date_string(input.astimezone())%0A assert res == '20190514T211023Z'%0A%0A%0Adef test_to_utc_date_string_dt_with_pytz_tzinfo():%0A input = datetime.datetime(2019, 5, 14, 21, 10, 23, 23)%0A res = _to_utc_date_string(SOMEWHERE_REMOTE.localize(input))%0A assert res == '20190514T231023Z'%0A%0A%0Adef test_to_utc_date_string_dt_with_local_tz():%0A input = datetime.datetime(2019, 5, 14, 21, 10, 23, 23)%0A res = _to_utc_date_string(input.astimezone())%0A exp_dt = tzlocal.get_localzone().localize(input).astimezone(datetime.timezone.utc)%0A exp = exp_dt.strftime(%22%25Y%25m%25dT%25H%25M%25SZ%22)%0A assert res == exp%0A%0A%0Adef test_to_utc_date_string_naive_dt():%0A input = datetime.datetime(2019, 5, 14, 21, 10, 23, 23)%0A res = _to_utc_date_string(input)%0A exp_dt = tzlocal.get_localzone().localize(input).astimezone(datetime.timezone.utc)%0A exp = exp_dt.strftime(%22%25Y%25m%25dT%25H%25M%25SZ%22)%0A assert res == exp%0A
7a70d230d3ceb3c37d718f138e80b132b9a05fae
Add migration for multiple repos per team.
edwin/teams/migrations/0005_auto_20150811_2236.py
edwin/teams/migrations/0005_auto_20150811_2236.py
Python
0
@@ -0,0 +1,497 @@ +# -*- coding: utf-8 -*-%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import models, migrations%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('teams', '0004_auto_20150516_0009'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterField(%0A model_name='team',%0A name='github_repo',%0A field=models.CharField(blank=True, help_text='Comma-separated list of repos, like %22mozilla/edwin,mozilla/edwin2%22', max_length=1024),%0A ),%0A %5D%0A
432ba7d3f923f6a22aef7bb45c7f658422968aa0
add python script to plot p/r curve
bin/plot-pr-curve.py
bin/plot-pr-curve.py
Python
0.000001
@@ -0,0 +1,1176 @@ +import numpy as np%0Aimport matplotlib.pyplot as plt%0Aimport matplotlib.ticker as ticker%0Aimport matplotlib.colors%0Aimport sys%0A%0A# change font family to match math%0A#plt.rc('font', family='serif')%0A%0Afontsize = 18%0Afont = %7B'family' : 'sans-serif',%0A# 'serif' : 'Times Regular',%0A 'size' : fontsize%7D%0Amatplotlib.rc('font', **font)%0A%0Aoutput_dir = %22plots%22%0A%0A# load in data%0Adata_fname = sys.argv%5B1%5D%0A%0Alabels = np.unique(np.loadtxt(data_fname, usecols=%5B2%5D, dtype='str'))%0A%0Aprint labels%0A%0Adata = np.loadtxt(data_fname, converters = %7B2: lambda y: np.where(labels==y)%5B0%5D%7D)%0A%0Aprint data%0A%0Arecall_idx = 0%0Aprecision_idx = 1%0Amodel_idx = 2%0A%0A# initialize figures%0Afig1 = plt.figure()%0Aax1 = fig1.add_subplot(111)%0Aax1.set_title(%22Recall vs. Precision%22, fontsize=fontsize)%0Aax1.set_xlabel(%22Recall%22)%0Aax1.set_ylabel(%22Precision%22)%0Afor i in range(len(labels)):%0A%09indices = np.where(data%5B:,model_idx%5D == i)%0A%09ax1.plot(data%5Bindices,recall_idx%5D%5B0%5D, data%5Bindices,precision_idx%5D%5B0%5D, label=labels%5Bi%5D)%0A%0Aax1.yaxis.set_major_formatter(ticker.FuncFormatter(lambda y, pos: ('%25.2f')%25(y)))%0A%0A# add legend%0Aax1.legend()%0A%0A#fig1.savefig(%22%25s/compare-accuracy-speed-margin.pdf%22 %25 (output_dir), bbox_inches='tight')%0A%0Aplt.show()%0A
2d7782508e6bfe1be88da3409ae67371dab7379d
Add files via upload
openquake/hazardlib/tests/gsim/skarlatoudis_2013_test.py
openquake/hazardlib/tests/gsim/skarlatoudis_2013_test.py
Python
0.000001
@@ -0,0 +1,1825 @@ +# -*- coding: utf-8 -*-%0A# vim: tabstop=4 shiftwidth=4 softtabstop=4%0A#%0A# Copyright (C) 2015-2019 GEM Foundation%0A#%0A# OpenQuake is free software: you can redistribute it and/or modify it%0A# under the terms of the GNU Affero General Public License as published%0A# by the Free Software Foundation, either version 3 of the License, or%0A# (at your option) any later version.%0A#%0A# OpenQuake is distributed in the hope that it will be useful,%0A# but WITHOUT ANY WARRANTY; without even the implied warranty of%0A# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the%0A# GNU Affero General Public License for more details.%0A#%0A# You should have received a copy of the GNU Affero General Public License%0A# along with OpenQuake. If not, see %3Chttp://www.gnu.org/licenses/%3E.%0A%0Afrom openquake.hazardlib.gsim.skarlatoudis_2013 import (%0A SkarlatoudisetalSlab2013)%0Afrom openquake.hazardlib.tests.gsim.utils import BaseGSIMTestCase%0A%0A%0Aclass SkarlatoudisetalSlab2013TestCase(BaseGSIMTestCase):%0A %22%22%22%0A Tests the Skarlatoudis et al. (2013) model for subduction%0A intraslab earthquakes%0A %22%22%22%0A GSIM_CLASS = SkarlatoudisetalSlab2013%0A MEAN_FILE = %22SKARL13/SKARL13_SSLAB_CENTRAL_MEAN_1.csv%22%0A TOTAL_FILE = %22SKARL13/SKARL13_SSLAB_CENTRAL_STDDEV_TOTAL.csv%22%0A INTER_FILE = %22SKARL13/SKARL13_SSLAB_CENTRAL_STDDEV_INTER.csv%22%0A INTRA_FILE = %22SKARL13/SKARL13_SSLAB_CENTRAL_STDDEV_INTRA.csv%22%0A%0A def test_mean(self):%0A self.check(self.MEAN_FILE,%0A max_discrep_percentage=0.1)%0A%0A def test_std_total(self):%0A self.check(self.TOTAL_FILE,%0A max_discrep_percentage=0.1)%0A%0A def test_std_inter(self):%0A self.check(self.INTER_FILE,%0A max_discrep_percentage=0.1)%0A%0A def test_std_intra(self):%0A self.check(self.INTRA_FILE,%0A max_discrep_percentage=0.1)%0A
f5237b61a50b66d6ac3123318af94db8ec95173b
Test tasks.get_email_addresses handles subentites.
entity_emailer/tests/test_tasks.py
entity_emailer/tests/test_tasks.py
Python
0
@@ -0,0 +1,1467 @@ +from entity.models import Entity, EntityRelationship%0Afrom django.contrib.contenttypes.models import ContentType%0Afrom django.test import TestCase%0Afrom django_dynamic_fixture import G, N%0A%0Afrom entity_emailer import tasks%0Afrom entity_emailer.models import Email%0A%0A%0Aclass Test_get_email_addresses(TestCase):%0A def setUp(self):%0A self.ct = ContentType.objects.get_for_model(Email)%0A self.super_entity = G(%0A Entity,%0A entity_meta=%7B'email': 'test_super@example.com'%7D,%0A entity_type=self.ct%0A )%0A self.sub_entity_1 = G(%0A Entity,%0A entity_meta=%7B'email': 'test_sub1@example.com'%7D,%0A entity_type=self.ct%0A )%0A self.sub_entity_2 = G(%0A Entity,%0A entity_meta=%7B'email': 'test_sub2@example.com'%7D,%0A entity_type=self.ct%0A )%0A G(EntityRelationship, sub_entity=self.sub_entity_1, super_entity=self.super_entity)%0A G(EntityRelationship, sub_entity=self.sub_entity_2, super_entity=self.super_entity)%0A%0A def test_returns_sub_entities_emails(self):%0A email = N(Email, send_to=self.super_entity, subentity_type=self.ct, context=%7B%7D)%0A addresses = tasks.get_email_addresses(email)%0A expected_addresses = %7Bu'test_sub1@example.com', u'test_sub2@example.com'%7D%0A self.assertEqual(set(addresses), expected_addresses)%0A%0A def test_returns_own_email(self):%0A pass%0A%0A def test_unsubscription_works(self):%0A pass%0A
4ec9406a19b5f42b0b05f37c12b99dd91853514f
Add all the data necessary for generations
tests/generator_test.py
tests/generator_test.py
from datetime import date, time, datetime from google.appengine.ext import testbed, ndb from gaend.main import app import unittest import webtest # References # cloud.google.com/appengine/docs/python/ndb/db_to_ndb # cloud.google.com/appengine/docs/python/ndb/entity-property-reference # cloud.google.com/appengine/docs/python/ndb/creating-entity-models#expando PROPERTIES = [ ndb.IntegerProperty, # [int], ndb.FloatProperty, # [float], ndb.BooleanProperty, # [bool], ndb.StringProperty, # [(basestring, lambda x, # len(s) < 1500)], ndb.TextProperty, # [basetring] ndb.BlobProperty, # [basestring], ndb.DateProperty, # [date], ndb.TimeProperty, # [time], ndb.DateTimeProperty, # [datetime], ndb.GeoPtProperty, # [ndb.GeoPt], ndb.KeyProperty, # [ndb.Model], ndb.StructuredProperty, # [ndb.Model] ndb.LocalStructuredProperty, # [ndb.Model], ndb.JsonProperty, # python list or dict ndb.PickleProperty # python list or dict ] # Untested Property Types # 1. ndb.BlobKeyProperty - Holdover from `db` days? # 2. ndb.UserProperty - Google recomends not using this # 3. ndb.ExpandoProperty - Why not just use ndb.Expando class? # 4. ndb.GenericProperty - Why not just use ndb.Expando class? class GeneratorTest(unittest.TestCase): def setUp(self): self.testapp = webtest.TestApp(app) self.testbed = testbed.Testbed() self.testbed.activate() self.testbed.init_datastore_v3_stub() self.testbed.init_memcache_stub() def tearDown(self): self.testbed.deactivate() def testTruthItself(self): assert True
Python
0.000291
@@ -356,16 +356,122 @@ xpando%0A%0A +SERIALIZE = %5B%7B'key1': True, 'key2': %5B%5D%7D, %5B1, 2.0, %7B%7D, 'json'%5D%5D%0A%0ACOMPUTED = lambda x: %22COMPUTED_PROPERTY%22%0A%0A PROPERTI @@ -475,17 +475,17 @@ RTIES = -%5B +%7B %0A ndb @@ -500,19 +500,17 @@ Property -, # +: %5Bint%5D,%0A @@ -530,19 +530,17 @@ Property -, # +: %5Bfloat%5D @@ -564,19 +564,17 @@ Property -, # +: %5Bbool%5D, @@ -596,19 +596,17 @@ Property -, # +: %5B(bases @@ -620,19 +620,17 @@ lambda x -, # +: len(s) @@ -664,23 +664,23 @@ erty -, # +: %5Bbase +s tring%5D +, %0A @@ -696,19 +696,17 @@ Property -, # +: %5Bbasest @@ -728,27 +728,25 @@ DateProperty -, # +: %5Bdate%5D,%0A @@ -762,19 +762,17 @@ Property -, # +: %5Btime%5D, @@ -796,19 +796,17 @@ Property -, # +: %5Bdateti @@ -827,27 +827,25 @@ eoPtProperty -, # +: %5Bndb.GeoPt%5D @@ -857,35 +857,33 @@ ndb.KeyProperty -, # +: %5Bndb.Model%5D,%0A @@ -898,35 +898,33 @@ ructuredProperty -, # +: %5Bndb.Model%5D%0A @@ -919,16 +919,17 @@ b.Model%5D +, %0A ndb @@ -952,19 +952,17 @@ Property -, # +: %5Bndb.Mo @@ -991,78 +991,93 @@ erty -, # python list or dict%0A ndb.PickleProperty # python list or dict%0A%5D +: SERIALIZE,%0A ndb.PickleProperty: SERIALIZE,%0A ndb.ComputedProperty: COMPUTED,%0A%7D %0A%0A# @@ -1103,13 +1103,11 @@ ypes +: %0A# - 1. ndb @@ -1151,19 +1151,16 @@ days?%0A# - 2. ndb.Use @@ -1208,23 +1208,20 @@ is%0A# - 3. ndb. -Expando +Generic Prop @@ -1267,70 +1267,497 @@ ss?%0A -# 4. ndb.GenericProperty - Why not just use ndb.Expando class? +%0Aclass DefaultModel(ndb.Model):%0A pass%0A%0ADEFAULTS = %7B%0A bool: False,%0A int: 0,%0A float: 0.0,%0A basestring: %22%22,%0A ndb.GeoPt: ndb.GeoPt(0,0),%0A ndb.Model: DefaultModel,%0A%7D%0A%0ACHOICES = %7B%0A bool: %5BTrue, False%5D,%0A int: %5B-1, 0, 1%5D,%0A float: %5B-1.0, 0.0, 1.0%5D,%0A basestring: %22%22,%0A ndb.GeoPt: ndb.GeoPt(0,0),%0A ndb.Model: DefaultModel,%0A%7D%0A%0APROPERTY_OPTIONS = %7B%0A 'indexed': bool,%0A 'repeated': bool,%0A 'required': bool,%0A 'default': DEFAULTS,%0A 'choices': CHOICES,%0A%7D %0A%0Acl
64e2946081adc3991a55d9871f69c9d41e42d6bf
Improve offer fixture generator
oscar/test/helpers.py
oscar/test/helpers.py
from decimal import Decimal as D import random import datetime from oscar.core.loading import get_class, get_classes Basket = get_class('basket.models', 'Basket') Free = get_class('shipping.methods', 'Free') Voucher = get_class('voucher.models', 'Voucher') OrderCreator = get_class('order.utils', 'OrderCreator') OrderTotalCalculator = get_class('checkout.calculators', 'OrderTotalCalculator') Partner, StockRecord = get_classes('partner.models', ('Partner', 'StockRecord')) (ProductClass, Product, ProductAttribute, ProductAttributeValue) = get_classes('catalogue.models', ('ProductClass', 'Product', 'ProductAttribute', 'ProductAttributeValue')) (Range, ConditionalOffer, Condition, Benefit) = get_classes('offer.models', ('Range', 'ConditionalOffer', 'Condition', 'Benefit')) def create_product(price=None, title="Dummy title", product_class="Dummy item class", partner="Dummy partner", partner_sku=None, upc=None, num_in_stock=10, attributes=None, **kwargs): """ Helper method for creating products that are used in tests. """ ic, __ = ProductClass._default_manager.get_or_create(name=product_class) item = Product._default_manager.create(title=title, product_class=ic, upc=upc, **kwargs) if price is not None or partner_sku or num_in_stock is not None: if not partner_sku: partner_sku = 'sku_%d_%d' % (item.id, random.randint(0, 10000)) if price is None: price = D('10.00') partner, __ = Partner._default_manager.get_or_create(name=partner) StockRecord._default_manager.create(product=item, partner=partner, partner_sku=partner_sku, price_excl_tax=price, num_in_stock=num_in_stock) if attributes: for key, value in attributes.items(): attr, __ = ProductAttribute.objects.get_or_create( name=key, code=key) ProductAttributeValue.objects.create( product=item, attribute=attr, value=value) return item def create_order(number=None, basket=None, user=None, shipping_address=None, shipping_method=None, billing_address=None, total_incl_tax=None, total_excl_tax=None, **kwargs): """ Helper method for creating an order for testing """ if not basket: basket = Basket.objects.create() basket.add_product(create_product(price=D('10.00'))) if not basket.id: basket.save() if shipping_method is None: shipping_method = Free() if total_incl_tax is None or total_excl_tax is None: calc = OrderTotalCalculator() total_incl_tax = calc.order_total_incl_tax(basket, shipping_method) total_excl_tax = calc.order_total_excl_tax(basket, shipping_method) order = OrderCreator().place_order( order_number=number, user=user, basket=basket, shipping_address=shipping_address, shipping_method=shipping_method, billing_address=billing_address, total_incl_tax=total_incl_tax, total_excl_tax=total_excl_tax, **kwargs) basket.set_as_submitted() return order def create_offer(): """ Helper method for creating an offer """ range = Range.objects.create(name="All products range", includes_all_products=True) condition = Condition.objects.create(range=range, type=Condition.COUNT, value=1) benefit = Benefit.objects.create(range=range, type=Benefit.PERCENTAGE, value=20) offer = ConditionalOffer.objects.create( name='Dummy offer', offer_type='Site', condition=condition, benefit=benefit) return offer def create_voucher(): """ Helper method for creating a voucher """ voucher = Voucher.objects.create( name="Test voucher", code="test", start_date=datetime.date.today(), end_date=datetime.date.today() + datetime.timedelta(days=12)) voucher.offers.add(create_offer()) return voucher
Python
0
@@ -3643,16 +3643,152 @@ e_offer( +name=%22Dummy offer%22, offer_type=%22Site%22,%0A max_applications=None, range=None, condition=None,%0A benefit=None ):%0A %22 @@ -3834,24 +3834,50 @@ fer%0A %22%22%22%0A + if range is None:%0A range = @@ -3957,16 +3957,19 @@ + includes @@ -3988,16 +3988,46 @@ s=True)%0A + if condition is None:%0A cond @@ -4064,32 +4064,35 @@ te(range=range,%0A + @@ -4175,24 +4175,27 @@ + value=1)%0A @@ -4191,16 +4191,44 @@ alue=1)%0A + if benefit is None:%0A bene @@ -4261,32 +4261,35 @@ te(range=range,%0A + @@ -4367,24 +4367,27 @@ + value=20)%0A @@ -4392,15 +4392,14 @@ -offer = +return Con @@ -4445,21 +4445,12 @@ ame= -'Dummy offer' +name ,%0A @@ -4470,14 +4470,18 @@ ype= -'Site' +offer_type ,%0A @@ -4534,26 +4534,52 @@ efit -) +, %0A -return offer + max_applications=max_applications) %0A%0A%0Ad
4c4891f24c0e5b093d3a9fcb0de86609b01a69c3
Add migration for replace location with country and city
fellowms/migrations/0053_auto_20160804_1447.py
fellowms/migrations/0053_auto_20160804_1447.py
Python
0.000172
@@ -0,0 +1,967 @@ +# -*- coding: utf-8 -*-%0A# Generated by Django 1.9.5 on 2016-08-04 14:47%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations%0Aimport django_countries.fields%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('fellowms', '0052_merge'),%0A %5D%0A%0A operations = %5B%0A migrations.RenameField(%0A model_name='event',%0A old_name='location',%0A new_name='city',%0A ),%0A migrations.RenameField(%0A model_name='fellow',%0A old_name='home_location',%0A new_name='home_city',%0A ),%0A migrations.AddField(%0A model_name='event',%0A name='country',%0A field=django_countries.fields.CountryField(default='UK', max_length=2),%0A ),%0A migrations.AddField(%0A model_name='fellow',%0A name='home_country',%0A field=django_countries.fields.CountryField(default='UK', max_length=2),%0A ),%0A %5D%0A
d6c5e3c40e2106b7ef4ddc800a1c00493d4f469f
Add customized Pool class.
tests/test_pool.py
tests/test_pool.py
Python
0
@@ -0,0 +1,1905 @@ +import gevent.pool%0Aimport gevent.queue%0Aimport gevent.event%0Aimport time%0Aimport traceback%0A%0A%0Adef timeit(func):%0A def wrap(*args, **kwargs):%0A begin_time = time.time()%0A try:%0A return func(*args, **kwargs)%0A except:%0A traceback.print_exc()%0A finally:%0A end_time = time.time()%0A print 'function %25s:' %25 func.__name__, end_time - begin_time%0A return wrap%0A%0Aglobal_counter = 0%0A%0A%0Adef test_func():%0A global global_counter%0A global_counter += 1%0A return global_counter%0A%0A%0Aclass Pool(object):%0A def __init__(self, pool_size=None):%0A self._task_queue = gevent.queue.JoinableQueue()%0A self._pool = gevent.pool.Pool(pool_size)%0A if pool_size is None:%0A pool_size = 100%0A%0A for _ in xrange(pool_size):%0A self._pool.spawn(self.worker_func)%0A%0A def worker_func(self):%0A while True:%0A task = self._task_queue.get()%0A if task is None:%0A self._task_queue.task_done()%0A break%0A task()%0A self._task_queue.task_done()%0A%0A def spawn(self, func, *args, **kwargs):%0A task = lambda: func(*args, **kwargs)%0A self._task_queue.put_nowait(task)%0A%0A def join(self):%0A for _ in xrange(len(self._pool)):%0A self._task_queue.put_nowait(None)%0A self._task_queue.join()%0A self._pool.join()%0A%0A def kill(self):%0A self._pool.kill()%0A%0A%0A@timeit%0Adef test_my_pool():%0A pool = Pool(1000)%0A for _ in xrange(100000):%0A pool.spawn(test_func)%0A%0A pool.join()%0A%0A@timeit%0Adef test_gevent_pool():%0A pool = gevent.pool.Pool(1000)%0A for _ in xrange(100000):%0A pool.spawn(test_func)%0A%0A pool.join()%0A%0A%0Aif __name__ == '__main__':%0A global_counter = 0%0A test_gevent_pool()%0A print 'global_counter', global_counter%0A global_counter = 0%0A test_my_pool()%0A print 'global_counter', global_counter
077e581326e0791e1bf5816baba6c6a6cba17d9d
Test for setting CHOICES_SEPARATOR
survey/tests/test_default_settings.py
survey/tests/test_default_settings.py
Python
0.000003
@@ -0,0 +1,602 @@ +from survey.tests import BaseTest%0Afrom django.test import override_settings%0Afrom django.conf import settings%0Afrom django.test import tag%0Afrom survey import set_default_settings%0A%0A%0A@tag(%22set%22)%0A@override_settings()%0Aclass TestDefaultSettings(BaseTest):%0A def test_set_choices_separator(self):%0A url = %22/admin/survey/survey/1/change/%22%0A del settings.CHOICES_SEPARATOR%0A self.login()%0A with self.assertRaises(AttributeError):%0A self.client.get(url)%0A set_default_settings()%0A response = self.client.get(url)%0A self.assertEqual(response.status_code, 200)%0A
813f42aee6b38031c4993d322e12053c91d10c8a
add failing test to recreate logrotate bug [#461]
tests/test_tail.py
tests/test_tail.py
Python
0
@@ -0,0 +1,2000 @@ +import logging%0Aimport subprocess%0Aimport tempfile%0Aimport unittest%0A%0A%0Aclass TestTail(unittest.TestCase):%0A def setUp(self):%0A self.log_file = tempfile.NamedTemporaryFile()%0A self.logrotate_config = tempfile.NamedTemporaryFile()%0A self.logrotate_config.write(%22%22%22%25s %7B%0A copytruncate%0A notifempty%0A missingok%0A rotate 1%0A weekly%0A %7D%22%22%22 %25 self.log_file.name)%0A self.logrotate_config.flush()%0A self.logrotate_state_file = tempfile.NamedTemporaryFile()%0A %0A def _trigger_logrotate(self):%0A subprocess.check_call(%5B%0A 'logrotate', %0A '-v', # Verbose logging%0A '-f', # Force the rotation even though the file isn't old%0A # Create a state file that you have file permissions for%0A '-s', self.logrotate_state_file.name, %0A self.logrotate_config.name%0A %5D) %0A %0A def test_logrotate_copytruncate(self):%0A from checks.utils import TailFile%0A %0A line_parser = lambda line: line%0A %0A tail = TailFile(logging.getLogger(), self.log_file.name, line_parser)%0A self.assertEquals(tail._size, 0)%0A %0A # Write some data to the log file%0A init_string = %22hey there, I am a log%5Cn%22%0A self.log_file.write(init_string)%0A self.log_file.flush()%0A %0A # Consume from the tail%0A gen = tail.tail(line_by_line=False, move_end=True)%0A gen.next()%0A %0A # Verify that the tail consumed the data I wrote%0A self.assertEquals(tail._size, len(init_string))%0A %0A # Trigger a copytruncate logrotation on the log file%0A self._trigger_logrotate()%0A %0A # Write a new line to the log file%0A new_string = %22I am shorter%5Cn%22%0A self.log_file.write(new_string)%0A self.log_file.flush()%0A %0A # Verify that the tail recognized the logrotation %0A self.assertEquals(tail._size, len(new_string))%0A %0A %0A
60774ca1a336fac5c0d9fb92ab6de509cd92dd43
Add tests for topsort.
tests/test_util.py
tests/test_util.py
Python
0
@@ -0,0 +1,706 @@ +import unittest2%0Aimport util%0A%0Aclass TopSortTest(unittest2.TestCase):%0A def test_error(self):%0A a,b = range(2)%0A deps = %5B(a,b), (b,a)%5D%0A with self.assertRaises(ValueError):%0A util.topological_sort(%5B%5D, deps)%0A%0A def test_multi_deps(self):%0A a,b,c,d = range(4)%0A start = %5Ba,b%5D%0A deps = %5B(%5Ba,b%5D, c),%0A (c, d)%5D%0A self.assertTrue(util.topological_sort(start, deps) in (%5Ba,b,c,d%5D,%0A %5Bb,a,c,d%5D))%0A def test_linear_deps(self):%0A a,b,c,d = range(4)%0A start = %5Ba%5D%0A deps = %5B(a,b),(b,c),(c,d)%5D%0A self.assertListEqual(util.topological_sort(start, deps), range(4))%0A
13917ab0aba2951bd10b64b53cdd358b169a432f
Create Bender_un_robot_dépressif.py
Medium/Bender_un_robot_dépressif.py
Medium/Bender_un_robot_dépressif.py
Python
0.000001
@@ -0,0 +1,2132 @@ +import sys%0Aimport math%0A%0A# Auto-generated code below aims at helping you parse%0A# the standard input according to the problem statement.%0A%0Al, c = %5Bint(i) for i in input().split()%5D%0AMap=%5B%5D%0AT=%5B%5D%0Afor i in range(l):%0A Map.append(input())%0A if %22@%22 in Map%5Bi%5D:%0A X=Map%5Bi%5D.index('@')%0A Y=i%0A if 'T' in Map%5Bi%5D:%0A T.append(%5BMap%5Bi%5D.index('T'),i%5D)%0A %0Adirection_loop=%5B'S','E','N','W'%5D%0Adirection_values=%5B('S',0,1),('N',0,-1),('E',1,0),('W',-1,0)%5D%0Adirection=('S',0,1)%0A%0Adef heading():%0A for i in direction_loop:%0A direction=heading_value(i)%0A if Map%5BY+direction%5B2%5D%5D%5BX+direction%5B1%5D%5D in %5B' ','S','E','N','W','T','I','B','$'%5D:%0A return direction%0A break%0A %0Adef heading_value(x):%0A for i in direction_values:%0A if x==i%5B0%5D:%0A return i%0A %0Amv_liste=%5B%5D%0Agoing=True%0Abeer=False%0Aloop=False%0Ac=0%0A%0Awhile going:%0A%0A if Map%5BY%5D%5BX%5D==%22B%22:%0A if beer:%0A beer=False%0A else:%0A beer=True%0A %0A if Map%5BY%5D%5BX%5D==%22I%22:%0A direction_loop.reverse()%0A %0A if Map%5BY%5D%5BX%5D==%22T%22:%0A for el in T:%0A if el!=%5BX,Y%5D:%0A X=el%5B0%5D%0A Y=el%5B1%5D%0A break%0A %0A if Map%5BY%5D%5BX%5D==%22$%22:%0A going=False%0A %0A else:%0A X_t1=X+direction%5B1%5D%0A Y_t1=Y+direction%5B2%5D%0A %0A if Map%5BY%5D%5BX%5D in %5B'S','N','E','W'%5D:%0A direction=heading_value(Map%5BY%5D%5BX%5D)%0A %0A elif Map%5BY_t1%5D%5BX_t1%5D=='#':%0A direction=heading()%0A elif Map%5BY_t1%5D%5BX_t1%5D=='X':%0A if beer:%0A Map%5BY_t1%5D=Map%5BY_t1%5D%5B0:X_t1%5D+' '+Map%5BY_t1%5D%5BX_t1+1::%5D%0A else:%0A direction=heading()%0A %0A X+=direction%5B1%5D%0A Y+=direction%5B2%5D%0A%0A if %5Bdirection%5B0%5D,(X,Y)%5D in mv_liste:%0A c+=1%0A if c%3Elen(mv_liste)/1.2:%0A %0A loop=True%0A going=False%0A %0A mv_liste.append(%5Bdirection%5B0%5D,(X,Y)%5D)%0A%0A %0Atrad=%5B'SOUTH','EAST','NORTH','WEST'%5D%0Adirection_loop=%5B'S','E','N','W'%5D%0A%0Aif loop:%0A print(%22LOOP%22)%0Aelse:%0A for el in mv_liste:%0A print(trad%5Bdirection_loop.index(el%5B0%5D)%5D)%0A
797eded64257e6a116b5c6f013a80ff62fe9978e
Soln. to largest number at least twice of others
Python/largest_atleast_twice.py
Python/largest_atleast_twice.py
Python
0.999999
@@ -0,0 +1,1252 @@ +# https://leetcode.com/problems/largest-number-at-least-twice-of-others/%0A# You are given an integer array nums where the largest integer is unique.%0A# Determine whether the largest element in the array is at least twice as much as every other number in the array.%0A# If it is, return the index of the largest element, or return -1 otherwise.%0Aimport pytest%0A%0A%0Aclass Solution:%0A def dominantIndex(self, nums: list%5Bint%5D) -%3E int:%0A if len(nums) == 1:%0A return 0%0A # find the highest and a number lesser than highest%0A highest = nums%5B0%5D%0A less_high = nums%5B1%5D%0A index = 0%0A for i, val in enumerate(nums):%0A if val %3E highest:%0A less_high = highest%0A highest = val%0A index = i%0A elif val %3E less_high and val %3C highest:%0A less_high = val%0A if highest %3E= less_high * 2:%0A return index%0A return -1%0A%0A%0A@pytest.mark.parametrize(%0A (%22nums%22, %22index%22),%0A %5B%0A (%5B1, 2, 3, 4%5D, -1),%0A (%5B1, 1, 2, 8%5D, 3),%0A (%5B3, 6, 1, 0%5D, 1),%0A (%5B1%5D, 0),%0A (%5B100, 20%5D, 0),%0A (%5B0, 0, 3, 2%5D, -1),%0A %5D,%0A)%0Adef test_basic(nums: list%5Bint%5D, index: int) -%3E None:%0A assert index == Solution().dominantIndex(nums)%0A
b4eebd858e07d33a3e7de8f9fda3ae009a0036c2
Add a node
scripts/buzzer1.py
scripts/buzzer1.py
Python
0.000043
@@ -0,0 +1,75 @@ +#!/usr/bin/env python%0Aimport rospy%0Arospy.init_node('buzzer')%0Arospy.spin()%0A%0A
fe226ce33f116480bfea8f258fdffa1fd96e379c
read temp from gotemp
gotemp.py
gotemp.py
Python
0.000001
@@ -0,0 +1,338 @@ +#!/usr/bin/python%0Aimport time%0Aimport struct%0A%0Aldusb = file(%22/dev/hidraw1%22)%0A%0Atime.sleep(0.5)%0A%0Apkt = ldusb.read(8)%0Aparsed_pkt = list(struct.unpack(%22%3CBBHHH%22, pkt))%0Anum_samples = parsed_pkt.pop(0)%0Aseqno = parsed_pkt.pop(0)%0Afor sample in range(num_samples):%0A cel = parsed_pkt%5Bsample%5D/128.0%0A fahr = (9.0/5.0 * cel) + 32.0%0A print(fahr)%0A%0A
9abecda7f3c981b1cde193be038171c63bf69020
Add root init
otherdave/__init__.py
otherdave/__init__.py
Python
0.000009
@@ -0,0 +1,33 @@ +# OtherDave/otherdave/__init__.py
79d550cd96862bc4a4c0db60a2db60d3efa5cd6d
add vcrpy test helper module
tests/vcrhelper.py
tests/vcrhelper.py
Python
0
@@ -0,0 +1,1367 @@ +%22%22%22vcrpy integration helpers.%22%22%22%0A%0Aimport os%0Aimport unittest%0A%0Aimport vcr%0A%0A%0ACASSETTE_LIB = os.path.join(%0A os.path.dirname(os.path.realpath(__file__)), 'cassettes')%0Aassert os.path.isdir(CASSETTE_LIB), %22Cassette library not found.%22%0A%0ARECORD_MODE = 'none'%0A%0A%0Aclass VCRHelper(unittest.TestCase):%0A%0A filter_headers = %5B%0A 'user-agent',%0A 'date',%0A 'public-key-pins',%0A %5D%0A%0A def do_filter_headers(self, thing):%0A for key, value in thing%5B'headers'%5D.items():%0A if key.lower() in self.filter_headers:%0A redact = '%3C%25s-FILTERED%3E' %25 key.upper()%0A thing%5B'headers'%5D%5Bkey%5D = redact%0A return thing%0A%0A def before_record_request(self, request):%0A # scrub any request data here%0A return request%0A%0A def before_record_response(self, response):%0A # scrub sensitive response data here%0A response = self.do_filter_headers(response)%0A return response%0A%0A def setUp(self, **vcrkwargs):%0A%0A defaults = %7B%0A 'filter_headers': self.filter_headers,%0A 'record_mode': RECORD_MODE,%0A 'cassette_library_dir': CASSETTE_LIB,%0A 'before_record_request': self.before_record_request,%0A 'before_record_response': self.before_record_response,%0A %7D%0A defaults.update(vcrkwargs)%0A self.vcr = vcr.VCR(%0A **defaults%0A )%0A
30d9dff89a56229ff1f7cf73181cf8fe10f31b6d
Test scanner
tests/test_full_scan.py
tests/test_full_scan.py
Python
0.000001
@@ -0,0 +1,192 @@ +import sys%0Aprint sys.path%0Afrom muzicast.collection import CollectionScanner%0A%0Ascanner = CollectionScanner(%5B'/shared/music-test'%5D)%0A%0Aassert type(scanner.directories) is list%0A%0Ascanner.full_scan()%0A
d1b7ed5f705c8e0935778636ade00a7452e2ea7f
Add management command for importing Holvi Invoices and Orders
project/holviapp/management/commands/import_holvidata.py
project/holviapp/management/commands/import_holvidata.py
Python
0
@@ -0,0 +1,1706 @@ +# -*- coding: utf-8 -*-%0Aimport datetime%0Aimport itertools%0A%0Aimport dateutil.parser%0Afrom django.core.management.base import BaseCommand, CommandError%0Afrom holviapp.importer import HolviImporter%0Afrom holviapp.utils import list_invoices, list_orders%0A%0A%0Adef yesterday_proxy():%0A now_yesterday = datetime.datetime.now() - datetime.timedelta(days=1)%0A start_yesterday = datetime.datetime.combine(now_yesterday.date(), datetime.datetime.min.time())%0A return start_yesterday.isoformat()%0A%0A%0Aclass Command(BaseCommand):%0A help = 'Import transaction data from Holvi API'%0A%0A def add_arguments(self, parser):%0A parser.add_argument('--all', action='store_true', help='Import all Holvi transactions (WARNING: this may take forever)')%0A parser.add_argument('since', type=str, nargs='?', default=yesterday_proxy(), help='Import transactions updated since datetime, defaults to yesterday midnight')%0A%0A def handle(self, *args, **options):%0A if (not options%5B'since'%5D%0A and not options%5B'all'%5D):%0A raise CommandError('Either since or all must be specified')%0A invoice_filters = %7B%7D%0A order_filters = %7B%7D%0A if not options.get('all', False):%0A since_parsed = dateutil.parser.parse(options%5B'since'%5D)%0A print(%22Importing since %25s%22 %25 since_parsed.isoformat())%0A invoice_filters%5B'update_time_from'%5D = since_parsed.isoformat()%0A order_filters%5B'filter_paid_time_from'%5D = since_parsed.isoformat()%0A%0A h = HolviImporter(itertools.chain(list_invoices(**invoice_filters), list_orders(**order_filters)))%0A transactions = h.import_transactions()%0A for t in transactions:%0A print(%22Imported transaction %25s%22 %25 t)%0A
cc25e521a99049bb1333c4a36df776c3303dda7b
add test for new functionality
tests/test_generator.py
tests/test_generator.py
Python
0
@@ -0,0 +1,597 @@ +from unittest import TestCase%0Aimport rectpack.packer%0Aimport random%0A%0A%0Aclass TestGenerator(TestCase):%0A %0A def setUp(self):%0A self.rectangles = %5B(w, h) for w in range(8,50, 8) for h in range(8,50, 8)%5D%0A%0A def test_factory(self):%0A p = rectpack.packer.newPacker()%0A for r in self.rectangles:%0A p.add_rect(*r)%0A p.add_factory(50, 50)%0A p.pack()%0A # check that bins were generated%0A self.assertGreater(len(p.bin_list()), 0)%0A # check that all of the rectangles made it in%0A self.assertEqual(len(p.rect_list()), len(self.rectangles))%0A
8ca6dd9d1089b5976d54e06f452a45306dbfb55e
Add generator test
tests/test_generator.py
tests/test_generator.py
Python
0
@@ -0,0 +1,521 @@ +import unittest%0Afrom echolalia.generator import Generator%0A%0Aclass GeneratorTestCase(unittest.TestCase):%0A%0A def setUp(self):%0A self.items = %5B'pystr', 'pyint'%5D%0A%0A def test_generate(self):%0A generator = Generator(items=self.items)%0A docs = generator.generate(3)%0A self.assertEqual(len(docs), 3)%0A for doc in docs:%0A self.assertIn('pystr', doc)%0A self.assertIn('pyint', doc)%0A self.assertIsInstance(doc, dict)%0A self.assertIsInstance(doc%5B'pystr'%5D, str)%0A self.assertIsInstance(doc%5B'pyint'%5D, int)%0A
ad0ed0b60db6b527b0c210d2e1a23d529d36889d
Create test_gutenberg.py
tests/test_gutenberg.py
tests/test_gutenberg.py
Python
0.000002
@@ -0,0 +1,223 @@ +%0Aimport pytest%0A%0Afrom dasem.gutenberg import Word2Vec%0A%0A%0A@pytest.fixture%0Adef w2v():%0A return Word2Vec()%0A%0A%0Adef test_w2v(w2v):%0A word_and_similarities = w2v.most_similar('dreng')%0A assert len(word_and_similarities) == 10%0A
6cad13197f7d2e399ef3e91a63a34637814c2ad1
fix import command
utils/test_mesh.py
utils/test_mesh.py
import unittest import numpy as np from finmag.util.oommf import mesh class TestIterCoordsInt(unittest.TestCase): def test_zyx_ordering(self): m = mesh.Mesh((3, 1, 1), cellsize=(1, 1, 1)) indices = [r for r in m.iter_coords_int()] expected = [[0, 0, 0], [1, 0, 0], [2, 0, 0]] assert np.array_equal(m.mesh_size, [3, 1, 1]) assert m.array_order == mesh.Mesh.ZYX assert np.array_equal(expected, indices) m = mesh.Mesh((2, 2, 2), cellsize=(1, 1, 1)) indices = [r for r in m.iter_coords_int()] expected = [[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0], [0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1]] assert np.array_equal(m.mesh_size, [2, 2, 2]) assert m.array_order == mesh.Mesh.ZYX assert np.array_equal(expected, indices) def test_xyz_ordering(self): m = mesh.Mesh((3, 1, 1), cellsize=(1, 1, 1), array_order=mesh.Mesh.XYZ) indices = [r for r in m.iter_coords_int()] expected = [[0, 0, 0], [1, 0, 0], [2, 0, 0]] assert np.array_equal(m.mesh_size, [3, 1, 1]) assert m.array_order == mesh.Mesh.XYZ assert np.array_equal(expected, indices) m = mesh.Mesh((2, 2, 2), cellsize=(1, 1, 1), array_order=mesh.Mesh.XYZ) indices = [r for r in m.iter_coords_int()] expected = [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]] assert np.array_equal(m.mesh_size, [2, 2, 2]) assert m.array_order == mesh.Mesh.XYZ assert np.array_equal(expected, indices) class TestIterCoords(unittest.TestCase): def test_zyx_ordering(self): m = mesh.Mesh((3, 1, 1), cellsize=(1, 1, 1)) coords = [r for r in m.iter_coords()] expected = [[0.5, 0.5, 0.5], [1.5, 0.5, 0.5], [2.5, 0.5, 0.5]] assert np.array_equal(expected, coords)
Python
0.00001
@@ -32,31 +32,8 @@ np%0A -from finmag.util.oommf impo
2427afc967169f1e9d942bb7d955454b7ad0a44e
add open/close/cancel position example
examples/py/phemex-open-cancel-close-positions.py
examples/py/phemex-open-cancel-close-positions.py
Python
0.000001
@@ -0,0 +1,1367 @@ +# -*- coding: utf-8 -*-%0A%0Aimport os%0Aimport sys%0Afrom pprint import pprint%0A%0Aroot = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))%0Asys.path.append(root + '/python')%0A%0Aimport ccxt # noqa: E402%0A%0A%0Aprint('CCXT Version:', ccxt.__version__)%0A%0Aexchange = ccxt.phemex(%7B%0A 'enableRateLimit': True, # https://github.com/ccxt/ccxt/wiki/Manual#rate-limit%0A 'apiKey': 'YOUR_API_KEY', # testnet keys if using the testnet sandbox%0A 'secret': 'YOUR_SECRET', # testnet keys if using the testnet sandbox%0A 'options': %7B%0A 'defaultType': 'swap',%0A %7D,%0A%7D)%0A%0A# exchange.set_sandbox_mode(True) # uncomment to use the testnet sandbox%0A%0Amarkets = exchange.load_markets()%0A%0Aamount = 10%0Asymbol = 'BTC/USD:USD'%0A%0A# Opening and Canceling a pending contract order (unrealistic price)%0Aorder = exchange.create_order(symbol, 'limit', 'buy', amount, '20000')%0Aexchange.cancel_order(order%5B'id'%5D, symbol)%0A%0A# Opening and exiting a filled contract position by issuing the exact same order but in the opposite direction%0A%0A# Opening a long position%0Aorder = exchange.create_order(symbol, 'market', 'buy', amount)%0A%0A# closing the previous position by issuing the exact same order but in the opposite direction%0A# with reduceOnly option to prevent an unwanted exposure increase%0AorderClose = exchange.create_order(symbol, 'market', 'sell', amount, None, %7B'reduceOnly': True%7D)
ad97be23fe9e267ed9d64b08fdf64631e234d43a
Add wierd migration
projects/migrations/0002_auto_20151208_1553.py
projects/migrations/0002_auto_20151208_1553.py
Python
0.000001
@@ -0,0 +1,573 @@ +# -*- coding: utf-8 -*-%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations, models%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('projects', '0001_squashed_0010_task'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterField(%0A model_name='project',%0A name='created',%0A field=models.DateTimeField(auto_now_add=True),%0A ),%0A migrations.AlterField(%0A model_name='project',%0A name='modified',%0A field=models.DateTimeField(auto_now=True),%0A ),%0A %5D%0A
b5da9dcf973a9a780c729f2855fb3784bfe9328a
Create heatdb.py
heatdb.py
heatdb.py
Python
0
@@ -0,0 +1,1492 @@ +import webapp2%0Aimport logging%0Aimport re%0Aimport cgi%0Aimport jinja2%0Aimport os%0Aimport random%0Aimport string%0Aimport hashlib%0Aimport hmac%0Aimport Cookie %0Aimport urllib2%0Aimport time%0Afrom datetime import datetime, timedelta%0Afrom google.appengine.api import memcache%0Afrom google.appengine.ext import db%0Afrom xml.dom import minidom%0A%0A%0A## see http://jinja.pocoo.org/docs/api/#autoescaping%0Adef guess_autoescape(template_name):%0A if template_name is None or '.' not in template_name:%0A return False%0A ext = template_name.rsplit('.', 1)%5B1%5D%0A return ext in ('html', 'htm', 'xml')%0A%0AJINJA_ENVIRONMENT = jinja2.Environment(%0A autoescape=guess_autoescape, ## see http://jinja.pocoo.org/docs/api/#autoescaping%0A loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),%0A extensions=%5B'jinja2.ext.autoescape'%5D)%0A %0A %0Aclass MyHandler(webapp2.RequestHandler):%0A def write(self, *items): %0A self.response.write(%22 : %22.join(items))%0A%0A def render_str(self, template, **params):%0A tplt = JINJA_ENVIRONMENT.get_template('templates/'+template)%0A return tplt.render(params)%0A%0A def render(self, template, **kw):%0A self.write(self.render_str(template, **kw))%0A%0A def render_json(self, d):%0A json_txt = json.dumps(d)%0A self.response.headers%5B'Content-Type'%5D = 'application/json; charset=UTF-8'%0A self.write(json_txt)%0A %0Aclass MainPage(MyHandler):%0A def get(self): %0A %0Aapplication = webapp2.WSGIApplication(%5B%0A ('/', MainPage),%5D,debug=True)%0A