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
b40eb5723eeab38edb2440d04d65f1c5be4ad4c0
Create solution.py
data_structures/linked_list/problems/anagrams/py/solution.py
data_structures/linked_list/problems/anagrams/py/solution.py
Python
0.000018
@@ -0,0 +1,393 @@ +import LinkedList%0A%0A# Problem description: %0A# Solution time complexity: %0A# Comments: %0A%0A# Linked List Node inside the LinkedList module is declared as:%0A#%0A# class Node:%0A# def __init__(self, val, nxt=None):%0A# self.val = val%0A# self.nxt = nxt%0A#%0A%0Adef AreAnagrams(left: LinkedList.Node, right: LinkedList.Node) -%3E bool:%0A raise NotImplementedError()%0A
e9a71173eae28b378052ddce4e0fe8a3d3313c4e
Disable screenshot_sync_tests on Mac.
content/test/gpu/gpu_tests/screenshot_sync.py
content/test/gpu/gpu_tests/screenshot_sync.py
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import screenshot_sync_expectations as expectations from telemetry import test from telemetry.core import util from telemetry.page import page from telemetry.page import page_set from telemetry.page import page_test # pylint: disable=W0401,W0614 from telemetry.page.actions.all_page_actions import * data_path = os.path.join( util.GetChromiumSrcDir(), 'content', 'test', 'data', 'gpu') class _ScreenshotSyncValidator(page_test.PageTest): def CustomizeBrowserOptions(self, options): options.AppendExtraBrowserArgs('--enable-gpu-benchmarking') def ValidatePage(self, page, tab, results): test_success = tab.EvaluateJavaScript('window.__testSuccess') if not test_success: message = tab.EvaluateJavaScript('window.__testMessage') raise page_test.Failure(message) class ScreenshotSyncPage(page.Page): def __init__(self, page_set, base_dir): super(ScreenshotSyncPage, self).__init__( url='file://screenshot_sync.html', page_set=page_set, base_dir=base_dir, name='ScreenshotSync') self.user_agent_type = 'desktop' def RunNavigateSteps(self, action_runner): action_runner.NavigateToPage(self) action_runner.WaitForJavaScriptCondition( 'window.__testComplete', timeout_in_seconds=120) class ScreenshotSyncProcess(test.Test): """Tests that screenhots are properly synchronized with the frame one which they were requested""" test = _ScreenshotSyncValidator def CreateExpectations(self, page_set): return expectations.ScreenshotSyncExpectations() def CreatePageSet(self, options): ps = page_set.PageSet(file_path=data_path, serving_dirs=['']) ps.AddPage(ScreenshotSyncPage(ps, ps.base_dir)) return ps
Python
0.000006
@@ -962,16 +962,37 @@ ssage)%0A%0A [email protected]('mac') %0Aclass S
48e19852c6e1f5a0f2792a62adeb560121d77d11
Create __init__.py
crispy/__init__.py
crispy/__init__.py
Python
0.000429
@@ -0,0 +1 @@ +%0A
bad7bfee43ef7d560b186d3f41af2aa35fe0c4af
allow FactorScheduler factor=1
python/mxnet/lr_scheduler.py
python/mxnet/lr_scheduler.py
""" learning rate scheduler, which adaptive changes the learning rate based on the progress """ import logging class LRScheduler(object): """Base class of a learning rate scheduler""" def __init__(self): """ base_lr : float the initial learning rate """ self.base_lr = 0.01 def __call__(self, num_update): """ Call to schedule current learning rate The training progress is presented by `num_update`, which can be roughly viewed as the number of minibatches executed so far. Its value is non-decreasing, and increases at most by one. The exact value is the upper bound of the number of updates applied to a weight/index See more details in https://github.com/dmlc/mxnet/issues/625 Parameters ---------- num_update: int the maximal number of updates applied to a weight. """ raise NotImplementedError("must override this") class FactorScheduler(LRScheduler): """Reduce learning rate in factor Assume the weight has been updated by n times, then the learning rate will be base_lr * factor^(floor(n/step)) Parameters ---------- step: int schedule learning rate after n updates factor: float the factor for reducing the learning rate """ def __init__(self, step, factor=1): super(FactorScheduler, self).__init__() if step < 1: raise ValueError("Schedule step must be greater or equal than 1 round") if factor >= 1.0: raise ValueError("Factor must be less than 1 to make lr reduce") self.step = step self.factor = factor self.count = 0 def __call__(self, num_update): """ Call to schedule current learning rate Parameters ---------- num_update: int the maximal number of updates applied to a weight. """ if num_update > self.count + self.step: self.count += self.step self.base_lr *= self.factor logging.info("Update[%d]: Change learning rate to %0.5e", num_update, self.base_lr) return self.base_lr class MultiFactorScheduler(LRScheduler): """Reduce learning rate in factor at steps specified in a list Assume the weight has been updated by n times, then the learning rate will be base_lr * factor^(sum((step/n)<=1)) # step is an array Parameters ---------- step: list of int schedule learning rate after n updates factor: float the factor for reducing the learning rate """ def __init__(self, step, factor=1): super(MultiFactorScheduler, self).__init__() assert isinstance(step, list) and len(step) >= 1 for i, _step in enumerate(step): if i != 0 and step[i] <= step[i-1]: raise ValueError("Schedule step must be an increasing integer list") if _step < 1: raise ValueError("Schedule step must be greater or equal than 1 round") if factor >= 1.0: raise ValueError("Factor must be less than 1 to make lr reduce") self.step = step self.cur_step_ind = 0 self.factor = factor self.count = 0 def __call__(self, num_update): """ Call to schedule current learning rate Parameters ---------- num_update: int the maximal number of updates applied to a weight. """ if self.cur_step_ind <= len(self.step)-1: if num_update > self.step[self.cur_step_ind]: self.count = self.step[self.cur_step_ind] self.cur_step_ind += 1 self.base_lr *= self.factor logging.info("Update[%d]: Change learning rate to %0.5e", num_update, self.base_lr) return self.base_lr
Python
0.000005
@@ -1565,33 +1565,32 @@ if factor %3E -= 1.0:%0A @@ -1616,36 +1616,39 @@ %22Factor must be -less +no more than 1 to make @@ -3133,17 +3133,16 @@ factor %3E -= 1.0:%0A @@ -3188,12 +3188,15 @@ be -less +no more tha
ca25a4e2aedd657a10c7bfa2849f9f3d16f5ee9f
Add Eq demo
demo/eq.py
demo/eq.py
Python
0.000001
@@ -0,0 +1,1630 @@ +# typeclasses, an educational implementation of Haskell-style type%0A# classes, in Python%0A#%0A# Copyright (C) 2010 Nicolas Trangez %3Ceikke eikke com%3E%0A#%0A# This library is free software; you can redistribute it and/or%0A# modify it under the terms of the GNU Lesser General Public%0A# License as published by the Free Software Foundation, version 2.1%0A# of the License.%0A#%0A# This library is distributed in the hope that it will be useful,%0A# but WITHOUT ANY WARRANTY; without even the implied warranty of%0A# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU%0A# Lesser General Public License for more details.%0A#%0A# You should have received a copy of the GNU Lesser General Public%0A# License along with this library; if not, write to the Free Software%0A# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,%0A# MA 02110-1301 USA%0A%0A'''Some demonstrations of the Eq typeclass and its %60eq%60 and %60ne%60 functions'''%0A%0Afrom typeclasses.eq import eq, ne%0A%0Aimport typeclasses.instances.list%0Aimport typeclasses.instances.tuple%0Afrom typeclasses.instances.maybe import Just, Nothing%0Afrom typeclasses.instances.tree import Branch, Leaf%0A%0A# List%0Aassert eq(%5B1, 2, 3%5D, %5B1, 2, 3%5D)%0Aassert ne(%5B0, 1, 2%5D, %5B1, 2, 3%5D)%0A# Tuple%0Aassert eq((1, 2, 3, ), (1, 2, 3, ))%0Aassert ne((0, 1, 2, ), (1, 2, 3, ))%0A# Maybe%0Aassert eq(Nothing, Nothing)%0Aassert eq(Just(1), Just(1))%0Aassert ne(Just(1), Just(2))%0Aassert ne(Just(1), Nothing)%0A# Tree%0Aassert eq(Branch(Branch(Leaf(0), Leaf(1)), Leaf(2)),%0A Branch(Branch(Leaf(0), Leaf(1)), Leaf(2)))%0Aassert ne(Branch(Branch(Leaf(0), Leaf(1)), Leaf(2)),%0A Branch(Branch(Leaf(0), Leaf(1)), Branch(Leaf(2), Leaf(3))))%0A
176ab29c5f0506d5ba94a2676b81f34f7e2a6b3b
Add migration for expiration_date change (#28)
groups_manager/migrations/0005_auto_20181001_1009.py
groups_manager/migrations/0005_auto_20181001_1009.py
Python
0.000002
@@ -0,0 +1,510 @@ +# -*- coding: utf-8 -*-%0A# Generated by Django 1.9 on 2018-10-01 10:09%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations, models%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('groups_manager', '0004_0_6_0_groupmember_expiration_date'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterField(%0A model_name='groupmember',%0A name='expiration_date',%0A field=models.DateTimeField(blank=True, default=None, null=True),%0A ),%0A %5D%0A
9e56283eaf998f59e4e07dd61999c4c5ac8d919c
Fix position of add_entities of binary sensor (#22866)
homeassistant/components/concord232/binary_sensor.py
homeassistant/components/concord232/binary_sensor.py
""" Support for exposing Concord232 elements as sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/binary_sensor.concord232/ """ import datetime import logging import requests import voluptuous as vol from homeassistant.components.binary_sensor import ( BinarySensorDevice, PLATFORM_SCHEMA, DEVICE_CLASSES) from homeassistant.const import (CONF_HOST, CONF_PORT) import homeassistant.helpers.config_validation as cv REQUIREMENTS = ['concord232==0.15'] _LOGGER = logging.getLogger(__name__) CONF_EXCLUDE_ZONES = 'exclude_zones' CONF_ZONE_TYPES = 'zone_types' DEFAULT_HOST = 'localhost' DEFAULT_NAME = 'Alarm' DEFAULT_PORT = '5007' DEFAULT_SSL = False SCAN_INTERVAL = datetime.timedelta(seconds=10) ZONE_TYPES_SCHEMA = vol.Schema({ cv.positive_int: vol.In(DEVICE_CLASSES), }) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_EXCLUDE_ZONES, default=[]): vol.All(cv.ensure_list, [cv.positive_int]), vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_ZONE_TYPES, default={}): ZONE_TYPES_SCHEMA, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Concord232 binary sensor platform.""" from concord232 import client as concord232_client host = config.get(CONF_HOST) port = config.get(CONF_PORT) exclude = config.get(CONF_EXCLUDE_ZONES) zone_types = config.get(CONF_ZONE_TYPES) sensors = [] try: _LOGGER.debug("Initializing client") client = concord232_client.Client('http://{}:{}'.format(host, port)) client.zones = client.list_zones() client.last_zone_update = datetime.datetime.now() except requests.exceptions.ConnectionError as ex: _LOGGER.error("Unable to connect to Concord232: %s", str(ex)) return False # The order of zones returned by client.list_zones() can vary. # When the zones are not named, this can result in the same entity # name mapping to different sensors in an unpredictable way. Sort # the zones by zone number to prevent this. client.zones.sort(key=lambda zone: zone['number']) for zone in client.zones: _LOGGER.info("Loading Zone found: %s", zone['name']) if zone['number'] not in exclude: sensors.append( Concord232ZoneSensor( hass, client, zone, zone_types.get( zone['number'], get_opening_type(zone)) ) ) add_entities(sensors, True) def get_opening_type(zone): """Return the result of the type guessing from name.""" if 'MOTION' in zone['name']: return 'motion' if 'KEY' in zone['name']: return 'safety' if 'SMOKE' in zone['name']: return 'smoke' if 'WATER' in zone['name']: return 'water' return 'opening' class Concord232ZoneSensor(BinarySensorDevice): """Representation of a Concord232 zone as a sensor.""" def __init__(self, hass, client, zone, zone_type): """Initialize the Concord232 binary sensor.""" self._hass = hass self._client = client self._zone = zone self._number = zone['number'] self._zone_type = zone_type @property def device_class(self): """Return the class of this sensor, from DEVICE_CLASSES.""" return self._zone_type @property def should_poll(self): """No polling needed.""" return True @property def name(self): """Return the name of the binary sensor.""" return self._zone['name'] @property def is_on(self): """Return true if the binary sensor is on.""" # True means "faulted" or "open" or "abnormal state" return bool(self._zone['state'] != 'Normal') def update(self): """Get updated stats from API.""" last_update = datetime.datetime.now() - self._client.last_zone_update _LOGGER.debug("Zone: %s ", self._zone) if last_update > datetime.timedelta(seconds=1): self._client.zones = self._client.list_zones() self._client.last_zone_update = datetime.datetime.now() _LOGGER.debug("Updated from zone: %s", self._zone['name']) if hasattr(self._client, 'zones'): self._zone = next((x for x in self._client.zones if x['number'] == self._number), None)
Python
0
@@ -2592,20 +2592,16 @@ )%0A%0A - add_
caa92a302f3dcc6ed084ebc9f20db28c63d48d29
Add missing file
irrigator_pro/uga/aggregates.py
irrigator_pro/uga/aggregates.py
Python
0.000006
@@ -0,0 +1,859 @@ +from django.db import connections%0Afrom django.db.models.aggregates import Aggregate%0Afrom django.db.models.sql.aggregates import Aggregate as SQLAggregate%0Afrom uga.models import UGAProbeData%0A%0A__initialized__ = False%0A%0Aclass SimpleAggregate(Aggregate):%0A def add_to_query(self, query, alias, col, source, is_summary):%0A aggregate = SQLAggregate(col, source=source, is_summary=is_summary, **self.extra)%0A aggregate.sql_function = self.sql_function%0A aggregate.is_ordinal = getattr(self, 'is_ordinal', False)%0A aggregate.is_computed = getattr(self, 'is_computed', False)%0A if hasattr(self, 'sql_template'):%0A aggregate.sql_template = self.sql_template%0A query.aggregates%5Balias%5D = aggregate%0A%0A%0Aclass Date(SimpleAggregate):%0A sql_function = 'Date'%0A name = 'Date'%0A
253cda3fc9d377dc64fe4b67b5fe55f911c8693f
Add startsliver script.
protogeni/test/startsliver.py
protogeni/test/startsliver.py
Python
0
@@ -0,0 +1,1720 @@ +#! /usr/bin/env python%0A#%0A# GENIPUBLIC-COPYRIGHT%0A# Copyright (c) 2008-2009 University of Utah and the Flux Group.%0A# All rights reserved.%0A# %0A# Permission to use, copy, modify and distribute this software is hereby%0A# granted provided that (1) source code retains these copyright, permission,%0A# and disclaimer notices, and (2) redistributions including binaries%0A# reproduce the notices in supporting documentation.%0A#%0A# THE UNIVERSITY OF UTAH ALLOWS FREE USE OF THIS SOFTWARE IN ITS %22AS IS%22%0A# CONDITION. THE UNIVERSITY OF UTAH DISCLAIMS ANY LIABILITY OF ANY KIND%0A# FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.%0A#%0A%0A#%0A#%0Aimport sys%0Aimport pwd%0Aimport getopt%0Aimport os%0Aimport time%0Aimport re%0Aimport xmlrpclib%0Afrom M2Crypto import X509%0A%0AACCEPTSLICENAME=1%0A%0Aexecfile( %22test-common.py%22 )%0A%0A#%0A# Get a credential for myself, that allows me to do things at the SA.%0A#%0Amycredential = get_self_credential()%0Aprint %22Got my SA credential%22%0A%0A#%0A# Lookup slice%0A#%0Amyslice = resolve_slice( SLICENAME, mycredential )%0Aprint %22Found the slice, asking for a credential ...%22%0A%0A#%0A# Get the slice credential.%0A#%0Aslicecred = get_slice_credential( myslice, mycredential )%0Aprint %22Got the slice credential, asking for a sliver credential ...%22%0A%0A#%0A# Get the sliver credential.%0A#%0Aparams = %7B%7D%0Aparams%5B%22credential%22%5D = slicecred%0Arval,response = do_method(%22cm%22, %22GetSliver%22, params)%0Aif rval:%0A Fatal(%22Could not get Sliver credential%22)%0A pass%0Aslivercred = response%5B%22value%22%5D%0Aprint %22Got the sliver credential, starting the sliver%22;%0A%0A#%0A# Start the sliver.%0A#%0Aparams = %7B%7D%0Aparams%5B%22credential%22%5D = slivercred%0Arval,response = do_method(%22cm%22, %22StartSliver%22, params)%0Aif rval:%0A Fatal(%22Could not start sliver%22)%0A pass%0Aprint %22Sliver has been started ...%22%0A%0A
aa88f2b64c8c2837022ee020862ec2c0a9a6e7ad
Add fabfile for generating docs in gh-pages branch.
fabfile.py
fabfile.py
Python
0
@@ -0,0 +1,1048 @@ +from __future__ import with_statement%0A%0Aimport os%0Afrom fabric.api import abort, local, task, lcd%0A%0A%0A@task(default=True)%0Adef docs(clean='no', browse_='no'):%0A with lcd('docs'):%0A local('make clean html')%0A temp_path = %22/tmp/openxc-python-docs%22%0A docs_path = %22%25s/docs/_build/html%22 %25 local(%22pwd%22, capture=True)%0A local('rm -rf %25s' %25 temp_path)%0A os.makedirs(temp_path)%0A with lcd(temp_path):%0A local('cp -R %25s %25s' %25 (docs_path, temp_path))%0A local('git checkout gh-pages')%0A local('cp -R %25s/html/* .' %25 temp_path)%0A local('touch .nojekyll')%0A local('git add -A')%0A local('git commit -m %22Update Sphinx docs.%22')%0A local('git push')%0A local('git checkout master')%0A%0A%0A@task%0Adef browse():%0A %22%22%22%0A Open the current dev docs in a browser tab.%0A %22%22%22%0A local(%22$BROWSER docs/_build/html/index.html%22)%0A%0A%0A@task(default=True)%0Adef test(args=None):%0A local(%22tox%22)%0A%0A%0A@task%0Adef upload():%0A %22%22%22%0A Build, register and upload to PyPI%0A %22%22%22%0A puts(%22Uploading to PyPI%22)%0A local('python setup.py sdist register upload')%0A
1e4f86f3184d0ae09d2a14690257ba9d4c44edb1
remove dups (local sequence alignments)
repertoire/collapse_reads.py
repertoire/collapse_reads.py
Python
0
@@ -0,0 +1,2262 @@ +#!/usr/bin/env python%0A# encoding: utf-8%0A%22%22%22%0Amatches = pairwise2.align.localms(target, query, 1, -1, -3, -2)%0Atry:%0A # highest scoring match first%0A return int(matches%5B0%5D%5B3%5D)%0Aexcept IndexError:%0A%22%22%22%0Aimport sys%0Afrom toolshed import nopen%0Afrom parsers import read_fastx%0Afrom Bio import pairwise2%0Afrom collections import OrderedDict%0A%0Adef fastq_to_dict(fastq):%0A %22%22%22docstring for fastq_to_dict%22%22%22%0A d = %7B%7D%0A with nopen(fastq) as fh:%0A for name, seq, qual in read_fastx(fh):%0A d%5Bname%5D = %7B'seq':seq,'qual':qual%7D%0A return d%0A%0Adef main(args):%0A fd = fastq_to_dict(args.fastq)%0A # convert to ordered dictionary%0A fd = OrderedDict(sorted(fd.items(), key=lambda (k, v): len(v%5B'seq'%5D)))%0A seen = %7B%7D%0A for i, (name, query) in enumerate(fd.iteritems(), start=1):%0A if i %25 1000 == 0:%0A print %3E%3E sys.stderr, %22%3E%3E processed %25d reads...%22 %25 i%0A subseq = False%0A q_id, q_cregion, q_fwork = name.split(%22:%22)%0A expected_score = len(query%5B'seq'%5D) - args.mismatches%0A # maps onto same length or longer seqs%0A for t_name, target in fd.iteritems():%0A if t_name == name: continue%0A # skipping reads we've already mapped%0A if seen.has_key(t_name): continue%0A t_id, t_cregion, t_fwork = t_name.split(%22:%22)%0A # only attempt to collapse things of the same c-region and framework%0A if q_cregion != t_cregion and q_fwork != t_fwork: continue%0A # locally align using smith-waterman%0A matches = pairwise2.align.localms(target%5B'seq'%5D, query%5B'seq'%5D, 1, -1, -1, -1)%0A high_score = matches%5B0%5D%5B2%5D%0A if high_score == expected_score:%0A subseq = True%0A break%0A if not subseq:%0A # print fastq record%0A print %22@%25s%5Cn%25s%5Cn+%5Cn%25s%22 %25 (name, query%5B'seq'%5D, query%5B'qual'%5D)%0A seen%5Bname%5D = %22%22%0A%0Aif __name__ == '__main__':%0A import argparse%0A p = argparse.ArgumentParser(description=__doc__,%0A formatter_class=argparse.RawDescriptionHelpFormatter)%0A p.add_argument('fastq', help=%22reads to collapse to unique%22)%0A p.add_argument('-m', '--mismatches', type=int, default=0,%0A help=%22mismatches to allow during mapping %5B %25(default)s %5D%22)%0A main(p.parse_args())
736093f945ff53c4fe6d9d8d2e0c4afc28d9ace3
Add answer to leetcode rotate list
chimera/py/leetcode_rotate_list.py
chimera/py/leetcode_rotate_list.py
Python
0.000002
@@ -0,0 +1,893 @@ +# coding=utf-8%0A%22%22%22%0Achimera.leetcode_rotate_list%0A~~~~~~~~~~~~~~~~~~~~~~~~~~~~%0A%0AGiven a list, rotate the list to the right by k places, where k is%0Anon-negative.%0A%0AFor example:%0AGiven 1-%3E2-%3E3-%3E4-%3E5-%3ENULL and k = 2,%0Areturn 4-%3E5-%3E1-%3E2-%3E3-%3ENULL.%0A%0A%22%22%22%0A%0A%0A# Definition for singly-linked list.%0A# class ListNode(object):%0A# def __init__(self, x):%0A# self.val = x%0A# self.next = None%0A%0Aclass Solution(object):%0A def rotateRight(self, head, k):%0A %22%22%22%0A :type head: ListNode%0A :type k: int%0A :rtype: ListNode%0A %22%22%22%0A if not head:%0A return head%0A tail = p = head%0A n = 0%0A while tail:%0A n += 1%0A p = tail%0A tail = tail.next%0A p.next = head%0A rotate = k %25 n%0A for i in xrange(n - rotate):%0A p = head%0A head = head.next%0A p.next = None%0A return head%0A
22bb91cfc1b1dc637e33625dcbaf3e8499b384ec
Add LinearRegression.py
1-LinearRegression/LinearRegression.py
1-LinearRegression/LinearRegression.py
Python
0.000295
@@ -0,0 +1,2821 @@ +import tensorflow as tf%0A%0A%0A# TensorFlow Example (1) - Linear Regression%0A#%0A# (model) y = ax + b%0A# By giving some pairs of (x, y) that satisfies the given model,%0A# TensorFlow can compute the value of 'a' and 'b'%0A# by using very simple Machine Learning(ML) algorithm.%0A%0A%0A# 1. implementing our model.%0A# TensorFlow has an element called 'node'.%0A# A 'node' can be formed from a Tensor(i.e. values),%0A# or by combining nodes with arithmetic operations.%0A# We should implement our model (y = ax + b) first.%0A%0A# There are a few types of values.%0A# 1. constants: values which cannot change.%0A# 2. placeholders: values that we should give when computing.%0A# 3. variables: values that can be changed while computing.%0A# therefore, in our model y = ax + b%0A# 'x' is given by us so it should be 'placeholder',%0A# and 'a' and 'b' is computed by TensorFlow, which therefore%0A# should be variables.%0Ax = tf.placeholder(tf.float32)%0Aa = tf.Variable(%5B1.0%5D, tf.float32)%0Ab = tf.Variable(%5B1.0%5D) # data type inferred automatically%0A%0Amodel_y = a * x + b # same with 'y = tf.add(tf.multiply(a, x), b)'%0A%0A%0A# 2. let the computer know our goal.%0A# To compute 'a' and 'b' value using ML,%0A# we should let machine know what is their goal.%0A# in this case, the computation result of the model should be%0A# the same with real value(which is given by us.)%0A# to accomplish this goal, we design a function(which is called%0A# 'loss function'), and the goal of the machine is to minimize%0A# the value of loss function.%0Areal_y = tf.placeholder(tf.float32)%0Aerror = model_y - real_y%0Asquared_error = tf.square(error) # make all errors positive to compute average%0Asum_error = tf.reduce_sum(squared_error) # this is our loss function whose value should be minimized.%0A%0A%0A# 3. compute 'a' and 'b' value using ML.%0A# now we designed our model and the goal of the machine.%0A# therefore, now what we have to do is just command the machine%0A# to find the value 'a' and 'b' that minimizes our loss function(sum_error)%0A# to do that, we give our machine some data sets.%0A# (the exact (x, y) pairs to compute 'a' and 'b' values.%0Ax_training_data = %5B1, 2, 3, 4%5D%0Ay_training_data = %5B3, 5, 7, 9%5D # y = 2x + 1 is the correct model%0A%0A# to run a TensorFlow computation, we need something called 'Session'.%0Asession = tf.Session()%0A%0A# first, make all the Variables to be set to its initial value(which are wrong)%0Asession.run(tf.global_variables_initializer())%0A%0A# then, make machine to compute the right 'a' and 'b' value.%0Aoptimizer = tf.train.GradientDescentOptimizer(0.01) # Machine's algorithm to find 'a' and 'b'%0Atrain = optimizer.minimize(sum_error)%0A%0A%0Afor _ in range(10000):%0A session.run(train, %7Bx: x_training_data, real_y: y_training_data%7D)%0A%0A%0A# 4. Machine finished computing 'a' and 'b' value.%0A# this code below will print out that values.%0Aa, b = session.run(%5Ba, b%5D)%0Aprint(%22a :%22, a)%0Aprint(%22b :%22, b)%0A
08d7e10d74297f16e4bcb5cfb7de0749d9d101bc
add missing fiel
codeskel/localcommands/__init__.py
codeskel/localcommands/__init__.py
Python
0.000006
@@ -0,0 +1,2 @@ + %0A
0c289af5ef7f26796bdc4b4183f456074f7440f7
Create dijkstra.py
3-AlgorithmsOnGraphs/Week4/dijkstra/dijkstra.py
3-AlgorithmsOnGraphs/Week4/dijkstra/dijkstra.py
Python
0.000001
@@ -0,0 +1,1388 @@ +#Uses python3%0A%0Aimport sys%0Aimport queue%0A%0A%0A%0Adef Dijkstra(adj, s, cost, t):%0A dist = list()%0A prev = list()%0A inf = 0%0A for c in cost:%0A inf += sum(c)%0A inf += 1%0A for u in range(0, len(adj)):%0A dist.append(inf)%0A prev.append(None)%0A dist%5Bs%5D = 0%0A H = queue.PriorityQueue()%0A for i, d in enumerate(dist):%0A H.put((d, i))%0A processed = set()%0A while not H.empty():%0A u = H.get()%5B1%5D%0A if u in processed:%0A pass%0A for i, v in enumerate(adj%5Bu%5D):%0A if dist%5Bv%5D %3E dist%5Bu%5D + cost%5Bu%5D%5Bi%5D:%0A dist%5Bv%5D = dist%5Bu%5D + cost%5Bu%5D%5Bi%5D%0A prev%5Bv%5D = u%0A H.put((dist%5Bv%5D, v))%0A processed.add(v)%0A%0A%0A if dist%5Bt%5D%3C inf:%0A return dist%5Bt%5D%0A else:%0A return -1%0A%0Adef distance(adj, cost, s, t):%0A return Dijkstra(adj, s, cost, t)%0A%0A%0Aif __name__ == '__main__':%0A # input = sys.stdin.read()%0A with open('test', 'r') as f:%0A input = f.read()%0A data = list(map(int, input.split()))%0A n, m = data%5B0:2%5D%0A data = data%5B2:%5D%0A edges = list(zip(zip(data%5B0:(3 * m):3%5D, data%5B1:(3 * m):3%5D), data%5B2:(3 * m):3%5D))%0A data = data%5B3 * m:%5D%0A adj = %5B%5B%5D for _ in range(n)%5D%0A cost = %5B%5B%5D for _ in range(n)%5D%0A for ((a, b), w) in edges:%0A adj%5Ba - 1%5D.append(b - 1)%0A cost%5Ba - 1%5D.append(w)%0A s, t = data%5B0%5D - 1, data%5B1%5D - 1%0A print(distance(adj, cost, s, t))%0A
18e8cee5c19329dac7e931cb00e67f8d19e3f89d
add script `compare_win_set`
examples/bunny/compare_win_set.py
examples/bunny/compare_win_set.py
Python
0
@@ -0,0 +1,793 @@ +from dd import cudd%0A%0A%0Ab = cudd.BDD()%0Au_gr1x = cudd.load('winning_set', b)%0Au_slugs = b.load('winning_set_bdd.txt')%0A%0Aenv_action_slugs = b.load('env_action_slugs.txt')%0Asys_action_slugs = b.load('sys_action_slugs.txt')%0Aassumption_0_slugs = b.load('assumption_0_slugs.txt')%0Agoal_0_slugs = b.load('goal_0_slugs.txt')%0A%0Aenv_action_gr1x = b.load('env_action_gr1x.txt')%0Asys_action_gr1x = b.load('sys_action_gr1x.txt')%0Aassumption_0_gr1x = b.load('assumption_0_gr1x.txt')%0Agoal_0_gr1x = b.load('goal_0_gr1x.txt')%0A%0Aassert env_action_slugs == env_action_gr1x%0Aassert sys_action_slugs == sys_action_gr1x%0Aassert assumption_0_slugs == assumption_0_gr1x%0Aassert goal_0_slugs == goal_0_gr1x%0A%0Aif u_gr1x == u_slugs:%0A print('Winning set is the same.')%0Aelse:%0A print('Different winning sets!')%0Adel u_gr1x, u_slugs%0A
cc19cdc3430df018e3a8fa63abaf796a897a475b
Add naive bayes SQL test.
Orange/tests/sql/test_naive_bayes.py
Orange/tests/sql/test_naive_bayes.py
Python
0.000001
@@ -0,0 +1,1084 @@ +import unittest%0A%0Afrom numpy import array%0A%0Aimport Orange.classification.naive_bayes as nb%0Afrom Orange.data.discretization import DiscretizeTable%0Afrom Orange.data.sql.table import SqlTable%0Afrom Orange.data.variable import DiscreteVariable%0A%0A%0Aclass NaiveBayesTest(unittest.TestCase):%0A def test_NaiveBayes(self):%0A table = SqlTable(host='localhost', database='test', table='iris',%0A type_hints=dict(iris=DiscreteVariable(%0A values=%5B'Iris-setosa', 'Iris-versicolor',%0A 'Iris-virginica'%5D),%0A __class_vars__=%5B'iris'%5D))%0A table = DiscretizeTable(table)%0A bayes = nb.BayesLearner()%0A clf = bayes(table)%0A # Single instance prediction%0A self.assertEqual(clf(table%5B0%5D), table%5B0%5D.get_class())%0A # Table prediction%0A pred = clf(table)%0A actual = array(%5Bins.get_class() for ins in table%5D)%0A ca = pred == actual%0A ca = ca.sum() / len(ca)%0A self.assertGreater(ca, 0.95)%0A self.assertLess(ca, 1.)%0A
0ed71f8c580e8eb80c55b817c3f971b946016f02
update docstring for Postman.connection
mailthon/postman.py
mailthon/postman.py
""" mailthon.postman ~~~~~~~~~~~~~~~~ This module implements the central Postman object. :copyright: (c) 2015 by Eeo Jun :license: MIT, see LICENSE for details. """ from contextlib import contextmanager from smtplib import SMTP from .response import SendmailResponse from .helpers import encode_address class Postman(object): """ Encapsulates a connection to a server and knows how to send MIME emails over a certain transport. When subclassing, change the ``transport`` and ``response_cls`` class variables to tweak the transport used and the response class, respectively. :param host: The address to a server. :param port: Port to connect to. :param middlewares: An iterable of middleware that will be used by the Postman. :param options: Dictionary of options to be passed to the underlying transport. """ transport = SMTP response_cls = SendmailResponse def __init__(self, host, port, middlewares=(), options=None): self.host = host self.port = port self.middlewares = list(middlewares) self.options = options or {} def use(self, middleware): """ Use a certain callable *middleware*, i.e. append it to the list of middlewares, and return it so it can be used as a decorator. """ self.middlewares.append(middleware) return middleware @contextmanager def connection(self): """ A context manager that returns a connection to the server using some transport, defaulting to SMTP. The transport will be called with the server address and port that has been passed to the constructor, in that order. """ conn = self.transport(self.host, self.port, **self.options) try: conn.ehlo() for item in self.middlewares: item(conn) yield conn finally: conn.quit() def deliver(self, conn, envelope): """ Deliver an *envelope* using a given connection *conn*, and return the response object. Does not close the connection. """ rejected = conn.sendmail( encode_address(envelope.mail_from), [encode_address(k) for k in envelope.receivers], envelope.string(), ) return self.response_cls(conn.noop(), rejected) def send(self, envelope): """ Sends an *envelope* and return a response object. """ with self.connection() as conn: return self.deliver(conn, envelope)
Python
0
@@ -1670,25 +1670,35 @@ ress - and port +, port, and options that ha s be @@ -1697,14 +1697,10 @@ t ha -s been +ve %0A @@ -1704,16 +1704,21 @@ +been passed t
c9dde0a5d40a79d98f01c4214a90321844355444
Include link details in IXP matcher, version bump
peeringdb/PeeringDB.py
peeringdb/PeeringDB.py
# Copyright 2015 Netflix. All rights reserved. # # The contents of this file are licensed under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with the # License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. import urllib2 import json import time from redis import Redis class PeeringDB: cache_enable = None cache_ttl = None cache_prefix = None redis = None def __init__(self, cache=True, cache_ttl=900, cache_prefix="peeringdb", cache_host="localhost", cache_port=6379, cache_db=0): self.cache_enable = cache self.cache_ttl = cache_ttl self.cache_prefix = cache_prefix self.redis = Redis(host=cache_host, port=cache_port, db=cache_db) return def pdb_get(self, param, cache=True): if cache is False or self.cache_enable is False: # no caching data = self.pdb_getsrc(param) else: # caching key = "%s_%s" % (self.cache_prefix, param) data = self.redis.get(key) if data is None: data = self.pdb_getsrc(param) p = self.redis.pipeline() p.set(key, data) p.expireat(key, int(time.time()) + self.cache_ttl) p.execute() return json.loads(data)["data"][0] def pdb_getsrc(self, param): agent = "peeringdb-py" url = "https://beta.peeringdb.com/api/%s" % (param) resp = urllib2.urlopen(url) return resp.read() def get_obj(self, type, id): return self.pdb_get("%s/%s" % (type, id)) # base objects def asn(self, asn): return self.get_obj("asn", asn) def fac(self, facid): return self.get_obj("fac", facid) def ixlan(self, ixlanid): return self.get_obj("ixlan", ixlanid) def ix(self, ixid): return self.get_obj("ix", ixid) def net(self, netid): return self.get_obj("net", netid) def org(self, orgid): return self.get_id("org", orgid) def poc(self, pocid): return self.get_id("poc", pocid) # helpers def matching_facility(self, asnnums): asns = {} facility_all = {} for asnnum in asnnums: asn = self.asn(asnnum) asns[asnnum] = asn for facility in asn["facility_set"]: facilityid = facility["facility"] if facility not in facility_all: facility_all[facility] = None facility_match = [] return facility_match def matching_ixlan(self, asnnums): asns = {} asn_ixlans = {} ixlan_all = {} ixlan_match = [] # get asn details for asnnum in asnnums: asn = self.asn(asnnum) asns[asnnum] = asn asn_ixlans[asnnum] = [] # get ixlans for each asn for link in asn["ixlink_set"]: ixlan_id = link["ix_lan"] asn_ixlans[asnnum].append(ixlan_id) if ixlan_id not in ixlan_all: ixlan_all[ixlan_id] = None # look for matches for ixlan in ixlan_all: occurs = 0 for asn in asns: if ixlan in asn_ixlans[asn]: occurs = occurs + 1 ixlan_all[ixlan] = occurs if occurs == len(asnnums): ixlan_obj = self.ixlan(ixlan) # grab ix object too ixlan_obj["ix_obj"] = self.ix(ixlan_obj["ix"]) ixlan_match.append(ixlan_obj) return ixlan_match
Python
0
@@ -3950,56 +3950,335 @@ lan_ -match.append(ixlan_obj)%0A%0A return ixlan_match +obj%5B%22links%22%5D = self.get_ixlanlinks(asns%5Basn%5D, ixlan)%0A ixlan_match.append(ixlan_obj)%0A%0A return ixlan_match%0A%0A%0A def get_ixlanlinks(self, asn, ixlan_id):%0A links = %5B%5D%0A for link in asn%5B%22ixlink_set%22%5D:%0A if link%5B%22ix_lan%22%5D == ixlan_id:%0A links.append(link)%0A return links %0A
78f89e96adedd1045f900d5f9f95c3eb35c12ca3
Create routine module with Tool class
performance/routine.py
performance/routine.py
Python
0
@@ -0,0 +1,59 @@ +%0A%0Aclass Tool:%0A def __init__(self, config):%0A pass%0A
6c0aab6c14539b1cd4eedcd1280bcc4eb35ff7ea
Create poly_talker.py
poly_talker.py
poly_talker.py
Python
0.000001
@@ -0,0 +1,664 @@ +#! /usr/bin/env python%0A%0Aimport rospy%0Afrom std_msgs.msg import String%0Afrom random import randint%0A%0Adef talker():%0A%09# List of names to be printed%0A%09words = %5B%22Dr. Bushey%22, %22Vamsi%22, %22Jon%22%5D%0A%09%0A%09# Registers with roscore a node called %22talker%22. %0A%09# ROS programs are called nodes.%0A%09rospy.init_node('talker')%0A%0A%09# Publisher object gets registered to roscore and creates a topic.%0A%09pub = rospy.Publisher('names', String)%0A%09%0A%09# How fast names will be posted. In Hertz.%0A%09rate = rospy.Rate(21)%0A%0A%09while not rospy.is_shutdown():%0A%09%09number = randint(0,2)%0A%09%09pub.publish(words%5Bnumber%5D)%0A%09%09rate.sleep()%0A%0Aif __name__ == '__main__':%0A%09try:%0A%09%09talker()%0A%09except rospy.ROSInterruptException:%0A%09%09pass%0A
7b3753428f04c86b95191e76ca2c50b54577411a
add problem 27
problem_027.py
problem_027.py
Python
0.019702
@@ -0,0 +1,1504 @@ +#!/usr/bin/env python%0A#-*-coding:utf-8-*-%0A%0A'''%0AEuler discovered the remarkable quadratic formula:%0A%0An%C2%B2 + n + 41%0A%0AIt turns out that the formula will produce 40 primes for%0Athe consecutive values n = 0 to 39.%0AHowever, when n = 40, 402 + 40 + 41 = 40(40 + 1) + 41 is%0Adivisible by 41, and certainly when n = 41, 41%C2%B2 + 41 + 41 is%0Aclearly divisible by 41.%0A%0AThe incredible formula n%C2%B2 %E2%88%92 79n + 1601 was discovered,%0Awhich produces 80 primes for the consecutive values n = 0 to 79.%0AThe product of the coefficients, %E2%88%9279 and 1601, is %E2%88%92126479.%0A%0AConsidering quadratics of the form:%0A%0An%C2%B2 + an + b, where %7Ca%7C %3C 1000 and %7Cb%7C %3C 1000%0A%0Awhere %7Cn%7C is the modulus/absolute value of n%0Ae.g. %7C11%7C = 11 and %7C%E2%88%924%7C = 4%0AFind the product of the coefficients, a and b,%0Afor the quadratic expression that produces the maximum number of%0Aprimes for consecutive values of n, starting with n = 0.%0A'''%0A%0Aimport math%0Aimport timeit%0A%0A%0Adef loop(i):%0A (ma, mb, mn) = (0, 0, 0)%0A primes = %5Bj for j in range(-i+1, i) if is_prime(abs(j))%5D%0A for a in primes:%0A for b in primes:%0A n = 0%0A while is_prime(n**2+a*n+b):%0A n += 1%0A (ma, mb, mn) = (a, b, n) if mn %3C n else (ma, mb, mn)%0A return ma, mb, mn, ma*mb%0A%0A%0Adef is_prime(n):%0A if n %3C 2:%0A return False%0A for i in range(2, int(math.sqrt(n))+1):%0A if n %25 i == 0:%0A return False%0A return True%0A%0A%0Aif __name__ == '__main__':%0A print loop(1000)%0A print timeit.Timer('problem_027.loop(1000)', 'import problem_027').timeit(1)
f530fb3ebe5639d7d6dfe013c5abc70769009a04
add script
collapse.py
collapse.py
Python
0.000001
@@ -0,0 +1,798 @@ +#!/usr/bin/env python%0Aimport json%0Aimport sys%0Aimport argparse%0Aimport xmldict%0A%0Af='bla.json'%0Aref=2%0Aout=%5B%5D%0Awith open(f) as data_file:%0A pages = json.load(data_file)%0A for page in pages:%0A data = page%5B'data'%5D%0A lineIter = iter(data)%0A oldline = None%0A for line in lineIter:%0A ref_line = line%5Bref%5D%5B'text'%5D%0A if not ref_line:%0A #print %22bla%22%0A if oldline:%0A for cellold,cellnew in zip(oldline,line):%0A cellold%5B'text'%5D = ' '.join( %5Bcellold%5B'text'%5D , cellnew%5B'text'%5D%5D).rstrip()%0A else:%0A if oldline:%0A out.append( oldline )%0A oldline = line%0A #print out%0Aprint json.dumps(out, sort_keys=True, indent=4)%0A #for line in data:%0A # print line%5Bref%5D%5B'text'%5D%0A # #for cell in line:%0A # # print cell%5B'text'%5D%0A # #print line%5B'text'%5D%0A
e9451a8b2d196353e393d265482e37faa651eb1e
Tue Nov 4 20:46:16 PKT 2014 Init
chromepass.py
chromepass.py
Python
0
@@ -0,0 +1,639 @@ +from os import getenv%0Aimport sqlite3%0Aimport win32crypt%0A%0Aappdata = getenv(%22APPDATA%22) %0Aconnection = sqlite3.connect(appdata + %22%5C..%5CLocal%5CGoogle%5CChrome%5CUser Data%5CDefault%5CLogin Data%22)%0Acursor = connection.cursor()%0Acursor.execute('SELECT action_url, username_value, password_value FROM logins')%0Afor information in cursor.fetchall():%0A #chrome encrypts the password with Windows WinCrypt.%0A%09#Fortunately Decrypting it is no big issue.%0A pass = win32crypt.CryptUnprotectData(information%5B2%5D, None, None, None, 0)%5B1%5D%0A%09if pass:%0A%09%09print 'website_link ' + information%5B0%5D%0A%09%09print 'Username: ' + information%5B1%5D%0A%09%09print 'Password: ' + password%0A
cf9b6b477e6d044e4065086f98906a0eb4504ff3
Add slack_nagios script
slack_nagios.py
slack_nagios.py
Python
0
@@ -0,0 +1,2175 @@ +#!/bin/python%0A%0Aimport argparse%0Aimport requests%0A%0A%22%22%22%0AA simple script to post nagios notifications to slack%0A%0ASimilar to https://raw.github.com/tinyspeck/services-examples/master/nagios.pl%0ABut adds proxy support%0A%0ANote: If your internal proxy only exposes an http interface, you will need to be running a modern version of urllib3.%0ASee https://github.com/kennethreitz/requests/issues/1359%0A%0ADesigned to work as such:%0Aslack_nagios.py -field slack_channel=#alerts -field HOSTALIAS=%22$HOSTNAME$%22 -field SERVICEDESC=%22$SERVICEDESC$%22 -field SERVICESTATE=%22$SERVICESTATE$%22 -field SERVICEOUTPUT=%22$SERVICEOUTPUT$%22 -field NOTIFICATIONTYPE=%22$NOTIFICATIONTYPE$%22%0Aslack_nagios.py -field slack_channel=#alerts -field HOSTALIAS=%22$HOSTNAME$%22 -field HOSTSTATE=%22$HOSTSTATE$%22 -field HOSTOUTPUT=%22$HOSTOUTPUT$%22 -field NOTIFICATIONTYPE=%22$NOTIFICATIONTYPE$%22%0A%22%22%22%0A%0A%0Adef send_alert(args):%0A if args.proxy:%0A proxy = %7B%0A %22http%22: args.proxy,%0A %22https%22: args.proxy%0A %7D%0A else:%0A proxy = %7B%7D%0A%0A url = %22https://%7Bd%7D/services/hooks/nagios?token=%7Bt%7D%22.format(%0A d=args.domain,%0A t=args.token%0A )%0A%0A payload = %7B%0A 'slack_channel': %22#%22 + args.channel%0A %7D%0A%0A for field in args.field:%0A key, value = field%5B0%5D.split('=')%0A payload%5Bkey%5D = value%0A%0A req = requests.post(url=url, proxies=proxy, data=payload)%0A if args.debug:%0A print(req.text)%0A print(req.status_code)%0A return req%0A%0A%0Aif __name__ == %22__main__%22:%0A parser = argparse.ArgumentParser(description=%22Post nagios notifications to slack%22)%0A%0A parser.add_argument('--debug', help=%22Debug mode%22, action='store_true')%0A parser.add_argument('--proxy', '-p', help=%22Proxy to use, full url format%22, default=None)%0A parser.add_argument('--domain', '-d', help=%22Slack domain to post to%22, required=True)%0A parser.add_argument('--channel', '-c', help=%22Channel to post to%22, required=True)%0A parser.add_argument('--token', '-t', help=%22Auth token%22, required=True)%0A parser.add_argument('-field', nargs='*', required=True, action='append',%0A help=%22Alert fields (Should be specified more than once)%22)%0A%0A args = parser.parse_args()%0A send_alert(args)%0A
f437b7875aa4bed06dcf3884bb81c009b7e473f0
Add 290-word-pattern.py
290-word-pattern.py
290-word-pattern.py
Python
0.999973
@@ -0,0 +1,1929 @@ +%22%22%22%0AQuestion:%0A Word Pattern%0A%0A Given a pattern and a string str, find if str follows the same pattern.%0A%0A Examples:%0A pattern = %22abba%22, str = %22dog cat cat dog%22 should return true.%0A pattern = %22abba%22, str = %22dog cat cat fish%22 should return false.%0A pattern = %22aaaa%22, str = %22dog cat cat dog%22 should return false.%0A pattern = %22abba%22, str = %22dog dog dog dog%22 should return false.%0A%0A Notes:%0A Both pattern and str contains only lowercase alphabetical letters.%0A Both pattern and str do not have leading or trailing spaces.%0A Each word in str is separated by a single space.%0A Each letter in pattern must map to a word with length that is at least 1.%0A%0A Credits:%0A Special thanks to @minglotus6 for adding this problem and creating all test cases.%0A%0APerformance:%0A 1. Total Accepted: 1839 Total Submissions: 6536 Difficulty: Easy%0A 2. Sorry. We do not have enough accepted submissions.%0A%22%22%22%0A%0A%0Aclass Solution(object):%0A def wordPattern(self, pattern, str):%0A %22%22%22%0A :type pattern: str%0A :type str: str%0A :rtype: bool%0A %22%22%22%0A patterns = list(pattern)%0A words = str.split(%22 %22)%0A%0A if len(patterns) != len(words):%0A return False%0A%0A short_to_long = dict()%0A seen_longs = set(%5B%5D)%0A for idx, short in enumerate(patterns):%0A long = words%5Bidx%5D%0A%0A if short not in short_to_long:%0A if long in seen_longs:%0A return False%0A short_to_long%5Bshort%5D = long%0A seen_longs.add(long)%0A else:%0A if short_to_long%5Bshort%5D != long:%0A return False%0A return True%0A%0A%0Aassert Solution().wordPattern(%22abba%22, %22dog cat cat dog%22) is True%0Aassert Solution().wordPattern(%22abba%22, %22dog cat cat fish%22) is False%0Aassert Solution().wordPattern(%22aaaa%22, %22dog cat cat dog%22) is False%0Aassert Solution().wordPattern(%22abba%22, %22dog dog dog dog%22) is False%0A
f39a640a8d5bf7d4a5d80f94235d1fa7461bd4dc
Add code for stashing a single nuxeo image on s3.
s3stash/stash_single_image.py
s3stash/stash_single_image.py
Python
0
@@ -0,0 +1,1899 @@ +#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0Aimport sys, os%0Aimport argparse%0Aimport logging%0Aimport json%0Afrom s3stash.nxstashref_image import NuxeoStashImage%0A%0Adef main(argv=None):%0A%0A parser = argparse.ArgumentParser(description='Produce jp2 version of Nuxeo image file and stash in S3.')%0A parser.add_argument('path', help=%22Nuxeo document path%22)%0A parser.add_argument('--bucket', default='ucldc-private-files/jp2000', help=%22S3 bucket name%22)%0A parser.add_argument('--region', default='us-west-2', help='AWS region')%0A parser.add_argument('--pynuxrc', default='~/.pynuxrc', help=%22rc file for use by pynux%22)%0A parser.add_argument('--replace', action=%22store_true%22, help=%22replace file on s3 if it already exists%22)%0A if argv is None:%0A argv = parser.parse_args()%0A%0A # logging%0A # FIXME would like to name log with nuxeo UID %0A filename = argv.path.split('/')%5B-1%5D%0A logfile = %22logs/%7B%7D.log%22.format(filename)%0A print %22LOG:%5Ct%7B%7D%22.format(logfile)%0A logging.basicConfig(filename=logfile, level=logging.INFO, format='%25(asctime)s (%25(name)s) %5B%25(levelname)s%5D: %25(message)s', datefmt='%25m/%25d/%25Y %25I:%25M:%25S %25p')%0A logger = logging.getLogger(__name__)%0A %0A # convert and stash jp2%0A nxstash = NuxeoStashImage(argv.path, argv.bucket, argv.region, argv.pynuxrc, argv.replace)%0A report = nxstash.nxstashref()%0A%0A # output report to json file%0A reportfile = %22reports/%7B%7D.json%22.format(filename)%0A with open(reportfile, 'w') as f:%0A json.dump(report, f, sort_keys=True, indent=4)%0A%0A # parse report to give basic stats%0A print %22REPORT:%5Ct%7B%7D%22.format(reportfile)%0A print %22SUMMARY:%22%0A if 'already_s3_stashed' in report.keys():%0A print %22already stashed:%5Ct%7B%7D%22.format(report%5B'already_s3_stashed'%5D)%0A print %22converted:%5Ct%7B%7D%22.format(report%5B'converted'%5D)%0A print %22stashed:%5Ct%7B%7D%22.format(report%5B'stashed'%5D) %0A%0A print %22%5CnDone.%22%0A%0Aif __name__ == %22__main__%22:%0A sys.exit(main())%0A
12821e2859151e8f949f55b8c363ff95d296a7d0
add setup.py for python interface
python/setup.py
python/setup.py
Python
0.000001
@@ -0,0 +1,607 @@ +#!/usr/bin/env python%0A%0Afrom distutils.core import setup, Extension%0A%0Asetup(name = %22LIBSVM%22,%0A version = %222.87%22,%0A author=%22Chih-Chung Chang and Chih-Jen Lin%22,%0A maintainer=%22Chih-Jen Lin%22,%0A maintainer_email=%[email protected]%22,%0A url=%22http://www.csie.ntu.edu.tw/~cjlin/libsvm/%22,%0A description = %22LIBSVM Python Interface%22,%0A ext_modules = %5BExtension(%22svmc%22,%0A %5B%22../svm.cpp%22, %22svmc_wrap.c%22%5D,%0A extra_compile_args=%5B%22-O3%22, %22-I../%22%5D%0A )%0A %5D,%0A py_modules=%5B%22svm%22%5D,%0A )%0A
fc911a4952a46ea372e1a42cff78351b4f8b42ef
complete 15 lattice paths
15-lattice-paths.py
15-lattice-paths.py
Python
0
@@ -0,0 +1,426 @@ +from collections import defaultdict%0Afrom math import factorial as fac%0A%0Aif __name__ == '__main__':%0A # Dynamic programming method%0A paths = defaultdict(dict)%0A for i in range(21):%0A paths%5B0%5D%5Bi%5D = 1%0A paths%5Bi%5D%5B0%5D = 1%0A for i in range(1, 21):%0A for j in range(1, 21):%0A paths%5Bi%5D%5Bj%5D = paths%5Bi-1%5D%5Bj%5D + paths%5Bi%5D%5Bj-1%5D%0A print(paths%5B20%5D%5B20%5D)%0A%0A # Pure math%0A print(fac(40)//fac(20)//fac(20))%0A
684387315025bc7789aa75def757894cb8d92154
add quickie Python JSON-filtering script
dev/filter_json.py
dev/filter_json.py
Python
0.000001
@@ -0,0 +1,1230 @@ +# == BSD2 LICENSE ==%0A# Copyright (c) 2014, Tidepool Project%0A# %0A# This program is free software; you can redistribute it and/or modify it under%0A# the terms of the associated License, which is identical to the BSD 2-Clause%0A# License as published by the Open Source Initiative at opensource.org.%0A# %0A# This program is distributed in the hope that it will be useful, but WITHOUT%0A# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS%0A# FOR A PARTICULAR PURPOSE. See the License for more details.%0A# %0A# You should have received a copy of the License along with this program; if%0A# not, you can obtain one from Tidepool Project at tidepool.org.%0A# == BSD2 LICENSE ==%0A%0A# Usage:%0A# python filter_json.py %3Cpath/to/JSON/file%3E %3Cfilter%3E %3Coptional/path/to/output/file%3E%0A%0Aimport json%0Aimport sys%0A%0Adef main():%0A o = open(sys.argv%5B1%5D, 'rU')%0A try:%0A output_file = open(sys.argv%5B3%5D, 'w')%0A except IndexError:%0A output_file = open('filter-output.json', 'w')%0A jsn = json.load(o)%0A%0A filtered = %5B%5D%0A%0A for obj in jsn:%0A if obj%5B'type'%5D == sys.argv%5B2%5D:%0A filtered.append(obj)%0A%0A print %3E%3E output_file, json.dumps(filtered, separators=(',',': '), indent=4)%0A%0Aif __name__ == '__main__':%0A main()
7d20f9bcbfda514c216fb7faaa08325f21c0e119
add 01 code
01-two-snum.py
01-two-snum.py
Python
0
@@ -0,0 +1,449 @@ +class Solution(object):%0A def twoSum(self, nums, target):%0A %22%22%22%0A :type nums: List%5Bint%5D%0A :type target: int%0A :rtype: List%5Bint%5D%0A %22%22%22%0A for i in range(len(nums)):%0A last = nums%5Bi%5D%0A # print last%0A for j, num in enumerate(nums%5Bi+1:%5D):%0A # print j, num%0A if last + num == target:%0A return %5Bi,i+1+j%5D%0A %0A %0A
dd2422293e403a9f664fe887d3fd0950ba540fc0
the inverse returns an int
044_pentagon_numbers.py
044_pentagon_numbers.py
Python
0.99996
@@ -0,0 +1,1201 @@ +#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A#%0A# A Solution to %22Pentagon numbers%22 %E2%80%93 Project Euler Problem No. 44%0A# by Florian Buetow%0A#%0A# Sourcecode: https://github.com/fbcom/project-euler%0A# Problem statement: https://projecteuler.net/problem=44%0A%0A%0Adef get_pentagonal_number(n):%0A return int(n*(3*n-1)/2)%0A%0A%0Adef is_pentagonal_number(n):%0A tmp = (1 + (1.0+24*n)**0.5) / 6 # inverse function of n*(3n-1)%0A return int(tmp) == tmp # n is pentagonal if the inverse function yields an int%0A%0A# Testcases%0Asome_pentagonal_numbers = %5B1, 5, 12, 22, 35, 51, 70, 92, 117, 145%5D%0Afor n in some_pentagonal_numbers:%0A assert is_pentagonal_number(n), %22Testcase failed%22%0Afor n in range(1, 11):%0A assert get_pentagonal_number(n) == some_pentagonal_numbers%5Bn-1%5D, %22Testcase failed%22%0A%0A# Solve%0Asolution = None%0Ak = 0%0Awhile not solution:%0A k += 1%0A p_k = get_pentagonal_number(k)%0A j = k%0A while j %3E 1:%0A j -= 1%0A p_j = get_pentagonal_number(j)%0A if is_pentagonal_number(p_k + p_j) and%5C%0A is_pentagonal_number(p_k - p_j):%0A solution = int(p_k - p_j)%0A # print %22p%25d=%25d, p%25d=%25d, solution=%25d%22 %25 (k, p_k, j, p_j, solution)%0A break%0A%0Aprint %22Solution:%22, solution%0A
b699a18f8928a6e859ebc34a843e4c8a64a22b26
add script to grid-search model parameters — script from scikit-learn: http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html#sklearn.model_selection.GridSearchCV
scripts/grid_search_digits.py
scripts/grid_search_digits.py
Python
0
@@ -0,0 +1,2764 @@ +%22%22%22%0A============================================================%0AParameter estimation using grid search with cross-validation%0A============================================================%0A%0AThis examples shows how a classifier is optimized by cross-validation,%0Awhich is done using the :class:%60sklearn.model_selection.GridSearchCV%60 object%0Aon a development set that comprises only half of the available labeled data.%0A%0AThe performance of the selected hyper-parameters and trained model is%0Athen measured on a dedicated evaluation set that was not used during%0Athe model selection step.%0A%0AMore details on tools available for model selection can be found in the%0Asections on :ref:%60cross_validation%60 and :ref:%60grid_search%60.%0A%0A%22%22%22%0A%0Afrom __future__ import print_function%0A%0Afrom sklearn import datasets%0Afrom sklearn.model_selection import train_test_split%0Afrom sklearn.model_selection import GridSearchCV%0Afrom sklearn.metrics import classification_report%0Afrom sklearn.svm import SVC%0A%0Aprint(__doc__)%0A%0A# Loading the Digits dataset%0Adigits = datasets.load_digits()%0A%0A# To apply an classifier on this data, we need to flatten the image, to%0A# turn the data in a (samples, feature) matrix:%0An_samples = len(digits.images)%0AX = digits.images.reshape((n_samples, -1))%0Ay = digits.target%0A%0A# Split the dataset in two equal parts%0AX_train, X_test, y_train, y_test = train_test_split(%0A X, y, test_size=0.5, random_state=0)%0A%0A# Set the parameters by cross-validation%0Atuned_parameters = %5B%7B'kernel': %5B'rbf'%5D, 'gamma': %5B1e-3, 1e-4%5D,%0A 'C': %5B1, 10, 100, 1000%5D%7D,%0A %7B'kernel': %5B'linear'%5D, 'C': %5B1, 10, 100, 1000%5D%7D%5D%0A%0Ascores = %5B'precision', 'recall'%5D%0A%0Afor score in scores:%0A print(%22# Tuning hyper-parameters for %25s%22 %25 score)%0A print()%0A%0A clf = GridSearchCV(SVC(C=1), tuned_parameters, cv=5,%0A scoring='%25s_macro' %25 score)%0A clf.fit(X_train, y_train)%0A%0A print(%22Best parameters set found on development set:%22)%0A print()%0A print(clf.best_params_)%0A print()%0A print(%22Grid scores on development set:%22)%0A print()%0A means = clf.cv_results_%5B'mean_test_score'%5D%0A stds = clf.cv_results_%5B'std_test_score'%5D%0A for mean, std, params in zip(means, stds, clf.cv_results_%5B'params'%5D):%0A print(%22%250.3f (+/-%250.03f) for %25r%22%0A %25 (mean, std * 2, params))%0A print()%0A%0A print(%22Detailed classification report:%22)%0A print()%0A print(%22The model is trained on the full development set.%22)%0A print(%22The scores are computed on the full evaluation set.%22)%0A print()%0A y_true, y_pred = y_test, clf.predict(X_test)%0A print(classification_report(y_true, y_pred))%0A print()%0A%0A# Note the problem is too easy: the hyperparameter plateau is too flat and the%0A# output model is the same for precision and recall with ties in quality.%0A
3c2316b69fcee9db820937c2814a9872e27f95a9
Implement frequent direction sketch
fd_sketch.py
fd_sketch.py
Python
0.000037
@@ -0,0 +1,2649 @@ +# -*- coding: utf-8 -*-%0A#!/usr/bin/env python%0A%0Aimport numpy as np%0Aimport numpy.linalg as ln%0Aimport math%0Aimport sys%0A%0A%22%22%22 This is a simple and deterministic method for matrix sketch.%0AThe original method has been introduced in %5BLiberty2013%5D_ .%0A%0A%5BLiberty2013%5D Edo Liberty, %22Simple and Deterministic Matrix Sketching%22, ACM SIGKDD, 2013.%0A%22%22%22%0A%0Adef sketch(mat_a, ell):%0A %22%22%22Compute a sketch matrix of input matrix %0A Note that %5Cell must be smaller than m * 2%0A %0A :param mat_a: original matrix to be sketched (n x m)%0A :param ell: the number of rows in sketch matrix%0A :returns: sketch matrix (%5Cell x m)%0A %22%22%22%0A%0A # number of columns%0A m = mat_a.shape%5B1%5D%0A%0A # Input error handling%0A if math.floor(ell / 2) %3E= m:%0A raise ValueError('Error: ell must be smaller than m * 2')%0A if ell %3E= mat_a.shape%5B0%5D:%0A raise ValueError('Error: ell must not be greater than n')%0A%0A # initialize output matrix B%0A mat_b = np.zeros(%5Bell, m%5D)%0A%0A # compute zero valued row list%0A zero_rows = np.nonzero(%5Bround(s, 7) == 0.0 for s in np.sum(mat_b, axis = 1)%5D)%5B0%5D.tolist()%0A %0A # repeat inserting each row of matrix A%0A for i in range(0, mat_a.shape%5B0%5D):%0A%0A # insert a row into matrix B%0A mat_b%5Bzero_rows%5B0%5D, :%5D = mat_a%5Bi, :%5D%0A%0A # remove zero valued row from the list%0A zero_rows.remove(zero_rows%5B0%5D)%0A%0A # if there is no more zero valued row%0A if len(zero_rows) == 0:%0A%0A # compute SVD of matrix B%0A mat_u, vec_sigma, mat_v = ln.svd(mat_b, full_matrices=False)%0A%0A # obtain squared singular value for threshold%0A squared_sv_center = vec_sigma%5Bmath.floor(ell / 2)%5D ** 2%0A%0A # update sigma to shrink the row norms%0A sigma_tilda = %5B(0.0 if d %3C 0.0 else math.sqrt(d)) for d in (vec_sigma ** 2 - squared_sv_center)%5D%0A%0A # update matrix B where at least half rows are all zero%0A mat_b = np.dot(np.diagflat(sigma_tilda), mat_v)%0A%0A # update the zero valued row list%0A zero_rows = np.nonzero(%5Bround(s, 7) == 0 for s in np.sum(mat_b, axis = 1)%5D)%5B0%5D.tolist()%0A%0A return mat_b%0A%0A%0Adef calculateError(mat_a, mat_b):%0A %22%22%22Compute the degree of error by sketching%0A%0A :param mat_a: original matrix%0A :param mat_b: sketch matrix%0A :returns: reconstruction error%0A %22%22%22%0A dot_mat_a = np.dot(mat_a.T, mat_a)%0A dot_mat_b = np.dot(mat_b.T, mat_b)%0A return ln.norm(dot_mat_a - dot_mat_b, ord = 2)%0A%0A%0Adef squaredFrobeniusNorm(mat_a):%0A %22%22%22Compute the squared Frobenius norm of a matrix%0A%0A :param mat_a: original matrix%0A :returns: squared Frobenius norm%0A %22%22%22%0A return ln.norm(mat_a, ord = 'fro') ** 2%0A
fe86df913b79fdf8c3627fe31b87c6dfa3da4f46
implement QEngine
engines/QEngine.py
engines/QEngine.py
Python
0.000007
@@ -0,0 +1,778 @@ +#!/usr/bin/env python3%0Afrom ChessEngine import ChessEngine%0Aimport chess%0Aimport sys%0Asys.path.append('.')%0Aimport data%0A%0Aclass QEngine(ChessEngine):%0A def __init__(self, picklefile):%0A super().__init__()%0A with open(picklefile, %22rb%22) as f:%0A self.Q = pickle.load(Q, f)%0A%0A def search(self):%0A s = data.state_from_board(board, hashable=True)%0A try:%0A a = Q%5Bs%5D%0A from_square = a // NUM_SQUARES%0A to_square = a %25 NUM_SQUARES%0A move = chess.Move(from_square, to_square)%0A except:%0A moves = list(self.board.generate_legal_moves())%0A move = random.choice(moves)%0A self.moves = %5Bmove%5D%0A%0Aif __name__ == %22__main__%22:%0A engine = QEngine(%22engines/sarsa_Q_-_.pickle%22)%0A engine.run()%0A
e782e519012c4734f591388114fc954fdc014acf
add thousands_separator in Python to format folder
src/Python/format/thousands_separator.py
src/Python/format/thousands_separator.py
Python
0
@@ -0,0 +1,72 @@ +#!/usr/bin/env python%0A%0Aprint %22 Formated number:%22, %22%7B:,%7D%22.format(102403)%0A
3e8c18b32058d9d33ae0d12744355bb65c2b96ed
add alembic migration for orders table
migrations/versions/187cf9175cee_add_orders_table.py
migrations/versions/187cf9175cee_add_orders_table.py
Python
0
@@ -0,0 +1,2064 @@ +%22%22%22add orders table%0A%0ARevision ID: 187cf9175cee%0ARevises: 3d8cf74c2de4%0ACreate Date: 2015-10-23 23:43:31.769594%0A%0A%22%22%22%0A%0A# revision identifiers, used by Alembic.%0Arevision = '187cf9175cee'%0Adown_revision = '3d8cf74c2de4'%0A%0Afrom alembic import op%0Aimport sqlalchemy as sa%0A%0A%0Adef upgrade():%0A ### commands auto generated by Alembic - please adjust! ###%0A op.create_table('orders',%0A sa.Column('id', sa.Integer(), nullable=False),%0A sa.Column('name', sa.Unicode(length=255), nullable=True),%0A sa.Column('email', sa.Unicode(length=255), nullable=True),%0A sa.Column('phone', sa.Unicode(length=12), nullable=True),%0A sa.Column('placed_date', sa.DateTime(), nullable=True),%0A sa.Column('dj', sa.UnicodeText(), nullable=True),%0A sa.Column('thank_on_air', sa.Boolean(), nullable=True),%0A sa.Column('first_time', sa.Boolean(), nullable=True),%0A sa.Column('premiums', sa.Unicode(length=255), nullable=True),%0A sa.Column('address1', sa.Unicode(length=255), nullable=True),%0A sa.Column('address2', sa.Unicode(length=255), nullable=True),%0A sa.Column('city', sa.Unicode(length=255), nullable=True),%0A sa.Column('state', sa.Unicode(length=255), nullable=True),%0A sa.Column('zipcode', sa.Integer(), nullable=True),%0A sa.Column('amount', sa.Integer(), nullable=True),%0A sa.Column('recurring', sa.Boolean(), nullable=True),%0A sa.Column('paid_date', sa.DateTime(), nullable=True),%0A sa.Column('shipped_date', sa.DateTime(), nullable=True),%0A sa.Column('tshirtsize', sa.Unicode(length=255), nullable=True),%0A sa.Column('tshirtcolor', sa.Unicode(length=255), nullable=True),%0A sa.Column('sweatshirtsize', sa.Unicode(length=255), nullable=True),%0A sa.Column('method', sa.Unicode(length=255), nullable=True),%0A sa.Column('custid', sa.Unicode(length=255), nullable=True),%0A sa.Column('comments', sa.UnicodeText(), nullable=True),%0A sa.PrimaryKeyConstraint('id')%0A )%0A ### end Alembic commands ###%0A%0A%0Adef downgrade():%0A ### commands auto generated by Alembic - please adjust! ###%0A op.drop_table('orders')%0A ### end Alembic commands ###%0A
64dede2c9a3d489eb8c93200ea8788c26db6da31
Create 6kyu_divisor_harmony.py
Solutions/6kyu/6kyu_divisor_harmony.py
Solutions/6kyu/6kyu_divisor_harmony.py
Python
0.000014
@@ -0,0 +1,292 @@ +def solve(a,b):%0A pairs=%7B%7D%0A for i in range(a,b):%0A ratio=div_sum(i)/i%0A try: pairs%5Bratio%5D=pairs%5Bratio%5D+%5Bi%5D%0A except: pairs%5Bratio%5D=%5Bi%5D%0A return sum(min(i) for i in pairs.values() if len(i)%3E=2)%0A%0A %0Adef div_sum(n):%0A return sum(i for i in range(1,n+1) if n%25i==0)%0A
de7b7d10e5776d631c15660255cf8ad2b85f3d25
Create Beginner 10-A.py
Beginner/10/10-A.py
Beginner/10/10-A.py
Python
0.000084
@@ -0,0 +1,60 @@ +#AtCoder Beginner 10 A%0Aname = raw_input()%0Aprint name + %22pp%22%0A
cd44c385812718d16cc7a490946c7142bebacbfa
Convert evesrp/__init__.py to use explicit unicode literals
evesrp/__init__.py
evesrp/__init__.py
from __future__ import absolute_import from __future__ import unicode_literals import locale import os import requests from flask import Flask, current_app, g from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.wtf.csrf import CsrfProtect db = SQLAlchemy() from .util import DB_STATS from .util.request import AcceptRequest __version__ = '0.7.1' requests_session = requests.Session() # Set default locale locale.setlocale(locale.LC_ALL, '') csrf = CsrfProtect() # Ensure models are declared from . import models from .auth import models as auth_models def create_app(config=None, **kwargs): app = Flask('evesrp', **kwargs) app.request_class = AcceptRequest app.config.from_object('evesrp.default_config') if config is not None: app.config.from_pyfile(config) if app.config['SECRET_KEY'] is None and 'SECRET_KEY' in os.environ: app.config['SECRET_KEY'] = os.environ['SECRET_KEY'] # Register SQLAlchemy monitoring before the DB is connected app.before_request(sqlalchemy_before) db.init_app(app) from .views.login import login_manager login_manager.init_app(app) before_csrf = list(app.before_request_funcs[None]) csrf.init_app(app) # Remove the context processor that checks CSRF values. All it is used for # is the template function. app.before_request_funcs[None] = before_csrf from .views import index, error_page, divisions, login, requests, api app.add_url_rule(rule='/', view_func=index) for error_code in (400, 403, 404, 500): app.register_error_handler(error_code, error_page) app.register_blueprint(divisions.blueprint, url_prefix='/division') app.register_blueprint(login.blueprint) app.register_blueprint(requests.blueprint, url_prefix='/request') app.register_blueprint(api.api, url_prefix='/api') app.register_blueprint(api.filters, url_prefix='/api/filter') from .views import request_count app.add_template_global(request_count) from .json import SRPEncoder app.json_encoder=SRPEncoder app.before_first_request(_copy_config_to_authmethods) app.before_first_request(_config_requests_session) app.before_first_request(_config_killmails) app.before_first_request(_copy_url_converter_config) # Configure the Jinja context # Inject variables into the context from .auth import PermissionType @app.context_processor def inject_enums(): return { 'ActionType': models.ActionType, 'PermissionType': PermissionType, 'app_version': __version__, 'site_name': app.config['SRP_SITE_NAME'] } # Auto-trim whitespace app.jinja_env.trim_blocks = True app.jinja_env.lstrip_blocks = True return app # SQLAlchemy performance logging def sqlalchemy_before(): DB_STATS.clear() g.DB_STATS = DB_STATS # Auth setup def _copy_config_to_authmethods(): current_app.auth_methods = current_app.config['SRP_AUTH_METHODS'] # Request detail URL setup def _copy_url_converter_config(): url_transformers = {} for config_key, config_value in current_app.config.items(): if config_value is None: continue index = config_key.rfind('_URL_TRANSFORMERS') if not config_key.endswith('_URL_TRANSFORMERS')\ or not config_key.startswith('SRP_'): continue attribute = config_key.replace('SRP_', '', 1) attribute = attribute.replace('_URL_TRANSFORMERS', '', 1) attribute = attribute.lower() url_transformers[attribute] = {t.name:t for t in config_value} current_app.url_transformers = url_transformers # temporary compatibility current_app.ship_urls = url_transformers.get('ship_type', None) current_app.pilot_urls = url_transformers.get('pilot', None) # Requests session setup def _config_requests_session(): try: ua_string = current_app.config['SRP_USER_AGENT_STRING'] except KeyError as outer_exc: try: ua_string = 'EVE-SRP/{version} ({email})'.format( email=current_app.config['SRP_USER_AGENT_EMAIL'], version=__version__) except KeyError as inner_exc: raise inner_exc requests_session.headers.update({'User-Agent': ua_string}) current_app.user_agent = ua_string # Killmail verification def _config_killmails(): current_app.killmail_sources = current_app.config['SRP_KILLMAIL_SOURCES']
Python
0.020146
@@ -36,48 +36,8 @@ ort%0A -from __future__ import unicode_literals%0A impo @@ -304,16 +304,17 @@ ion__ = +u '0.7.1'%0A @@ -1437,16 +1437,17 @@ le(rule= +u '/', vie @@ -2547,16 +2547,16 @@ sion__,%0A - @@ -2599,16 +2599,17 @@ E_NAME'%5D +, %0A
75b4c2deac9ff23a5a3c24b3d2450cd23ae3d705
Fix crash in repo info when `%` is used in commit messages
subcmds/info.py
subcmds/info.py
# # Copyright (C) 2012 The Android Open Source Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from command import PagedCommand from color import Coloring from error import NoSuchProjectError from git_refs import R_M class _Coloring(Coloring): def __init__(self, config): Coloring.__init__(self, config, "status") class Info(PagedCommand): common = True helpSummary = "Get info on the manifest branch, current branch or unmerged branches" helpUsage = "%prog [-dl] [-o [-b]] [<project>...]" def _Options(self, p, show_smart=True): p.add_option('-d', '--diff', dest='all', action='store_true', help="show full info and commit diff including remote branches") p.add_option('-o', '--overview', dest='overview', action='store_true', help='show overview of all local commits') p.add_option('-b', '--current-branch', dest="current_branch", action="store_true", help="consider only checked out branches") p.add_option('-l', '--local-only', dest="local", action="store_true", help="Disable all remote operations") def Execute(self, opt, args): self.out = _Coloring(self.manifest.globalConfig) self.heading = self.out.printer('heading', attr = 'bold') self.headtext = self.out.printer('headtext', fg = 'yellow') self.redtext = self.out.printer('redtext', fg = 'red') self.sha = self.out.printer("sha", fg = 'yellow') self.text = self.out.printer('text') self.dimtext = self.out.printer('dimtext', attr = 'dim') self.opt = opt mergeBranch = self.manifest.manifestProject.config.GetBranch("default").merge self.heading("Manifest branch: ") self.headtext(self.manifest.default.revisionExpr) self.out.nl() self.heading("Manifest merge branch: ") self.headtext(mergeBranch) self.out.nl() self.printSeparator() if not opt.overview: self.printDiffInfo(args) else: self.printCommitOverview(args) def printSeparator(self): self.text("----------------------------") self.out.nl() def printDiffInfo(self, args): try: projs = self.GetProjects(args) except NoSuchProjectError: return for p in projs: self.heading("Project: ") self.headtext(p.name) self.out.nl() self.heading("Mount path: ") self.headtext(p.worktree) self.out.nl() self.heading("Current revision: ") self.headtext(p.revisionExpr) self.out.nl() localBranches = p.GetBranches().keys() self.heading("Local Branches: ") self.redtext(str(len(localBranches))) if len(localBranches) > 0: self.text(" [") self.text(", ".join(localBranches)) self.text("]") self.out.nl() if self.opt.all: self.findRemoteLocalDiff(p) self.printSeparator() def findRemoteLocalDiff(self, project): #Fetch all the latest commits if not self.opt.local: project.Sync_NetworkHalf(quiet=True, current_branch_only=True) logTarget = R_M + self.manifest.manifestProject.config.GetBranch("default").merge bareTmp = project.bare_git._bare project.bare_git._bare = False localCommits = project.bare_git.rev_list( '--abbrev=8', '--abbrev-commit', '--pretty=oneline', logTarget + "..", '--') originCommits = project.bare_git.rev_list( '--abbrev=8', '--abbrev-commit', '--pretty=oneline', ".." + logTarget, '--') project.bare_git._bare = bareTmp self.heading("Local Commits: ") self.redtext(str(len(localCommits))) self.dimtext(" (on current branch)") self.out.nl() for c in localCommits: split = c.split() self.sha(split[0] + " ") self.text(" ".join(split[1:])) self.out.nl() self.printSeparator() self.heading("Remote Commits: ") self.redtext(str(len(originCommits))) self.out.nl() for c in originCommits: split = c.split() self.sha(split[0] + " ") self.text(" ".join(split[1:])) self.out.nl() def printCommitOverview(self, args): all_branches = [] for project in self.GetProjects(args): br = [project.GetUploadableBranch(x) for x in project.GetBranches().keys()] br = [x for x in br if x] if self.opt.current_branch: br = [x for x in br if x.name == project.CurrentBranch] all_branches.extend(br) if not all_branches: return self.out.nl() self.heading('Projects Overview') project = None for branch in all_branches: if project != branch.project: project = branch.project self.out.nl() self.headtext(project.relpath) self.out.nl() commits = branch.commits date = branch.date self.text('%s %-33s (%2d commit%s, %s)' % ( branch.name == project.CurrentBranch and '*' or ' ', branch.name, len(commits), len(commits) != 1 and 's' or '', date)) self.out.nl() for commit in commits: split = commit.split() self.text('{0:38}{1} '.format('','-')) self.sha(split[0] + " ") self.text(" ".join(split[1:])) self.out.nl()
Python
0.000003
@@ -2018,32 +2018,38 @@ text = self.out. +nofmt_ printer('text')%0A
871e9e4bdca027e577bdcde38f483e2de32c8528
Add simple example
examples/simple.py
examples/simple.py
Python
0.000375
@@ -0,0 +1,1578 @@ +# -*- coding: utf-8 -*-%0A%0Aimport time%0A%0Afrom apns_proxy_client import APNSProxyClient%0A%0Avalid_token = %22YOUR VALID TOKEN%22%0A%0A%0Adef main():%0A client = APNSProxyClient(host=%22localhost%22, port=5556, application_id=%2214%22)%0A i = 0%0A%0A with client:%0A token = valid_token%0A%0A client.send(token, 'Alert with default sound')%0A%0A time.sleep(2)%0A%0A client.send(token, 'Alert with custom sound', sound='custom')%0A%0A time.sleep(2)%0A%0A client.send(token, 'I am silent', sound=None)%0A%0A time.sleep(2)%0A%0A client.send(token, 'Alert with badge', badge=2)%0A%0A time.sleep(2)%0A%0A client.send(token, None, badge=99, sound=None)%0A%0A time.sleep(2)%0A%0A one_hour_later = int(time.time()) + (60 * 60)%0A client.send(token, 'I am long life', expiry=one_hour_later)%0A%0A time.sleep(2)%0A%0A client.send(token, 'I am low priority', priority=5)%0A%0A time.sleep(2)%0A%0A # For background fetch%0A client.send(token, None, sound=None, content_available=True)%0A%0A time.sleep(2)%0A%0A client.send(token, 'With custom field', custom=%7B%0A 'foo': True,%0A 'bar': %5B200, 300%5D,%0A 'boo': %22Hello%22%0A %7D)%0A %0A time.sleep(2)%0A%0A client.send(token, %7B%0A 'body': 'This is JSON alert',%0A 'action_loc_key': None,%0A 'loc_key': 'loc key',%0A 'loc_args': %5B'one', 'two'%5D,%0A 'launch_image': 'aa.png'%0A %7D)%0A%0A client.send(token, 'This message never send to device', test=True)%0A%0A%0Aif __name__ == %22__main__%22:%0A main()%0A print(%22Done%22)%0A
9ec5e3f57a64e6242b5d91eb0bf66e238fa48ec2
call superclass __init__() in constructor
smartcard/pyro/PyroReader.py
smartcard/pyro/PyroReader.py
"""PyroReaderClient: concrete reader class for Remote Readers __author__ = "gemalto http://www.gemalto.com" Copyright 2001-2012 gemalto Author: Jean-Daniel Aussel, mailto:[email protected] This file is part of pyscard. pyscard is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. pyscard 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with pyscard; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import Pyro.core import Pyro.naming from smartcard.Exceptions import NoCardException from smartcard.reader.Reader import Reader class PyroReader(Reader): """Remote reader class.""" def __init__(self, readername): """Constructs a new Remote Reader client implementation from a Pyro URI.""" ns = Pyro.naming.NameServerLocator().getNS() self.uri = ns.resolve(':pyscard.smartcard.readers.' + readername) self.reader = Pyro.core.getAttrProxyForURI(self.uri) self.name = self.reader.name def addtoreadergroup(self, groupname): """Add reader to a reader group.""" self.reader.addtoreadergroup(groupname) def removefromreadergroup(self, groupname): """Remove a reader from a reader group""" self.reader.removefromreadergroup(groupname) def createConnection(self): """Return a card connection thru a remote reader.""" uri = self.reader.createConnection() return Pyro.core.getAttrProxyForURI(uri) class Factory: def create(readername): return PyroReader(readername) create = staticmethod(create) def readers(groups=[]): readernames = [] try: ns = Pyro.naming.NameServerLocator().getNS() readernames = ns.list(':pyscard.smartcard.readers') except Pyro.errors.NamingError: print('Warning: pyro name server not found') remotereaders = [] for readername in readernames: remotereaders.append(PyroReader.Factory.create(readername[0])) return remotereaders readers = staticmethod(readers) if __name__ == '__main__': SELECT = [0xA0, 0xA4, 0x00, 0x00, 0x02] DF_TELECOM = [0x7F, 0x10] from smartcard.util import * remotereaders = PyroReader.readers() for reader in remotereaders: try: print(reader.name, ', uri: ', reader.uri) connection = reader.createConnection() connection.connect() print(toHexString(connection.getATR())) data, sw1, sw2 = connection.transmit(SELECT + DF_TELECOM) print("%X %X" % (sw1, sw2)) except NoCardException as x: print('no card in reader')
Python
0.000024
@@ -1231,24 +1231,61 @@ yro URI.%22%22%22%0A + super().__init__(readername)%0A ns =
9f7bd49350b0d1b8a8986b28db75a5b369bf7bb5
Add py solution for 393. UTF-8 Validation
py/utf-8-validation.py
py/utf-8-validation.py
Python
0.000002
@@ -0,0 +1,940 @@ +class Solution(object):%0A def validUtf8(self, data):%0A %22%22%22%0A :type data: List%5Bint%5D%0A :rtype: bool%0A %22%22%22%0A it = iter(data)%0A while True:%0A try:%0A c = it.next() & 0xff%0A try:%0A t = 0x80%0A n = 0%0A while t %3E 0:%0A if t & c:%0A n += 1%0A t %3E%3E= 1%0A else:%0A break%0A if n == 1 or n %3E 4:%0A return False%0A elif n %3E 1:%0A for _ in xrange(n - 1):%0A c = it.next() & 0xff%0A if c & 0xc0 != 0x80:%0A return False%0A except StopIteration:%0A return False%0A except StopIteration:%0A return True%0A%0A
fb70822079c47962f0f713bcea43af80fe58d93e
add example using the VTKMesh class
examples/mesh_vtk_example.py
examples/mesh_vtk_example.py
Python
0
@@ -0,0 +1,1246 @@ +from numpy import array%0A%0Afrom simphony.cuds.mesh import Point, Cell, Edge, Face%0Afrom simphony.core.data_container import DataContainer%0Afrom simphony_mayavi.cuds.api import VTKMesh%0A%0A%0Apoints = array(%5B%0A %5B0, 0, 0%5D, %5B1, 0, 0%5D, %5B0, 1, 0%5D, %5B0, 0, 1%5D,%0A %5B2, 0, 0%5D, %5B3, 0, 0%5D, %5B3, 1, 0%5D, %5B2, 1, 0%5D,%0A %5B2, 0, 1%5D, %5B3, 0, 1%5D, %5B3, 1, 1%5D, %5B2, 1, 1%5D%5D,%0A 'f')%0A%0Acells = %5B%0A %5B0, 1, 2, 3%5D, # tetra%0A %5B4, 5, 6, 7, 8, 9, 10, 11%5D%5D # hex%0A%0Afaces = %5B%5B2, 7, 11%5D%5D%0Aedges = %5B%5B1, 4%5D, %5B3, 8%5D%5D%0A%0Amesh = VTKMesh('example')%0A%0A# add points%0Auids = %5B%0A mesh.add_point(%0A Point(coordinates=point, data=DataContainer(TEMPERATURE=index)))%0A for index, point in enumerate(points)%5D%0A%0A# add edges%0Aedge_uids = %5B%0A mesh.add_edge(%0A Edge(points=%5Buids%5Bindex%5D for index in element%5D))%0A for index, element in enumerate(edges)%5D%0A%0A# add faces%0Aface_uids = %5B%0A mesh.add_face(%0A Face(points=%5Buids%5Bindex%5D for index in element%5D))%0A for index, element in enumerate(faces)%5D%0A%0A# add cells%0Acell_uids = %5B%0A mesh.add_cell(%0A Cell(points=%5Buids%5Bindex%5D for index in element%5D))%0A for index, element in enumerate(cells)%5D%0A%0A%0Aif __name__ == '__main__':%0A from simphony.visualisation import mayavi_tools%0A%0A # Visualise the Mesh object%0A mayavi_tools.show(mesh)%0A
bdc062830a943a312dc6b56002f5ca6ae3990b80
add example
examples/peer/peer_matrix.py
examples/peer/peer_matrix.py
Python
0.000002
@@ -0,0 +1,440 @@ +import cupy%0A%0A%0Adef main():%0A gpus = cupy.cuda.runtime.getDeviceCount()%0A for peerDevice in range(gpus):%0A for device in range(gpus):%0A if peerDevice == device:%0A continue%0A flag = cupy.cuda.runtime.deviceCanAccessPeer(device, peerDevice)%0A print(%0A f'Can access #%7BpeerDevice%7D memory from #%7Bdevice%7D: '%0A f'%7Bflag == 1%7D')%0A%0A%0Aif __name__ == '__main__':%0A main()%0A
51530297a561fa9630f69c70810c1b4bbeb7ecf0
Create testmessage table
migrations/versions/187eade64ef0_create_testmessage_table.py
migrations/versions/187eade64ef0_create_testmessage_table.py
Python
0
@@ -0,0 +1,976 @@ +%22%22%22Create testmessage table%0A%0ARevision ID: 187eade64ef0%0ARevises: 016f138b2da8%0ACreate Date: 2016-06-21 16:11:47.905481%0A%0A%22%22%22%0A%0A# revision identifiers, used by Alembic.%0Arevision = '187eade64ef0'%0Adown_revision = '016f138b2da8'%0A%0Afrom alembic import op%0Aimport sqlalchemy as sa%0A%0A%0Adef upgrade():%0A op.create_table(%0A 'testmessage',%0A sa.Column('id', sa.GUID(), nullable=False),%0A sa.Column('test_id', sa.GUID(), nullable=False),%0A sa.Column('artifact_id', sa.GUID(), nullable=False),%0A sa.Column('start_offset', sa.Integer(), nullable=False),%0A sa.Column('length', sa.Integer(), nullable=False),%0A sa.PrimaryKeyConstraint('id'),%0A sa.ForeignKeyConstraint(%5B'test_id'%5D, %5B'test.id'%5D, ondelete='CASCADE'),%0A sa.ForeignKeyConstraint(%5B'artifact_id'%5D, %5B'artifact.id'%5D, ondelete='CASCADE'),%0A )%0A op.create_index('idx_testmessage_test_id', 'testmessage', %5B'test_id'%5D, unique=False)%0A%0A%0Adef downgrade():%0A op.drop_table('testmessage')%0A
cc84a5c71f84596af61b2de4a16cd62ff0209b16
Add migration file
migrations/versions/fd02d1c7d64_add_hail_migration_fields.py
migrations/versions/fd02d1c7d64_add_hail_migration_fields.py
Python
0.000001
@@ -0,0 +1,1350 @@ +%22%22%22Add hail migration fields%0A%0ARevision ID: fd02d1c7d64%0ARevises: 59e5faf237f8%0ACreate Date: 2015-04-15 12:04:43.286358%0A%0A%22%22%22%0A%0A# revision identifiers, used by Alembic.%0Arevision = 'fd02d1c7d64'%0Adown_revision = '59e5faf237f8'%0A%0Afrom alembic import op%0Aimport sqlalchemy as sa%0Afrom sqlalchemy.dialects import postgresql%0A%0Adef upgrade():%0A ### commands auto generated by Alembic - please adjust! ###%0A op.create_table('hail',%0A sa.Column('id', sa.Integer(), nullable=False),%0A sa.Column('creation_datetime', sa.DateTime(), nullable=False),%0A sa.Column('client_id', sa.Integer(), nullable=False),%0A sa.Column('client_lon', sa.Float(), nullable=False),%0A sa.Column('client_lat', sa.Float(), nullable=False),%0A sa.Column('taxi_id', sa.Integer(), nullable=False),%0A sa.Column('status', sa.Enum('emitted', 'received', 'sent_to_operator', 'received_by_operator', 'received_by_taxi', 'accepted_by_taxi', 'declined_by_taxi', 'incident_client', 'incident_taxi', 'timeout_client', 'timeout_taxi', 'outdated_client', 'outdated_taxi', name='hail_status'), nullable=False),%0A sa.Column('last_status_change', sa.DateTime(), nullable=True),%0A sa.PrimaryKeyConstraint('id')%0A )%0A ### end Alembic commands ###%0A%0A%0Adef downgrade():%0A ### commands auto generated by Alembic - please adjust! ###%0A op.drop_table('hail')%0A ### end Alembic commands ###%0A
730c7e0e36f0466172c050dd791915938c648953
summarize git-shortlog by mail
gist/git_shortlog_mail.py
gist/git_shortlog_mail.py
Python
0.999844
@@ -0,0 +1,772 @@ +%22%22%22%0ABackground:%0A%0Agit shortlog -nse%0A%0AUser may use different nick name in git-shortlog, but always use same mail.%0AThis command cannot map user by mail. I have to use complex .mailmap file.%0A%0AWrite this script to summarize commit number by mail instead of by user name.%0A%0AHow to use:%0A%0A git shortlog -nse %3E git_shortlog.list%0A python git_shortlog_mail.py%0A%0A%22%22%22%0Awith open(%22git_shortlog.list%22) as fp:%0A dct = %7B%7D%0A for l in fp:%0A l = l.split()%0A k = l%5B-1%5D%0A v = int(l%5B0%5D.strip())%0A if k in dct:%0A dct%5Bk%5D += v%0A else:%0A dct%5Bk%5D = v%0A view = %5B(name, num) for num, name in dct.iteritems()%5D%0A view.sort(reverse=True)%0A for i in range(len(view)):%0A num, name = view%5Bi%5D%0A print %22%25d%5Ct%25d%5Ct%25s%22 %25 (i + 1, num, name)%0A
fc84c19cdbbe86b1a57efb3468cdfc26785ca4a6
add utility helper to format table for console output
rawdisk/util/output.py
rawdisk/util/output.py
Python
0
@@ -0,0 +1,834 @@ +import numpy as np%0A%0Adef format_table(headers, columns, values, ruler='-'):%0A printable_rows = %5B%5D%0A%0A table = np.empty((len(values), len(columns)), dtype=object)%0A%0A for row, value in enumerate(values):%0A table%5Brow%5D = %5Bstr(getattr(value, column)) for column in columns%5D%0A%0A column_widths = %5B%0A max(len(headers%5Bcol%5D), len(max(table%5B:, col%5D, key=len)))%0A for col in range(len(columns))%5D%0A%0A # print header%0A printable_rows.append(' '.join(%5Bheader.ljust(column_widths%5Bcol%5D)%0A for col, header in enumerate(headers)%5D))%0A%0A printable_rows.append(' '.join(%5B'-' * width for width in column_widths%5D))%0A%0A for row in table:%0A printable_rows.append(' '.join(%5Bcol.ljust(column_widths%5Bidx%5D)%0A for idx, col in enumerate(row)%5D))%0A%0A return printable_rows%0A
100a03003adf3f425d59b69e95078bd0f1e82193
Add test script for segfault bug reported by Jeremy Hill.
test/reopen_screen.py
test/reopen_screen.py
Python
0.000011
@@ -0,0 +1,1645 @@ +#!/usr/bin/env python%0A%0A# Test for bug reported by Jeremy Hill in which re-opening the screen%0A# would cause a segfault.%0A%0Aimport VisionEgg%0AVisionEgg.start_default_logging(); VisionEgg.watch_exceptions()%0A%0Afrom VisionEgg.Core import Screen, Viewport, swap_buffers%0Aimport pygame%0Afrom pygame.locals import QUIT,KEYDOWN,MOUSEBUTTONDOWN%0Afrom VisionEgg.Text import Text%0Afrom VisionEgg.Dots import DotArea2D%0A%0Adef run():%0A screen = Screen()%0A screen.parameters.bgcolor = (0.0,0.0,0.0) # black (RGB)%0A%0A dots = DotArea2D( position = ( screen.size%5B0%5D/2.0, screen.size%5B1%5D/2.0 ),%0A size = ( 300.0 , 300.0 ),%0A signal_fraction = 0.1,%0A signal_direction_deg = 180.0,%0A velocity_pixels_per_sec = 10.0,%0A dot_lifespan_sec = 5.0,%0A dot_size = 3.0,%0A num_dots = 100)%0A%0A text = Text( text = %22Vision Egg dot_simple_loop demo.%22,%0A position = (screen.size%5B0%5D/2,2),%0A anchor = 'bottom',%0A color = (1.0,1.0,1.0))%0A%0A viewport = Viewport( screen=screen, stimuli=%5Bdots,text%5D )%0A%0A # The main loop below is an alternative to using the%0A # VisionEgg.FlowControl.Presentation class.%0A%0A quit_now = 0%0A while not quit_now:%0A for event in pygame.event.get():%0A if event.type in (QUIT,KEYDOWN,MOUSEBUTTONDOWN):%0A quit_now = 1%0A screen.clear()%0A viewport.draw()%0A swap_buffers()%0A screen.close()%0A%0Aprint %22run 1%22%0Arun()%0Aprint %22run 2%22%0Arun()%0Aprint %22done%22%0A
35849cf3650c5815c0124f90fad3d3fa2ef9abc6
Create InsertationSort2.py
InsertationSort2.py
InsertationSort2.py
Python
0
@@ -0,0 +1,488 @@ +def compareAndRep(numbers , a , b):%0A%09temp = numbers%5Ba%5D%0A%09numbers%5Ba%5D = numbers%5Bb%5D%0A%09numbers%5Bb%5D = temp%0A%09return numbers %0A%0Adef printList(numbers):%0A%09strp = %22%22%0A%09for i in range(0 , len(numbers)):%0A%09%09strp += str(numbers%5Bi%5D)%0A%09%09if(i+1 %3C len(numbers)):%0A%09%09%09strp += %22 %22%0A%09print strp%0A%0AN = int(raw_input())%0Anumbers = map(int , raw_input().strip().split(%22 %22))%0Afor i in range(1 , N):%0A%09for j in range (0 , i ):%0A%09%09if(numbers%5Bi%5D %3C numbers%5Bj%5D):%0A%09%09%09numbers = compareAndRep(numbers , i , j)%0A%0A%09printList(numbers) %0A%0A
97e46b93124758bec85d2e81a6843c22a265bce3
Add entry point for GC repo importer
ForgeImporters/setup.py
ForgeImporters/setup.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from setuptools import setup, find_packages setup(name='ForgeImporters', description="", long_description="", classifiers=[], keywords='', author='', author_email='', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=['Allura', ], entry_points=""" # -*- Entry points: -*- [allura.project_importers] google-code = forgeimporters.google.project:GoogleCodeProjectImporter [allura.importers] """,)
Python
0
@@ -1449,24 +1449,95 @@ .importers%5D%0A + google-code-repo = forgeimporters.google.code:GoogleRepoImporter%0A %22%22%22,)%0A
1e7421878e90949abc4f6fac5835bd27b472d2b6
Add example script for the newly added mixed_diffusivity
example_Knudsen.py
example_Knudsen.py
Python
0
@@ -0,0 +1,1801 @@ +import openpnm as op%0Aimport numpy as np%0Aimport matplotlib.pyplot as plt%0A%0A%0A# Get Deff w/o including Knudsen effect%0Aspacing = 1.0%0Anet = op.network.Cubic(shape=%5B10, 10, 10%5D, spacing=spacing)%0Ageom = op.geometry.StickAndBall(network=net)%0Aair = op.phases.Air(network=net)%0Aphys = op.physics.Standard(network=net, geometry=geom, phase=air)%0Afd = op.algorithms.FickianDiffusion(network=net, phase=air)%0Afd.set_value_BC(pores=net.pores(%22left%22), values=1.0)%0Afd.set_value_BC(pores=net.pores(%22right%22), values=0.0)%0Afd.run()%0AL = (net.shape * net.spacing)%5B1%5D%0AA = (net.shape * net.spacing)%5B%5B0, 2%5D%5D.prod()%0AMdot = fd.rate(pores=net.pores(%22left%22)).squeeze()%0ADeff0 = Mdot * L / A%0A%0A# Get Deff w/ including Knudsen effect%0Amdiff = op.models.physics.diffusive_conductance.mixed_diffusivity%0Aphys.add_model(propname=%22throat.diffusive_conductance%22, model=mdiff)%0Aspacings = np.linspace(1e-9, 1e-4, 20)%0Aspacings = np.logspace(-9, -3, 25)%0ADeff = %5B%5D%0A%0Afor spacing in spacings:%0A np.random.seed(10)%0A net = op.network.Cubic(shape=%5B10, 10, 10%5D, spacing=spacing)%0A geom = op.geometry.StickAndBall(network=net)%0A air = op.phases.Air(network=net)%0A phys = op.physics.Standard(network=net, geometry=geom, phase=air)%0A phys.add_model(propname=%22throat.diffusive_conductance%22, model=mdiff)%0A fd = op.algorithms.FickianDiffusion(network=net, phase=air)%0A fd.set_value_BC(pores=net.pores(%22left%22), values=1.0)%0A fd.set_value_BC(pores=net.pores(%22right%22), values=0.0)%0A fd.run()%0A L = (net.shape * net.spacing)%5B1%5D%0A A = (net.shape * net.spacing)%5B%5B0, 2%5D%5D.prod()%0A Mdot = fd.rate(pores=net.pores(%22left%22)).squeeze()%0A Deff.append(Mdot * L / A)%0A%0A# Plot ratio of Deff w/ Knudsen to that w/o%0ADeff = np.array(Deff)%0Aplt.figure()%0Aplt.plot(spacings, Deff/Deff0)%0Aplt.xscale(%22log%22)%0Aplt.xlabel(%22spacing (m)%22)%0Aplt.ylabel(%22Deff/Deff0%22)%0A
a6bbcc46765fee52eba9c31b95d456977fbeeefe
add beautify for print beautify words
Scripts/beautify.py
Scripts/beautify.py
Python
0.000007
@@ -0,0 +1,485 @@ +#!/usr/bin/env python%0A%0Aimport sys%0A%0A%0Adef beautify(line, bold=False):%0A k = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'%0A v = '%F0%9D%92%9C%E2%84%AC%F0%9D%92%9E%F0%9D%92%9F%E2%84%B0%E2%84%B1%F0%9D%92%A2%E2%84%8B%E2%84%90%F0%9D%92%A5%F0%9D%92%A6%E2%84%92%E2%84%B3%F0%9D%92%A9%F0%9D%92%AA%F0%9D%92%AB%F0%9D%92%AC%E2%84%9B%F0%9D%92%AE%F0%9D%92%AF%F0%9D%92%B0%F0%9D%92%B1%F0%9D%92%B2%F0%9D%92%B3%F0%9D%92%B4%F0%9D%92%B5%F0%9D%92%B6%F0%9D%92%B7%F0%9D%92%B8%F0%9D%92%B9%E2%84%AF%F0%9D%92%BB%E2%84%8A%F0%9D%92%BD%F0%9D%92%BE%F0%9D%92%BF%F0%9D%93%80%F0%9D%93%81%F0%9D%93%82%F0%9D%93%83%E2%84%B4%F0%9D%93%85%F0%9D%93%86%F0%9D%93%87%F0%9D%93%88%F0%9D%93%89%F0%9D%93%8A%F0%9D%93%8B%F0%9D%93%8C%F0%9D%93%8D%F0%9D%93%8E%F0%9D%93%8F'%0A bv = '%F0%9D%93%90%F0%9D%93%91%F0%9D%93%92%F0%9D%93%93%F0%9D%93%94%F0%9D%93%95%F0%9D%93%96%F0%9D%93%97%F0%9D%93%98%F0%9D%93%99%F0%9D%93%9A%F0%9D%93%9B%F0%9D%93%9C%F0%9D%93%9D%F0%9D%93%9E%F0%9D%93%9F%F0%9D%93%A0%F0%9D%93%A1%F0%9D%93%A2%F0%9D%93%A3%F0%9D%93%A4%F0%9D%93%A5%F0%9D%93%A6%F0%9D%93%A7%F0%9D%93%A8%F0%9D%93%A9%F0%9D%93%AA%F0%9D%93%AB%F0%9D%93%AC%F0%9D%93%AD%F0%9D%93%AE%F0%9D%93%AF%F0%9D%93%B0%F0%9D%93%B1%F0%9D%93%B2%F0%9D%93%B3%F0%9D%93%B4%F0%9D%93%B5%F0%9D%93%B6%F0%9D%93%B7%F0%9D%93%B8%F0%9D%93%B9%F0%9D%93%BA%F0%9D%93%BB%F0%9D%93%BC%F0%9D%93%BD%F0%9D%93%BE%F0%9D%93%BF%F0%9D%94%80%F0%9D%94%81%F0%9D%94%82%F0%9D%94%83'%0A%0A chars = dict(zip(k, bv if bold else v))%0A return ''.join(%5Bchars.get(char, char) for char in line%5D)%0A%0A%0Aif __name__ == '__main__':%0A user_input = ' '.join(sys.argv%5B1:%5D)%0A result = beautify(user_input)%0A print(result)%0A
cbafc49d098ee1166aae32eae79a808e576a1afa
Hello world
Simple/hello.py
Simple/hello.py
Python
0.999979
@@ -0,0 +1,23 @@ +print(%22Hello, world%22)%0D%0A
e1772c008d607a2545ddaa05508b1a74473be0ec
Add TaskInstance index on job_id
airflow/migrations/versions/7171349d4c73_add_ti_job_id_index.py
airflow/migrations/versions/7171349d4c73_add_ti_job_id_index.py
Python
0
@@ -0,0 +1,1041 @@ +# -*- coding: utf-8 -*-%0A#%0A# Licensed under the Apache License, Version 2.0 (the %22License%22);%0A# you may not use this file except in compliance with the License.%0A# You may obtain a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS,%0A# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A# See the License for the specific language governing permissions and%0A# limitations under the License.%0A%0A%22%22%22add ti job_id index%0A%0ARevision ID: 7171349d4c73%0ARevises: cc1e65623dc7%0ACreate Date: 2017-08-14 18:08:50.196042%0A%0A%22%22%22%0A%0A# revision identifiers, used by Alembic.%0Arevision = '7171349d4c73'%0Adown_revision = 'cc1e65623dc7'%0Abranch_labels = None%0Adepends_on = None%0A%0Afrom alembic import op%0Aimport sqlalchemy as sa%0A%0A%0Adef upgrade():%0A op.create_index('ti_job_id', 'task_instance', %5B'job_id'%5D, unique=False)%0A%0A%0Adef downgrade():%0A op.drop_index('ti_job_id', table_name='task_instance')%0A
74dee1d09fdc09f93af3d15286336d7face4ba08
add test file for proper_parens.
test_proper_parens.py
test_proper_parens.py
Python
0
@@ -0,0 +1,887 @@ +from __future__ import unicode_literals%0Afrom proper_parens import check_statement%0A%0A%0Adef test_check_statement():%0A%0A # Edge cases of strings of length one%0A value = %22)%22%0A assert check_statement(value) == -1%0A%0A value = %22(%22%0A assert check_statement(value) == 1%0A%0A # Edge cases of strings of length two%0A value = %22()%22%0A assert check_statement(value) == 0%0A%0A # 'Balanced' but broken%0A value = %22)(%22%0A assert check_statement(value) == -1%0A%0A # Broken beginnning, middle, and end%0A value = %22)()%22%0A assert check_statement(value) == -1%0A%0A value = %22())()%22%0A assert check_statement(value) == -1%0A%0A value = %22())%22%0A assert check_statement(value) == -1%0A%0A # Open beginnning, middle, and end%0A value = %22(()%22%0A assert check_statement(value) == 1%0A%0A value = %22()(()%22%0A assert check_statement(value) == 1%0A%0A value = %22()(%22%0A assert check_statement(value) == 1%0A
77637c0eca6ba5cd00e8f1fbe863a1fd293c980f
Create __init__.py
tests/CAN/__init__.py
tests/CAN/__init__.py
Python
0.000429
@@ -0,0 +1 @@ +%0A
9d982f3f910c985e8ac29b0c7e271031fd815ee0
Remove useless known hosts warnings
ssh/ssher.py
ssh/ssher.py
""" Simple, robust SSH client for basic I/O """ import logging import os import stat import tempfile from contextlib import contextmanager from subprocess import check_call, check_output from pkgpanda.util import write_string log = logging.getLogger(__name__) class Tunnelled(): def __init__(self, base_cmd: list, target: str): """ Args: base_cmd: list of strings that will be evaluated by check_call to send commands through the tunnel target: string in the form user@host """ self.base_cmd = base_cmd self.target = target def command(self, cmd: list, **kwargs) -> bytes: """ Run a command at the tunnel target Args: cmd: list of strings that will be sent as a command to the target **kwargs: any keywork args that can be passed into subprocess.check_output. For more information, see: https://docs.python.org/3/library/subprocess.html#subprocess.check_output """ run_cmd = self.base_cmd + [self.target] + cmd log.debug('Running socket cmd: ' + ' '.join(run_cmd)) if 'stdout' in kwargs: return check_call(run_cmd, **kwargs) else: return check_output(run_cmd, **kwargs) def copy_file(self, src: str, dst: str) -> None: """ Copy a file from localhost to target Args: src: local path representing source data dst: destination for path """ cmd = self.base_cmd + ['-C', self.target, 'cat>' + dst] log.debug('Copying {} to {}:{}'.format(src, self.target, dst)) with open(src, 'r') as fh: check_call(cmd, stdin=fh) @contextmanager def temp_data(key: str) -> (str, str): """ Provides file paths for data required to establish the SSH tunnel Args: key: string containing the private SSH key Returns: (path_for_temp_socket_file, path_for_temp_ssh_key) """ temp_dir = tempfile.mkdtemp() socket_path = temp_dir + '/control_socket' key_path = temp_dir + '/key' write_string(key_path, key) os.chmod(key_path, stat.S_IREAD | stat.S_IWRITE) yield (socket_path, key_path) os.remove(key_path) # might have been deleted already if SSH exited correctly if os.path.exists(socket_path): os.remove(socket_path) os.rmdir(temp_dir) @contextmanager def open_tunnel(user: str, key: str, host: str, port: int=22) -> Tunnelled: """ Provides clean setup/tear down for an SSH tunnel Args: user: SSH user key: string containing SSH private key host: string containing target host port: target's SSH port """ target = user + '@' + host with temp_data(key) as temp_paths: base_cmd = [ '/usr/bin/ssh', '-oConnectTimeout=10', '-oControlMaster=auto', '-oControlPath=' + temp_paths[0], '-oStrictHostKeyChecking=no', '-oUserKnownHostsFile=/dev/null', '-oBatchMode=yes', '-oPasswordAuthentication=no', '-p', str(port)] start_tunnel = base_cmd + ['-fnN', '-i', temp_paths[1], target] log.debug('Starting SSH tunnel: ' + ' '.join(start_tunnel)) check_call(start_tunnel) log.debug('SSH Tunnel established!') yield Tunnelled(base_cmd, target) close_tunnel = base_cmd + ['-O', 'exit', target] log.debug('Closing SSH Tunnel: ' + ' '.join(close_tunnel)) check_call(close_tunnel) class Ssher: """ class for binding SSH user and key to tunnel """ def __init__(self, user: str, key: str): self.user = user self.key = key def command(self, host: str, cmd: list, port: int=22, **kwargs) -> bytes: with open_tunnel(self.user, self.key, host, port) as tunnel: return tunnel.command(cmd, **kwargs) def get_home_dir(self, host: str, port: int=22) -> str: """ Returns the SSH home dir """ return self.command(host, ['pwd'], port=port).decode().strip()
Python
0
@@ -3042,16 +3042,48 @@ /null',%0A + '-oLogLevel=ERROR',%0A
b936fe0b01a29f8638f662a4a779226fe93cd6fa
Create 5kyu_faulty_odometer.py
Solutions/5kyu/5kyu_faulty_odometer.py
Solutions/5kyu/5kyu_faulty_odometer.py
Python
0.000344
@@ -0,0 +1,171 @@ +BASE = '012356789'%0A%0Adef faulty_odometer(num):%0A result = 0%0A for i, n in enumerate(str(num)%5B::-1%5D):%0A result += BASE.index(n) * len(BASE) ** i%0A return result%0A
ab753bc09d27cc00780d48769d8c12a9015fae18
Create 0062_siteoption_copyright_notice.py
radio/migrations/0062_siteoption_copyright_notice.py
radio/migrations/0062_siteoption_copyright_notice.py
Python
0
@@ -0,0 +1,876 @@ +# -*- coding: utf-8 -*-%0A# Save default html text for index and about page%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations, models%0A%0Adef set_default_html(apps, schema_editor):%0A%0A SiteOption = apps.get_model('radio', 'SiteOption')%0A SiteOption(name='COPYRIGHT_NOTICE', %0A value = 'Copyright 2019',%0A javascript_visible = True,%0A template_visible = True,%0A description = 'Edit to update Copyright notice',%0A ).save()%0A%0Adef nothing_to_do(apps, schema_editor):%0A SiteOption = apps.get_model('radio', 'SiteOption')%0A SiteOption.objects.get(name='COPYRIGHT_NOTICE').delete()%0A%0A%0Aclass Migration(migrations.Migration):%0A %0A dependencies = %5B%0A ('radio', '0061_transmission_has_audio'),%0A %5D%0A%0A operations = %5B%0A migrations.RunPython(set_default_html, nothing_to_do),%0A %5D%0A
fa7b12066fd81ed97bb0ecbd13690f850021915f
Create crossover.py
cea/optimization/master/crossover.py
cea/optimization/master/crossover.py
Python
0.000001
@@ -0,0 +1,3242 @@ +%22%22%22%0ACrossover routines%0A%0A%22%22%22%0Afrom __future__ import division%0A%0Afrom deap import tools%0A%0Afrom cea.optimization.master.validation import validation_main%0A%0A%0Adef crossover_main(individual, indpb,%0A column_names,%0A heating_unit_names_share,%0A cooling_unit_names_share,%0A column_names_buildings_heating,%0A column_names_buildings_cooling,%0A district_heating_network,%0A district_cooling_network%0A ):%0A%0A # create dict of individual with his/her name%0A individual_with_name_dict = dict(zip(column_names, individual))%0A%0A if district_heating_network:%0A%0A # MUTATE BUILDINGS CONNECTED%0A buildings_heating = %5Bindividual_with_name_dict%5Bcolumn%5D for column in column_names_buildings_heating%5D%0A # apply mutations%0A buildings_heating_mutated = tools.cxUniform(buildings_heating, indpb)%5B0%5D%0A # take back to the individual%0A for column, cross_over_value in zip(column_names_buildings_heating, buildings_heating_mutated):%0A individual_with_name_dict%5Bcolumn%5D = cross_over_value%0A%0A # MUTATE SUPPLY SYSTEM UNITS SHARE%0A heating_units_share = %5Bindividual_with_name_dict%5Bcolumn%5D for column in heating_unit_names_share%5D%0A # apply mutations%0A heating_units_share_mutated = tools.cxUniform(heating_units_share, indpb)%5B0%5D%0A # takeback to teh individual%0A for column, cross_over_value in zip(heating_unit_names_share, heating_units_share_mutated):%0A individual_with_name_dict%5Bcolumn%5D = cross_over_value%0A%0A if district_cooling_network:%0A%0A # MUTATE BUILDINGS CONNECTED%0A buildings_cooling = %5Bindividual_with_name_dict%5Bcolumn%5D for column in column_names_buildings_cooling%5D%0A # apply mutations%0A buildings_cooling_mutated = tools.cxUniform(buildings_cooling, indpb)%5B0%5D%0A # take back to teh individual%0A for column, cross_over_value in zip(column_names_buildings_cooling, buildings_cooling_mutated):%0A individual_with_name_dict%5Bcolumn%5D = cross_over_value%0A%0A # MUTATE SUPPLY SYSTEM UNITS SHARE%0A cooling_units_share = %5Bindividual_with_name_dict%5Bcolumn%5D for column in cooling_unit_names_share%5D%0A # apply mutations%0A cooling_units_share_mutated = tools.cxUniform(cooling_units_share, indpb)%5B0%5D%0A # takeback to teh individual%0A for column, cross_over_value in zip(cooling_unit_names_share, cooling_units_share_mutated):%0A individual_with_name_dict%5Bcolumn%5D = cross_over_value%0A%0A # now validate individual%0A individual_with_name_dict = validation_main(individual_with_name_dict,%0A column_names_buildings_heating,%0A column_names_buildings_cooling,%0A district_heating_network,%0A district_cooling_network%0A )%0A%0A # now pass all the values mutated to the original individual%0A for i, column in enumerate(column_names):%0A individual%5Bi%5D = individual_with_name_dict%5Bcolumn%5D%0A%0A return individual, # add the, because deap needs this%0A
c2509a25eaf3522a55d061f940931447bbf023f1
test pyCharm
lp3thw/ex41.py
lp3thw/ex41.py
Python
0.000002
@@ -0,0 +1,2330 @@ +import random%0Afrom urllib.request import urlopen%0Aimport sys%0A%0AWORD_URL = %22http://learncodethehardway.org/words.txt%22%0AWORDS = %5B%5D%0A%0APHRASES = %7B%0A %22class %25%25%25(%25%25%25):%22:%0A %22Make a class named %25%25%25 that is-a %25%25%25.%22,%0A %22class %25%25%25(object):%5Cn%5Ctdef __init__(self, ***)%22:%0A %22class %25%25%25 has-a __init__ that takes self and *** params.%22,%0A %22class %25%25%25(object):%5Cn%5Ctdef ***(self, @@@)%22:%0A %22class %25%25%25 has-a function *** that takes self and @@@ params.%22,%0A %22*** = %25%25%25()%22:%0A %22Set *** to an instance of class %25%25%25.%22,%0A %22***.***(@@@)%22:%0A %22From *** get the *** function, call it with params self, @@@.%22,%0A %22***.*** = '***'%22:%0A %22From *** get the *** attribute and set it to '***'.%22%0A%7D%0A%0A# do they want to drill phrases first%0Aif len(sys.argv) == 2 and sys.argv%5B1%5D == %22english%22:%0A PHRASES_FIRST = True%0Aelse:%0A PHRASES_FIRST = False%0A%0A# load up the words from the website%0Afor word in urlopen(WORD_URL).readlines():%0A WORDS.append(str(word.strip(), encoding=%22utf-8%22))%0A%0A%0Adef convert(snippet, phrase):%0A class_names = %5Bw.capitalize() for w in%0A random.sample(WORDS, snippet.count(%22%25%25%25%22))%5D%0A other_names = random.sample(WORDS, snippet.count(%22***%22))%0A results = %5B%5D%0A param_names = %5B%5D%0A%0A for i in range(0, snippet.count(%22@@@%22)):%0A param_count = random.randint(1, 3)%0A param_names.append(', '.join(%0A random.sample(WORDS, param_count)))%0A%0A for sentence in snippet, phrase:%0A result = sentence%5B:%5D%0A%0A # fake class names%0A for word in class_names:%0A result = result.replace(%22%25%25%25%22, word, 1)%0A%0A # fake other names%0A for word in other_names:%0A result = result.replace(%22***%22, word, 1)%0A%0A # fake parameter lists%0A for word in param_names:%0A result = result.replace(%22@@@%22, word, 1)%0A%0A results.append(result)%0A%0A return results%0A%0A%0A# keep going until they hit CTRL-D%0Atry:%0A while True:%0A snippets = list(PHRASES.keys())%0A random.shuffle(snippets)%0A%0A for snippet in snippets:%0A phrase = PHRASES%5Bsnippet%5D%0A question, answer = convert(snippet, phrase)%0A if PHRASES_FIRST:%0A question, answer = answer, question%0A%0A print(question)%0A%0A input(%22%3E %22)%0A print(f%22ANSWER: %7Banswer%7D%5Cn%5Cn%22)%0Aexcept EOFError:%0A print(%22%5CnBye%22)%0A
c50f1bd892f5bc17bb77cd9d09ae5d0d1db8d75c
vowel count Day 5
submissions/j-nordell/Day5/vowelcount.py
submissions/j-nordell/Day5/vowelcount.py
Python
0.99922
@@ -0,0 +1,343 @@ +vowel_dict = %7B'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0%7D%0Avowels = %5B'a', 'e', 'i', 'o', 'u'%5D%0Auser_text = input(%22Please enter some text: %22)%0Auser_text = list(user_text)%0A%0Afor letter in user_text:%0A if letter in vowels:%0A vowel_dict%5Bletter%5D += 1%0A %0A%0Aprint(%22Here are the results: %22)%0A%0Afor key, value in vowel_dict.items():%0A print(key, value)%0A %0A
24cfe61a9e1d8ed5a78b2338e652085fc5b3f4e1
Add example delete
examples/delete.py
examples/delete.py
Python
0.99966
@@ -0,0 +1,952 @@ +# Licensed under the Apache License, Version 2.0 (the %22License%22); you may%0A# not use this file except in compliance with the License. You may obtain%0A# a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS, WITHOUT%0A# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the%0A# License for the specific language governing permissions and limitations%0A# under the License.%0A%0Aimport sys%0A%0Afrom examples import common%0Afrom examples import session%0A%0A%0Adef run_delete(opts):%0A sess = session.make_session(opts)%0A cls = common.find_resource_cls(opts)%0A data = common.get_data_option(opts)%0A obj = cls.new(**data)%0A obj.delete(sess)%0A print('Deleted: %25s' %25 str(data))%0A return%0A%0A%0Aif __name__ == %22__main__%22:%0A opts = common.setup()%0A sys.exit(common.main(opts, run_delete))%0A
0cb6b839509d3f5ecf0e2196c53decbf6fdac65e
add renameDate.py
renameDates.py
renameDates.py
Python
0.000008
@@ -0,0 +1,1338 @@ +#! Python3%0A# renameDate.py - rename file name that include date in US format (MM-DD-YYYY)%0A# to EU format (DD-MM-YYYY)%0A%0Aimport shutil, os, re%0A%0A#Regex for US dates%0AdatePattern = re.compile(r%22%22%22%5E(.*?) # All text before date%0A ((0%7C1)?%5Cd)- # one or two month digits %0A ((0%7C1%7C2%7C3)?%5Cd)- # one or two day digits%0A ((19%7C20)%5Cd%5Cd) # four year digits%0A (.*?)$ # all text after date%0A %22%22%22, re.VERBOSE)%0A%0A# Loop for files in working catalog%0Afor amerFilename in os.listdir('.'):%0A mo = datePattern.search(amerFilename)%0A%0A # Leave files with names than not include dates%0A if mo == None:%0A continue%0A %0A # Taking different parts of filename%0A beforePart = mo.group(1)%0A monthPart = mo.group(2)%0A dayPart = mo.group(4)%0A yearPart = mo.group(6)%0A afterPart = mo.group(8)%0A%0A # Forming names in EU format%0A euroFilename = beforePart + dayPart + '-' + monthPart + '-' + yearPart + afterPart%0A%0A # Taking fool absolute paths to files%0A absWorkingDir = os.path.abspath('.')%0A amerFilename = os.path.join(absWorkingDir, amerFilename)%0A euroFilename = os.path.join(absWorkingDir, euroFilename)%0A%0A # Renaming files%0A print('Changing name %22%25s%22 to %22%25s%22...' %25 (amerFilename, euroFilename))%0A shutil.move(amerFilename, euroFilename)
b920103c5aef9fa38d91e2fe0eafaeb8fd18d27b
Create FileEncryptor.py
FileEncryptor.py
FileEncryptor.py
Python
0.000001
@@ -0,0 +1,1995 @@ +import os%0Afrom Crypto.Cipher import AES%0Afrom Crypto.Hash import SHA256%0Afrom Crypto import Random%0A%0Adef encrypt(key, filename):%0A chunksize = 64 * 1024%0A outputFile = %22(encrypted)%22 + filename%0A filesize = str(os.path.getsize(filename)).zfill(16)%0A IV = Random.new().read(16)%0A%0A encryptor = AES.new(key, AES.MODE_CBC, IV)%0A%0A with open(filename, 'rb') as infile:%0A with open(outputFile, 'wb') as outfile:%0A outfile.write(filesize.encode('utf-8'))%0A outfile.write(IV)%0A%0A while True:%0A chunk = infile.read(chunksize)%0A%0A if len(chunk) == 0:%0A break%0A elif len(chunk) %25 16 != 0:%0A chunk += b' ' * (16 - (len(chunk) %25 16))%0A%0A outfile.write(encryptor.encrypt(chunk))%0A%0A%0Adef decrypt(key, filename):%0A chunksize = 64 * 1024%0A outputFile = filename%5B11:%5D%0A%0A with open(filename, 'rb') as infile:%0A filesize = int(infile.read(16))%0A IV = infile.read(16)%0A%0A decryptor = AES.new(key, AES.MODE_CBC, IV)%0A%0A with open(outputFile, 'wb') as outfile:%0A while True:%0A chunk = infile.read(chunksize)%0A%0A if len(chunk) == 0:%0A break%0A%0A outfile.write(decryptor.decrypt(chunk))%0A%0A outfile.truncate(filesize)%0A%0Adef getKey(password):%0A hasher = SHA256.new(password.encode('utf-8'))%0A return hasher.digest()%0A%0A%0Adef Main():%0A choice = input(%22Would you like to (E)ncrypt or (D)ecrypt?: %22)%0A%0A if choice == 'E':%0A filename = input('File to encrypt: ')%0A password = input(%22Password: %22)%0A encrypt(getKey(password), filename)%0A print(%22Done.%22)%0A elif choice == 'D':%0A filename = input(%22File to decrypt: %22)%0A password = input(%22Password: %22)%0A decrypt(getKey(password), filename)%0A print(%22Done%22)%0A else:%0A print(%22You didn't type E or D, closing....%22)%0A%0Aif __name__ == '__main__':%0A Main()%0AStatus API Training Shop Blog About%0A
06e0f140c517e467445a59be989ba3b9ddd76503
add tests for stdlib xpath
python/ql/test/library-tests/frameworks/stdlib/XPathExecution.py
python/ql/test/library-tests/frameworks/stdlib/XPathExecution.py
Python
0.000002
@@ -0,0 +1,665 @@ +match = %22dc:title%22%0Ans = %7B'dc': 'http://purl.org/dc/elements/1.1/'%7D%0A%0Aimport xml.etree.ElementTree as ET%0Atree = ET.parse('country_data.xml')%0Aroot = tree.getroot()%0A%0Aroot.find(match, namespaces=ns) # $ MISSING: getXPath=match%0Aroot.findall(match, namespaces=ns) # $ MISSING: getXPath=match%0Aroot.findtext(match, default=None, namespaces=ns) # $ MISSING: getXPath=match%0A%0Afrom xml.etree.ElementTree import ElementTree%0Atree = ElementTree()%0Atree.parse(%22index.xhtml%22)%0A%0Atree.find(match, namespaces=ns) # $ MISSING: getXPath=match%0Atree.findall(match, namespaces=ns) # $ MISSING: getXPath=match%0Atree.findtext(match, default=None, namespaces=ns) # $ MISSING: getXPath=match%0A
70f7096d353ee3edccf6e52e21c6a74db158d906
Configure settings for py.test
conftest.py
conftest.py
Python
0.000001
@@ -0,0 +1,177 @@ +import os%0A%0Afrom django.conf import settings%0A%0A%0Adef pytest_configure():%0A if not settings.configured:%0A os.environ%5B'DJANGO_SETTINGS_MODULE'%5D = 'multimedia.tests.settings'%0A
4863696bbfb46a836b4febc3397e51dd20214414
add repoquery-recursive.py for downloading rpm packages and their dependencies exceluding which comes from install media
repoquery-recursive.py
repoquery-recursive.py
Python
0
@@ -0,0 +1,784 @@ +#!/usr/bin/python3%0Aimport sys%0Aimport subprocess%0A%0Arepoquery = %5B'repoquery', '--plugins', '--resolve', '--qf',%0A%09'%25%7Bname%7D.%25%7Barch%7D %25%7Brepoid%7D %25%7Blocation%7D', '--plugins', '-R'%5D%0A%0Apackage_info = dict()%0A%0Adef check_dep(packages):%09%0A%09#print(packages)%0A%09if len(packages) == 0:%0A%09%09return%0A%09cmd = repoquery + packages%0A%09output = subprocess.check_output(cmd).decode(%22utf-8%22)%0A%09wait_for_checking = %5B%5D%0A%09for line in output.split('%5Cn'):%0A%09%09if len(line) == 0:%0A%09%09%09continue%0A%09%09(package_name, repoid, location) = line.split(' ')%0A%09%09if (repoid != 'InstallMedia' and %0A%09%09%09%09package_name not in package_info):%0A%09%09%09package_info%5Bpackage_name%5D = (repoid, location)%0A%09%09%09wait_for_checking.append(package_name)%0A%09check_dep(wait_for_checking)%0A%0Acheck_dep(sys.argv%5B1:%5D)%0A%0Afor package in package_info:%0A%09print(package_info%5Bpackage%5D%5B1%5D)%0A%0A
eefe2a1f4dc7482f75a2cd3cfd94c1048ba688c6
Add back $0.25 tip amount; #180
gittip/__init__.py
gittip/__init__.py
import datetime import locale import os from decimal import Decimal try: # XXX This can't be right. locale.setlocale(locale.LC_ALL, "en_US.utf8") except locale.Error: locale.setlocale(locale.LC_ALL, "en_US.UTF-8") BIRTHDAY = datetime.date(2012, 6, 1) CARDINALS = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] MONTHS = [None, 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] def age(): today = datetime.date.today() nmonths = today.month - BIRTHDAY.month plural = 's' if nmonths != 1 else '' if nmonths < 10: nmonths = CARDINALS[nmonths] else: nmonths = str(nmonths) return "%s month%s" % (nmonths, plural) db = None # This global is wired in wireup. It's an instance of # gittip.postgres.PostgresManager. # Not sure we won't want this for something yet. Prune if you don't find it in # the codebase in a month. OLD_OLD_AMOUNTS= [Decimal(a) for a in ('0.00', '0.08', '0.16', '0.32', '0.64', '1.28')] OLD_AMOUNTS= [Decimal(a) for a in ('0.25',)] AMOUNTS = [Decimal(a) for a in ('0.00', '1.00', '3.00', '6.00', '12.00', '24.00')] RESTRICTED_IDS = None # canonizer # ========= # This is an Aspen hook to ensure that requests are served on a certain root # URL, even if multiple domains point to the application. class X: pass canonical_scheme = None canonical_host = None def canonize(request): """Enforce a certain scheme and hostname. Store these on request as well. """ scheme = request.headers.get('X-Forwarded-Proto', 'http') # per Heroku host = request.headers['Host'] bad_scheme = scheme != canonical_scheme bad_host = bool(canonical_host) and (host != canonical_host) # '' and False => '' if bad_scheme or bad_host: url = '%s://%s' % (canonical_scheme, canonical_host) if request.line.method in ('GET', 'HEAD', 'OPTIONS', 'TRACE'): # Redirect to a particular path for idempotent methods. url += request.line.uri.path.raw if request.line.uri.querystring: url += '?' + request.line.uri.querystring.raw else: # For non-idempotent methods, redirect to homepage. url += '/' request.redirect(url, permanent=True) def configure_payments(request): # Work-around for https://github.com/balanced/balanced-python/issues/5 import balanced balanced.configure(os.environ['BALANCED_API_SECRET'])
Python
0.000008
@@ -1162,16 +1162,24 @@ ('0.00', + '0.25', '1.00',
0e2504171dc5679b5cdd1cb219ad1cd1e9f29262
add a test case for performance benchmarking.
tests/perf_unicorn.py
tests/perf_unicorn.py
Python
0.000003
@@ -0,0 +1,1419 @@ +%0Aimport sys%0Aimport os%0Aimport time%0A%0Aimport angr%0Aimport simuvex.s_options as so%0Aimport nose.tools%0A%0Atest_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../'))%0A%0Adef perf_unicorn_0():%0A p = angr.Project(os.path.join(test_location, 'binaries', 'tests', 'x86_64', 'perf_unicorn_0'))%0A%0A s_unicorn = p.factory.entry_state(add_options=so.unicorn %7C %7Bso.STRICT_PAGE_ACCESS%7D, remove_options=%7Bso.LAZY_SOLVES%7D) # unicorn%0A%0A pg_unicorn = p.factory.path_group(s_unicorn)%0A%0A start = time.time()%0A pg_unicorn.run()%0A elapsed = time.time() - start%0A%0A print %22Elapsed %25f sec%22 %25 elapsed%0A print pg_unicorn.one_deadended%0A%0Adef perf_unicorn_1():%0A p = angr.Project(os.path.join(test_location, 'binaries', 'tests', 'x86_64', 'perf_unicorn_1'))%0A%0A s_unicorn = p.factory.entry_state(add_options=so.unicorn %7C %7Bso.STRICT_PAGE_ACCESS%7D, remove_options=%7Bso.LAZY_SOLVES%7D) # unicorn%0A%0A pg_unicorn = p.factory.path_group(s_unicorn)%0A%0A start = time.time()%0A pg_unicorn.run()%0A elapsed = time.time() - start%0A%0A print %22Elapsed %25f sec%22 %25 elapsed%0A print pg_unicorn.one_deadended%0A%0Aif __name__ == %22__main__%22:%0A%0A if len(sys.argv) %3E 1:%0A for arg in sys.argv%5B1:%5D:%0A print 'perf_' + arg%0A globals()%5B'perf_' + arg%5D()%0A%0A else:%0A for fk, fv in globals().items():%0A if fk.startswith('perf_') and callable(fv):%0A print fk%0A res = fv()%0A
e3b7b9e5f8ca1be061c71c764fd62d6aeed3fd43
Add test suite for bqlmath.
tests/test_bqlmath.py
tests/test_bqlmath.py
Python
0
@@ -0,0 +1,2539 @@ +# -*- coding: utf-8 -*-%0A%0A# Copyright (c) 2010-2016, MIT Probabilistic Computing Project%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 itertools%0A%0Aimport apsw%0Aimport pytest%0A%0Afrom bayeslite import bayesdb_open%0Afrom bayeslite import bqlmath%0A%0Afrom bayeslite.math_util import abserr%0Afrom bayeslite.util import cursor_value%0A%0A%0Adef get_python_math_call(name, probe):%0A func = bqlmath.bqlmath_funcs%5Bname%5D%0A if isinstance(probe, tuple):%0A return func(*probe)%0A else:%0A return func(probe)%0A%0Adef get_sql_math_call(name, probe):%0A if isinstance(probe, tuple):%0A return 'SELECT %25s%25s' %25 (name, str(probe))%0A else:%0A return 'SELECT %25s(%25s)' %25 (name, probe)%0A%0APROBES_FLOAT = %5B-2.5, -1, -0.1, 0, 0.1, 1, 2.5%5D%0APROBES_TUPLE = itertools.combinations(PROBES_FLOAT, 2)%0APROBES = itertools.chain(PROBES_FLOAT, PROBES_TUPLE)%0AFUNCS = bqlmath.bqlmath_funcs.iterkeys()%0A%[email protected]('name,probe', itertools.product(FUNCS, PROBES))%0Adef test_math_func_one_param(name, probe):%0A # Retrieve result from python.%0A python_value_error = None%0A python_type_error = None%0A try:%0A result_python = get_python_math_call(name, probe)%0A except ValueError:%0A python_value_error = True%0A except TypeError:%0A python_type_error = True%0A%0A # Retrieve result from SQL.%0A sql_value_error = None%0A sql_type_error = None%0A try:%0A with bayesdb_open(':memory') as bdb:%0A cursor = bdb.execute(get_sql_math_call(name, probe))%0A result_sql = cursor_value(cursor)%0A except ValueError:%0A sql_value_error = True%0A except (TypeError, apsw.SQLError):%0A sql_type_error = True%0A%0A # Domain error on both.%0A if python_value_error or sql_value_error:%0A assert python_value_error and sql_value_error%0A # Arity error on both.%0A elif python_type_error or sql_type_error:%0A assert python_type_error and sql_type_error%0A # Both invocations succeeded, confirm results match.%0A else:%0A assert abserr(result_python, result_sql) %3C 1e-4%0A
2014f326eb73f7b30fe9cad8f30df80e7b8b3f26
add first test
tests/test_ipcheck.py
tests/test_ipcheck.py
Python
0.000003
@@ -0,0 +1,69 @@ +class TestBoundaryValue:%0A def test_WeakNomral(self):%0A pass%0A
d95a7d6017dd6a08d9c8df5af9c61ee2cb23d217
add test code for wrapper.py
tests/test_wrapper.py
tests/test_wrapper.py
Python
0.000002
@@ -0,0 +1,803 @@ +import sys%0Asys.path.append('..')%0Aimport unittest%0Afrom wrapper import xp%0Afrom chainer import cuda%0Afrom chainer import Variable%0A%0Aclass WrapperTestCase(unittest.TestCase):%0A%0A def test_xp(self):%0A try:%0A cuda.check_cuda_available()%0A module = 'cupy'%0A except:%0A module = 'numpy'%0A self.assertEqual(xp.__name__, module)%0A%0A def test_Zeros(self):%0A zeros = xp.Zeros((1, 1), dtype=xp.float32)%0A self.assertEqual(type(zeros), Variable)%0A self.assertEqual(zeros.data%5B0%5D%5B0%5D, 0.0)%0A self.assertEqual(zeros.data.dtype, xp.float32)%0A%0A def test_Array(self):%0A arr = xp.Array(%5B0%5D, dtype=xp.int32)%0A self.assertEqual(type(arr), Variable)%0A self.assertEqual(arr.data%5B0%5D, 0)%0A self.assertEqual(arr.data.dtype, xp.int32)%0A
6733cc00015458c307272a3124857bf686b06fbb
Create h.py
h.py
h.py
Python
0.000002
@@ -0,0 +1,23 @@ +print %22Hello, World!%22 %0A
553009b8f0cb0396f266d10dc5b6010ad60e7a25
Solve task #21
21.py
21.py
Python
0.999999
@@ -0,0 +1,899 @@ +# Definition for singly-linked list.%0A# class ListNode(object):%0A# def __init__(self, x):%0A# self.val = x%0A# self.next = None%0A%0Aclass Solution(object):%0A def mergeTwoLists(self, l1, l2):%0A %22%22%22%0A :type l1: ListNode%0A :type l2: ListNode%0A :rtype: ListNode%0A %22%22%22%0A def step(l, y):%0A x = ListNode(l.val)%0A y.next = x%0A y = y.next%0A l = l.next%0A return %5Bl, y%5D%0A %0A if not l1 or not l2:%0A return l1 or l2%0A %0A x = y = ListNode(0)%0A %0A while (l1 is not None) and (l2 is not None):%0A if l1.val %3C l2.val:%0A l1, y = step(l1, y)%0A else:%0A l2, y = step(l2, y)%0A %0A if l1 is None:%0A y.next = l2%0A else:%0A y.next = l1%0A %0A return x.next%0A %0A
7b949393c0cf20b9f21ff3e743a6ad35b3cccb49
Create 22.py
22.py
22.py
Python
0.000004
@@ -0,0 +1,2391 @@ +import copy%0Aimport math%0A%0A# %5B 0 %7C 1 %7C 2 %7C 3 %7C 4 %7C 5 %5D%0A#spell = %5Bspell id %7C mana %7C damage %7C armor %7C mana %7C timer%5D%0Aspells = %5B(0, 53, 4, 0, 0, 0), (1, 73, 2, 2, 0, 0), (2, 113, 0, 0, 0, 6), (3, 173, 3, 0, 0, 6), (4, 229, 0, 0, 101, 5)%5D%0A%0A#2 = Shield%0A%0A#timer = %5Bspell id, turns left%5D%0AbossDamage = 9%0AInf = 100000%0Abest = Inf%0Adef minManaToWin(me, boss, mana, manaUsed, timers, myMove):%0A #print(me, boss, mana, manaUsed, timers, myMove)%0A global spells, bossDamage, Inf, best%0A%0A if me %3E 0 and boss %3C= 0:%0A #win%0A print(manaUsed)%0A best = min(best, manaUsed)%0A return 0%0A%0A if me %3C= 0:%0A return Inf%0A%0A if manaUsed %3E best:%0A return Inf%0A%0A if myMove:%0A me -= 1%0A if me %3C= 0:%0A return Inf%0A%0A #apply timers%0A shieldOn = False%0A new_timers = %5B%5D%0A for timer in timers:%0A if timer%5B0%5D == 2:%0A shieldOn = True%0A spell = spells%5Btimer%5B0%5D%5D%0A mana += spell%5B4%5D%0A me += spell%5B3%5D%0A boss -= spell%5B2%5D%0A if timer%5B1%5D %3E 1:%0A new_timers += %5B%5Btimer%5B0%5D, timer%5B1%5D - 1%5D%5D%0A%0A if me %3E 0 and boss %3C= 0:%0A #win%0A print(manaUsed)%0A best = min(best, manaUsed)%0A return 0%0A%0A res = Inf%0A if myMove:%0A for spell in spells:%0A if spell%5B1%5D %3C= mana:%0A if spell%5B5%5D == 0:%0A #immediately%0A tmp = minManaToWin(me + spell%5B3%5D, boss - spell%5B2%5D, mana - spell%5B1%5D, manaUsed + spell%5B1%5D, new_timers, False)%0A res = min(res, tmp + spell%5B1%5D)%0A else:%0A inUse = False%0A for t in new_timers:%0A if t%5B0%5D == spell%5B0%5D:%0A #already appled spell%0A inUse = True%0A break%0A if inUse:%0A continue%0A #add timer%0A tmp = minManaToWin(me, boss, mana - spell%5B1%5D, manaUsed + spell%5B1%5D, new_timers + %5B%5Bspell%5B0%5D, spell%5B5%5D%5D%5D, False)%0A res = min(res, tmp + spell%5B1%5D)%0A else:%0A #boss' move%0A myArmor = 7 if shieldOn else 0%0A me -= bossDamage - myArmor%0A tmp = minManaToWin(me, boss, mana, manaUsed, new_timers, True)%0A res = min(res, tmp)%0A return res%0A%0A%0Aresult = minManaToWin(50, 51, 500, 0, %5B%5D, True)%0Aprint ('res =', result)%0A
62237000f3ae92638214d96f323a81d6a492d9cd
Update existing FAs with current tier programs (#4829)
financialaid/management/commands/migrate_finaid_program_tiers.py
financialaid/management/commands/migrate_finaid_program_tiers.py
Python
0
@@ -0,0 +1,1614 @@ +%22%22%22%0AUpdate FinancialAid objects with current tier program%0A%22%22%22%0Afrom django.core.management import BaseCommand, CommandError%0A%0Afrom financialaid.models import FinancialAid, TierProgram%0A%0A%0Aclass Command(BaseCommand):%0A %22%22%22%0A Updates the existing financial aid objects to current tier programs%0A %22%22%22%0A help = %22Updates the existing financial aid objects to current tier programs%22%0A%0A def handle(self, *args, **kwargs): # pylint: disable=unused-argument%0A%0A fin_aids = FinancialAid.objects.filter(%0A tier_program__current=False,%0A )%0A updated_count = 0%0A for financial_aid in fin_aids:%0A try:%0A threshold = financial_aid.tier_program.income_threshold%0A tier_program = TierProgram.objects.get(%0A income_threshold=threshold,%0A current=True,%0A )%0A%0A except TierProgram.DoesNotExist:%0A raise CommandError(%0A 'Could not find a current tier program with threshold %22%7B%7D%22 for financial aid %7B%7D'.format(%0A threshold,%0A financial_aid.id%0A )%0A )%0A except TierProgram.MultipleObjectsReturned:%0A raise CommandError(%0A 'There are multiple tier programs with threshold %22%7B%7D%22'.format(threshold)%0A )%0A%0A financial_aid.tier_program = tier_program%0A financial_aid.save_and_log(None)%0A updated_count += 1%0A%0A self.stdout.write(self.style.SUCCESS('Updated %7B%7D financial aid instances'.format(updated_count)))%0A
57af6d6d8b4c67f7b437f512e4d8eb4ea66a20f9
Add morse script
morse/morse.py
morse/morse.py
Python
0.000001
@@ -0,0 +1,1716 @@ +# Import modules%0Afrom microbit import *%0A%0A# define morse code dictionary%0Amorse = %7B%0A %22a%22: %22.-%22,%0A %22b%22: %22-...%22,%0A %22c%22: %22-.-.%22,%0A %22d%22: %22-..%22,%0A %22e%22: %22.%22,%0A %22f%22: %22..-.%22,%0A %22s%22: %22...%22,%0A %22o%22: %22---%22,%0A %22m%22: %22--%22,%0A %221%22: %22.----%22,%0A %222%22: %22..---%22,%0A %223%22: %22...--%22,%0A %224%22: %22....-%22,%0A %225%22: %22.....%22,%0A %226%22: %22-....%22,%0A %227:%22 %22--...%22,%0A %228%22: %22---..%22,%0A %229%22: %22----.%22,%0A %220%22: %22-----%22%0A %7D%0A%0Acurrent_letter = %22%22%0Apressed = 0%0Apaused = 0%0Aletters = %5B%5D%0A%0Adef detect_dot_dash(time_pressed):%0A return %22.%22 if time_pressed %3C= 50 else %22-%22%0A%0Adef get_letter(code):%0A global morse%0A for key,value in morse.items():%0A if code == value:%0A return key%0A%0A return %22%22%0A%0Awhile True:%0A sleep(1) # do not use all the cpu power%0A # make a loop to test for the button being pressed%0A if button_a.is_pressed():%0A if paused %3E= 100:%0A letters.append(get_letter(current_letter))%0A current_letter = %22%22%0A%0A if paused %3E= 200:%0A letters.append(%22_%22)%0A%0A paused = 0%0A%0A pressed = 1%0A while button_a.is_pressed():%0A # wait until the button is not pressed any more%0A sleep(1) # do not use all the cpu power%0A pressed += 1%0A # measure the time%0A current_letter += detect_dot_dash(pressed)%0A paused = 1%0A else:%0A if paused %3E 0:%0A paused +=1%0A%0A if button_b.is_pressed() or accelerometer.current_gesture() == %22shake%22:%0A letters.append(get_letter(current_letter))%0A display.scroll(%22%22.join(letters))%0A paused = 0%0A pressed = 0%0A current_letter = %22%22%0A letters = %5B%5D%0A
9609529e3a5c25c37be342d2bd1efe33e25128ff
Add IO file
IO.py
IO.py
Python
0.000001
@@ -0,0 +1,193 @@ +import RPi.GPIO as GPIO%0A%0A%0Adef gettemp():%0A return 80%0A%0A%0Adef setfan(state):%0A pass%0A%0A %0Adef setac(state):%0A if state:%0A # Always turn on the fan when the ac is on%0A setfan(True)
47fffb67871325f1b12d6150f12b2d9c44984837
implement top contributors functionality in gitguard
gitguard.py
gitguard.py
Python
0
@@ -0,0 +1,969 @@ +import re%0Aimport subprocess%0Aimport github%0A%0A%22%22%22%0Agitguard_extractor.py%0A%0AExtracts data for the visualizer.%0A%0Arepo_link is in the format USER/REPO_NAME or ORGANIZATION/REPO_NAME%0A%22%22%22%0A%0AREGEX_REPO_LINK_DELIMITER = '%5Cs*/%5Cs*'%0A%0Adef process_repo_link(repo_link):%0A #returns owner, repo_name%0A return re.compile(REGEX_REPO_LINK_DELIMITER).split(repo_link)%0A%0Adef get_top_contributor(repo_link):%0A return get_top_n_contributors(repo_link, 1)%0A%0Adef get_top_n_contributors(repo_link, n):%0A owner, repo = process_repo_link(repo_link)%0A%0A # connect to github API%0A gh = github.GitHub()%0A contributors = gh.repos(owner)(repo).contributors.get() %0A%0A answer = ''%0A persons = 0%0A for contributor in contributors:%0A answer += '%255d %25s%5Cn' %25 (contributor%5B'contributions'%5D, contributor%5B'login'%5D)%0A persons += 1%0A%0A # only show top n contributors%0A if persons %3E= n:%0A break%0A%0A answer += '%5CnTop contributors for %25s!' %25 repo_link%0A return answer%0A
a9fa88d11f5338f8662d4d6e7dc2103a80144be0
Revert "Remove model"
table/models.py
table/models.py
Python
0
@@ -0,0 +1,57 @@ +from django.db import models%0A%0A# Create your models here.%0A
c821be39a3853bf8a14e8c4089904dfe633ad276
Solve task #412
412.py
412.py
Python
0.999999
@@ -0,0 +1,481 @@ +class Solution(object):%0A def fizzBuzz(self, n):%0A %22%22%22%0A :type n: int%0A :rtype: List%5Bstr%5D%0A %22%22%22%0A def fizzBuzz(i, x):%0A return %7B1: str(i), 3: %22Fizz%22, 5: %22Buzz%22, 15: %22FizzBuzz%22%7D%5Bx%5D%0A %0A ans = %5B%5D%0A x = 1%0A for i in range(1, n + 1):%0A if i %25 3 == 0:%0A x *= 3%0A if i %25 5 == 0:%0A x *= 5%0A ans.append(fizzBuzz(i, x))%0A x = 1%0A return ans%0A %0A
e51322e7ee4afabee8b98137bc5e56b0a0f803ec
Solve #461
461.py
461.py
Python
0.999797
@@ -0,0 +1,482 @@ +class Solution(object):%0A def hammingDistance(self, x, y):%0A %22%22%22%0A :type x: int%0A :type y: int%0A :rtype: int%0A %22%22%22%0A x, y = list(bin(x)%5B2:%5D), list(bin(y)%5B2:%5D)%0A s1 = list('0' * max(len(x), len(y)))%0A s2 = list('0' * max(len(x), len(y)))%0A s1%5Blen(s1) - len(x):%5D = x%0A s2%5Blen(s2) - len(y):%5D = y%0A k = 0%0A for i in range(len(s1)):%0A if s1%5Bi%5D != s2%5Bi%5D:%0A k += 1%0A return k%0A %0A
2206f2dac5cb15c10fa59f14597133b6a0d3a314
Create ALE.py
ALE.py
ALE.py
Python
0.000001
@@ -0,0 +1,2089 @@ +%22%22%22%0AAsynchronous Learning Engine (ALE)%0A%0ASupports PWS standard desktop (studio)%0AMentor Queues%0ALoad Balancing / Air Traffic Control%0ACourses / Flights%0A%0AA mentor queue is a worker queue with%0Atasks pending, in process, complete.%0AThe many subclasses of Task are only hinted%0Aat in this overview.%0A%0AExample Tasks (Transactions archiving to Chronofile):%0ASet start time on booked flight, notify students%0ATake Off%0AIn-flight Services (the learning experience)%0ALand%0APostmortem **/ Archive Stats%0A%0A** sounds dire and we do try experimental courses%0Asometimes that %22crash%22 but in this shoptalk it's%0Ahow we discuss any completed flight.%0A%0AIn-flight the students have a Call Bell for%0Aspecial services. We run %22shows%22 which in the%0Abetter schools are highly interactive and require%0Aa lot of student activity. Passivism is a killer%0Awhen it comes to building confidence and competence%0Ain one's tools, as Scott Gray would point out during%0Afaculty meetings.%0A%0AA normal / standard flight consists of working%0Athrough course materials in a PWS Studio with%0Aasynchronous feedback from one or more mentors.%0AThe %22flight%22 (course) is also a unit of accounting%0Ai.e. we containerize it in terms of fixed cost%0Aoverhead, tuition, compensation and so on. See%0Aworkflow diagrams.%0A%0AALE:%0A%0AIn the OO version, ALE is the root object, adding mixins as needed%0A%0AKirby Urner%0A%0AWant graphics?%0Ahttps://www.flickr.com/photos/kirbyurner/sets/72157654417641521%0A%0A%22%22%22%0A%0Aclass Flight(ALE):%0A pass%0A %0Aclass AirTrafficUtils(ALE):%0A pass%0A%0Aclass Passenger(AWS):%0A pass%0A%0Aclass PWS:%0A pass%0A%0Aclass Dispatcher(AirTrafficUtils):%0A pass%0A%0Aclass Student(Passenger):%0A pass%0A%0Aclass Task:%0A # Examples: Start Class, Submit Work, Annotate Materials, Return Work%0A pass%0A%0Aclass Mentor(Oasis): # # Example mixin (ways to %22phone home%22)%0A pass%0A%0Aclass Course(Flight): # Expense Unit for accounting / bookkeeping%0A pass%0A %0Aclass Oversight(ALE):%0A pass%0A%0Aclass Admin(Oversight):%0A pass%0A%0Aclass Recruiting(Mentor):%0A pass # Exhibited Mentors, free samples%0A%0Aclass StudentSupport(Oversight):%0A pass # guidance functions (%22Travel Agency%22)%0A%0A%0A
6be70d01bdf58389db2a6adc4035f82669d02a61
Allow use of GoogleMaps plugin without Multilingual support
cms/plugins/googlemap/cms_plugins.py
cms/plugins/googlemap/cms_plugins.py
from cms.plugin_pool import plugin_pool from cms.plugin_base import CMSPluginBase from django.utils.translation import ugettext_lazy as _ from cms.plugins.googlemap.models import GoogleMap from cms.plugins.googlemap.settings import GOOGLE_MAPS_API_KEY from cms.plugins.googlemap import settings from django.forms.widgets import Media class GoogleMapPlugin(CMSPluginBase): model = GoogleMap name = _("Google Map") render_template = "cms/plugins/googlemap.html" def render(self, context, instance, placeholder): context.update({ 'object':instance, 'placeholder':placeholder, }) return context def get_plugin_media(self, request, context, plugin): if 'GOOGLE_MAPS_API_KEY' in context: key = context['GOOGLE_MAPS_API_KEY'] else: key = GOOGLE_MAPS_API_KEY return Media(js = ('http://maps.google.com/maps?file=api&amp;v=2&amp;key=%s&amp;hl=%s' % (key, request.LANGUAGE_CODE),)) plugin_pool.register_plugin(GoogleMapPlugin)
Python
0
@@ -1,24 +1,57 @@ +from django.conf import settings%0A from cms.plugin_pool imp @@ -282,51 +282,8 @@ KEY%0A -from cms.plugins.googlemap import settings%0A from @@ -855,16 +855,94 @@ API_KEY%0A + lang = getattr(request, 'LANGUAGE_CODE', settings.LANGUAGE_CODE%5B0:2%5D)%0A @@ -1040,35 +1040,17 @@ ey, -request.LANGUAGE_CODE +lang ),))%0A - %0Aplu
5c952e7a54bcff7bcdbd3b2a2d85f1f93ce95242
add first test: config+store
test/test_1100_conf_store.py
test/test_1100_conf_store.py
Python
0.000029
@@ -0,0 +1,2361 @@ +# test mod_md basic configurations%0A%0Aimport os.path%0Aimport pytest%0Aimport re%0Aimport subprocess%0Aimport sys%0Aimport time%0A%0Afrom ConfigParser import SafeConfigParser%0Afrom datetime import datetime%0Afrom httplib import HTTPConnection%0Afrom testbase import TestEnv%0A%0Aconfig = SafeConfigParser()%0Aconfig.read('test.ini')%0APREFIX = config.get('global', 'prefix')%0A%0Adef setup_module(module):%0A print(%22setup_module module:%25s%22 %25 module.__name__)%0A TestEnv.init()%0A TestEnv.apache_err_reset()%0A TestEnv.APACHE_CONF_SRC = %22test_configs_data%22%0A status = TestEnv.apachectl(None, %22start%22)%0A assert status == 0%0A %0Adef teardown_module(module):%0A print(%22teardown_module module:%25s%22 %25 module.__name__)%0A status = TestEnv.apachectl(None, %22stop%22)%0A%0A%0Aclass TestConf:%0A%0A def setup_method(self, method):%0A print(%22setup_method: %25s%22 %25 method.__name__)%0A (self.errors, self.warnings) = TestEnv.apache_err_count()%0A TestEnv.clear_store()%0A%0A def teardown_method(self, method):%0A print(%22teardown_method: %25s%22 %25 method.__name__)%0A%0A # --------- add to store ---------%0A%0A @pytest.mark.parametrize(%22confFile,dnsLists%22, %5B%0A (%22test_001%22, %5B%5B%22example.org%22, %22www.example.org%22, %22mail.example.org%22%5D%5D),%0A (%22test_002%22, %5B%5B%22example.org%22, %22www.example.org%22, %22mail.example.org%22%5D, %5B%22example2.org%22, %22www.example2.org%22, %22mail.example2.org%22%5D%5D)%0A %5D)%0A def test_001(self, confFile, dnsLists):%0A # just one ManagedDomain definition%0A assert TestEnv.apachectl(confFile, %22graceful%22) == 0%0A assert TestEnv.is_live(TestEnv.HTTPD_URL, 1)%0A for i in range (0, len(dnsLists)):%0A self._check_md(dnsLists%5Bi%5D%5B0%5D, dnsLists%5Bi%5D, 1)%0A%0A # --------- _utils_ ---------%0A%0A def _new_errors(self):%0A (errors, warnings) = TestEnv.apache_err_count()%0A return errors - self.errors%0A%0A def _new_warnings(self):%0A (errors, warnings) = TestEnv.apache_err_count()%0A return warnings - self.warnings%0A%0A def _check_md(self, name, dnsList, state):%0A jout = TestEnv.a2md(%5B%22list%22%5D)%5B'jout'%5D%0A assert jout%0A output = jout%5B'output'%5D%0A mdFound = False%0A for i in range (0, len(output)):%0A md = output%5Bi%5D%0A if name == md%5B'name'%5D:%0A mdFound = True%0A assert md%5B'domains'%5D == dnsList%0A assert md%5B'state'%5D == state%0A assert mdFound == True
c15c4a663c257cad6763cf92c50b7ad706017c74
Remove extraneous imports in the base view package
evesrp/views/__init__.py
evesrp/views/__init__.py
from collections import OrderedDict from urllib.parse import urlparse import re from flask import render_template, redirect, url_for, request, abort, jsonify,\ flash, Markup, session from flask.views import View from flask.ext.login import login_user, login_required, logout_user, \ current_user from flask.ext.wtf import Form from flask.ext.principal import identity_changed, AnonymousIdentity from sqlalchemy.orm.exc import NoResultFound from wtforms.fields import StringField, PasswordField, SelectField, \ SubmitField, TextAreaField, HiddenField from wtforms.fields.html5 import URLField, DecimalField from wtforms.widgets import HiddenInput from wtforms.validators import InputRequired, ValidationError, AnyOf, URL from .. import app, auth_methods, db, requests_session, killmail_sources from ..auth import SubmitRequestsPermission, ReviewRequestsPermission, \ PayoutRequestsPermission, admin_permission from ..auth.models import User, Group, Division, Pilot from ..models import Request, Modifier, Action @app.route('/') @login_required def index(): return render_template('base.html')
Python
0
@@ -2,1047 +2,99 @@ rom -collections import OrderedDict%0Afrom urllib.parse import urlparse%0Aimport re%0A%0Afrom flask import render_template, redirect, url_for, request, abort, jsonify,%5C%0A flash, Markup, session%0Afrom flask.views import View%0Afrom flask.ext.login import login_user, login_required, logout_user, %5C%0A current_user%0Afrom flask.ext.wtf import Form%0Afrom flask.ext.principal import identity_changed, AnonymousIdentity%0Afrom sqlalchemy.orm.exc import NoResultFound%0Afrom wtforms.fields import StringField, PasswordField, SelectField, %5C%0A SubmitField, TextAreaField, HiddenField%0Afrom wtforms.fields.html5 import URLField, DecimalField%0Afrom wtforms.widgets import HiddenInput%0Afrom wtforms.validators import InputRequired, ValidationError, AnyOf, URL%0A%0Afrom .. import app, auth_methods, db, requests_session, killmail_sources%0Afrom ..auth import SubmitRequestsPermission, ReviewRequestsPermission, %5C%0A PayoutRequestsPermission, admin_permission%0Afrom ..auth.models import User, Group, Division, Pilot%0Afrom ..models import Request, Modifier, Action +flask import render_template%0Afrom flask.ext.login import login_required%0A%0Afrom .. import app %0A%0A%0A@
d40b4c250f7d1c0c6a6c198b3e1ea69e0049830e
Create syb.py
syb.py
syb.py
Python
0.000039
@@ -0,0 +1,380 @@ +# -*- coding: utf-8 -*-%0A%22%22%22%0A Star Yuuki Bot%0A ~~~~~~~~~~~%0A LineClient for sending and receiving message from LINE server.%0A Copyright: (c) 2015 SuperSonic Software Foundation and Star Inc.%0A Website:%0A SuperSonic Software Foundation: http://supersonic-org.cf%0A Star Inc.: http://startw.cf%0A License: Mozilla Public License 2.0%0A%22%22%22%0A%0Aprint %22Come Soon...%22%0A
774877893b9f94711b717d01b896deefe65eb211
create file
app.py
app.py
Python
0.000003
@@ -0,0 +1,307 @@ +%22%22%22%0A@import rdflib external lib%0A%22%22%22%0Aimport rdflib%0A%0AjsonldData = open(%22LearningObjectsExpanded.jsonld%22).read()%0AqueryData = open(%22findRecommendations.query%22).read()%0A%0Agraph = rdflib.Graph()%0Agraph.parse(data=jsonldData,format='json-ld')%0A%0Aresults = graph.query(queryData)%0A%0Afor result in results:%0A print(result)%0A
921221e4ad7d74b6f9d8b0b75417fe84fd01715f
Add script to concatenate all titers to one file tracking source/passage Fixes #76
tdb/concatenate.py
tdb/concatenate.py
Python
0.000003
@@ -0,0 +1,1153 @@ +import argparse%0A%0Aparser = argparse.ArgumentParser()%0Aparser.add_argument('-f', '--files', nargs='*', default=%5B%5D, help=%22tsvs that will be concatenated%22)%0Aparser.add_argument('-o', '--output', type=str, default=%22data/titers_complete.tsv%22)%0A%0Adef concat(files,out):%0A with open(out, 'w') as o:%0A for filename in files:%0A%0A print %22Concatenating and annotating %25s into %25s.%22 %25 (filename, out)%0A%0A if %22cdc%22 in filename.lower():%0A source = %22cdc%22%0A elif %22crick%22 in filename.lower():%0A source = %22crick%22%0A else:%0A source = %22none%22%0A%0A if %22egg%22 in filename.lower():%0A passage = %22egg%22%0A elif %22cell%22 in filename.lower():%0A passage = %22egg%22%0A else:%0A passage = %22none%22%0A%0A with open(filename, 'r') as f:%0A for line in f.readlines():%0A print line%0A line = line.strip()%0A l = %22%25s%5Ct%25s%5Ct%25s%5Cn%22 %25 (line, source, passage)%0A o.write(l)%0A%0Aif __name__==%22__main__%22:%0A args = parser.parse_args()%0A concat(args.files, args.output)%0A
ad489edc8059b75d9ec78d0aeb03ac3592b93923
Add Federal Labor Relations Authority.
inspectors/flra.py
inspectors/flra.py
Python
0
@@ -0,0 +1,2563 @@ +#!/usr/bin/env python%0A%0Aimport datetime%0Aimport logging%0Aimport os%0Afrom urllib.parse import urljoin%0A%0Afrom bs4 import BeautifulSoup%0Afrom utils import utils, inspector%0A%0A# https://www.flra.gov/OIG%0A# Oldest report: 1999%0A%0A# options:%0A# standard since/year options for a year range to fetch from.%0A#%0A# Notes for IG's web team:%0A#%0A%0AAUDIT_REPORTS_URL = %22https://www.flra.gov/IG_audit-reports%22%0AINTERNAL_REVIEWS_URL = %22https://www.flra.gov/IG_internal-reviews%22%0AQA_REVIEWS_URL = %22https://www.flra.gov/OIG_QA_Reviews%22%0ASEMIANNUAL_REPORTS_URL = %22https://www.flra.gov/IG_semi-annual_reports%22%0A%0Adef run(options):%0A year_range = inspector.year_range(options)%0A%0A # Pull the reports%0A for url in %5BAUDIT_REPORTS_URL, INTERNAL_REVIEWS_URL, QA_REVIEWS_URL, SEMIANNUAL_REPORTS_URL%5D:%0A doc = BeautifulSoup(utils.download(url))%0A results = doc.select(%22div.node ul li%22)%0A for result in results:%0A report = report_from(result, url, year_range)%0A if report:%0A inspector.save_report(report)%0A%0Adef report_from(result, landing_url, year_range):%0A title = result.text.strip()%0A%0A if 'Non-Public Report' in title:%0A unreleased = True%0A report_url = None%0A report_id = %22-%22.join(title.split())%0A else:%0A unreleased = False%0A link = result.find(%22a%22)%0A # Some reports have incorrect relative paths%0A relative_report_url = link.get('href').replace(%22../%22, %22%22)%0A report_url = urljoin(landing_url, relative_report_url)%0A report_filename = report_url.split(%22/%22)%5B-1%5D%0A report_id, _ = os.path.splitext(report_filename)%0A%0A estimated_date = False%0A try:%0A published_on = datetime.datetime.strptime(title, '%25B %25Y')%0A except ValueError:%0A # For reports where we can only find the year, set them to Nov 1st of that year%0A published_on_year = int(result.find_previous(%22p%22).text.strip())%0A published_on = datetime.datetime(published_on_year, 11, 1)%0A estimated_date = True%0A%0A if published_on.year not in year_range:%0A logging.debug(%22%5B%25s%5D Skipping, not in requested range.%22 %25 report_url)%0A return%0A%0A report = %7B%0A 'inspector': 'flra',%0A 'inspector_url': 'https://www.flra.gov/OIG',%0A 'agency': 'flra',%0A 'agency_name': 'Federal Labor Relations Authority',%0A 'file_type': 'pdf',%0A 'report_id': report_id,%0A 'url': report_url,%0A 'title': title,%0A 'published_on': datetime.datetime.strftime(published_on, %22%25Y-%25m-%25d%22),%0A %7D%0A if estimated_date:%0A report%5B'estimated_date'%5D = estimated_date%0A if unreleased:%0A report%5B'unreleased'%5D = unreleased%0A report%5B'landing_url'%5D = landing_url%0A return report%0A%0Autils.run(run) if (__name__ == %22__main__%22) else None%0A
241cc8fc668b9f6c38d23a97d9ff28cc4c481bf3
Create github_watchdog,py
github_watchdog.py
github_watchdog.py
Python
0.000126
@@ -0,0 +1,17 @@ +#!/usr/bin/bash%0A%0A
45af6f13e302fb4e790f8ec5a5730f25c6a9450b
add new segmenter debugging script
kraken/contrib/heatmap_overlay.py
kraken/contrib/heatmap_overlay.py
Python
0
@@ -0,0 +1,1061 @@ +#! /usr/bin/env python%0A%22%22%22%0AProduces semi-transparent neural segmenter output overlays%0A%22%22%22%0A%0Aimport sys%0Aimport torch%0Aimport numpy as np%0Afrom PIL import Image%0Afrom kraken.lib import segmentation, vgsl, dataset%0Aimport torch.nn.functional as F%0Afrom typing import *%0Aimport glob%0Afrom os.path import splitext, exists%0A%0Amodel = vgsl.TorchVGSLModel.load_model(sys.argv%5B1%5D)%0Amodel.eval()%0Abatch, channels, height, width = model.input%0A%0Atransforms = dataset.generate_input_transforms(batch, height, width, channels, 0, valid_norm=False)%0A%0Aimgs = sys.argv%5B2:%5D%0Atorch.set_num_threads(1)%0A%0Afor img in imgs:%0A print(img)%0A im = Image.open(img)%0A with torch.no_grad():%0A o = model.nn(transforms(im).unsqueeze(0))%0A o = F.interpolate(o, size=im.size%5B::-1%5D)%0A o = o.squeeze().numpy()%0A heat = Image.fromarray((o%5B1%5D*255).astype('uint8'))%0A heat.save(splitext(img)%5B0%5D + '.heat.png')%0A overlay = Image.new('RGBA', im.size, (0, 130, 200, 255))%0A Image.composite(overlay, im.convert('RGBA'), heat).save(splitext(img)%5B0%5D + '.overlay.png')%0A del o%0A del im%0A%0A
d39a3bae3f6ca66df044e725cd164082170f4ec7
Modify the config file.
snippet/lib/python/config.py
snippet/lib/python/config.py
Python
0
@@ -0,0 +1,939 @@ +# coding: utf-8%0A%0Afrom oslo_config import cfg%0Afrom oslo_log import log%0A%0ACONF = cfg.CONF%0A%0A_ROOTS = %5B%22root%22%5D%0A_DEFAULT_LOG_LEVELS = %5B'root=INFO'%5D%0A_DEFAULT_LOG_FORMAT = %22%25(asctime)s - %25(name)s - %25(levelname)s - %25(message)s%22%0A%0A%0Adef parse_args(argv, project, version=None, default_config_files=None,%0A default_log_format=None, default_log_levels=None):%0A if project not in _ROOTS:%0A _DEFAULT_LOG_LEVELS.append('%25s=INFO' %25 project)%0A _ROOTS.append(project)%0A log_fmt = default_log_format if default_log_format else _DEFAULT_LOG_FORMAT%0A log_lvl = default_log_levels if default_log_levels else _DEFAULT_LOG_LEVELS%0A%0A log.set_defaults(log_fmt, log_lvl)%0A log.register_options(CONF)%0A%0A # (TODO): Configure the options of the other libraries, which must be called%0A # before parsing the configuration file.%0A%0A CONF(argv%5B1:%5D, project=project, version=version,%0A default_config_files=default_config_files)%0A
be2f50aae308377dbabd66b5ec78ffb2bd8ae218
Add tse_number as index
politicos/migrations/versions/488fc5ad2ffa_political_party_add_tse_number_as_index.py
politicos/migrations/versions/488fc5ad2ffa_political_party_add_tse_number_as_index.py
Python
0.002058
@@ -0,0 +1,425 @@ +%22%22%22political party: add tse_number as index%0A%0ARevision ID: 488fc5ad2ffa%0ARevises: 192bd4ccdacb%0ACreate Date: 2015-07-08 13:44:38.208146%0A%0A%22%22%22%0A%0A# revision identifiers, used by Alembic.%0Arevision = '488fc5ad2ffa'%0Adown_revision = '192bd4ccdacb'%0A%0Afrom alembic import op%0A%0A%0Adef upgrade():%0A op.create_index('idx_tse_number', 'political_party', %5B'tse_number'%5D)%0A%0A%0Adef downgrade():%0A op.drop_index('idx_tse_number', 'political_party')%0A
75756f20d4b63daa8425609620e4b32dcb9faab4
Add cryptography unit with morse code functions
units/cryptography.py
units/cryptography.py
Python
0.000001
@@ -0,0 +1,1316 @@ +%0Afrom .errors import UnitOutputError%0A%0Acharacter_to_morse = %7B%0A%09'A': %22.-%22, 'B': %22-...%22, 'C': %22-.-.%22, 'D': %22-..%22, 'E': '.', 'F': %22..-.%22, 'G': %22--.%22, 'H': %22....%22, %0A%09'I': %22..%22, 'J': %22.---%22, 'K': %22-.-%22, 'L': %22.-..%22, 'M': %22--%22, 'N': %22-.%22, 'O': %22---%22, 'P': %22.--.%22, %0A%09'Q': %22--.-%22, 'R': %22.-.%22, 'S': %22...%22, 'T': '-', 'U': %22..-%22, 'V': %22...-%22, 'W': %22.--%22, 'X': %22-..-%22, %0A%09'Y': %22-.--%22, 'Z': %22--..%22, '0': %22----%22, '1': %22.----%22, '2': %22..---%22, '3': %22...--%22, '4': %22....-%22, %0A%09'5': %22.....%22, '6': %22-....%22, '7': %22--...%22, '8': %22---..%22, '9': %22----.%22, '.': %22.-.-.-%22, ',': %22--..--%22, %0A%09':': %22---...%22, '?': %22..--..%22, %22'%22: %22.---.%22, '-': %22-....-%22, '/': %22-..-.%22, '!': %22-.-.--%22, %0A%09'(': %22-.--.%22, ')': %22-.--.-%22, '&': %22.-...%22, ';': %22-.-.-.%22, '=': %22-...-%22, '+': %22.-.-.%22, %0A%09'_': %22..--.-%22, '%22': %22.-..-.%22, '$': %22...-..-%22, '@': %22.--.-.%22, ' ': '/'%0A%7D%0A%0Amorse_to_character = %7Bvalue: key for key, value in character_to_morse.items()%7D%0A%0Adef encode_morse_code(message):%0A%09try:%0A%09%09return ' '.join(character_to_morse%5Bcharacter%5D for character in message.upper())%0A%09except KeyError as e:%0A%09%09raise UnitOutputError(f%22Unable to encode %7Be%7D%22)%0A%0Adef decode_morse_code(message):%0A%09try:%0A%09%09return ' '.join(''.join(morse_to_character%5Bcharacter%5D for character in word.split(' ')) for word in message.split(%22 / %22))%0A%09except KeyError as e:%0A%09%09raise UnitOutputError(f%22Unable to decode %7Be%7D%22)%0A%0A
93b3cfb5dd465f956fa6c9ceb09be430684c85ae
Add two pass solution
leetcode/q019/solution.py
leetcode/q019/solution.py
Python
0.000031
@@ -0,0 +1,1115 @@ +%22%22%22%0D%0AGiven a linked list, remove the n-th node from the end of list and return its head.%0D%0A%0D%0AExample:%0D%0A%0D%0AGiven linked list: 1-%3E2-%3E3-%3E4-%3E5, and n = 2.%0D%0A%0D%0AAfter removing the second node from the end, the linked list becomes 1-%3E2-%3E3-%3E5.%0D%0ANote:%0D%0A%0D%0AGiven n will always be valid.%0D%0A%22%22%22%0D%0A%0D%0A# Definition for singly-linked list.%0D%0A# class ListNode:%0D%0A# def __init__(self, x):%0D%0A# self.val = x%0D%0A# self.next = None%0D%0A%0D%0Aclass Solution:%0D%0A def removeNthFromEnd(self, head: ListNode, n: int) -%3E ListNode:%0D%0A d = 1%0D%0A current = head.next%0D%0A while current:%0D%0A d += 1%0D%0A current = current.next%0D%0A%0D%0A removal_index = d - n%0D%0A if removal_index %3C= 0:%0D%0A return head.next%0D%0A%0D%0A counter = 1%0D%0A prior = head%0D%0A current = head.next%0D%0A while counter %3C removal_index:%0D%0A prior = current%0D%0A current = prior.next%0D%0A counter += 1%0D%0A if current.next is None:%0D%0A prior.next = None%0D%0A else:%0D%0A following = current.next%0D%0A prior.next = following%0D%0A%0D%0A return head%0D%0A%0D%0A%0D%0A%0D%0A%0D%0A