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
4d47d14e2f630652c36765abf5907d6800a8012d
Revert "Revert "Initial python to find public APIs in Hadoop and compare them to outp…"" (#73) (cherry picked from commit a24236206b35744835781d42ff1dededbc685721)
bigtop-tests/spec-tests/runtime/src/test/python/find-public-apis.py
bigtop-tests/spec-tests/runtime/src/test/python/find-public-apis.py
Python
0
@@ -0,0 +1,2606 @@ +#!/usr/bin/python%0A%0A'''%0ALicensed to the Apache Software Foundation (ASF) under one%0Aor more contributor license agreements. See the NOTICE file%0Adistributed with this work for additional information%0Aregarding copyright ownership. The ASF licenses this file%0Ato you under the Apache License, Version 2.0 (the%0A%22License%22); you may not use this file except in compliance%0Awith the License. You may obtain a copy of the License at%0A%0A http://www.apache.org/licenses/LICENSE-2.0%0A%0AUnless required by applicable law or agreed to in writing, software%0Adistributed under the License is distributed on an %22AS IS%22 BASIS,%0AWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0ASee the License for the specific language governing permissions and%0Alimitations under the License.%0A'''%0A%0Aimport os%0Aimport re%0Aimport warnings%0Afrom optparse import OptionParser%0A%0Adef main():%0A parser = OptionParser()%0A parser.add_option(%22-d%22, %22--directory%22, help=%22Top level directory of source tree%22)%0A parser.add_option(%22-r%22, %22--report%22, help=%22API compatibility report file, in HTML format%22)%0A%0A (options, args) = parser.parse_args()%0A%0A # Get the ATS endpoint if it's not given.%0A if options.directory == None:%0A print %22You must specify a top level directory of the source tree%22%0A return 1%0A%0A if options.report == None:%0A print %22You must specify the report to check against%22%0A return 1%0A%0A publicClasses = set()%0A for directory in os.walk(options.directory):%0A for afile in directory%5B2%5D:%0A if re.search(%22%5C.java$%22, afile) != None:%0A handle = open(os.path.join(directory%5B0%5D, afile))%0A # Figure out the package we're in%0A pre = re.search(%22org/apache/hadoop%5B%5Cw/%5D*%22, directory%5B0%5D)%0A if pre == None:%0A warnings.warn(%22No package for %22 + directory%5B0%5D)%0A continue%0A package = pre.group(0)%0A expecting = 0%0A for line in handle:%0A if re.search(%22@InterfaceAudience.Public%22, line) != None:%0A expecting = 1%0A classname = re.search(%22class (%5Cw*)%22, line)%0A if classname != None and expecting == 1:%0A publicClasses.add(package + %22/%22 + classname.group(1))%0A expecting = 0%0A handle.close()%0A%0A handle = open(options.report)%0A haveChecked = set()%0A for line in handle:%0A classre = re.search(%22mangled: %3Cb%3E(org/apache/hadoop%5B%5Cw/%5D+)%22, line)%0A if classre != None:%0A classname = classre.group(1)%0A if classname not in haveChecked:%0A if classname in publicClasses:%0A print %22Warning, found change in public class %22 + classname%0A haveChecked.add(classname)%0A handle.close()%0A %0A%0A%0A%0Amain()%0A%0A %0A
e63d18f9ef70e7a42344cf13322676efa2226fa2
Create largest_rectangle_in_histogram.py
largest_rectangle_in_histogram.py
largest_rectangle_in_histogram.py
Python
0.001693
@@ -0,0 +1,1345 @@ +%22%22%22%0Ahttps://www.youtube.com/watch?v=VNbkzsnllsU%0A%22%22%22%0A%0A%0Adef largest_rectangle_in_histogram(histogram):%0A %22Return area of largest rectangle under histogram.%22%0A assert all(height %3E= 0 for height in histogram)%0A%0A # Use stacks to keep track of how long a rectangle of height h%0A # extends to the right.%0A%0A largest = 0%0A positions = %5B0%5D%0A heights = %5B0%5D%0A%0A for i,height in enumerate(histogram):%0A if height %3E heights%5B-1%5D:%0A # Track new tallest rectangle.%0A positions.append(i)%0A heights.append(height)%0A elif height %3C heights%5B-1%5D:%0A # Close rectangles taller than height.%0A while height %3C heights%5B-1%5D:%0A h, p = heights.pop(), positions.pop()%0A largest = max(largest, h * (i - p))%0A%0A i = len(histogram)%0A while heights:%0A # Close open rectangles.%0A h, p = heights.pop(), positions.pop()%0A largest = max(largest, h * (i - p))%0A%0A return largest%0A%0A%0Adef tests():%0A assert largest_rectangle_in_histogram(%5B%5D) == 0%0A assert largest_rectangle_in_histogram(%5B4%5D) == 4%0A assert largest_rectangle_in_histogram(%5B1, 3, 2, 1, 2%5D) == 5%0A assert largest_rectangle_in_histogram(map(lambda x: x * 10000000, %5B1, 3, 2, 1, 2%5D)) == 5 * 10000000%0A assert largest_rectangle_in_histogram(%5B1, 2, 1, 3, 2, 0, 1%5D) == 5%0A%0A print 'tests pass!'%0A
f2854aff3dde6439d990f8fd7d69e70dd4664b93
Add tags app admin
opps/core/tags/admin.py
opps/core/tags/admin.py
Python
0.000001
@@ -0,0 +1,368 @@ +# -*- encoding: utf-8 -*-%0Afrom django.contrib import admin%0A%0Afrom .models import Tag%0A%0A%0Aclass TagAdmin(admin.ModelAdmin):%0A list_display = ('name', 'date_insert')%0A search_fields = ('name',)%0A prepopulated_fields = %7B%22slug%22: %5B%22name%22%5D%7D%0A%0A fieldsets = %5B(None, %7B'fields': ('name', 'slug',)%7D)%5D%0A%0A class Meta:%0A model = Tag%0A%0Aadmin.site.register(Tag, TagAdmin)%0A
c3d37914777ee9e2356bfa691361351423b0615a
make a nova server instance return it's host's hostname
heat/network_aware_resources.py
heat/network_aware_resources.py
Python
0.000015
@@ -0,0 +1,600 @@ +from heat.engine.resources.openstack.nova.server import Server as NovaServer%0A%0Afrom oslo_log import log as logging%0Aimport traceback%0A%0ALOG = logging.getLogger(__name__)%0A%0A%0Aclass NetworkAwareServer(NovaServer):%0A OS_EXT_HOST_KEY = 'OS-EXT-SRV-ATTR:host'%0A%0A def get_attribute(self, key, *path):%0A if key == %22host%22:%0A server, data = self.get_live_resource_data()%0A return data.get(self.OS_EXT_HOST_KEY)%0A return super(NetworkAwareServer, self).get_attribute(key, *path)%0A%0A%0Adef resource_mapping():%0A return %7B%0A 'OS::NetworkAware::Server': NetworkAwareServer,%0A %7D%0A
8dd9578cb70e4a628e0abef1da613f32f864a343
version bump
taca/__init__.py
taca/__init__.py
""" Main TACA module """ __version__ = '0.6.11.0'
Python
0.000001
@@ -39,13 +39,13 @@ = '0.6.1 -1 +2 .0'%0A
425363751244d5ff75e61126fd1481094c941129
Create luhn.py for pypi package
luhn/luhn.py
luhn/luhn.py
Python
0
@@ -0,0 +1,3044 @@ +#!/usr/bin/env python3%0A%0A# Python 3.4 Implementation of the Luhn Algorithm%0A# Checks to see if 14, 15 or 16 digit account number is Luhn Compliant. %0A# See https://en.wikipedia.org/wiki/Luhn_algorithm for formula details. %0A# This file is suitable for unittest testing%0A# CardNumber is an account number (for example) received as a string%0A# Code is intentionally verbose to demonstrate each step clearly.%0A%0Aclass aLuhn(object):%0A def doLuhn(cardNumber):%0A cardLength = str(cardNumber)%0A try: %0A cardNumbers = int(cardNumber)%0A except ValueError:%0A return(False)%0A cardLength = len(cardLength)%0A everyOtherFromFarRightFor16 = %5B-2,-4,-6,-8,-10,-12,-14,-16%5D%0A everyOtherFromFarRightFor15 = %5B-2,-4,-6,-8,-10,-12,-14%5D%0A everyOddFromFarRightButOneFor15 = %5B-3,-5,-7,-9,-11,-13,-15%5D%0A everyOddFromFarRightButOneFor14 = %5B-3,-5,-7,-9,-11,-13%5D%0A doubleList = %5B%5D%0A doubleSet = %5B%5D%0A addUpDoubles = 0%0A addUpOthers = 0%0A # setup the counting variables for appropriate card lengths%0A if (cardLength == 16):%0A doubleList = everyOtherFromFarRightFor16%0A addUpTheOddDigits = everyOddFromFarRightButOneFor15%0A elif (cardLength == 15):%0A doubleList = everyOtherFromFarRightFor15%0A addUpTheOddDigits = everyOddFromFarRightButOneFor15%0A elif (cardLength == 14):%0A doubleList = everyOtherFromFarRightFor15%0A addUpTheOddDigits = everyOddFromFarRightButOneFor14%0A else:%0A return(False)%0A # select the items for doubling%0A for each in doubleList:%0A doubleThis = cardNumber%5Beach%5D%0A doubleThis = int(doubleThis) * 2%0A nowDoubled = str(doubleThis)%0A # add single digit items to the doubleSet%0A if (len(nowDoubled) == 1):%0A nowDoubled = nowDoubled%0A doubleSet.append(nowDoubled)%0A else:%0A # add each digit of 2-digit items to each other %0A # and then add each item to the the doubleSet%0A db1, db2 = nowDoubled%5B0%5D, nowDoubled%5B1%5D%0A db1, db2 = int(db1), int(db2)%0A dbladd = db1 + db2%0A doubleSet.append(dbladd)%0A # add all items in the doubleSet together%0A for each in doubleSet:%0A addUpDoubles += int(each)%0A # add together all items not previously doubled %0A for each in addUpTheOddDigits:%0A addOther = cardNumber%5Beach%5D%0A otherToAdd = int(addOther)%0A addUpOthers += otherToAdd%0A # add all the summed up additions together %0A totalSum = int(addUpDoubles) + int(addUpOthers)%0A # multiply totalSum by 9, then Modulus '%25' that number by 10%0A totalSumTimesNine = (totalSum * 9)%0A modTheTotalSum = (totalSumTimesNine %25 10)%0A # compare modTheTotalSum to the right-most digit of cardNumber %0A if (str(modTheTotalSum) == cardNumber%5B-1%5D):%0A return(True)%0A else:%0A return(False)%0A
be271f41103efdc26aadbc2cf3e39446bf2a05bc
Define Application class.
taxe/__init__.py
taxe/__init__.py
Python
0
@@ -0,0 +1,620 @@ +# -*- coding: utf-8 -*-%0A%0Afrom functools import wraps%0Afrom werkzeug.wrappers import Request, Response%0A%0Aclass Application(object):%0A%0A def route(self, url):%0A def deco(function):%0A @wraps(function)%0A def _(*args, **kwargs):%0A print self, url%0A return function(*args, **kwargs)%0A return _%0A return deco%0A%0A @Request.application%0A def __call__(self, request):%0A return Response('Hello World')%0A%0Aif __name__ == '__main__':%0A from werkzeug.serving import run_simple%0A application = Application()%0A run_simple('localhost', 4000, application)%0A
d0c7dfad3e7769b6f89828733414a4a68677696a
Create UnorderedList.py
Python/GenPythonProblems/UnorderedList.py
Python/GenPythonProblems/UnorderedList.py
Python
0
@@ -0,0 +1,1959 @@ +## http://interactivepython.org/runestone/static/pythonds/BasicDS/ImplementinganUnorderedListLinkedLists.html%0Aclass Node:%0A def __init__(self,initdata):%0A self.data = initdata%0A self.next = None%0A%0A def getData(self):%0A return self.data%0A%0A def getNext(self):%0A return self.next%0A%0A def setData(self,newdata):%0A self.data = newdata%0A%0A def setNext(self,newnext):%0A self.next = newnext%0A%0A%0Aclass UnorderedList:%0A%0A def __init__(self):%0A self.head = None%0A%0A def isEmpty(self):%0A return self.head == None%0A%0A def add(self,item):%0A temp = Node(item)%0A temp.setNext(self.head)%0A self.head = temp%0A%0A def size(self):%0A current = self.head%0A count = 0%0A while current != None:%0A count = count + 1%0A current = current.getNext()%0A%0A return count%0A%0A def search(self,item):%0A current = self.head%0A found = False%0A while current != None and not found:%0A if current.getData() == item:%0A found = True%0A else:%0A current = current.getNext()%0A%0A return found%0A%0A def remove(self,item):%0A current = self.head%0A previous = None%0A found = False%0A while not found:%0A if current.getData() == item:%0A found = True%0A else:%0A previous = current%0A current = current.getNext()%0A%0A if previous == None:%0A self.head = current.getNext()%0A else:%0A previous.setNext(current.getNext())%0A%0Amylist = UnorderedList()%0A%0Amylist.add(31)%0Amylist.add(77)%0Amylist.add(17)%0Amylist.add(93)%0Amylist.add(26)%0Amylist.add(54)%0A%0Aprint(mylist.size())%0Aprint(mylist.search(93))%0Aprint(mylist.search(100))%0A%0Amylist.add(100)%0Aprint(mylist.search(100))%0Aprint(mylist.size())%0A%0Amylist.remove(54)%0Aprint(mylist.size())%0Amylist.remove(93)%0Aprint(mylist.size())%0Amylist.remove(31)%0Aprint(mylist.size())%0Aprint(mylist.search(93))%0A
6ac4db0b9bfc638d708fd7341b0f3e1437ce8f97
add dir cmmbbo to hold code for docker scheduler
cmbbo/main.py
cmbbo/main.py
Python
0
@@ -0,0 +1,15 @@ +#coding: utf-8%0A
4f06672cb18673941f625987b51b9fabe57ea8ac
find kth smallest
Python/search/find_kthsmallest.py
Python/search/find_kthsmallest.py
Python
0.999975
@@ -0,0 +1,399 @@ +'''%0AFind the kth smallest element in an unsorted array%0A'''%0Aimport heapq%0Adef kth_smallest(arr, k):%0A%0A # O(n) complexity%0A heapq.heapify(arr)%0A%0A # k*log(n)%0A for _ in range(k-1):%0A # log(n)%0A heapq.heappop(arr)%0A return heapq.heappop(arr)%0A%0A%0Aassert kth_smallest(%5B5, 4, 3, 1, 10%5D, 1) == 1%0Aassert kth_smallest(%5B5, 4, 3, 1, 10%5D, 2) == 3%0Aassert kth_smallest(%5B5, 4, 3, 1, 10%5D, 3) == 4%0A
4ab45fc2dee8676566467706c0a433315c8fe3c8
Add test
skbio/util/tests/test_testing.py
skbio/util/tests/test_testing.py
Python
0
@@ -0,0 +1,675 @@ +# ----------------------------------------------------------------------------%0A# Copyright (c) 2013--, scikit-bio development team.%0A#%0A# Distributed under the terms of the Modified BSD License.%0A#%0A# The full license is in the file COPYING.txt, distributed with this software.%0A# ----------------------------------------------------------------------------%0A%0Aimport os%0A%0Aimport numpy.testing as npt%0A%0Afrom skbio.util.testing import get_data_path%0A%0A%0Adef test_get_data_path():%0A fn = 'parrot'%0A path = os.path.dirname(os.path.abspath(__file__))%0A data_path = os.path.join(path, 'data', fn)%0A data_path_2 = get_data_path(fn)%0A npt.assert_string_equal(data_path_2, data_path)%0A%0A
ce3a5186c8522cb0e8a2f3aa5e843846bb7f4e27
Remove whitespace from the beginning and the end of the string
techgig_strip.py
techgig_strip.py
Python
0.999807
@@ -0,0 +1,57 @@ +def main():%0A a=raw_input()%0A print a.strip()%0Amain()%0A
ac85219bec0eea5619ebec802e74382399b0f87c
Add a VERY simple redis returner
salt/returners/redis.py
salt/returners/redis.py
Python
0.00003
@@ -0,0 +1,573 @@ +'''%0AReturn data to a redis server%0AThis is a VERY simple example for pushing data to a redis server and is not%0Anessisarily intended as a usable interface.%0A'''%0A%0Aimport redis%0A%0A__opts__ = %7B%0A 'redis.host': 'mcp',%0A 'redis.port': 6379,%0A 'redis.db': '0',%0A %7D%0A%0Adef returner(ret):%0A '''%0A Return data to a redis data store%0A '''%0A serv = redis.Redis(%0A host=__opts__%5B'redis.host'%5D,%0A port=__opts__%5B'redis.port'%5D,%0A db=__opts__%5B'redis.db'%5D)%0A serv.set(ret%5B'id'%5D + ':' + red%5B'jid'%5D, str(ret%5B'return'%5D))%0A
dfdaac63df7e4d8b381215fafd1f88c2af4781f2
Update __openerp__.py
sale_product_variants_types/__openerp__.py
sale_product_variants_types/__openerp__.py
# -*- encoding: utf-8 -*- ############################################################################## # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see http://www.gnu.org/licenses/. # ############################################################################## { "name": "Sale product variants types", "version": "1.0", "depends": [ "sale_product_variants", "product_attribute_types", ], "author": "OdooMRP team", "contributors": [ "Oihane Crucelaegui <oihanecrucelaegi@avanzosc.es>", ], "category": "Hidden/Dependency", "website": "http://www.odoomrp.com", "summary": "", "description": """ This module extends product variants on sales. It adds the possibility of defining a custom value when the attribute is range type. """, "data": [ "views/sale_order_view.xml", ], "installable": True, "auto_install": True, }
Python
0.000024
@@ -1377,16 +1377,19 @@ bute is +of range ty
96bbf25be25482a7edfd92ec9b956b0bbeab39c4
Add a basic summary query implementation
src/traffic/__init__.py
src/traffic/__init__.py
Python
0.003632
@@ -0,0 +1,1834 @@ +from datetime import datetime%0Aimport zmq%0A%0Afrom messages import common_pb2, replies_pb2, requests_pb2%0A%0A%0Aclass Connection(object):%0A def __init__(self, uri, context=None):%0A self._uri = uri%0A if context is None:%0A context = zmq.Context()%0A self._context = context%0A self._socket = self._context.socket(zmq.REQ)%0A self._connected = False%0A%0A def connect(self):%0A assert not self._connected%0A self._socket.connect(self._uri)%0A self._connected = True%0A%0A def disconnect(self):%0A assert self._connected%0A self._socket.disconnect(self._uri)%0A self._connected = False%0A%0A def __enter__(self):%0A self.connect()%0A return self%0A%0A def __exit__(self, type, value, traceback):%0A self.disconnect()%0A%0A def send_msg(self, msg):%0A assert self._connected%0A assert isinstance(msg, requests_pb2.Request)%0A%0A self._socket.send(msg.SerializeToString())%0A reply = replies_pb2.Reply()%0A reply.ParseFromString(self._socket.recv())%0A return reply%0A%0A%0Adef get_summary_unix(conn, interval_start, interval_end, clients):%0A assert interval_start %3C interval_end;%0A assert len(clients) != 0%0A %0A request = requests_pb2.Request()%0A request.version=1%0A%0A message = request.summary%0A message.range.start = interval_start%0A message.range.end = interval_end%0A%0A message.addresses.extend(clients)%0A%0A reply = conn.send_msg(request)%0A%0A return reply.summary%0A%0A%0Adef get_summary(conn, interval_start, interval_end, clients):%0A assert isinstance(interval_start, datetime)%0A assert isinstance(interval_end, datetime)%0A%0A epoch = datetime(1970,1,1)%0A return get_summary_unix(conn,%0A int((interval_start - epoch).total_seconds()),%0A int((interval_end - epoch).total_seconds()),%0A clients)%0A%0A
4060a7d2c9ec0b6701d36184fe3e2bad71744730
Fix --verbose bug
vint/__init__.py
vint/__init__.py
import sys from argparse import ArgumentParser import pkg_resources import logging from vint.linting.linter import Linter from vint.linting.env import build_environment from vint.linting.config.config_container import ConfigContainer from vint.linting.config.config_cmdargs_source import ConfigCmdargsSource from vint.linting.config.config_default_source import ConfigDefaultSource from vint.linting.config.config_global_source import ConfigGlobalSource from vint.linting.config.config_project_source import ConfigProjectSource from vint.linting.policy_set import PolicySet from vint.linting.formatter.formatter import Formatter from vint.linting.formatter.json_formatter import JSONFormatter from vint.linting.formatter.statistic_formatter import StatisticFormatter LOG_FORMAT = 'vint %(levelname)s: %(message)s' def main(): env = _build_env(sys.argv) config_dict = _build_config_dict(env) parser = _build_argparser() _init_logger(config_dict) paths_to_lint = env['file_paths'] if len(paths_to_lint) == 0: logging.error('nothing to check') parser.print_help() parser.exit(status=1) for path_to_lint in paths_to_lint: if not path_to_lint.exists() or not path_to_lint.is_file(): logging.error('no such file or directory: `{path}`'.format( path=str(path_to_lint))) parser.exit(status=1) violations = _lint_all(paths_to_lint, config_dict) if len(violations) == 0: parser.exit(status=0) _print_violations(violations, config_dict) parser.exit(status=1) def _init_logger(config_dict): cmdargs = config_dict['cmdargs'] log_level = logging.DEBUG if 'verbose' in cmdargs else logging.WARNING logging.basicConfig(format=LOG_FORMAT, level=log_level) def _build_config_dict(env): config = ConfigContainer( ConfigDefaultSource(env), ConfigGlobalSource(env), ConfigProjectSource(env), ConfigCmdargsSource(env), ) return config.get_config_dict() def _build_argparser(): parser = ArgumentParser(prog='vint', description='Lint Vim script') parser.add_argument('-v', '--version', action='version', version=_get_version()) parser.add_argument('-V', '--verbose', action='store_true', help='output verbose message') parser.add_argument('-e', '--error', action='store_true', help='report only errors') parser.add_argument('-w', '--warning', action='store_true', help='report errors and warnings') parser.add_argument('-s', '--style-problem', action='store_true', help='report errors, warnings and style problems') parser.add_argument('-m', '--max-violations', type=int, help='limit max violations count') parser.add_argument('-c', '--color', action='store_true', help='colorize output when possible') parser.add_argument('-j', '--json', action='store_true', help='output json style') parser.add_argument('-t', '--stat', action='store_true', help='output statistic info') parser.add_argument('files', nargs='*', help='file or directory path to lint') return parser def _build_cmdargs(argv): """ Build command line arguments dict to use; - displaying usages - vint.linting.env.build_environment This method take an argv parameter to make function pure. """ parser = _build_argparser() namespace = parser.parse_args(argv[1:]) cmdargs = vars(namespace) return cmdargs def _build_env(argv): """ Build an environment object. This method take an argv parameter to make function pure. """ cmdargs = _build_cmdargs(argv) env = build_environment(cmdargs) return env def _build_linter(config_dict): policy_set = PolicySet() linter = Linter(policy_set, config_dict) return linter def _lint_all(paths_to_lint, config_dict): violations = [] linter = _build_linter(config_dict) for file_path in paths_to_lint: violations += linter.lint_file(file_path) return violations def _get_formatter(config_dict): if 'cmdargs' not in config_dict: return Formatter(config_dict) cmdargs = config_dict['cmdargs'] if 'json' in cmdargs and cmdargs['json']: return JSONFormatter(config_dict) elif 'stat' in cmdargs and cmdargs['stat']: return StatisticFormatter(config_dict) else: return Formatter(config_dict) def _print_violations(violations, config_dict): formatter = _get_formatter(config_dict) output = formatter.format_violations(violations) print(output) def _get_version(): version = pkg_resources.require('vim-vint')[0].version return version
Python
0.000002
@@ -1643,24 +1643,71 @@ 'cmdargs'%5D%0A%0A + is_verbose = cmdargs.get('verbose', False)%0A log_leve @@ -1731,28 +1731,18 @@ if -' +is_ verbose -' in cmdargs els
cdee6a6a568576a2afbf72014c3cc0eb6b5d2afe
Make sure feed and exec info doesn't get added to webui log records that are created while a feed is executing.
flexget/logger.py
flexget/logger.py
import logging import logging.handlers import re class FlexGetLogger(logging.Logger): """Custom logger that adds feed and execution info to log records.""" execution = '' feed = '' def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None): extra = {'feed': FlexGetLogger.feed, 'execution': FlexGetLogger.execution} return logging.Logger.makeRecord(self, name, level, fn, lno, msg, args, exc_info, func, extra) class FlexGetFormatter(logging.Formatter): """Custom formatter that can handle both regular log records and those created by FlexGetLogger""" plain_fmt = '%(asctime)-15s %(levelname)-8s %(name)-29s %(message)s' flexget_fmt = '%(asctime)-15s %(levelname)-8s %(name)-13s %(feed)-15s %(message)s' def __init__(self): logging.Formatter.__init__(self, self.plain_fmt, '%Y-%m-%d %H:%M') def format(self, record): if hasattr(record, 'feed'): self._fmt = self.flexget_fmt else: self._fmt = self.plain_fmt return logging.Formatter.format(self, record) def set_execution(execution): FlexGetLogger.execution = execution def set_feed(feed): FlexGetLogger.feed = feed class PrivacyFilter(logging.Filter): """Edits log messages and <hides> obviously private information.""" def __init__(self): self.replaces = [] def hide(name): s = '([?&]%s=)\w+' % name p = re.compile(s) self.replaces.append(p) for param in ['passwd', 'password', 'pw', 'pass', 'passkey', \ 'key', 'apikey', 'user', 'username', 'uname', 'login', 'id']: hide(param) def filter(self, record): if not isinstance(record.msg, basestring): return False for p in self.replaces: record.msg = p.sub(r'\g<1><hidden>', record.msg) record.msg = record.msg return False _logging_configured = False _mem_handler = None _logging_started = False def initialize(unit_test=False): global _logging_configured, _mem_handler if not _logging_configured: logging.addLevelName(5, 'DEBUGALL') _logging_configured = True if unit_test: logging.basicConfig() return # root logger logger = logging.getLogger() formatter = FlexGetFormatter() _mem_handler = logging.handlers.MemoryHandler(1000 * 1000, 100) _mem_handler.setFormatter(formatter) logger.addHandler(_mem_handler) # hackish way to turn on debug level before optik processes options import sys if '--debug' in sys.argv: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) def start(filename=None, level=logging.INFO, debug=False, quiet=False): global _logging_configured, _mem_handler, _logging_started if not _logging_started: if debug: hdlr = logging.StreamHandler() else: hdlr = logging.handlers.RotatingFileHandler(filename, maxBytes=1000 * 1024, backupCount=9) hdlr.setFormatter(_mem_handler.formatter) _mem_handler.setTarget(hdlr) # root logger logger = logging.getLogger() logger.removeHandler(_mem_handler) logger.addHandler(hdlr) logger.addFilter(PrivacyFilter()) logger.setLevel(level) logger.getEffectiveLevel() if not debug and not quiet: console = logging.StreamHandler() console.setFormatter(hdlr.formatter) logger.addHandler(console) # flush memory handler to the console without # destroying the buffer if len(_mem_handler.buffer) > 0: for record in _mem_handler.buffer: console.handle(record) # flush what we have stored from the plugin initialization _mem_handler.flush() _logging_started = True def flush(): """Flushes memory logger to console""" console = logging.StreamHandler() console.setFormatter(_mem_handler.formatter) logger = logging.getLogger() logger.addHandler(console) if len(_mem_handler.buffer) > 0: for record in _mem_handler.buffer: console.handle(record) _mem_handler.flush() # Set our custom logger class as default logging.setLoggerClass(FlexGetLogger)
Python
0.000002
@@ -45,16 +45,34 @@ ort re%0D%0A +import threading%0D%0A %0D%0A%0D%0Aclas @@ -188,37 +188,33 @@ -execution = ''%0D%0A feed = '' +local = threading.local() %0D%0A%0D%0A @@ -331,16 +331,24 @@ 'feed': +getattr( FlexGetL @@ -353,20 +353,34 @@ tLogger. -feed +local, 'feed', '') ,%0D%0A @@ -404,16 +404,24 @@ ution': +getattr( FlexGetL @@ -418,32 +418,40 @@ r(FlexGetLogger. +local, ' execution%7D%0D%0A @@ -443,16 +443,22 @@ xecution +', '') %7D%0D%0A @@ -1248,16 +1248,22 @@ tLogger. +local. executio @@ -1320,16 +1320,22 @@ tLogger. +local. feed = f
e9f88f1c43189fe429730c488f4514bf78edea4e
Add python -m mistune cli
mistune/__main__.py
mistune/__main__.py
Python
0.000003
@@ -0,0 +1,2338 @@ +import sys%0Aimport argparse%0Afrom . import (%0A create_markdown,%0A __version__ as version%0A)%0A%0A%0Adef _md(args):%0A if args.plugin:%0A plugins = args.plugin%0A else:%0A # default plugins%0A plugins = %5B'strikethrough', 'footnotes', 'table', 'speedup'%5D%0A return create_markdown(%0A escape=args.escape,%0A hard_wrap=args.hardwrap,%0A renderer=args.renderer,%0A plugins=plugins,%0A )%0A%0A%0Adef _output(text, args):%0A if args.output:%0A with open(args.output, 'w') as f:%0A f.write(text)%0A else:%0A print(text)%0A%0A%0ACMD_HELP = '''Mistune, a sane and fast python markdown parser.%0A%0AHere are some use cases of the command line tool:%0A%0A $ python -m mistune -m %22Hi **Markdown**%22%0A %3Cp%3EHi %3Cstrong%3EMarkdown%3C/strong%3E%3C/p%3E%0A%0A $ python -m mistune -f README.md%0A %3Cp%3E...%0A'''%0A%0A%0Adef cli():%0A parser = argparse.ArgumentParser(%0A prog='python -m mistune',%0A description=CMD_HELP,%0A formatter_class=argparse.RawDescriptionHelpFormatter,%0A )%0A parser.add_argument(%0A '-m', '--message',%0A help='the markdown message to conver',%0A )%0A parser.add_argument(%0A '-f', '--file',%0A help='the markdown file to convert',%0A )%0A parser.add_argument(%0A '-p', '--plugin',%0A metavar='NAME',%0A action='extend',%0A nargs='+',%0A help='specifiy a plugin to use',%0A )%0A parser.add_argument(%0A '--escape',%0A action='store_true',%0A help='turn on escape option',%0A )%0A parser.add_argument(%0A '--hardwrap',%0A action='store_true',%0A help='turn on hardwrap option',%0A )%0A parser.add_argument(%0A '-o', '--output',%0A help='write the rendered result into file',%0A )%0A parser.add_argument(%0A '-r', '--renderer',%0A default='html',%0A help='specify the output renderer',%0A )%0A parser.add_argument('--version', action='version', version='mistune ' + version)%0A args = parser.parse_args()%0A%0A if not args.message and not args.file:%0A print('You MUST specify a message or file')%0A return sys.exit(1)%0A%0A if args.message:%0A md = _md(args)%0A text = md(args.message)%0A _output(text, args)%0A elif args.file:%0A md = _md(args)%0A text = md.read(args.file)%5B0%5D%0A _output(text, args)%0A%0A%0Aif __name__ == '__main__':%0A cli()%0A
4af4d5d293d057bd12454200e7a1a72679c218a5
Create zipatoconnection.py
src/zipatoconnection.py
src/zipatoconnection.py
Python
0.000004
@@ -0,0 +1,492 @@ +import requests%0A%0Aclass ZipatoConnection(Settings):%0A%0A __init__(self, serial):%0A %22%22%22%0A Initializes a ZipatoConnection.%0A %0A :param str serial: Zipato Box serial.%0A %0A %22%22%22%0A self.serial = serial%0A %0A def set_sensor_status(self, ep, apikey, status):%0A %22%22%22%0A Set status of a sensor.%0A %0A :param str ep: Target ep.%0A :param str ep: Target apikey.%0A :param bool ep: Status value to set the sensor to.%0A %0A %22%22%22%0A %0A
d0e2daf892de6b35ba90926f446c70ec3079f468
Update version.
__init__.py
__init__.py
# -*- coding: utf-8 -*- """Kernel of Pyslvs. This kernel can work without GUI. Modules: + Solver: + parser + tinycadlib + Sketch Solve solver + triangulation + Number synthesis: + number + Structure Synthesis: + atlas + Dimensional synthesis: + planarlinkage + rga + firefly + de Dependents: + lark-parser + pygments (optional: provide highlighting) """ __author__ = "Yuan Chang" __copyright__ = "Copyright (C) 2016-2019" __license__ = "AGPL" __email__ = "pyslvs@gmail.com" __version__ = (19, 3, 0, 'release') __version_str__ = f"{__version__[0]}.{__version__[1]:02d}.{__version__[2]} ({__version__[3]})" from .expression import ( get_vlinks, VJoint, VPoint, VLink, Coordinate, ) from .bfgs import vpoint_solving from .triangulation import vpoints_configure, ExpressionStack from .tinycadlib import ( plap, pllp, plpp, pxy, vpoint_dof, expr_parser, expr_solving, data_collecting, ) from .verify import Verification from .planar_linkage import Planar from .rga import Genetic from .firefly import Firefly from .de import Differential from .number import number_synthesis, contracted_link from .graph import ( Graph, link_assortments, contracted_link_assortments, ) from .planar_check import is_planar from .graph_layout import external_loop_layout from .atlas import topo from .expression_parser import ( color_names, color_rgb, parse_params, parse_pos, parse_vpoints, parse_vlinks, edges_view, graph2vpoints, HAS_PYGMENTS, ) from .example import example_list from .collection import collection_list if HAS_PYGMENTS: from .expression_parser import PMKSLexer __all__ = [ '__version__', '__version_str__', 'Genetic', 'Firefly', 'Differential', 'Coordinate', 'plap', 'pllp', 'plpp', 'pxy', 'expr_parser', 'expr_solving', 'data_collecting', 'get_vlinks', 'VJoint', 'VPoint', 'VLink', 'vpoint_solving', 'Planar', 'number_synthesis', 'contracted_link', 'is_planar', 'external_loop_layout', 'topo', 'Graph', 'link_assortments', 'contracted_link_assortments', 'vpoints_configure', 'ExpressionStack', 'vpoint_dof', 'color_names', 'color_rgb', 'parse_params', 'parse_pos', 'parse_vpoints', 'parse_vlinks', 'edges_view', 'graph2vpoints', 'PMKSLexer', 'example_list', 'collection_list', 'Verification', ]
Python
0
@@ -539,22 +539,18 @@ 19, -3 +4 , 0, ' -release +dev ')%0A_
3e345bc4a17cf53c40ef51cd2ae1732744be7e60
Add custom form for editing and updating of decks
cardbox/deck_forms.py
cardbox/deck_forms.py
Python
0
@@ -0,0 +1,442 @@ +from django.forms import ModelForm%0Afrom django.forms.widgets import Textarea, TextInput%0Afrom deck_model import Deck%0A%0Aclass DeckForm(ModelForm):%0A %22%22%22The basic form for updating or editing decks%22%22%22%0A%0A class Meta:%0A model = Deck%0A fields = ('title', 'description')%0A widgets = %7B%0A 'title': TextInput(attrs=%7B'class': %22form-control%22%7D),%0A 'description': Textarea(attrs=%7B'class': %22form-control%22%7D)%0A %7D
95d93518d664c9d8b095061bc854907c29f05623
Add dummy keygen
tests/__init__.py
tests/__init__.py
Python
0.000001
@@ -0,0 +1,1941 @@ +from cryptography.hazmat.backends import default_backend%0Afrom cryptography.hazmat.primitives.asymmetric import rsa, padding%0Afrom cryptography.hazmat.primitives.serialization import Encoding, PrivateFormat, PublicFormat, BestAvailableEncryption%0Aimport os%0A%0Af4 = 65537%0A%0Aos.environ%5B'EQ_PUBLIC_KEY'%5D = './jwt-test-keys/sr-public.pem'%0Aos.environ%5B'EQ_PRIVATE_KEY'%5D = './jwt-test-keys/sr-private.pem'%0A%0Aos.environ%5B'PUBLIC_KEY'%5D = './jwt-test-keys/sdx-public.pem'%0Aos.environ%5B'PRIVATE_KEY'%5D = './jwt-test-keys/sdx-private.pem'%0Aos.environ%5B'PRIVATE_KEY_PASSWORD'%5D = %22digitaleq%22%0A%0Abackend = default_backend()%0A%0Aeq_private_key = rsa.generate_private_key(%0A public_exponent=f4,%0A key_size=3072,%0A backend=default_backend()%0A)%0A%0Aeq_private_bytes = eq_private_key.private_bytes(%0A encoding=Encoding.PEM,%0A format=PrivateFormat.TraditionalOpenSSL,%0A encryption_algorithm=BestAvailableEncryption(b'digitaleq')%0A)%0A%0Aeq_public_key = eq_private_key.public_key().public_bytes(%0A encoding=Encoding.PEM,%0A format=PublicFormat.SubjectPublicKeyInfo%0A)%0A%0Aif not os.path.exists('./jwt-test-keys'):%0A os.mkdir('./jwt-test-keys')%0A%0Af = open('./jwt-test-keys/sr-public.pem', 'w')%0Af.write(eq_public_key.decode('UTF8'))%0Af.close()%0A%0Af = open('./jwt-test-keys/sr-private.pem', 'w')%0Af.write(eq_private_bytes.decode('UTF8'))%0Af.close()%0A%0Asde_private_key = rsa.generate_private_key(%0A public_exponent=f4,%0A key_size=3072,%0A backend=default_backend()%0A)%0A%0Asde_private_bytes = sde_private_key.private_bytes(%0A encoding=Encoding.PEM,%0A format=PrivateFormat.TraditionalOpenSSL,%0A encryption_algorithm=BestAvailableEncryption(b'digitaleq')%0A)%0A%0Asde_public_key = sde_private_key.public_key().public_bytes(%0A encoding=Encoding.PEM,%0A format=PublicFormat.SubjectPublicKeyInfo%0A)%0A%0Af = open('./jwt-test-keys/sdx-public.pem', 'w')%0Af.write(sde_public_key.decode('UTF8'))%0Af.close()%0A%0Af = open('./jwt-test-keys/sdx-private.pem', 'w')%0Af.write(sde_private_bytes.decode('UTF8'))%0Af.close()
fa8b40b8ebc088f087ff76c36068fea67dae0824
Add management command for updating genome coordinate names using Ensembl-INSDC mapping
rnacentral/portal/management/commands/update_coordinate_names.py
rnacentral/portal/management/commands/update_coordinate_names.py
Python
0
@@ -0,0 +1,1259 @@ +%22%22%22%0ACopyright %5B2009-2017%5D EMBL-European Bioinformatics Institute%0ALicensed under the Apache License, Version 2.0 (the %22License%22);%0Ayou may not use this file except in compliance with the License.%0AYou may obtain a copy of the License at%0A http://www.apache.org/licenses/LICENSE-2.0%0AUnless required by applicable law or agreed to in writing, software%0Adistributed under the License is distributed on an %22AS IS%22 BASIS,%0AWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0ASee the License for the specific language governing permissions and%0Alimitations under the License.%0A%22%22%22%0A%0Afrom django.core.management.base import BaseCommand%0Afrom django.db import connection%0A%0A%0Aclass Command(BaseCommand):%0A %22%22%22%0A Usage:%0A python manage.py update_coordinate_names%0A %22%22%22%0A def handle(self, *args, **options):%0A %22%22%22%0A Main function, called by django.%0A %22%22%22%0A sql = %22%22%22%0A UPDATE rnc_coordinates a%0A SET%0A %09name = b.ensembl_name,%0A %09primary_start = local_start,%0A %09primary_end = local_end%0A FROM ensembl_insdc_mapping b%0A WHERE%0A a.primary_accession = b.insdc%0A AND a.name IS NULL%0A %22%22%22%0A with connection.cursor() as cursor:%0A cursor.execute(sql)%0A
6418807dbba9fb946ffeb05aee525c51c2e71f75
Fix fixture, add doc string
tests/fixtures.py
tests/fixtures.py
Python
0
@@ -0,0 +1,344 @@ +%22%22%22Defines fixtures that can be used to streamline tests and / or define dependencies%22%22%22%0Afrom random import randint%0A%0Aimport pytest%0A%0Aimport hug%0A%0A%0A@pytest.fixture%0Adef hug_api():%0A %22%22%22Defines a dependency for and then includes a uniquely identified hug API for a single test case%22%22%22%0A return hug.API('fake_api_%7B%7D'.format(randint(0, 1000000)))%0A
47c1dfd602281c56973de0d8afe64b923eb29592
Add unit tests for env module.
test/test_env.py
test/test_env.py
Python
0
@@ -0,0 +1,735 @@ +from _ebcf_alexa import env%0Afrom unittest.mock import patch, call%0Aimport pytest%0A%0A%0A@pytest.yield_fixture%0Adef mock_now():%0A with patch.object(env, 'now') as now:%0A yield now%0A%0A%0A@patch('datetime.datetime')%0Adef test_now_is_utc(fake_datetime):%0A assert env.now()%0A assert fake_datetime.now.call_args == call(tz=env.UTC)%0A%0A%0Adef test_local_now(mock_now):%0A assert env.localnow() == mock_now.return_value.astimezone.return_value%0A assert mock_now.return_value.astimezone.call_args == call(env.TZ)%0A%0A%0Adef test_date(mock_now):%0A assert env.date() == mock_now.return_value.date.return_value%0A%0A%0Adef test_local_date():%0A with patch.object(env, 'localnow') as ln:%0A assert env.localdate() == ln.return_value.date.return_value%0A%0A
c727cee4dc579f5fe09b54877118a681a2597c47
add tests for log module
test/test_log.py
test/test_log.py
Python
0.000001
@@ -0,0 +1,473 @@ +%22%22%22Test for custom logging functions.%22%22%22%0A%0Aimport logging%0A%0Afrom mapchete.log import user_process_logger, driver_logger%0A%0A%0Adef test_user_process_logger():%0A logger = user_process_logger(__name__)%0A assert isinstance(logger, logging.Logger)%0A assert logger.name == %22mapchete.user_process.test_log%22%0A%0A%0Adef test_driver_logger():%0A logger = driver_logger(__name__)%0A assert isinstance(logger, logging.Logger)%0A assert logger.name == %22mapchete.formats.drivers.test_log%22%0A
fc9e9b4b9bdee1bd1f6b112c90772702cf60ad2d
Add a unittest-based test suite for scenarios
test_converge.py
test_converge.py
Python
0.999868
@@ -0,0 +1,1697 @@ +#!/usr/bin/env python%0A%0Aimport functools%0Aimport logging%0Aimport unittest%0A%0Aimport converge%0Aimport converge.processes%0A%0Afrom converge.framework import datastore%0Afrom converge.framework import scenario%0A%0A%0Adef with_scenarios(TestCase):%0A loader = unittest.defaultTestLoader%0A%0A def create_test_func(generic_test, params):%0A @functools.wraps(generic_test)%0A def test_func(testcase, *args, **kwargs):%0A for key, value in params.items():%0A setattr(testcase, key, value)%0A return generic_test(testcase, *args, **kwargs)%0A%0A return test_func%0A%0A for test_name in loader.getTestCaseNames(TestCase):%0A base_test = getattr(TestCase, test_name)%0A%0A for scenario in getattr(TestCase, 'scenarios', %5B%5D):%0A name, parameters = scenario%0A%0A test_func = create_test_func(base_test, parameters)%0A setattr(TestCase, '%25s(%25s)' %25 (test_name, name), test_func)%0A%0A delattr(TestCase, test_name)%0A%0A TestCase.scenarios = None%0A return TestCase%0A%0A%0A@with_scenarios%0Aclass ScenarioTest(unittest.TestCase):%0A%0A scenarios = %5B(name, %7B'name': name, 'path': path%7D)%0A for name, path in scenario.list_all('scenarios')%5D%0A%0A def setUp(self):%0A super(ScenarioTest, self).setUp()%0A self.procs = converge.processes.Processes()%0A%0A def tearDown(self):%0A datastore.Datastore.clear_all()%0A super(ScenarioTest, self).tearDown()%0A%0A def test_scenario(self):%0A runner = scenario.Scenario(self.name, self.path)%0A runner(self.procs.event_loop,%0A **converge.scenario_globals(self.procs, self))%0A%0A%0Aif __name__ == '__main__':%0A #converge.setup_log(logging.root)%0A unittest.main()%0A
6bd2371c1e48d7886e3515b7f2f95d0f7dbdf6c7
Remove this one noisy debug statement.
fedmsg/utils.py
fedmsg/utils.py
# This file is part of fedmsg. # Copyright (C) 2012 Red Hat, Inc. # # fedmsg 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. # # fedmsg 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 fedmsg; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Authors: Ralph Bean <rbean@redhat.com> # import zmq import logging import inspect try: from collections import OrderedDict except ImportError: from ordereddict import OrderedDict _log = logging.getLogger('fedmsg') def set_high_water_mark(socket, config): """ Set a high water mark on the zmq socket. Do so in a way that is cross-compatible with zeromq2 and zeromq3. """ if config['high_water_mark']: if hasattr(zmq, 'HWM'): # zeromq2 socket.setsockopt(zmq.HWM, config['high_water_mark']) else: # zeromq3 socket.setsockopt(zmq.SNDHWM, config['high_water_mark']) socket.setsockopt(zmq.RCVHWM, config['high_water_mark']) # TODO -- this should be in kitchen, not fedmsg def guess_calling_module(default=None): # Iterate up the call-stack and return the first new top-level module for frame in (f[0] for f in inspect.stack()): modname = frame.f_globals['__name__'].split('.')[0] if modname != "fedmsg": return modname # Otherwise, give up and just return the default. return default def set_tcp_keepalive(socket, config): """ Set a series of TCP keepalive options on the socket if and only if 1) they are specified explicitly in the config and 2) the version of pyzmq has been compiled with support We ran into a problem in FedoraInfrastructure where long-standing connections between some hosts would suddenly drop off the map silently. Because PUB/SUB sockets don't communicate regularly, nothing in the TCP stack would automatically try and fix the connection. With TCP_KEEPALIVE options (introduced in libzmq 3.2 and pyzmq 2.2.0.1) hopefully that will be fixed. See the following - http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html - http://api.zeromq.org/3-2:zmq-setsockopt """ keepalive_options = { # Map fedmsg config keys to zeromq socket constants 'zmq_tcp_keepalive': 'TCP_KEEPALIVE', 'zmq_tcp_keepalive_cnt': 'TCP_KEEPALIVE_CNT', 'zmq_tcp_keepalive_idle': 'TCP_KEEPALIVE_IDLE', 'zmq_tcp_keepalive_intvl': 'TCP_KEEPALIVE_INTVL', } for key, const in keepalive_options.items(): if key in config: attr = getattr(zmq, const, None) if attr: _log.debug("Setting %r %r" % (const, config[key])) socket.setsockopt(attr, config[key]) def load_class(location): """ Take a string of the form 'fedmsg.consumers.ircbot:IRCBotConsumer' and return the IRCBotConsumer class. """ mod_name, cls_name = location = location.strip().split(':') tokens = mod_name.split('.') fromlist = '[]' if tokens > 1: fromlist = '.'.join(tokens[:-1]) module = __import__(mod_name, fromlist=fromlist) try: return getattr(module, cls_name) except AttributeError as e: raise ImportError("%r not found in %r" % (cls_name, mod_name)) def dict_query(dic, query): """ Query a dict with 'dotted notation'. Returns an OrderedDict. A query of "foo.bar.baz" would retrieve 'wat' from this:: dic = { 'foo': { 'bar': { 'baz': 'wat', } } } Multiple queries can be specified if comma-separated. For instance, the query "foo.bar.baz,foo.bar.something_else" would return this:: OrderedDict({ "foo.bar.baz": "wat", "foo.bar.something_else": None, }) """ def _browse(tokens, d): """ Recurse through a dict to retrieve a value. """ current, rest = tokens[0], tokens[1:] if not rest: return d.get(current, None) if current in d: if isinstance(d[current], dict): return _browse(rest, d[current]) elif rest: return None else: return d[current] keys = [key.strip().split('.') for key in query.split(',')] return OrderedDict([ ('.'.join(tokens), _browse(tokens, dic)) for tokens in keys ])
Python
0.000001
@@ -969,45 +969,8 @@ t%0A%0A%0A -_log = logging.getLogger('fedmsg')%0A%0A%0A def @@ -3098,75 +3098,8 @@ tr:%0A - _log.debug(%22Setting %25r %25r%22 %25 (const, config%5Bkey%5D))%0A
f65c6f3939c50326eea14bd0dadc77b7c9364dd2
Add a module to deal with credentials
gssapi/creds.py
gssapi/creds.py
Python
0
@@ -0,0 +1,748 @@ +from __future__ import absolute_import%0A%0Afrom ctypes import cast, byref, c_char_p, c_void_p, string_at%0A%0Afrom .gssapi_h import (%0A GSS_C_NO_CREDENTIAL, GSS_C_NO_NAME, GSS_C_INDEFINITE, GSS_C_NO_OID_SET, GSS_C_BOTH,%0A GSS_S_COMPLETE,%0A OM_uint32, gss_cred_id_t,%0A gss_init_sec_context, gss_accept_sec_context, gss_delete_sec_context, gss_release_buffer,%0A gss_release_cred, gss_release_name%0A)%0Afrom .error import GSSException, GSSMechException%0Afrom .names import MechName%0A%0A%0Aclass Credential(object):%0A %22%22%22Wraps a GSS credential handle (gss_cred_id_t)%22%22%22%0A%0A def __init__(self, desired_name=GSS_C_NO_NAME, time_req=GSS_C_INDEFINITE,%0A desired_mechs=GSS_C_NO_OID_SET, cred_usage=GSS_C_BOTH):%0A super(Credential, self).__init__()%0A
c88b95bd28b1ece65fc4631f73e95dac5b48f038
Add new py-fixtures package (#14026)
var/spack/repos/builtin/packages/py-fixtures/package.py
var/spack/repos/builtin/packages/py-fixtures/package.py
Python
0
@@ -0,0 +1,604 @@ +# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other%0A# Spack Project Developers. See the top-level COPYRIGHT file for details.%0A#%0A# SPDX-License-Identifier: (Apache-2.0 OR MIT)%0A%0Afrom spack import *%0A%0A%0Aclass PyFixtures(PythonPackage):%0A %22%22%22Fixtures, reusable state for writing clean tests and more.%22%22%22%0A%0A homepage = %22https://launchpad.net/python-fixtures%22%0A url = %22https://pypi.io/packages/source/f/fixtures/fixtures-3.0.0.tar.gz%22%0A%0A version('3.0.0', sha256='fcf0d60234f1544da717a9738325812de1f42c2fa085e2d9252d8fff5712b2ef')%0A%0A depends_on('py-setuptools', type='build')%0A
9692c1494e52238fdbc388ef5aba4ae551b46a88
Create ohmycoins.py
ohmycoins.py
ohmycoins.py
Python
0.000003
@@ -0,0 +1,1161 @@ +#!/usr/bin/env python3%0A# -*- coding: utf-8 -*-%0A%0Aimport requests%0Afrom bs4 import BeautifulSoup%0A%0A%0A#Put your Ether addresses here in the list%0Aaddresses = %5B%5D%0A%0A%0A#Etherscan%0Adef get_ether(address):%0A url = 'https://etherscan.io/address/' + address%0A r = requests.get(url)%0A soup = BeautifulSoup(r.text, 'html.parser')%0A eth = soup.find_all('table')%5B0%5D.find_all('td')%5B1%5D.text.replace('%5Cn','').split(' ')%5B0%5D%0A eth = float(eth.replace(',', ''))%0A assets = %7B'ETH': eth%7D%0A balancelist = soup.find(id='balancelist')%0A for i in balancelist.find_all('li')%5B:-1%5D:%0A br = i.a.br.text.split('@')%5B0%5D%0A token = br.split(' ')%5B1%5D%0A amount = float(br.split(' ')%5B0%5D.replace(',', ''))%0A if token in assets.keys():%0A print('Warning: Duplicated token symbol %7B0%7D. Using the first one.'.format(token))%0A continue%0A assets%5Btoken%5D = amount%0A return assets%0A%0A%0Adef dict_add(a, b):%0A for k2, v2 in b.items(): %0A if k2 in a.keys():%0A a%5Bk2%5D += v2%0A else:%0A a%5Bk2%5D = v2%0A return a%0A%0A%0Amycoins = %7B%7D%0Afor address in addresses:%0A assets = get_ether(address)%0A mycoins = dict_add(mycoins, assets)%0A
2ad504a1a40e08aea3105642821190f9b928fab7
create tags package
tags/__init__.py
tags/__init__.py
Python
0.000001
@@ -0,0 +1,30 @@ +VERSION = (0, 1, 0, 'dev', 1)%0A
a317e86e0faab308421588f649f6dd7ba65cd03b
Add rscommon/pickle_.py
rscommon/pickle_.py
rscommon/pickle_.py
Python
0.000001
@@ -0,0 +1,1022 @@ +##########################################%0D%0A# File: pickle_.py #%0D%0A# Copyright Richard Stebbing 2014. #%0D%0A# Distributed under the MIT License. #%0D%0A# (See accompany file LICENSE or copy at #%0D%0A# http://opensource.org/licenses/MIT) #%0D%0A##########################################%0D%0A%0D%0A# Imports%0D%0Aimport cPickle%0D%0A%0D%0A# dump%0D%0Adef dump(path, obj, raise_on_failure=True):%0D%0A own_fid = False%0D%0A if isinstance(path, basestring):%0D%0A path = open(path,'w+b')%0D%0A own_fid = True%0D%0A%0D%0A try:%0D%0A cPickle.dump(obj, path, cPickle.HIGHEST_PROTOCOL)%0D%0A except IOError:%0D%0A if raise_on_failure:%0D%0A raise%0D%0A finally:%0D%0A if own_fid:%0D%0A try:%0D%0A path.close()%0D%0A except IOError:%0D%0A pass%0D%0A%0D%0A# load%0D%0Adef load(file_):%0D%0A own_fid = False%0D%0A if isinstance(file_, basestring):%0D%0A file_ = open(file_,'rb')%0D%0A own_fid = True%0D%0A%0D%0A obj = cPickle.load(file_)%0D%0A%0D%0A if own_fid:%0D%0A file_.close()%0D%0A%0D%0A return obj%0D%0A
2a832e8a9a0881200756db5aa99650745c0ecc16
rename to
tools/packing.py
tools/packing.py
#!/usr/bin/env python import os import shutil import subprocess from contextlib import contextmanager @contextmanager def pushd(path): currentDir = os.getcwd() os.chdir(path) yield os.chdir(currentDir) def printInfo(message): print os.path.basename(__file__) + ' >> ' + message def installDependencies(): printInfo('Start bower install') with pushd('app'): subprocess.check_call('bower install', shell=True) def copy(src, des): printInfo('Copying ' + src + ' to ' + des) if os.path.isdir(src): shutil.copytree(src, des) else: if not os.path.exists(os.path.dirname(des)): os.makedirs(os.path.dirname(des)) shutil.copy2(src, des) def zip(destFile): printInfo('Start zipping deploy directory') shutil.make_archive(destFile, 'zip', 'deploy') printInfo('Created ' + destFile + '.zip') def copyDeployFiles(): os.makedirs('deploy') source_dir = os.path.join(os.getcwd(), 'app') target_dir = os.path.join(os.getcwd(), 'deploy') copy_list = ['index.html', 'manifest.json', 'js/index.js', 'js/background.js', 'js/lib/hterm_all.min.js', 'css/main.css', 'images', 'bower_components/jquery/dist/jquery.min.js', 'bower_components/bootstrap/dist/js/bootstrap.min.js', 'bower_components/bootstrap/dist/css/bootstrap.min.css'] for single_file in copy_list: source_path = os.path.join(source_dir, single_file) target_path = os.path.join(target_dir, single_file) copy(source_path, target_path) def main(): installDependencies() copyDeployFiles() # TODO: Minify js/index.js, js/background.js zip('archive') if __name__ == '__main__': main()
Python
0.999995
@@ -715,22 +715,21 @@ zipping -deploy +build directo @@ -773,22 +773,21 @@ 'zip', ' -deploy +build ')%0A pri @@ -864,22 +864,21 @@ kedirs(' -deploy +build ')%0A sou @@ -966,14 +966,13 @@ ), ' -deploy +build ')%0A%0A
8e8c14446a0089ee7fa57cfd5520c7d6d6e2711e
Add Python user customization file.
usercustomize.py
usercustomize.py
Python
0
@@ -0,0 +1,450 @@ +%22%22%22 Customize Python Interpreter.%0A%0ALink your user customizing file to this file.%0A%0AFor more info see: https://docs.python.org/3/library/site.html%0A%0A%22Default value is ~/.local/lib/pythonX.Y/site-packages for UNIX and%0Anon-framework Mac OS X builds, ~/Library/Python/X.Y/lib/python/site-packages%0Afor Mac framework builds, and %25APPDATA%25%5CPython%5CPythonXY%5Csite-packages on%0AWindows.%22%0A%0ASun May 4 18:06:08 CST 2014%0A%22%22%22%0A%0Aimport cgitb%0Acgitb.enable(format='text')%0A
ab2fdecf3fb34b999c3943d6445fca148763c025
add debug info
jip/util.py
jip/util.py
#! /usr/bin/env jython # Copyright (C) 2011 Sun Ning<classicning@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # import os import sys import urllib import urllib2 import time from StringIO import StringIO import Queue import threading from . import JIP_VERSION, logger JIP_USER_AGENT = 'jip/%s' % JIP_VERSION BUF_SIZE = 4096 class DownloadException(Exception): pass def download(url, target, async=False, close_target=False, quiet=True): ### download file to target (target is a file-like object) if async: pool.submit(url, target) else: request = urllib2.Request(url=url) request.add_header('User-Agent', JIP_USER_AGENT) try: t0 = time.time() source = urllib2.urlopen(request) size = source.headers.getheader('Content-Length') if not quiet: logger.info('[Downloading] %s %s bytes to download' % (url, size)) buf=source.read(BUF_SIZE) while len(buf) > 0: target.write(buf) buf = source.read(BUF_SIZE) source.close() if close_target: target.close() t1 = time.time() if not quiet: logger.info('[Downloading] Download %s completed in %f secs' % (url, (t1-t0))) except urllib2.HTTPError: raise DownloadException() except urllib2.URLError: raise DownloadException() def download_string(url): buf = StringIO() download(url, buf) data = buf.getvalue() buf.close() return data class DownloadThreadPool(object): def __init__(self, size=3): self.queue = Queue.Queue() self.workers = [threading.Thread(target=self._do_work) for _ in range(size)] self.initialized = False def init_threads(self): for worker in self.workers: worker.setDaemon(True) worker.start() self.initialized = True def _do_work(self): while True: url, target = self.queue.get() download(url, target, close_target=True, quiet=False) self.queue.task_done() def join(self): self.queue.join() def submit(self, url, target): if not self.initialized: self.init_threads() self.queue.put((url, target)) pool = DownloadThreadPool(3) def get_virtual_home(): if 'VIRTUAL_ENV' in os.environ: JYTHON_HOME = os.environ['VIRTUAL_ENV'] else: logger.warn('Warning: no virtualenv detected, remember to activate it.') if 'JYTHON_HOME' in os.environ: JYTHON_HOME = os.environ['JYTHON_HOME'] else: ## fail back to use current directory JYTHON_HOME = os.getcwd() return JYTHON_HOME def get_lib_path(): JYTHON_HOME = get_virtual_home() DEFAULT_JAVA_LIB_PATH = os.path.join(JYTHON_HOME, 'javalib') if not os.path.exists(DEFAULT_JAVA_LIB_PATH): os.mkdir(DEFAULT_JAVA_LIB_PATH) return DEFAULT_JAVA_LIB_PATH
Python
0.000001
@@ -2355,24 +2355,27 @@ b2.HTTPError +, e :%0A @@ -2400,16 +2400,22 @@ ception( +url, e )%0A @@ -2439,16 +2439,19 @@ URLError +, e :%0A @@ -2480,16 +2480,22 @@ ception( +url, e )%0A%0Adef d
13be4749aef2415ab84ffbd090c5b24d8ed98af5
Add test case of BloArticle class
tests/TestBloArticle.py
tests/TestBloArticle.py
Python
0
@@ -0,0 +1,640 @@ +import unittest%0Afrom blo.BloArticle import BloArticle%0A%0A%0Aclass TestBloArticle(unittest.TestCase):%0A def setUp(self):%0A self.blo_article = BloArticle()%0A%0A def test_failed_load_from_file(self):%0A file_path = %22%22%0A with self.assertRaises(FileNotFoundError):%0A self.blo_article.load_from_file(file_path)%0A%0A def test_success_load_from_file(self):%0A file_path = %22./test_article_1.md%22%0A self.assertIsNone(self.blo_article.load_from_file(file_path))%0A self.assertFalse(self.blo_article._raw_text == %22%22)%0A%0A def test_convert_to_html(self):%0A pass%0A%0A def test_get_digest(self):%0A pass%0A
4442fabf9292efa44a82f420e2d3e807d7d15b04
Add more tests to cli
tests/test_cli.py
tests/test_cli.py
Python
0
@@ -0,0 +1,2175 @@ +from click.testing import CliRunner%0Afrom tinydb import TinyDB, where%0Afrom tinydb.storages import MemoryStorage%0Aimport pytest%0Atry:%0A import mock%0Aexcept ImportError:%0A from unittest import mock%0A%0Afrom passpie import cli%0A%0A%0A@pytest.fixture%0Adef mock_db(mocker):%0A credentials = %5B%0A %7B'login': 'foo', 'name': 'bar', 'fullname': 'foo@bar',%0A 'password': '', 'comment': ''%7D,%0A %7B'login': 'foa', 'name': 'bazzy', 'fullname': 'foa@bazzy',%0A 'password': '', 'comment': ''%7D,%0A %7B'login': 'spam', 'name': 'egg', 'fullname': 'spam@egg',%0A 'password': '', 'comment': ''%7D,%0A %5D%0A database = TinyDB(storage=MemoryStorage)%0A database.insert_multiple(credentials)%0A MockDB = mock.MagicMock(return_value=database)%0A mocker.patch('passpie.cli.Database', MockDB)%0A return database%0A%0A%0Adef test_cli_search_find_results_by_login_regex(mock_db):%0A runner = CliRunner()%0A result = runner.invoke(cli.search, %5B'fo%5Boa%5D'%5D)%0A%0A assert result.exit_code == 0%0A assert 'foo' in result.output%0A assert 'foa' in result.output%0A assert 'spam' not in result.output%0A%0A%0Adef test_cli_remove_delete_credential_found_by_database(mock_db):%0A runner = CliRunner()%0A result = runner.invoke(cli.remove, %5B'foo@bar'%5D, input='y')%0A result_print = runner.invoke(cli.cli)%0A%0A assert result.exit_code == 0%0A assert 'foo' not in result_print.output%0A%0A%0Adef test_cli_add_credential_to_database(mock_db):%0A fullname = 'test_user@example'%0A runner = CliRunner()%0A result = runner.invoke(cli.add, %5Bfullname, '--random'%5D)%0A%0A assert result.exit_code == 0%0A assert mock_db.get(where('fullname') == fullname)%0A%0A%0Adef test_cli_copy_credential_password_to_database(mocker, mock_db):%0A fullname = 'foo@bar'%0A password = 's3cr3t'%0A mocker.patch('passpie.cli.ensure_passphrase')%0A mock_pyperclip = mocker.patch('passpie.cli.pyperclip')%0A mocker.patch('passpie.cli.Cryptor.decrypt',%0A mock.Mock(return_value=password))%0A runner = CliRunner()%0A result = runner.invoke(cli.copy, %5Bfullname%5D, input='passphrase')%0A%0A assert result.exit_code == 0%0A assert mock_pyperclip.copy.called%0A mock_pyperclip.copy.assert_called_once_with(password)%0A
b2e10a344a940ae2cce9656c435c7a6f4919a53b
add cli invoke tests
tests/test_cli.py
tests/test_cli.py
Python
0.000001
@@ -0,0 +1,274 @@ +%0Aimport pytest%0Afrom click.testing import CliRunner%0A%0Aimport bgpfu.cli%0A%0A%0Adef test_cli_invoke():%0A runner = CliRunner()%0A res = runner.invoke(bgpfu.cli.cli, %5B'as_set'%5D)%0A res = runner.invoke(bgpfu.cli.cli, %5B'prefixlist'%5D)%0A res = runner.invoke(bgpfu.cli.cli, %5B'raw'%5D)%0A%0A
943b12735f891c87ff62796195e562a7522d3486
Improve search algorithm for GAE SDK in depot_tools integration tests.
tests/local_rietveld.py
tests/local_rietveld.py
#!/usr/bin/env python # Copyright (c) 2011 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. """Setups a local Rietveld instance to test against a live server for integration tests. It makes sure Google AppEngine SDK is found, download Rietveld and Django code if necessary and starts the server on a free inbound TCP port. """ import optparse import os import socket import sys import time sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) import subprocess2 class Failure(Exception): pass def test_port(port): s = socket.socket() try: return s.connect_ex(('127.0.0.1', port)) == 0 finally: s.close() def find_free_port(): # Test to find an available port starting at 8080. port = 8080 max_val = (2<<16) while test_port(port) and port < max_val: port += 1 if port == max_val: raise Failure('Having issues finding an available port') return port class LocalRietveld(object): """Downloads everything needed to run a local instance of Rietveld.""" def __init__(self, base_dir=None): # Paths self.base_dir = base_dir if not self.base_dir: self.base_dir = os.path.dirname(os.path.abspath(__file__)) self.base_dir = os.path.realpath(os.path.join(self.base_dir, '..')) self.sdk_path = os.path.abspath( os.path.join(self.base_dir, '..', 'google_appengine')) self.dev_app = os.path.join(self.sdk_path, 'dev_appserver.py') self.rietveld = os.path.join(self.base_dir, 'tests', '_rietveld') self.test_server = None self.port = None def install_prerequisites(self): # First, verify the Google AppEngine SDK is available. if not os.path.isfile(self.dev_app): raise Failure('Install google_appengine sdk in %s' % self.sdk_path) # Second, checkout rietveld if not available. if not os.path.isdir(self.rietveld): print('Checking out rietveld...') try: subprocess2.check_call( ['svn', 'co', '-q', 'http://rietveld.googlecode.com/svn/trunk@681', self.rietveld]) except (OSError, subprocess2.CalledProcessError), e: raise Failure('Failed to checkout rietveld\n%s' % e) else: print('Syncing rietveld...') try: subprocess2.check_call( ['svn', 'up', '-q', '-r', '681'], cwd=self.rietveld) except (OSError, subprocess2.CalledProcessError), e: raise Failure('Failed to sync rietveld\n%s' % e) def start_server(self, verbose=False): self.install_prerequisites() self.port = find_free_port() if verbose: pipe = None else: pipe = subprocess2.VOID cmd = [ sys.executable, self.dev_app, '--skip_sdk_update_check', '.', '--port=%d' % self.port, '--datastore_path=' + os.path.join(self.rietveld, 'tmp.db'), '-c'] # CHEAP TRICK # By default you only want to bind on loopback but I'm testing over a # headless computer so it's useful to be able to access the test instance # remotely. if os.environ.get('GAE_LISTEN_ALL', '') == 'true': cmd.extend(('-a', '0.0.0.0')) self.test_server = subprocess2.Popen( cmd, stdout=pipe, stderr=pipe, cwd=self.rietveld) # Loop until port 127.0.0.1:port opens or the process dies. while not test_port(self.port): self.test_server.poll() if self.test_server.returncode is not None: raise Failure( 'Test rietveld instance failed early on port %s' % self.port) time.sleep(0.01) def stop_server(self): if self.test_server: self.test_server.kill() self.test_server.wait() self.test_server = None self.port = None def main(): parser = optparse.OptionParser() parser.add_option('-v', '--verbose', action='store_true') options, args = parser.parse_args() if args: parser.error('Unknown arguments: %s' % ' '.join(args)) instance = LocalRietveld() try: instance.start_server(verbose=options.verbose) print 'Local rietveld instance started on port %d' % instance.port while True: time.sleep(0.1) finally: instance.stop_server() if __name__ == '__main__': main()
Python
0.000002
@@ -1278,43 +1278,158 @@ - self.base_dir = os.path.realpath( +# TODO(maruel): This should be in /tmp but that would mean having to fetch%0A # everytime. This test is already annoyingly slow.%0A self.rietveld = os.p @@ -1453,20 +1453,26 @@ e_dir, ' -..') +_rietveld' )%0A se @@ -1478,43 +1478,233 @@ elf. -sdk_path = os.path.abspath(%0A +test_server = None%0A self.port = None%0A%0A # Find the GAE SDK%0A previous_dir = ''%0A self.sdk_path = ''%0A base_dir = self.base_dir%0A while base_dir != previous_dir:%0A previous_dir = base_dir%0A self.sdk_path = os. @@ -1705,37 +1705,32 @@ = os.path.join( -self. base_dir, '..', @@ -1726,14 +1726,8 @@ dir, - '..', 'go @@ -1746,29 +1746,37 @@ ne') -) %0A -self.dev_app = + if not os.path.isfile( os.p @@ -1804,145 +1804,131 @@ h, ' -dev_appserver.py')%0A self.rietveld = os.path.join(self.base_dir, 'tests', '_rietveld')%0A self.test_server = None%0A self.port = None +VERSION')):%0A base_dir = os.path.dirname(base_dir)%0A self.dev_app = os.path.join(self.sdk_path, 'dev_appserver.py') %0A%0A @@ -2080,16 +2080,27 @@ Failure( +%0A 'Install @@ -2126,16 +2126,29 @@ dk in %25s + or higher up ' %25 self @@ -2148,24 +2148,24 @@ %25 self. -sdk_path +base_dir )%0A%0A #
a753b26dc3564515a3368c3bd6ecbbf8bb8dc589
Add TODO
tests/test_migration.py
tests/test_migration.py
import unittest from nose.tools import * # PEP8 asserts from modularodm import StoredObject, fields, exceptions from tests.base import ModularOdmTestCase class TestMigration(ModularOdmTestCase): def define_objects(self): # Use a single storage object for both schema versions self._storage = self.make_storage() class V1(StoredObject): _id = fields.StringField(_primary_key=True, index=True) my_string = fields.StringField() my_float = fields.FloatField() my_number = fields.FloatField() my_null = fields.StringField(required=False) _meta = { 'optimistic': True, 'version': 1, 'optimistic': True } V1.set_storage(self._storage) class V2(StoredObject): _id = fields.StringField(_primary_key=True, index=True) my_string = fields.StringField() my_int = fields.IntegerField(default=5) my_number = fields.IntegerField() my_null = fields.StringField(required=False) @classmethod def _migrate(cls, old, new): if old.my_string: new.my_string = old.my_string + 'yo' if old.my_number: new.my_number = int(old.my_number) _meta = { 'optimistic': True, 'version_of': V1, 'version': 2, 'optimistic': True } V2.set_storage(self._storage) return V1, V2 def set_up_objects(self): self.record = self.V1(my_string='hi', my_float=1.2, my_number=3.4) self.record.save() self.migrated_record = self.V2.load(self.record._primary_key) self.migrated_record.save() def test_version_number(self): assert_equal(self.migrated_record._version, 2) def test_new_field(self): assert_in('my_int', self.migrated_record._fields) assert_equal(self.migrated_record.my_int, 5) def test_deleted_field(self): assert_in('my_float', self.record._fields) assert_not_in('my_float', self.migrated_record._fields) def test_migrated_field(self): assert_equal(self.migrated_record.my_string, 'hiyo') def test_versions_contain_same_records(self): for i in range(5): record = self.V1(my_string="foo") record.save() assert_equal(len(self.V1.find()), len(self.V2.find())) # Primary keys are the same for old_rec, new_rec in zip(self.V1.find(), self.V2.find()): assert_equal(old_rec._primary_key, new_rec._primary_key) def test_changed_number_type_field(self): assert_true(isinstance(self.migrated_record._fields['my_number'], fields.IntegerField)) assert_true(isinstance(self.migrated_record.my_number, int)) assert_equal(self.migrated_record.my_number, int(self.record.my_number)) def test_making_field_required_without_default_raises_error(self): class V3(StoredObject): _id = fields.StringField(_primary_key=True, index=True) my_string = fields.StringField() my_int = fields.IntegerField(default=5) my_number = fields.IntegerField() my_null = fields.StringField(required=True) _meta = { 'optimistic': True, 'version_of': self.V2, 'version': 3, 'optimistic': True } V3.set_storage(self._storage) migrated = V3.load(self.migrated_record._primary_key) assert_raises(exceptions.ValidationError, lambda: migrated.save()) def test_making_field_required_with_default(self): class V3(StoredObject): _id = fields.StringField(_primary_key=True, index=True) my_string = fields.StringField() my_int = fields.IntegerField(default=5) my_number = fields.IntegerField() my_null = fields.StringField(required=True) @classmethod def _migrate(cls, old, new): if not old.my_null: new.my_null = 'default' _meta = { 'optimistic': True, 'version_of': self.V2, 'version': 3, 'optimistic': True } V3.set_storage(self._storage) old = self.V1() old.save() migrated = V3.load(old._primary_key) migrated.save() assert_equal(migrated.my_null, "default") def test_migrate_all(self): for i in range(5): rec = self.V1(my_string="foo{0}".format(i)) rec.save() self.V2.migrate_all() assert_greater_equal(self.V2.find(), 5) for record in self.V2.find(): assert_true(record.my_string.endswith("yo")) def test_save_migrated(self): try: self.migrated_record.save() except: assert False if __name__ == '__main__': unittest.main()
Python
0.000002
@@ -3059,32 +3059,105 @@ es_error(self):%0A + # TODO: This test raises a warning for setting a non-field value%0A class V3
c659f31cfb3eadd66838036ea285070f564fdced
Add rendering test
tests/test_rendering.py
tests/test_rendering.py
Python
0.000001
@@ -0,0 +1,580 @@ +# -*- coding: utf-8 -*-%0Afrom __future__ import absolute_import, unicode_literals%0Aimport pytest%0A%0Afrom PIL.Image import Image%0Afrom psd_tools.user_api.psd_image import PSDImage, merge_layers%0Afrom tests.utils import decode_psd, full_name%0A%0A%0ACLIP_FILES = %5B%0A ('clipping-mask.psd',),%0A ('clipping-mask2.psd',)%0A%5D%0A%0A%0A@pytest.mark.parametrize((%22filename%22,), CLIP_FILES)%0Adef test_render_clip_layers(filename):%0A psd = PSDImage.load(full_name(filename))%0A image1 = psd.as_PIL()%0A image2 = psd.as_PIL_merged()%0A assert isinstance(image1, Image)%0A assert isinstance(image2, Image)%0A
436719050ada475d840004a49c693d08c3f92034
Add a widget for line editors.
greatbigcrane/project/widgets.py
greatbigcrane/project/widgets.py
Python
0
@@ -0,0 +1,622 @@ +from django.forms.widgets import Textarea%0Afrom django.utils.safestring import mark_safe%0A%0Aclass LineEditorWidget(Textarea):%0A class Media:%0A js = ('js/jquery-1.4.2.min.js' ,'js/jquery.lineeditor.js')%0A%0A def render(self, name, value, attrs=None):%0A if isinstance(value,list):%0A value = %22%5Cn%22.join(value)%0A rendered = super(LineEditorWidget, self).render(name, value, attrs)%0A return rendered + mark_safe(u'''%3Cscript type=%22text/javascript%22 defer=%22defer%22%3E%0A $(function() %7B%0A $(%22#id_%25s%22).lineeditor();%0A %7D%0A );%0A %3C/script%3E''' %25 (name))%0A
52d03e19bd61dcba56d1d7fc3944afcc6d9b6a8d
make nautilus use backspace for back
.local/share/nautilus-python/extensions/BackspaceBack.py
.local/share/nautilus-python/extensions/BackspaceBack.py
Python
0.00001
@@ -0,0 +1,605 @@ +#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A#%0A# by Ricardo Lenz, 2016-jun%0A# riclc@hotmail.com%0A#%0A%0Aimport os, gi%0Agi.require_version('Nautilus', '3.0')%0Afrom gi.repository import GObject, Nautilus, Gtk, Gio, GLib%0A%0Adef ok():%0A app = Gtk.Application.get_default()%0A app.set_accels_for_action( %22win.up%22, %5B%22BackSpace%22%5D )%0A #print app.get_actions_for_accel(%22BackSpace%22)%0A #print app.get_actions_for_accel(%22%3Calt%3EUp%22)%0A%0A%0Aclass BackspaceBack(GObject.GObject, Nautilus.LocationWidgetProvider):%0A def __init__(self):%0A pass%0A %0A def get_widget(self, uri, window):%0A ok()%0A return None%0A%0A
e778f67101a9ba8e38e249263d49738d3239f557
test select prefix cursor
test_p_cursor.py
test_p_cursor.py
Python
0.000001
@@ -0,0 +1,1370 @@ +%0Aimport sys%0A%0Asys.path.append('./build/lib.linux-x86_64-2.7/')%0A%0Afrom voidptr import VoidPtr as vp%0Aimport spapi as sp%0A%0Aenv = vp(%22env%22)%0Actl = vp(%22ctl%22)%0Adb = vp(%22db%22)%0Ao = vp(%22o%22)%0At = vp(%22t%22)%0A%0Aprint %22env%22, sp.env(env)%0Aprint %22env,ctl%22, sp.ctl(env,ctl)%0Aprint %22ctl_set%22, sp.ctl_set(ctl,%22sophia.path%22,%22./test_data%22)%0Aprint %22ctl_set%22, sp.ctl_set(ctl,%22db%22,%22test_p%22)%0Aprint %22open env%22, sp.open(env)%0Aprint %22db%22, sp.db(ctl,%22db.test_p%22,db)%0Aprint %22transaction begin%22, sp.begin(env,t)%0A%0Afor j in xrange (6)%0A for k in xrange(6):%0A print %22prepare obj%22 , sp.obj(db, o)%0A%0A key = %22a%25db%25dc%25d%22 %25 (k,k,k)%0A print %22key -%3E %22,key%0A%0A print %22set field%22,sp.set_field(o,%22key%22,key )%0A print %22set fieled%22,sp.set_field(o,%22value%22,%22abcd%25d%22 %25 k)%0A print %22db set obj%22,sp.db_set( t, o ) %0A%0Aprint %22transaction commit%22, sp.commit(t)%0A%0Acursor = vp(%22cursor%22)%0A#cursor2 = vp(%22cursor2%22)%0A#o2 = vp(%22o2%22)%0A%0A#print %22obj db o2%22 , sp.obj(db, o2)%0Aprint %22obj db o%22 , sp.obj(db, o)%0A%0Aprint %22set key %22, sp.set_field(o,%22key%22,%22a5%22)%0Aprint %22set order %3E to o%22,sp.set_field(o,%22order%22,%22%3E%22)%0A#print %22set order %3E to o2%22,sp.set_field(o2,%22order%22,%22%3E%22)%0A%0A%0Aprint %22inti cursors%22%0Aprint cursor.tag, sp.cursor(db,o,cursor)%0A#print cursor2.tag, sp.cursor(db,o2,cursor2)%0A%0Awhile sp.cursor_get(cursor,o):%0A print sp.get_field(o,%22key%22)%0A #if sp.cursor_get(cursor2,o2):%0A # print sp.get_field(o2,%22key%22)%0A%0A%0A%0A%0A
2a1777a74d6f2cba61485f281f0c048cbbdca727
Add valgrind tests file.
test_valgrind.py
test_valgrind.py
Python
0
@@ -0,0 +1,990 @@ +%0Afrom __future__ import print_function%0A%0Aimport shutil%0Aimport os%0A%0Afrom model_test_helper import ModelTestHelper%0A%0Atests = %7B'om_360x300-valgrind' : ('om'),%0A 'cm_360x300-valgrind' : ('cm')%7D%0A%0Aclass TestValgrind(ModelTestHelper):%0A %22%22%22%0A Run the model in valgrind.%0A %22%22%22%0A%0A def __init__(self):%0A super(TestBasicRun, self).__init__()%0A%0A def pre_run_cleanup(self, exp):%0A%0A paths = self.make_paths(exp)%0A%0A try:%0A shutil.rmtree(paths%5B'archive'%5D)%0A os.remove(paths%5B'archive_link'%5D)%0A except OSError, e:%0A if not e.strerror == 'No such file or directory':%0A raise e%0A%0A def check_run(self, key):%0A%0A print('############ Running %7B%7D ############'.format(key))%0A self.pre_run_cleanup(key)%0A self.do_basic_access_run(key, model=tests%5Bkey%5D%5B0%5D)%0A%0A # FIXME: check that valgrind does not find any problems.%0A%0A def test_runs(self):%0A for k in tests.keys():%0A yield self.check_run, k%0A
f9273e7b905bdc94f3e161b17225a11120810b26
handle core serice by self-defined-class
google_service.py
google_service.py
Python
0
@@ -0,0 +1,1742 @@ +import httplib2%0Aimport os%0A%0Aimport oauth2client%0Afrom apiclient import discovery%0Afrom oauth2client import client, tools%0A%0Atry:%0A import argparse%0A flags = argparse.ArgumentParser(parents=%5Btools.argparser%5D).parse_args()%0Aexcept ImportError:%0A flags = None%0A%0A%0Aclass Gooooogle():%0A def __init__(self):%0A self.credentials = self._get_credentials()%0A self.service = self._new_service()%0A%0A def _get_credentials(self):%0A %22%22%22Gets valid user credentials from storage.%0A%0A If nothing has been stored, or if the stored credentials are invalid,%0A the OAuth2 flow is completed to obtain the new credentials.%0A%0A Returns:%0A Credentials, the obtained credential.%0A %22%22%22%0A credential_dir = os.path.join('./', '.credentials')%0A if not os.path.exists(credential_dir):%0A os.makedirs(credential_dir)%0A credential_path = os.path.join(credential_dir, self.CREDENTIALS_NAME)%0A%0A store = oauth2client.file.Storage(credential_path)%0A credentials = store.get()%0A if not credentials or credentials.invalid:%0A flow = client.flow_from_clientsecrets(%0A self.CLIENT_SECRET_FILE, self.SCOPES)%0A flow.user_agent = self.APPLICATION_NAME%0A if flags:%0A credentials = tools.run_flow(flow, store, flags)%0A else: # Needed only for compatability with Python 2.6%0A credentials = tools.run(flow, store)%0A return credentials%0A%0A def _new_service(self):%0A %22%22%22Creates a Google Drive API service object.%0A %22%22%22%0A httplib = self.credentials.authorize(httplib2.Http())%0A return discovery.build(%0A self.API_NAME,%0A self.API_VERSION,%0A http=httplib)%0A
556530f4933b1323ef8e4414c324a0aa2d0b81bd
Add the example bundles.
tests/example.py
tests/example.py
Python
0
@@ -0,0 +1,2111 @@ +# This file is part of the Juju GUI, which lets users view and manage Juju%0A# environments within a graphical interface (https://launchpad.net/juju-gui).%0A# Copyright (C) 2013 Canonical Ltd.%0A#%0A# This program is free software: you can redistribute it and/or modify it under%0A# the terms of the GNU Affero General Public License version 3, as published by%0A# the Free Software Foundation.%0A#%0A# This program is distributed in the hope that it will be useful, but WITHOUT%0A# ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,%0A# SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU%0A# Affero General Public License for more details.%0A#%0A# You should have received a copy of the GNU Affero General Public License%0A# along with this program. If not, see %3Chttp://www.gnu.org/licenses/%3E.%0A%0A%22%22%22Example data used in tests.%22%22%22%0A%0A%0ABUNDLE1 = %22%22%22%0Abundle1:%0A series: precise%0A services:%0A wordpress:%0A charm: %22cs:precise/wordpress-15%22%0A num_units: 1%0A options:%0A debug: %22no%22%0A engine: nginx%0A tuning: single%0A %22wp-content%22: %22%22%0A annotations:%0A %22gui-x%22: 313%0A %22gui-y%22: 51%0A mysql:%0A charm: %22cs:precise/mysql-26%22%0A num_units: 1%0A options:%0A %22binlog-format%22: MIXED%0A %22block-size%22: %225%22%0A %22dataset-size%22: %2280%25%22%0A flavor: distro%0A %22ha-bindiface%22: eth0%0A %22ha-mcastport%22: %225411%22%0A %22max-connections%22: %22-1%22%0A %22preferred-storage-engine%22: InnoDB%0A %22query-cache-size%22: %22-1%22%0A %22query-cache-type%22: %22OFF%22%0A %22rbd-name%22: mysql1%0A %22tuning-level%22: safest%0A vip: %22%22%0A vip_cidr: %2224%22%0A vip_iface: eth0%0A annotations:%0A %22gui-x%22: 669.5%0A %22gui-y%22: -33.5%0A relations:%0A - - %22wordpress:db%22%0A - %22mysql:db%22%0A%22%22%22%0A%0ABUNDLE2 = %22%22%22%0Abundle2:%0A series: precise%0A services:%0A mediawiki:%0A charm: %22cs:precise/mediawiki-9%22%0A num_units: 1%0A options:%0A admins: %22%22%0A debug: false%0A logo: %22%22%0A name: Please set name of wiki%0A skin: vector%0A annotations:%0A %22gui-x%22: 432%0A %22gui-y%22: 120%0A relations: %5B%5D%0A%22%22%22%0A
1dec974693222864537b20b31ac33656bea92912
add LogFactory
py3utils/_log.py
py3utils/_log.py
Python
0.000001
@@ -0,0 +1,551 @@ +#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A#%0A# date: 2018/4/15%0A# author: he.zhiming%0A#%0A%0Afrom __future__ import unicode_literals, absolute_import%0A%0Aimport logging%0Aimport logging.config%0Afrom logging import handlers%0A%0A%0Aclass LogFactory:%0A _LOG_CONFIG_DICT = %7B%0A%0A %7D%0A%0A logging.config.dictConfig(_LOG_CONFIG_DICT)%0A%0A @classmethod%0A def get_logger(cls, logger_name) -%3E logging.Logger:%0A return logging.getLogger(logger_name)%0A%0A%0ADEBUGGER = LogFactory.get_logger('debugger')%0ACONSOLE_LOGGER = LogFactory.get_logger('console_logger')%0A
6f9d02510ad861bf8ae5ad8f1ae335a4e565756d
Add initial unit tests for io module
tests/test_io.py
tests/test_io.py
Python
0
@@ -0,0 +1,670 @@ +from unittest.mock import MagicMock, patch%0A%0Aimport pytest%0A%0Afrom isort import io%0A%0A%0Aclass TestFile:%0A def test_read(self, tmpdir):%0A test_file_content = %22%22%22# -*- encoding: ascii -*-%0A%0Aimport %E2%98%BA%0A%22%22%22%0A test_file = tmpdir.join(%22file.py%22)%0A test_file.write(test_file_content)%0A%0A # able to read file even with incorrect encoding, if it is UTF-8 compatible%0A assert io.File.read(test_file).contents == test_file_content%0A%0A # unless the locale is also ASCII%0A with pytest.raises(io.UnableToDetermineEncoding):%0A with patch(%22locale.getpreferredencoding%22, lambda value: %22ascii%22):%0A io.File.read(test_file).contents%0A
b48c5c0beb07039bdd0cef3bd0973d29e5b8254d
Fix Entry.
sugar/graphics/entry.py
sugar/graphics/entry.py
# Copyright (C) 2007, One Laptop Per Child # # This library 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 of the License, or (at your option) any later version. # # This library 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 this library; if not, write to the # Free Software Foundation, Inc., 59 Temple Place - Suite 330, # Boston, MA 02111-1307, USA. import math import logging import gobject import gtk import hippo import pango from sugar.graphics import style from sugar.graphics.color import Color from sugar.graphics.button import Button from sugar.graphics.roundbox import RoundBox class Entry(hippo.CanvasBox, hippo.CanvasItem): __gtype_name__ = 'SugarEntry' __gproperties__ = { 'text' : (str, None, None, None, gobject.PARAM_READWRITE) } __gsignals__ = { 'button-activated': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ([int])) } def __init__(self): hippo.CanvasBox.__init__(self, orientation=hippo.ORIENTATION_HORIZONTAL) self.props.yalign = hippo.ALIGNMENT_CENTER self._buttons = {} self._round_box = RoundBox() self._round_box.props.border_color = Color.FRAME_BORDER.get_int() self.append(self._round_box, hippo.PACK_EXPAND) self._entry = self.create_entry() self._entry.props.has_frame = False self._update_colors(focused=False) self._entry.modify_text(gtk.STATE_SELECTED, Color.BLACK.get_gdk_color()) self._entry.connect('focus-in-event', self._entry_focus_in_event_cb) self._entry.connect('focus-out-event', self._entry_focus_out_event_cb) self._entry.connect('activate', self._entry_activate_cb) fd = pango.FontDescription() fd.set_size(int(round(style.default_font_size * pango.SCALE))) self._entry.modify_font(fd) self._canvas_widget = hippo.CanvasWidget() self._canvas_widget.props.widget = self._entry self._round_box.append(self._canvas_widget, hippo.PACK_EXPAND) def create_entry(): """ Subclasses can override this method in order to provide a different entry widget. """ return gtk.Entry() def add_button(self, icon_name, action_id): button = Button(icon_name=icon_name) button.props.scale = style.small_icon_scale button.props.yalign = hippo.ALIGNMENT_CENTER button.props.xalign = hippo.ALIGNMENT_START button.connect('activated', self._button_activated_cb) self._round_box.append(button) self._buttons[button] = action_id def do_set_property(self, pspec, value): self._entry.set_property(pspec.name, value) def do_get_property(self, pspec): return self._entry.get_property(pspec.name) def _entry_focus_in_event_cb(self, widget, event): self._update_colors(focused=True) self.emit_paint_needed(0, 0, -1, -1) def _entry_focus_out_event_cb(self, widget, event): self._update_colors(focused=False) self.emit_paint_needed(0, 0, -1, -1) def _entry_activate_cb(self, entry): self.emit_activated() def _button_activated_cb(self, button): self.emit('button-activated', self._buttons[button]) def _update_colors(self, focused): if focused: self._round_box.props.background_color = \ Color.ENTRY_BACKGROUND_FOCUSED.get_int() self._entry.modify_base(gtk.STATE_NORMAL, Color.ENTRY_BACKGROUND_FOCUSED.get_gdk_color()) self._entry.modify_base(gtk.STATE_SELECTED, Color.ENTRY_SELECTION_FOCUSED.get_gdk_color()) self._entry.modify_text(gtk.STATE_NORMAL, Color.ENTRY_TEXT_FOCUSED.get_gdk_color()) else: self._round_box.props.background_color = \ Color.ENTRY_BACKGROUND_UNFOCUSED.get_int() self._entry.modify_base(gtk.STATE_NORMAL, Color.ENTRY_BACKGROUND_UNFOCUSED.get_gdk_color()) self._entry.modify_base(gtk.STATE_SELECTED, Color.ENTRY_SELECTION_UNFOCUSED.get_gdk_color()) self._entry.modify_text(gtk.STATE_NORMAL, Color.ENTRY_TEXT_UNFOCUSED.get_gdk_color())
Python
0
@@ -2507,16 +2507,20 @@ e_entry( +self ):%0A
d94260f0be472d2c163e9ae57aacc25a8e9f2519
Package contrib
t5x/contrib/__init__.py
t5x/contrib/__init__.py
Python
0
@@ -0,0 +1,648 @@ +# Copyright 2022 The T5X Authors.%0A#%0A# Licensed under the Apache License, Version 2.0 (the %22License%22);%0A# you may not use this file except in compliance with the License.%0A# You may obtain a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS,%0A# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A# See the License for the specific language governing permissions and%0A# limitations under the License.%0A%0A%22%22%22This empty file is needed for packaging the contrib modules.%22%22%22%0A
0f32a1e193a0064e5d5313cdc205d15cea71f1e7
Test for a long hippo scrolling view.
tests/graphics/hipposcalability.py
tests/graphics/hipposcalability.py
Python
0
@@ -0,0 +1,925 @@ +import hippo%0Aimport gtk%0Aimport gobject%0A%0Afrom sugar.graphics.icon import CanvasIcon%0Afrom sugar.graphics.roundbox import CanvasRoundBox%0A%0Aimport common%0A%0Atest = common.Test()%0A%0Acanvas = hippo.Canvas()%0Atest.pack_start(canvas)%0Acanvas.show()%0A%0Ascrollbars = hippo.CanvasScrollbars()%0Acanvas.set_root(scrollbars)%0A%0Abox = hippo.CanvasBox(padding=10, spacing=10)%0Ascrollbars.set_root(box)%0A%0Adef idle_cb():%0A global countdown%0A%0A for i in range(0, 100):%0A entry = CanvasRoundBox(padding=10, spacing=10)%0A%0A for j in range(0, 3):%0A icon = CanvasIcon(icon_name='go-left')%0A entry.append(icon)%0A%0A for j in range(0, 2):%0A text = hippo.CanvasText(text='Text %25s %25s' %25 (countdown, j))%0A entry.append(text)%0A%0A box.append(entry)%0A%0A countdown -= 1%0A%0A return countdown %3E 0%0A%0Acountdown = 1000%0Agobject.idle_add(idle_cb)%0A%0Atest.show()%0A%0Aif __name__ == %22__main__%22:%0A common.main(test)%0A
f0204e3061b110028fde5312fdb7b613e361b16e
Create output.py
trendpy/output.py
trendpy/output.py
Python
0.000295
@@ -0,0 +1,1148 @@ +# -*- coding: utf-8 -*-%0A%0A# output.py%0A%0A# MIT License%0A%0A# Copyright (c) 2017 Rene Jean Corneille%0A%0A# Permission is hereby granted, free of charge, to any person obtaining a copy%0A# of this software and associated documentation files (the %22Software%22), to deal%0A# in the Software without restriction, including without limitation the rights%0A# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell%0A# copies of the Software, and to permit persons to whom the Software is%0A# furnished to do so, subject to the following conditions:%0A%0A# The above copyright notice and this permission notice shall be included in all%0A# copies or substantial portions of the Software.%0A%0A# THE SOFTWARE IS PROVIDED %22AS IS%22, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR%0A# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,%0A# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE%0A# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER%0A# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,%0A# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE%0A# SOFTWARE.%0A
277b12fdd5af885466fd3ff6f8ccfd47555fbabe
Fix `RedisQuotaTest.test_uses_defined_quotas`.
tests/sentry/quotas/redis/tests.py
tests/sentry/quotas/redis/tests.py
# -*- coding: utf-8 -*- from __future__ import absolute_import import mock from redis.client import ( Script, StrictRedis, ) from exam import fixture, patcher from sentry.quotas.redis import ( IS_RATE_LIMITED_SCRIPT, RedisQuota, ) from sentry.testutils import TestCase def test_is_rate_limited_script(): client = StrictRedis(db=9) script = Script(client, IS_RATE_LIMITED_SCRIPT) # The item should not be rate limited by either key. assert map(bool, script(('foo', 'bar'), (1, 2))) == [False, False] # The item should be rate limited by the first key (1). assert map(bool, script(('foo', 'bar'), (1, 2))) == [True, False] # The item should still be rate limited by the first key (1), but *not* # rate limited by the second key (2) even though this is the third time # we've checked the quotas. This ensures items that are rejected by a lower # quota don't affect unrelated items that share a parent quota. assert map(bool, script(('foo', 'bar'), (1, 2))) == [True, False] client.get('foo') == '1' client.get('bar') == '1' class RedisQuotaTest(TestCase): @fixture def quota(self): inst = RedisQuota(hosts={ 0: {'db': 9} }) return inst @patcher.object(RedisQuota, 'get_project_quota') def get_project_quota(self): inst = mock.MagicMock() inst.return_value = 0 return inst @patcher.object(RedisQuota, 'get_organization_quota') def get_organization_quota(self): inst = mock.MagicMock() inst.return_value = 0 return inst def test_default_host_is_local(self): quota = RedisQuota() self.assertEquals(len(quota.cluster.hosts), 1) self.assertEquals(quota.cluster.hosts[0].host, 'localhost') def test_skips_unset_quotas(self): # This assumes ``get_*_quota`` methods are mocked. assert set(self.quota._get_quotas(self.project)) == set() def test_uses_defined_quotas(self): self.get_project_quota.return_value = 200 self.get_organization_quota.return_value = 300 assert set(self.quota._get_quotas(self.project)) == set(( (self.quota._get_project_key(self.project), 200), (self.quota._get_organization_key(self.project.team), 300), )) @mock.patch('sentry.quotas.redis.is_rate_limited') def test_bails_immediately_without_any_quota(self, is_rate_limited): # This assumes ``get_*_quota`` methods are mocked. result = self.quota.is_rate_limited(self.project) assert not is_rate_limited.called assert not result.is_limited @mock.patch('sentry.quotas.redis.is_rate_limited', return_value=(False, False)) def test_is_not_limited_without_rejections(self, is_rate_limited): self.get_organization_quota.return_value = 100 self.get_project_quota.return_value = 200 assert not self.quota.is_rate_limited(self.project).is_limited @mock.patch('sentry.quotas.redis.is_rate_limited', return_value=(True, False)) def test_is_limited_on_rejections(self, is_rate_limited): self.get_organization_quota.return_value = 100 self.get_project_quota.return_value = 200 assert self.quota.is_rate_limited(self.project).is_limited
Python
0
@@ -2295,12 +2295,20 @@ ect. -team +organization ), 3
a78fe01101de6143885f2559a519024a86d97315
Add new command dev_guess_downloader.
allmychanges/management/commands/dev_guess_downloader.py
allmychanges/management/commands/dev_guess_downloader.py
Python
0
@@ -0,0 +1,383 @@ +# coding: utf-8%0Afrom django.core.management.base import BaseCommand%0Afrom twiggy_goodies.django import LogMixin%0A%0Afrom allmychanges.downloader import guess_downloader%0A%0A%0Aclass Command(LogMixin, BaseCommand):%0A help = u%22%22%22Command to test how downloader guesser workds for given url.%22%22%22%0A%0A def handle(self, *args, **options):%0A url = args%5B0%5D%0A print guess_downloader(url)%0A
c5dbebe13e2c1c7018a1701e3c8e37ae29f9a387
add solution for Reverse Integer
src/reverseInteger.py
src/reverseInteger.py
Python
0.000018
@@ -0,0 +1,412 @@ +class Solution:%0A # @return an integer%0A%0A def reverse(self, x):%0A int_max = 2147483647%0A limit = int_max/10%0A if x %3E 0:%0A sig = 1%0A elif x %3C 0:%0A sig = -1%0A x = -x%0A else:%0A return x%0A y = 0%0A while x:%0A if y %3E limit:%0A return 0%0A y = y*10 + (x %25 10)%0A x /= 10%0A return y*sig%0A
6f3ae8a9e8a400b8882cf57fa0753c1c44b85c2a
Create pdf_all.py
pdf_all.py
pdf_all.py
Python
0
@@ -0,0 +1,740 @@ +#!/usr/bin/env python%0A# encoding:UTF-8%0A%22%22%22%0AThis script runs a file through all of the PDF tools%0A%22%22%22%0A%0Aimport sys%0A%0Aimport pdf_js%0Aimport pdf_links%0Aimport pdf_strings%0Aimport pdf_openaction%0A%0A%0Adef run_all(fpath):%0A print %22*%22*20 + %22PDF OpenAction%22 + %22*%22*20%0A pdf_openaction.extract_openactions(fpath)%0A print %22*%22*20 + %22PDF URLs%22 + %22*%22*20%0A pdf_links.extract_urls(fpath)%0A print %22*%22*20 + %22PDF JavaScript%22 + %22*%22*20%0A pdf_js.extract_js(fpath)%0A print %22*%22*20 + %22PDF Strings%22 + %22*%22*20%0A pdf_strings.get_strings(fpath)%0A%0A%0Adef main():%0A if len(sys.argv) %3C 2:%0A print %22USAGE: %25s %25s %3Cfilename%3E%22 %25 (sys.executable, sys.argv%5B0%5D)%0A sys.exit(1)%0A fpath = sys.argv%5B1%5D%0A run_all(fpath)%0A%0Aif __name__ == %22__main__%22:%0A main()%0A
288a59cfeade739260a1f76cf632d735677022be
Add the start of some test for the scoring stuff.
src/test_scores_db.py
src/test_scores_db.py
Python
0.999996
@@ -0,0 +1,397 @@ +import scores_db%0Aimport mock%0Aimport redis_client%0Aimport control%0Afrom twisted.internet import defer%0A%0Adef test_set_scores():%0A fake_connection = mock.Mock()%0A fake_connection.set = mock.Mock()%0A with mock.patch('redis_client.connection', fake_connection):%0A scores_db.scores.set_match_score(1, 'ABC', 12)%0A fake_connection.set.assert_called_once_with('comp:scores:1:ABC:game', 12)%0A
a0e4ba8dbdd14f51d17d2fb1c4e0829894d7cd10
Add utility file for playbook
src/utils/playbook.py
src/utils/playbook.py
Python
0.000001
@@ -0,0 +1,327 @@ +from django.conf import settings%0Afrom ansible.models import Playbook%0Aimport os%0A%0A%0Adef content_loader(pk, slug):%0A playbook = Playbook.query_set.get(pk=pk)%0A playbook_dir = playbook.directory%0A # TODO: for now assume without validation%0A playbook_file = os.path.join(playbook_dir, slug + '.yml')%0A return playbook_file%0A
41bed7865c9002086f5599059700ed8599c8c7ef
Copy of existing (manual) https debug tool
Sketches/MPS/ProxyHTTP/https.py
Sketches/MPS/ProxyHTTP/https.py
Python
0
@@ -0,0 +1,2207 @@ +#!/usr/bin/python%0A# -*- coding: utf-8 -*-%0A%0A# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)%0A#%0A# (1) Kamaelia Contributors are listed in the AUTHORS file and at%0A# http://www.kamaelia.org/AUTHORS - please extend this file,%0A# not this notice.%0A#%0A# Licensed under the Apache License, Version 2.0 (the %22License%22);%0A# you may not use this file except in compliance with the License.%0A# You may obtain a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS,%0A# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A# See the License for the specific language governing permissions and%0A# limitations under the License.%0A%0Afrom Kamaelia.Chassis.Graphline import Graphline%0Afrom Kamaelia.Internet.TCPClient import TCPClient%0Afrom Kamaelia.Util.Console import ConsoleEchoer, ConsoleReader%0Afrom Kamaelia.Util.OneShot import OneShot%0A%0Aprint %22%22%22%0AThis is a simple demonstration program that shows that it is possible to%0Abuild simple clients for manually connecting to SSL based sources - such%0Aas HTTPS sources.%0A%0AThis program connects the the subversion server for Kamaelia on port%0A443 on sourceforge - ie on kamaelia.svn.sourceforge.net. When you are%0Aconnected you are connected through an encrypted connection, which means%0Ayou could type the following and get code back from the server:%0A%0AGET /svnroot/kamaelia/trunk/Code/Python/Kamaelia/Examples/SimpleGraphicalApps/Ticker/Ulysses HTTP/1.0%0AHost: kamaelia.svn.sourceforge.net%0A%0AThat's pretty much the purpose of this example program.%0A%22%22%22%0A%0AGraphline(%0A MAKESSL = OneShot(%22 make ssl %22), # The actual message here is not necessary%0A CONSOLE = ConsoleReader(),%0A ECHO = ConsoleEchoer(),%0A CONNECTION = TCPClient(%22kamaelia.svn.sourceforge.net%22, 443),%0A linkages = %7B%0A (%22MAKESSL%22, %22outbox%22): (%22CONNECTION%22, %22makessl%22),%0A (%22CONSOLE%22, %22outbox%22): (%22CONNECTION%22, %22inbox%22),%0A (%22CONSOLE%22, %22signal%22): (%22CONNECTION%22, %22control%22),%0A (%22CONNECTION%22, %22outbox%22): (%22ECHO%22, %22inbox%22),%0A (%22CONNECTION%22, %22signal%22): (%22ECHO%22, %22control%22),%0A %7D%0A).run()%0A
4fd051fd6d048e64f574097a3ca314111087ee45
Fix up conv models to match current master.
theanets/convolution.py
theanets/convolution.py
# -*- coding: utf-8 -*- '''This module contains convolution network structures.''' from . import feedforward class Regressor(feedforward.Regressor): '''A regressor attempts to produce a target output. A convolutional regression model takes the following inputs during training: - ``x``: A three-dimensional array of input data. Each element of axis 0 of ``x`` is expected to be one moment in time. Each element of axis 1 of ``x`` holds a single sample from a batch of data. Each element of axis 2 of ``x`` represents the measurements of a particular input variable across all times and all data items. - ``targets``: A two-dimensional array of target output data. Each element of axis 0 of ``targets`` is expected to be one moment in time. Each element of axis 1 of ``targets`` holds a single sample from a batch of data. Each element of axis 2 of ``targets`` represents the measurements of a particular output variable across all times and all data items. ''' def __init__(self, layers=(), loss='mse', weighted=False): super(feedforward.Regressor, self).__init__( layers=layers, loss=loss, in_dim=4, out_dim=2, weighted=weighted) class Classifier(feedforward.Classifier): '''A classifier attempts to match a 1-hot target output. Unlike a feedforward classifier, where the target labels are provided as a single vector, a recurrent classifier requires a vector of target labels for each time step in the input data. So a recurrent classifier model requires the following inputs for training: - ``x``: A three-dimensional array of input data. Each element of axis 0 of ``x`` is expected to be one moment in time. Each element of axis 1 of ``x`` holds a single sample in a batch of data. Each element of axis 2 of ``x`` represents the measurements of a particular input variable across all times and all data items in a batch. - ``labels``: A one-dimensional vector of integer target labels. Each element of ``labels`` is expected to be the class index for a single batch item. ''' def __init__(self, layers=(), loss='xe', weighted=False): super(feedforward.Classifier, self).__init__( layers=layers, loss=loss, in_dim=4, out_dim=1, weighted=weighted)
Python
0
@@ -205,1030 +205,93 @@ put. +''' %0A%0A -A convolutional regression model takes the following inputs during training:%0A%0A - %60%60x%60%60: A three-dimensional array of input data. Each element of axis 0 of%0A %60%60x%60%60 is expected to be one moment in time. Each element of axis 1 of%0A %60%60x%60%60 holds a single sample from a batch of data. Each element of axis 2%0A of %60%60x%60%60 represents the measurements of a particular input variable across%0A all times and all data items.%0A%0A - %60%60targets%60%60: A two-dimensional array of target output data. Each element%0A of axis 0 of %60%60targets%60%60 is expected to be one moment in time. Each%0A element of axis 1 of %60%60targets%60%60 holds a single sample from a batch of%0A data. Each element of axis 2 of %60%60targets%60%60 represents the measurements of%0A a particular output variable across all times and all data items.%0A '''%0A%0A def __init__(self, layers=(), loss='mse', weighted=False):%0A super(feedforward.Regressor, self).__init__(%0A layers=layers, loss=loss, in_dim=4, out_dim=2, weighted=weighted) +INPUT_NDIM = 4%0A '''Number of dimensions for holding input data arrays.''' %0A%0A%0Ac @@ -395,1017 +395,90 @@ put. +''' %0A%0A -Unlike a feedforward classifier, where the target labels are provided as a%0A single vector, a recurrent classifier requires a vector of target labels for%0A each time step in the input data. So a recurrent classifier model requires%0A the following inputs for training:%0A%0A - %60%60x%60%60: A three-dimensional array of input data. Each element of axis 0 of%0A %60%60x%60%60 is expected to be one moment in time. Each element of axis 1 of%0A %60%60x%60%60 holds a single sample in a batch of data. Each element of axis 2 of%0A %60%60x%60%60 represents the measurements of a particular input variable across%0A all times and all data items in a batch.%0A%0A - %60%60labels%60%60: A one-dimensional vector of integer target labels. Each%0A element of %60%60labels%60%60 is expected to be the class index for a single batch%0A item.%0A '''%0A%0A def __init__(self, layers=(), loss='xe', weighted=False):%0A super(feedforward.Classifier, self).__init__(%0A layers=layers, loss=loss, in_dim=4, out_dim=1, weighted=weighted) +INPUT_NDIM = 4%0A '''Number of dimensions for holding input data arrays.''' %0A
1dc795fcf3e6c09a9a77fb008ee3b5fe5c7c3719
fix bug 1035957 - correct received_at column
alembic/versions/391e42da94dd_bug_1035957_use_literal_now_for_.py
alembic/versions/391e42da94dd_bug_1035957_use_literal_now_for_.py
Python
0
@@ -0,0 +1,782 @@ +%22%22%22bug 1035957 - use literal NOW() for received_at, do not evaluate at migration time%0A%0A%0ARevision ID: 391e42da94dd%0ARevises: 495bf3fcdb63%0ACreate Date: 2014-07-08 10:55:04.115932%0A%0A%22%22%22%0A%0A# revision identifiers, used by Alembic.%0Arevision = '391e42da94dd'%0Adown_revision = '495bf3fcdb63'%0A%0Afrom alembic import op%0Afrom socorro.lib import citexttype, jsontype, buildtype%0Afrom socorro.lib.migrations import fix_permissions, load_stored_proc%0A%0Aimport sqlalchemy as sa%0Afrom sqlalchemy import types%0Afrom sqlalchemy.dialects import postgresql%0Afrom sqlalchemy.sql import table, column%0A%0A%0Adef upgrade():%0A op.alter_column(u'raw_adi', u'received_at', server_default=sa.text('NOW()')),%0A%0A%0Adef downgrade():%0A op.alter_column(u'raw_adi', u'received_at', server_default='2014-06-24 00:29:17.218147+00'),%0A
05ce8407af2075ebcc002583b4224659d19dc9db
Add unit tests for spack help command (#6779)
lib/spack/spack/test/cmd/help.py
lib/spack/spack/test/cmd/help.py
Python
0
@@ -0,0 +1,2759 @@ +##############################################################################%0A# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.%0A# Produced at the Lawrence Livermore National Laboratory.%0A#%0A# This file is part of Spack.%0A# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.%0A# LLNL-CODE-647188%0A#%0A# For details, see https://github.com/spack/spack%0A# Please also see the NOTICE and LICENSE files for our notice and the LGPL.%0A#%0A# This program is free software; you can redistribute it and/or modify%0A# it under the terms of the GNU Lesser General Public License (as%0A# published by the Free Software Foundation) version 2.1, February 1999.%0A#%0A# This program is distributed in the hope that it will be useful, but%0A# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF%0A# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and%0A# conditions of the GNU 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 program; if not, write to the Free Software%0A# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA%0A##############################################################################%0Aimport pytest%0A%0Afrom spack.main import SpackCommand%0A%0A%0A@pytest.mark.xfail%0Adef test_reuse_after_help():%0A %22%22%22Test %60spack help%60 can be called twice with the same SpackCommand.%22%22%22%0A help_cmd = SpackCommand('help')%0A help_cmd()%0A%0A # This second invocation will somehow fail because the parser no%0A # longer works after add_all_commands() is called in%0A # SpackArgumentParser.format_help_sections().%0A #%0A # TODO: figure out why this doesn't work properly and change this%0A # test to use a single SpackCommand.%0A #%0A # It seems that parse_known_args() finds %22too few arguments%22 the%0A # second time through b/c add_all_commands() ends up leaving extra%0A # positionals in the parser. But this used to work before we loaded%0A # commands lazily.%0A help_cmd()%0A%0A%0Adef test_help():%0A %22%22%22Sanity check the help command to make sure it works.%22%22%22%0A help_cmd = SpackCommand('help')%0A out = help_cmd()%0A assert 'These are common spack commands:' in out%0A%0A%0Adef test_help_all():%0A %22%22%22Test the spack help --all flag%22%22%22%0A help_cmd = SpackCommand('help')%0A out = help_cmd('--all')%0A assert 'Complete list of spack commands:' in out%0A%0A%0Adef test_help_spec():%0A %22%22%22Test the spack help --spec flag%22%22%22%0A help_cmd = SpackCommand('help')%0A out = help_cmd('--spec')%0A assert 'spec expression syntax:' in out%0A%0A%0Adef test_help_subcommand():%0A %22%22%22Test the spack help subcommand argument%22%22%22%0A help_cmd = SpackCommand('help')%0A out = help_cmd('help')%0A assert 'get help on spack and its commands' in out%0A
3590a162363ff62859eccf9f7f46c74f2c5cadc4
Create PAKvsIND.py
PAKvsIND.py
PAKvsIND.py
Python
0
@@ -0,0 +1,2098 @@ +# -*- coding: utf-8 -*-%0A%22%22%22%0ACreated on Tue Jun 20 01:56:57 2017%0A%0A@author: Muhammad Salek Ali%0A%22%22%22%0A%0A# 1- Importing libraries for twitter and NLP%0A#--------------------------------------------%0Aimport numpy as np%0Aimport tweepy%0Afrom textblob import TextBlob%0A%0A%0A# 2- Authentication%0A#-------------------%0AconsumerKey= 'enter_yours_here'%0AconsumerSecret= 'enter_yours_here'%0A%0AaccessToken='enter_yours_here'%0AaccessTokenSecret='enter_yours_here'%0A%0Aauth = tweepy.OAuthHandler(consumerKey, consumerSecret)%0Aauth.set_access_token(accessToken, accessTokenSecret)%0A%0Aapi = tweepy.API(auth)%0A%0A%0A# 3- Prepare query features%0A#---------------------------%0A%0Ateams = %5B'India', 'Pakistan'%5D%0Ahashtag = %22PAKvsIND%22 %0A%0A#Tweets to be collected:%0AfromDate = %222017-06-17%22%0A%0A%0A# 4- Analysis Result Labels%0A#----------------------------%0Adef senti(analysis, threshold = 0):%0A if analysis.sentiment%5B0%5D%3Ethreshold:%0A return 'Positive'%0A elif analysis.sentiment%5B0%5D==threshold:%0A return 'Neutral'%0A else:%0A return 'Negative'%0A%0A%0A# 5- Retrieve Tweets and Save Them%0A#----------------------------------%0A%0AmeanPolarities = dict()%0A%0Afor team in teams:%0A teamPolarities = %5B%5D%0A%0A #Save the tweets in csv%0A with open('%25s_tweets.csv' %25 team, 'w') as teamFile:%0A teamFile.write('tweet,label,sentiment%5Cn')%0A maxQuery=5000%0A for tweet in tweepy.Cursor(api.search,%0A q=%5Bhashtag,team%5D,%0A include_entities=True%0A ).items():%0A text = TextBlob(tweet.text)%0A #Get the label corresponding to the sentiment analysis%0A teamPolarities.append(text.sentiment%5B0%5D)%0A print (len(teamPolarities))%0A print (senti(text))%0A teamFile.write('%25s,%25s,%25s%5Cn' %25 (tweet.text.encode('utf8'), senti(text),str(text.sentiment%5B0%5D)))%0A if (len(teamPolarities)%3E=maxQuery):%0A break%0A #Save the mean for final results%0A meanPolarities%5Bteam%5D = np.mean(teamPolarities)%0A%0A%0A# 6- Output a Result%0A#--------------------%0A%0Aprint ('Mean Sentiment Polarities:')%0Aprint(meanPolarities)%0A
3b82f7ada9e80eb581cf924dbf7b0490f864b264
break at 500
012_highly_divisible_triangular_number.py
012_highly_divisible_triangular_number.py
Python
0.000005
@@ -0,0 +1,581 @@ +#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A#%0A# A Solution to %22Highly divisible triangular number%22 %E2%80%93 Project Euler Problem No. 12%0A# by Florian Buetow%0A#%0A# Sourcecode: https://github.com/fbcom/project-euler%0A# Problem statement: https://projecteuler.net/problem=12%0A#%0A%0Ai = n = 0%0Awhile True:%0A i = i + 1%0A n = i*(i+1)/2 # sum of 1 to i%0A counter = 2 # 1 and n are two trivial factors of n%0A for d in range(2, int(n**0.5)+1):%0A if n %25 d == 0:%0A counter = counter + 2%0A if counter %3E 500:%0A break%0A%0Aprint %22Solution: %25d has %25d factors%22 %25 (n, counter)%0A
f31dd0c7f23273207eab5e30a3ea42b5edf30f2b
work in progress, script to balance PTR records
mnm-balance-reversezones.py
mnm-balance-reversezones.py
Python
0
@@ -0,0 +1,2923 @@ +#!/usr/bin/env python3%0A# Copyright (C) 2013 Men & Mice%0A#%0A# Permission to use, copy, modify, and/or distribute this software for any%0A# purpose with or without fee is hereby granted, provided that the above%0A# copyright notice and this permission notice appear in all copies.%0A#%0A# THE SOFTWARE IS PROVIDED %22AS IS%22 AND MEN & MICE DISCLAIMS ALL WARRANTIES WITH%0A# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY%0A# AND FITNESS. IN NO EVENT SHALL MEN & MICE BE LIABLE FOR ANY SPECIAL, DIRECT,%0A# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM%0A# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE%0A# OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR%0A# PERFORMANCE OF THIS SOFTWARE.%0A%0A%22%22%22%0AThis script balances the forward lookup and reverse lookup zones. It%0Achecks that all A/AAAA record entries have matching PTR records, and%0Ait looks for PTR records without matching A/AAAA records (orphaned PTR%0Arecords). %0A%0AIt is the script version of the %22reverse-zone-wizard%22 and the %22find%0Aorphan PTR records%22 functions in the Men & Mice GUI.%0A%0AThis script requires the Men & Mice Suite CLI mmcmd%0A%0AAuthor: Carsten Strotmann - carsten@menandmice.com%0AVersion: 0.1 (wip)%0ADate: 2013-09-04%0A%22%22%22%0A%0Aimport os%0Aimport sys%0Aimport subprocess%0Aimport string%0Afrom optparse import OptionParser%0A%0Aserver = %22127.0.0.1%22%0Ammcmdpgm = %22/usr/bin/mmcmd%22%0Auser = %22administrator%22%0Apassword = %22menandmice%22%0Amasterserver = %22ns1.example.com%22%0A%0Adef mmcmd(cmd, debugflag=False):%0A if debugflag: %0A print(%22mmcmd %7B%7D%22.format(cmd))%0A output = subprocess.check_output(%5Bmmcmdpgm, %0A %22-q%22, %22-s%7B%7D%22.format(server), %0A %22-u%7B%7D%22.format(user), %0A %22-p%7B%7D%22.format(password), %0A %22%7B%7D; quit;%22.format(cmd)%5D, timeout=60).decode(%22utf8%22)%0A return output%0A%0A%0A# Main program%0Aif __name__ == %22__main__%22:%0A parser = OptionParser(usage=%22Usage: %25prog %5B--help %7C options%5D%22)%0A parser.add_option(%22-d%22, action=%22store_true%22, dest=%22debugflag%22,%0A default=False, help=%22print debug information%22)%0A parser.add_option(%22-r%22, action=%22store_true%22, dest=%22removeflag%22,%0A default=False, %0A help=%22remove orphaned PTR records%22)%0A parser.add_option(%22-a%22, action=%22store_true%22, dest=%22addflag%22,%0A default=False, %0A help=%22add missing PTR records%22)%0A (options, args) = parser.parse_args()%0A%0A print (%22Balancing reverse zones ...%22)%0A%0A zones = mmcmd(%22zones%22, options.debugflag).lower()%0A zones = zones.splitlines()%0A zonelist = %5Bz.split(%22 %22,1)%5B0%5D for z in zones%5D%0A zonelist = %5Bz for z in zonelist if not '::' in z%5D%0A rev4zonelist = %5Bz for z in zonelist if z.endswith(%22in-addr.arpa%22)%5D %0A rev6zonelist = %5Bz for z in zonelist if z.endswith(%22ip6.arpa%22)%5D %0A%0A%0A
2187ae0b6303ae1745749b270c5c46937d8dde33
Create mexican_wave.py
mexican_wave.py
mexican_wave.py
Python
0.998674
@@ -0,0 +1,255 @@ +#Kunal Gautam%0A#Codewars : @Kunalpod%0A#Problem name: Mexican Wave%0A#Problem level: 6 kyu%0A%0Adef wave(str):%0A li=%5B%5D%0A for i in range(len(str)):%0A x=list(str)%0A x%5Bi%5D=x%5Bi%5D.upper()%0A li.append(''.join(x))%0A return %5Bx for x in li if x!=str%5D%0A
fdc40675eabaeee191fa3a047705b677d431f58c
Create a small form class to facilitate easy use of Djangos CSRF functionality
src/whitelist/util/apply_whitelist_form.py
src/whitelist/util/apply_whitelist_form.py
Python
0
@@ -0,0 +1,198 @@ +from django import forms%0A%0Aclass ApplyWhitelistForm(forms.Form):%0A %22%22%22A small placeholder form class to allow Django's form magic to take%0A hold of the %22apply whitelist%22 button.%0A %22%22%22%0A pass%0A
252c0916e4db033c3aee81e232a64e649f6bc926
add a command to trigger a bulk sync
crate_project/apps/crate/management/commands/trigger_bulk_sync.py
crate_project/apps/crate/management/commands/trigger_bulk_sync.py
Python
0.000001
@@ -0,0 +1,240 @@ +from django.core.management.base import BaseCommand%0A%0Afrom pypi.tasks import bulk_synchronize%0A%0A%0Aclass Command(BaseCommand):%0A%0A def handle(self, *args, **options):%0A bulk_synchronize.delay()%0A print %22Bulk Synchronize Triggered%22%0A
457ba730a6541ab27ce8cbe06cbb6bfe246bba74
Add a simple HTTP Basic Authentication decorator for the API
towel/api/decorators.py
towel/api/decorators.py
Python
0
@@ -0,0 +1,943 @@ +from functools import wraps%0Aimport httplib%0A%0Afrom django.contrib.auth import authenticate%0Afrom django.utils.cache import patch_vary_headers%0A%0A%0Adef http_basic_auth(func):%0A @wraps(func)%0A @vary_on_headers('Authorization')%0A def _decorator(request, *args, **kwargs):%0A if 'HTTP_AUTHORIZATION' in request.META:%0A meth, _, auth = request.META%5B'HTTP_AUTHORIZATION'%5D.partition(' ')%0A if meth.lower() == 'basic':%0A try:%0A auth = auth.strip().decode('base64')%0A except Exception:%0A return HttpResponse('Invalid authorization header',%0A status=httplib.BAD_REQUEST)%0A%0A username, sep, password = auth.partition(':')%0A user = authenticate(username=username, password=password)%0A if user:%0A request.user = user%0A%0A return func(request, *args, **kwargs)%0A return _decorator%0A
457937561f6a581edd495d7f9559f57b94108c24
add really basic game implementation
haive/game.py
haive/game.py
Python
0
@@ -0,0 +1,1949 @@ +%0A# An interactive wrapper for the model%0A%0Afrom haive import model%0Afrom collections import namedtuple%0A%0Adef tuple_from_string(string):%0A return tuple(int(item) for item in string.split(','))%0A%0Ahuman = 'human'%0Aai = 'ai'%0Aplayer_types = (human, ai)%0A%0AMove = namedtuple('Move', ('token','source','destination'))%0A%0Aclass Game(object):%0A def __init__(self, m, players, ai=None):%0A self.m = m%0A self.ai = ai%0A self.active_player = model.black%0A self.players = players%0A%0A def make_move(self, move):%0A if move.token is not None:%0A self.m.add(move.token, move.destination)%0A elif move.source is not None:%0A self.m.move(move.source, move.destination)%0A else:%0A raise ValueError%0A%0A def human_move(self):%0A print(self.render_model())%0A source, destination = input(%22Please enter a move for %22+self.active_player+%22: %22).split(%22 %22)%0A if source in model.kinds:%0A human_move = Move(token=model.Token(colour=self.active_player, kind=source), source=None, destination=tuple_from_string(destination))%0A else:%0A human_move = Move(token=None, source=tuple_from_string(source), destination=tuple_from_string(destination))%0A self.make_move(human_move)%0A%0A def ai_move(self):%0A self.make_move(self.ai.choose_move(self.m, self.active_player))%0A%0A def play(self):%0A while self.m.winner() is None:%0A if self.players%5Bself.active_player%5D == human:%0A self.human_move()%0A elif self.players%5Bself.active_player%5D == ai:%0A self.ai_move()%0A else:%0A raise ValueError%0A self.active_player = self.m.colour_opposite(self.active_player)%0A return self.m.winner()%0A%0A def render_model(self):%0A print(self.m.state)%0A%0Aif __name__ == '__main__':%0A game = Game(model.Model(), %7Bmodel.black:human, model.white:human%7D)%0A winner = game.play()%0A print(winner, %22won!%22)
c8d441fbee372abc61867d594f0645d9d79a36f0
add raw data parser script
parseRawData/parseRawXML.py
parseRawData/parseRawXML.py
Python
0.000001
@@ -0,0 +1,1402 @@ +#!/usr/bin/python%0A%0Aimport sys%0Aimport json%0A%0Afrom bs4 import BeautifulSoup%0A%0Aimport logging%0Alogging.basicConfig(format='%25(asctime)s - %25(name)s - %25(levelname)s - %25(message)s')%0Alogger = logging.getLogger(__name__)%0Alogger.setLevel(logging.DEBUG)%0A%0A%0A%0Adef extract_xml(markup):%0A %22%22%22%0A Extract %60url%60, %60title%60, 'description%60, and %60topic%60 from XML 'ExternalPage' markup%0A %22%22%22%0A soup = BeautifulSoup(markup, 'lxml')%0A tag = soup.externalpage%0A%0A result = dict()%0A result%5B'url'%5D = tag%5B'about'%5D%0A result%5B'title'%5D = tag.title.text%0A result%5B'description'%5D = tag.description.text%0A result%5B'topic'%5D = tag.topic.text.split('/')%0A return result%0A%0A%0Adef main(argv):%0A%0A cnt = 0%0A xml = ''%0A trigger = False%0A with sys.stdin as f:%0A for line in f:%0A # set up start tag%0A if '%3CExternalPage' in line:%0A trigger = True%0A # set up close tag%0A elif '%3C/ExternalPage%3E' in line:%0A cnt += 1%0A trigger = False%0A xml += line.rstrip('%5Cn')%0A%0A # process xml block%0A result = extract_xml(xml)%0A logger.info(%22processed%5Ct%25d%5Ct%25s%22 %25 (cnt, result%5B'url'%5D))%0A print %3E%3E sys.stdout, json.dumps(result)%0A xml = ''%0A%0A if trigger:%0A xml += line.rstrip('%5Cn').replace('d:', '')%0A%0A%0Aif __name__ == %22__main__%22:%0A main(sys.argv%5B1:%5D)%0A%0A
e83dd0bfa4f601ed3c5ea9687d2781e83a2e6bf4
Add logger
cpnest/logger.py
cpnest/logger.py
Python
0.00002
@@ -0,0 +1,1059 @@ +import logging%0A%0Adef start_logger(output=None, verbose=0):%0A %22%22%22%0A Start an instance of Logger for logging%0A%0A output : %60str%60%0A output directory (./)%0A%0A verbose: %60int%60%0A Verbosity, 0=CRITICAL, 1=WARNING, 2=INFO, 3=DEBUG%0A%0A fmt: %60str%60%0A format for logger (None) See logging documentation for details%0A%0A %22%22%22%0A # possible levels%0A verbose = min(verbose, 3)%0A # levels 0, 1, 2, 3%0A levels = %5B'CRITICAL', 'WARNING', 'INFO', 'DEBUG'%5D%0A level = levels%5Bverbose%5D%0A fmt = '%25(asctime)s - %25(name)-8s: %25(message)s'%0A # setup logger%0A logger = logging.getLogger('CPNest')%0A logger.setLevel(level)%0A # handle command line output%0A ch = logging.StreamHandler()%0A ch.setFormatter(logging.Formatter(fmt, datefmt='%25Y-%25m-%25d, %25H:%25M:%25S'))%0A logger.addHandler(ch)%0A%0A if output is not None:%0A # log to file%0A fh = logging.FileHandler(output + 'cpnest.log')%0A fh.setFormatter(logging.Formatter(fmt))%0A logger.addHandler(fh)%0A print(logger.critical('Logging level: %7B%7D'.format(level)))%0A return logger%0A
5fe88aa7d814bb630c29a7afcf511caba8c03ece
add placeholder
htdocs/c/c.py
htdocs/c/c.py
Python
0
@@ -0,0 +1,533 @@ +import os%0Aimport sys%0A%0Atilecachepath, wsgi_file = os.path.split(__file__)%0Asys.path.insert(0, %22/opt/iem/include/python/%22)%0Asys.path.insert(0, %22/opt/iem/include/python/TileCache/%22)%0A%0Afrom TileCache.Service import Service, wsgiHandler%0A%0Acfgfiles = os.path.join(tilecachepath, %22tilecache.cfg%22)%0A%0AtheService = %7B%7D%0A%0A%0Adef wsgiApp(environ, start_response):%0A global theService%0A%0A cfgs = cfgfiles%0A if not theService:%0A theService = Service.load(cfgs)%0A return wsgiHandler(environ, start_response, theService)%0A%0A%0Aapplication = wsgiApp%0A
4a1b7c7e1c6bd1df2d31e37a0cf97853faafb8e5
Add BrowserScraper class
BrowserScraper.py
BrowserScraper.py
Python
0
@@ -0,0 +1,2523 @@ +import time%0Afrom selenium import webdriver%0Afrom selenium.common.exceptions import StaleElementReferenceException%0A%0A%0Aclass BrowserScraper():%0A def __init__(self, username, level, driver=None):%0A if driver is None:%0A self.driver = webdriver.Chrome('./chromedriver')%0A pass%0A%0A def wait(self):%0A time.sleep(3)%0A%0A def scrapeUser(self, userLink):%0A self.driver.get(userLink)%0A links = self.driver.find_elements_by_tag_name('a')%0A users = %5B%5D%0A%0A safetyCounter = 0%0A for link in links:%0A%0A try:%0A linkAdress = link.get_attribute(%22href%22)%0A except StaleElementReferenceException:%0A links = self.driver.find_elements_by_tag_name('a')%5B:safetyCounter%5D%0A continue%0A%0A if %22taken-by%22 in linkAdress:%0A link.click()%0A self.wait()%0A potentialUsers = self.driver.find_elements_by_tag_name('a')%0A if potentialUsers is not None:%0A for potentialUser in potentialUsers:%0A%0A if potentialUser.get_attribute('href') is not None and potentialUser.get_attribute(%0A 'title') in potentialUser.get_attribute('href') and BrowserScraper.isUserLink(%0A potentialUser):%0A users.append(potentialUser.get_attribute('href'))%0A%0A potentialCloseButtons = self.driver.find_elements_by_tag_name('button')%0A%0A for potentialCloseButton in potentialCloseButtons:%0A if 'CLOSE' in potentialCloseButton.text.upper():%0A potentialCloseButton.click()%0A safetyCounter += 1%0A return set(users)%0A%0A @classmethod%0A def getUserLink(cls, username):%0A return %22https://www.instagram.com/%22 + username + %22/%22%0A%0A @classmethod%0A def isUserLink(cls, link):%0A address = link.get_attribute('href')%0A parent = link.find_element_by_xpath('..')%0A%0A return %22/accounts/%22 not in address and %5C%0A %22/p/%22 not in address and %5C%0A %22/legal/%22 not in address and %5C%0A 'LI' in parent.get_property(%22tagName%22).upper() and %5C%0A '/blog.instagram.com/' not in address and %5C%0A '/about/' not in address and %5C%0A '/explore/' not in address and %5C%0A '/developer/' not in address and %5C%0A 'instagram-press.com' not in address and %5C%0A 'help.instagram.com' not in address%0A
c313a21274f4e77d0c4baad13c5c0f5781ac13ef
Create special-binary-string.py
Python/special-binary-string.py
Python/special-binary-string.py
Python
0.999098
@@ -0,0 +1,613 @@ +# Time: f(n) = kf(n/k) + n/k * klogk %3C= O(logn * nlogk) %3C= O(n%5E2)%0A# n is the length of S, k is the max number of special strings in each depth%0A# Space: O(n)%0A %0Aclass Solution(object):%0A def makeLargestSpecial(self, S):%0A %22%22%22%0A :type S: str%0A :rtype: str%0A %22%22%22%0A result = %5B%5D%0A j = count = 0%0A for i, v in enumerate(S):%0A count += 1 if v == '1' else -1%0A if count == 0:%0A result.append(%221%7B%7D0%22.format(self.makeLargestSpecial(S%5Bj+1:i%5D)))%0A j = i+1%0A result.sort(reverse = True)%0A return %22%22.join(result)%0A
63f3e2027948d98781bdd66a0341501facb4b46c
Add test file
image_test.py
image_test.py
Python
0.000001
@@ -0,0 +1,518 @@ +import unittest%0A%0Aclass TestStringMethods(unittest.TestCase):%0A%0A def test_upper(self):%0A self.assertEqual('foo'.upper(), 'FOO')%0A%0A def test_isupper(self):%0A self.assertTrue('FOO'.isupper())%0A self.assertFalse('Foo'.isupper())%0A%0A def test_split(self):%0A s = 'hello world'%0A self.assertEqual(s.split(), %5B'hello', 'world'%5D)%0A # check that s.split fails when the separator is not a string%0A with self.assertRaises(TypeError):%0A s.split(2)%0A%0Aif __name__ == '__main__':%0A unittest.main()%0A
a4ca12fb7f3525206a9a921ab64e31bc145cc9d3
Create __init__.py
__init__.py
__init__.py
Python
0.000429
@@ -0,0 +1 @@ +%0A
102ad365089794d337820714ab281f99af0797b0
update make_base_url
qiniu/auth_token.py
qiniu/auth_token.py
# -*- coding: utf-8 -*- import json import base64 import time import rpc import config import urllib import auth_digest class PutPolicy(object): scope = None # 可以是 bucketName 或者 bucketName:key expires = 3600 # 默认是 3600 秒 callbackUrl = None callbackBody = None returnUrl = None returnBody = None endUser = None asyncOps = None def __init__(self, scope): self.scope = scope def token(self, mac=None): if mac is None: mac = auth_digest.Mac() token = dict( scope = self.scope, deadline = int(time.time()) + self.expires, ) if self.callbackUrl is not None: token["callbackUrl"] = self.callbackUrl if self.callbackBody is not None: token["callbackBody"] = self.callbackBody if self.returnUrl is not None: token["returnUrl"] = self.returnUrl if self.returnBody is not None: token["returnBody"] = self.returnBody if self.endUser is not None: token["endUser"] = self.endUser if self.asyncOps is not None: token["asyncOps"] = self.asyncOps b = json.dumps(token, separators=(',',':')) return mac.sign_with_data(b) class GetPolicy(object): expires = 3600 def __init__(self): pass def make_request(self, base_url, mac=None): ''' * return private_url ''' if mac is None: mac = auth_digest.Mac() deadline = int(time.time()) + self.expires if '?' in base_url: base_url += '&' else: base_url += '?' base_url = '%se=%s' % (base_url, str(deadline)) token = mac.sign(base_url) return '%s&token=%s' % (base_url, token) def make_base_url(domain, key): ''' * domain => str * key => str * return base_url ''' return ''.join(['http://', domain, '/', urllib.quote(key)])
Python
0.000001
@@ -1646,39 +1646,32 @@ rn ' -'.join(%5B'http://', +http://%25s/%25s' %25 ( domain, - '/', url @@ -1684,11 +1684,10 @@ ote(key) -%5D )%0A
647e3b463d1b71ea1a3bd34d11e6a5855b4ea70d
Create __init__.py
__init__.py
__init__.py
Python
0.000429
@@ -0,0 +1 @@ +%0A
988598d0385ce63d951b3cc0817392cf2271575c
change encoding to utf8
__init__.py
__init__.py
Python
0.999791
@@ -0,0 +1,107 @@ +import sys %0A%0Aif not sys.getdefaultencoding()=='utf8':%0A reload(sys) %0A sys.setdefaultencoding('utf8') %0A
51f91603952bc0063630425b582b874f2faea2dd
Change to 2x stddev
src/sentry/tasks/check_alerts.py
src/sentry/tasks/check_alerts.py
""" sentry.tasks.check_alerts ~~~~~~~~~~~~~~~~~~~~~~~~~ - Store a sorted set per project - Each sorted set contains the number of events seen in the interval (1 minute) - An additional set contains the number of unique events seen - Every minute we iterate this sorted set (we can exploit the queue just like buffers to avoid crons) - We clear the results immediately to no-op any concurrent tasks that might try to run - The task fires off a set of subtasks that individually check each project - Each project's value is compared to the historic value in the last N minutes (15m for redis counters or a period of time using the SQL counters) - We only alert if an alert has not been seen on this condition in the last N minutes Notes: - Nydus optimizes out multiple writes/gets, so its not as expensive as it looks - If there are not enough data points in history, alerts are never sent (as they could be false positives) Last Notified will be tracked by using a new Alert model, which has the following properties: - users alerted - datetime - type - ident Type and ident would be similar to how Activity works. Alert expiration threshold MUST be > MINUTE_NORMALIZATION. :copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import division import math import time from datetime import datetime, timedelta from celery.task import periodic_task, task from celery.task.schedules import crontab from django.conf import settings as dj_settings from django.utils import timezone def fsteps(start, stop, steps): step = (stop - start) / steps while start <= stop: yield start start += step def meanstdv(x): n, mean, std = len(x), 0, 0 for a in x: mean = mean + a mean = mean / float(n) for a in x: std = std + (a - mean) ** 2 std = math.sqrt(std / float(n - 1)) return mean, std @periodic_task(ignore_result=True, run_every=crontab(minute='*')) def check_alerts(**kwargs): """ Iterates all current keys and fires additional tasks to check each individual project's alert settings. """ from sentry import app from sentry.utils.queue import maybe_delay timestamp = time.time() - 60 when = datetime.fromtimestamp(timestamp) if dj_settings.USE_TZ: when = when.replace(tzinfo=timezone.utc) results = app.counter.extract_counts(prefix='project', when=timestamp)['results'] for project_id, count in results: maybe_delay(check_project_alerts, project_id=int(project_id), when=when, count=int(count), expires=120, ) @task(ignore_result=True) def check_project_alerts(project_id, when, count, **kwargs): """ Given 'when' and 'count', which should signify recent times we compare it to historical data for this project and if over a given threshold, create an alert. """ from sentry.constants import MINUTE_NORMALIZATION from sentry.conf import settings from sentry.models import ProjectCountByMinute, ProjectOption, Alert try: threshold, min_events = ProjectOption.objects.get(project=project_id, key='project_alert_pct') except ProjectOption.DoesNotExist: threshold, min_events = settings.DEFAULT_ALERT_PROJECT_THRESHOLD if not threshold and min_events: return if min_events > count: return # number of 15 minute intervals to capture intervals = 8 min_date = when - timedelta(minutes=MINUTE_NORMALIZATION) max_date = min_date - timedelta(minutes=(intervals * MINUTE_NORMALIZATION)) # get historical data data = list(ProjectCountByMinute.objects.filter( project=project_id, date__lt=min_date, date__gte=max_date, ).values_list('times_seen', flat=True)) # Bail if we dont have enough data points if len(data) != intervals: return mean, stddev = meanstdv(data) previous = (mean + stddev) / MINUTE_NORMALIZATION if count / previous * 100 > threshold: Alert.maybe_alert( project_id=project_id, message='Rate of events per minute increased from %d to %d' % (previous, count), )
Python
0.000015
@@ -4028,16 +4028,20 @@ + stddev + * 2 ) / MINU
879032d31d8cf89df14489107015b7f29ace1490
Solve designer door mat
python/designer-door-mat.py
python/designer-door-mat.py
Python
0.999927
@@ -0,0 +1,1708 @@ +# Size: 7 x 21%0A# ---------.%7C.---------%0A# ------.%7C..%7C..%7C.------%0A# ---.%7C..%7C..%7C..%7C..%7C.---%0A# -------WELCOME-------%0A# ---.%7C..%7C..%7C..%7C..%7C.---%0A# ------.%7C..%7C..%7C.------%0A# ---------.%7C.---------%0A%0A%0Aclass DoorMat:%0A%0A DASH = %22-%22%0A DOT = %22.%22%0A PIPE = %22%7C%22%0A WELCOME = %22WELCOME%22%0A%0A def __init__(self, N, M):%0A self.N = N%0A self.M = M%0A self.middle_line_number = (self.N - 1) // 2%0A%0A def print_door_mat(self):%0A %5Bprint(self.line(line_number)) for line_number in range(0, N)%5D%0A%0A def line(self, line_number):%0A if(line_number == self.middle_line_number):%0A return self.welcome_line()%0A return self.design_line(line_number)%0A%0A def welcome_line(self):%0A return '%7B:%7Bfill%7D%5E%7Bline_length%7D%7D'.format(self.WELCOME, fill=self.DASH, line_length=self.M)%0A%0A def design_line(self, line_number):%0A return '%7B:%7Bfill%7D%5E%7Bline_length%7D%7D'.format(self.design_for_line(line_number), fill=self.DASH, line_length=self.M)%0A%0A def design_for_line(self, line_number):%0A return self.DOT + self.middle_design(line_number) + self.DOT%0A%0A def middle_design(self, line_number):%0A if(line_number == 0):%0A return self.PIPE%0A%0A pattern = self.PIPE + self.DOT + self.DOT%0A return pattern * self.pattern_repeat_for_line(line_number) + self.PIPE%0A%0A def pattern_repeat_for_line(self, line_number):%0A if line_number %3C self.middle_line_number:%0A return line_number * 2%0A pattern_repeat = (self.N - 1 - line_number) * 2%0A # print(%22pattern repeat: %7B%7D for line number: %7B%7D%22.format(pattern_repeat, line_number))%0A return pattern_repeat%0A%0A%0AN, M = map(int, input().strip().split(%22 %22))%0Adoormat = DoorMat(N, M)%0Adoormat.print_door_mat()%0A
0b9926313831b8fd5c2e72cfc2559f7bdd1c2855
Add class utils
nisl/_utils/class_helper.py
nisl/_utils/class_helper.py
Python
0.000001
@@ -0,0 +1,928 @@ +from sets import Set%0Aimport inspect%0A%0A%0Adef get_params(_class, _object, ignore=None):%0A%0A _ignore = Set(%5B'memory', 'memory_level', 'verbose', 'copy'%5D)%0A if ignore is not None:%0A _ignore.update(ignore)%0A%0A # params is a dictionary%0A params = _class.get_params(_object)%0A%0A for i in _ignore:%0A if i in params:%0A params.pop(i)%0A%0A for p in params:%0A if hasattr(_object, p):%0A params%5Bp%5D = getattr(_object, p)%0A%0A return params%0A%0A%0Adef retrieve_scope():%0A try:%0A caller_frame = inspect.currentframe().f_back.f_back%0A if 'self' in caller_frame.f_locals:%0A caller_name = caller_frame.f_locals%5B'self'%5D.__class__.__name__%0A caller_name = '%25s.%25s' %25 (caller_name,%0A caller_frame.f_code.co_name)%0A #caller_name = caller_frame.f_code.co_name%0A return caller_name%0A except Exception:%0A return 'Unknown'%0A
f71d6b2fe05290ab976e3ba433185ec649a35c20
Move get_context_from_function_and_args() to context.py
openstack/common/context.py
openstack/common/context.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # All Rights Reserved. # # 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. """ Simple class that stores security context information in the web request. Projects should subclass this class if they wish to enhance the request context or provide additional information in their specific WSGI pipeline. """ import uuid def generate_request_id(): return 'req-' + str(uuid.uuid4()) class RequestContext(object): """ Stores information about the security context under which the user accesses the system, as well as additional request information. """ def __init__(self, auth_tok=None, user=None, tenant=None, is_admin=False, read_only=False, show_deleted=False, request_id=None): self.auth_tok = auth_tok self.user = user self.tenant = tenant self.is_admin = is_admin self.read_only = read_only self.show_deleted = show_deleted if not request_id: request_id = generate_request_id() self.request_id = request_id def to_dict(self): return {'user': self.user, 'tenant': self.tenant, 'is_admin': self.is_admin, 'read_only': self.read_only, 'show_deleted': self.show_deleted, 'auth_token': self.auth_tok, 'request_id': self.request_id} def get_admin_context(show_deleted="no"): context = RequestContext(None, tenant=None, is_admin=True, show_deleted=show_deleted) return context
Python
0.000663
@@ -899,16 +899,33 @@ e.%0A%22%22%22%0A%0A +import itertools%0A import u @@ -2210,8 +2210,395 @@ context%0A +%0A%0Adef get_context_from_function_and_args(function, args, kwargs):%0A %22%22%22Find an arg of type RequestContext and return it.%0A%0A This is useful in a couple of decorators where we don't%0A know much about the function we're wrapping.%0A %22%22%22%0A%0A for arg in itertools.chain(kwargs.values(), args):%0A if isinstance(arg, RequestContext):%0A return arg%0A%0A return None%0A
417e76de84f067a90fdcda93ee82d63cc7e56c7b
Add downloader.py
steamplog/downloader.py
steamplog/downloader.py
Python
0
@@ -0,0 +1,2095 @@ +from __future__ import print_function%0Aimport sys%0Aimport json%0Aimport urllib2%0A%0A%0Aclass Downloader(object):%0A '''Download data via Steam-API'''%0A def __init__(self, api_key):%0A self.API = api_key%0A%0A def download_stats(self, steam_id):%0A '''Download owned games from Steam Web API'''%0A URL = %5B'https://api.steampowered.com/'%0A 'IPlayerService/GetOwnedGames/v0001/'%0A '?include_played_free_games=1&format=json',%0A '&key=', self.API,%0A '&steamid=', steam_id%5D%0A URL = ''.join(%5Burl_str for url_str in URL%5D)%0A try:%0A request = urllib2.urlopen(URL)%0A except urllib2.URLError, e:%0A if hasattr(e, 'reason'):%0A print('We failed to reach the server.', file=sys.stderr)%0A print('Reason: ', e.reason, file=sys.stderr)%0A elif hasattr(e, 'code'):%0A print('The server couldn%5C't fulfill the request.',%0A file=sys.stderr)%0A print('Error code: ', e.code, file=sys.stderr)%0A sys.exit(1)%0A response = json.load(request)%0A if %22games%22 not in response%5B'response'%5D:%0A print %3E%3E sys.stderr, 'ERROR: No games found'%0A sys.exit(1)%0A else:%0A return response%5B'response'%5D%5B'games'%5D%0A%0A def download_applist(self):%0A '''Download app names dictionary and return as list'''%0A URL = 'http://api.steampowered.com/ISteamApps/GetAppList/v2'%0A try:%0A request = urllib2.urlopen(URL)%0A except urllib2.URLError, e:%0A if hasattr(e, 'reason'):%0A print('We failed to reach ', URL, file=sys.stderr)%0A print('Reason: ', e.reason, file=sys.stderr)%0A elif hasattr(e, 'code'):%0A print('The server couldn%5C't fulfill the request.',%0A file=sys.stderr)%0A print('Error code: ', e.code, file=sys.stderr)%0A sys.exit(1)%0A json_dict = json.load(request)%0A return %5B(app%5B'appid'%5D, app%5B'name'%5D)%0A for app in json_dict%5B'applist'%5D%5B'apps'%5D%5D%0A
f9b8a92359e15883c5ee7b4dbc259001d59e379d
introduce bnip classes
BrainNetworksInPython/scripts/classes.py
BrainNetworksInPython/scripts/classes.py
Python
0
@@ -0,0 +1,3127 @@ +import numpy as np%0Aimport networkx as nx%0Aimport pandas as pd%0Aimport make_graphs as mkg%0Aimport graph_measures as gm%0A%0A%0Adef cascader(dict1, dict2, name):%0A return %7Bkey: value.update(%7Bname: dict2%5Bkey%5D%7D)%0A for key, value in dict1.items()%7D%0A%0A%0Aclass BrainNetwork(nx.classes.graph.Graph):%0A def __init__(self,%0A network,%0A parcellation,%0A centroids,%0A names_308_style=False):%0A if isinstance(network, nx.classes.graph.Graph):%0A # Copy graph%0A nx.classes.graph.Graph.__init__(self)%0A self.__dict__.update(network.__dict__)%0A else:%0A # Create weighted graph%0A if isinstance(network, pd.DataFrame):%0A M = network.values%0A elif isinstance(network, np.ndarray):%0A M = network%0A M%5Bnp.diag_indices_from(M)%5D = 0%0A nx.classes.graph.Graph.__init__(self, M)%0A%0A # assign names and centroids to nodes%0A mkg.assign_node_names(self,%0A parcellation,%0A names_308_style=names_308_style)%0A mkg.assign_node_centroids(self, centroids)%0A%0A%0Aclass BinaryBrainNetwork(nx.classes.graph.Graph):%0A def __init__(self, brainnetwork, cost, mst=True):%0A%0A nx.classes.graph.Graph.__init__(self)%0A self.__dict__.update(brainnetwork.__dict__)%0A%0A self = mkg.threshold_graph(self, self.cost, mst=mst)%0A self.graph%5B'cost'%5D = cost%0A self.graph%5B'mst'%5D = mst%0A%0A def partition(self):%0A nodal_partition, module_partition = gm.calc_nodal_partition(self)%0A cascader(self._node, nodal_partition, 'module')%0A self.graph%5B'partition'%5D = module_partition%0A%0A def calculate_nodal_measures(self):%0A '''%0A Calculates%0A '''%0A%0A # ==== SET UP ======================%0A # If you haven't passed the nodal partition%0A # then calculate it here%0A if 'partition' not in self.graph:%0A self.partition()%0A%0A # ==== MEASURES ====================%0A # ---- Degree ----------------------%0A cascader(self._node, dict(self.degree), 'degree')%0A # ---- Closeness -------------------%0A cascader(self._node, nx.closeness_centrality(self), 'closeness')%0A # ---- Betweenness -----------------%0A cascader(self._node, nx.betweenness_centrality(self), 'betweenness')%0A # ---- Shortest path length --------%0A cascader(self._node, gm.shortest_path(self), 'shortest_path')%0A # ---- Clustering ------------------%0A cascader(self._node, nx.clustering(self), 'clustering')%0A # ---- Participation coefficent ----%0A cascader(self._node, gm.participation_coefficient(self,%0A self.graph%5B'partition'%5D), 'pc')%0A%0A # ---- Euclidean distance and ------%0A # ---- interhem proporition --------%0A gm.assign_nodal_distance(self)%0A gm.assign_interhem(self)%0A%0A def export_nodal_measures(self):%0A '''%0A Returns the node attribute data from G as a pandas dataframe.%0A '''%0A return pd.DataFrame.from_dict(self._node).transpose()%0A
cd9da9cf624a80acaebe92e075760ff8c2dbb7b1
Add test_first_audit_catchup_during_ordering
plenum/test/audit_ledger/test_first_audit_catchup_during_ordering.py
plenum/test/audit_ledger/test_first_audit_catchup_during_ordering.py
Python
0
@@ -0,0 +1,2719 @@ +import pytest%0A%0Afrom plenum.test import waits%0Afrom plenum.common.constants import LEDGER_STATUS, DOMAIN_LEDGER_ID%0Afrom plenum.common.messages.node_messages import MessageReq, CatchupReq%0Afrom plenum.server.catchup.node_leecher_service import NodeLeecherService%0Afrom plenum.test.delayers import ppDelay, pDelay, cDelay, DEFAULT_DELAY%0Afrom plenum.test.helper import sdk_send_random_and_check%0Afrom plenum.test.node_request.test_timestamp.helper import get_timestamp_suspicion_count%0Afrom plenum.test.node_catchup.helper import ensure_all_nodes_have_same_data%0Afrom plenum.test.stasher import delay_rules, start_delaying, stop_delaying_and_process%0Afrom stp_core.loop.eventually import eventually%0A%0A%0Adef delay_domain_ledger_catchup():%0A def delay(msg):%0A msg = msg%5B0%5D%0A if isinstance(msg, MessageReq) and %5C%0A msg.msg_type == LEDGER_STATUS and %5C%0A msg.params.get('ledgerId') == DOMAIN_LEDGER_ID:%0A return DEFAULT_DELAY%0A if isinstance(msg, CatchupReq) and %5C%0A msg.ledgerId == DOMAIN_LEDGER_ID:%0A return DEFAULT_DELAY%0A%0A return delay%0A%0A%0Adef test_first_audit_catchup_during_ordering(tdir, tconf, looper, txnPoolNodeSet, sdk_pool_handle, sdk_wallet_client):%0A lagging_node = txnPoolNodeSet%5B-1%5D%0A other_nodes = txnPoolNodeSet%5B:-1%5D%0A other_stashers = %5Bnode.nodeIbStasher for node in other_nodes%5D%0A%0A def lagging_node_state() -%3E NodeLeecherService.State:%0A return lagging_node.ledgerManager._node_leecher._state%0A%0A def check_lagging_node_is_not_syncing_audit():%0A assert lagging_node_state() != NodeLeecherService.State.SyncingAudit%0A%0A # Prevent lagging node from catching up domain ledger (and finishing catchup)%0A with delay_rules(other_stashers, delay_domain_ledger_catchup()):%0A # Start catchup on lagging node%0A lagging_node.ledgerManager.start_catchup()%0A assert lagging_node_state() == NodeLeecherService.State.SyncingAudit%0A%0A # Ensure that audit ledger is caught up by lagging node%0A looper.run(eventually(check_lagging_node_is_not_syncing_audit))%0A assert lagging_node_state() != NodeLeecherService.State.Idle%0A%0A # Order request on all nodes except lagging one where they goes to stashed state%0A sdk_send_random_and_check(looper, txnPoolNodeSet,%0A sdk_pool_handle, sdk_wallet_client, 1)%0A%0A # Now catchup should end and lagging node starts processing stashed PPs%0A # and resumes ordering%0A%0A # ensure that all nodes will have same data after that%0A ensure_all_nodes_have_same_data(looper, txnPoolNodeSet)%0A%0A # ensure that no suspicions about obsolete PP have been raised%0A assert get_timestamp_suspicion_count(lagging_node) == 0%0A
af536ba048860001c2eea2ada1fb5861c9fdf578
Fix migrations, historical models to not have any properties
django_auth_policy/migrations/0002_users_nullable.py
django_auth_policy/migrations/0002_users_nullable.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.db.models.deletion from django.conf import settings def fill_repr(apps, schema_editor): LoginAttempt = apps.get_model("django_auth_policy", "LoginAttempt") for item in LoginAttempt.objects.all(): item.user_repr = item.user.get_username() item.save(update_fields=['user_repr']) PasswordChange = apps.get_model("django_auth_policy", "PasswordChange") for item in PasswordChange.objects.all(): item.user_repr = item.user.get_username() item.save(update_fields=['user_repr']) UserChange = apps.get_model("django_auth_policy", "UserChange") for item in UserChange.objects.all(): item.user_repr = item.user.get_username() item.by_user_repr = item.by_user.get_username() item.save(update_fields=['user_repr', 'by_user_repr']) class Migration(migrations.Migration): dependencies = [ ('django_auth_policy', '0001_initial'), ] operations = [ migrations.AddField( model_name='loginattempt', name='user_repr', field=models.CharField(default='', max_length=200, verbose_name='user', blank=True), preserve_default=False, ), migrations.AddField( model_name='passwordchange', name='user_repr', field=models.CharField(default='', max_length=200, verbose_name='user', blank=True), preserve_default=False, ), migrations.AddField( model_name='userchange', name='by_user_repr', field=models.CharField(default='', max_length=200, verbose_name='by user', blank=True), preserve_default=False, ), migrations.AddField( model_name='userchange', name='user_repr', field=models.CharField(default='', max_length=200, verbose_name='user', blank=True), preserve_default=False, ), migrations.AlterField( model_name='loginattempt', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, verbose_name='user', blank=True, to=settings.AUTH_USER_MODEL, null=True), preserve_default=True, ), migrations.AlterField( model_name='passwordchange', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, verbose_name='user', blank=True, to=settings.AUTH_USER_MODEL, null=True), preserve_default=True, ), migrations.AlterField( model_name='userchange', name='by_user', field=models.ForeignKey(related_name='changed_users', on_delete=django.db.models.deletion.SET_NULL, verbose_name='by user', blank=True, to=settings.AUTH_USER_MODEL, null=True), preserve_default=True, ), migrations.AlterField( model_name='userchange', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, verbose_name='user', blank=True, to=settings.AUTH_USER_MODEL, null=True), preserve_default=True, ), migrations.RunPython(fill_repr), ]
Python
0
@@ -203,16 +203,96 @@ ditor):%0A + from django.contrib.auth import get_user_model%0A User = get_user_model()%0A%0A Logi @@ -384,36 +384,57 @@ Attempt.objects. -all( +filter(user__isnull=False ):%0A item. @@ -437,32 +437,40 @@ tem.user_repr = +getattr( item.user.get_us @@ -458,38 +458,45 @@ tr(item.user -.get_username( +, User.USERNAME_FIELD )%0A it @@ -672,32 +672,40 @@ tem.user_repr = +getattr( item.user.get_us @@ -693,38 +693,45 @@ tr(item.user -.get_username( +, User.USERNAME_FIELD )%0A it @@ -899,24 +899,32 @@ user_repr = +getattr( item.user.ge @@ -916,38 +916,45 @@ tr(item.user -.get_username( +, User.USERNAME_FIELD )%0A it @@ -971,16 +971,24 @@ _repr = +getattr( item.by_ @@ -995,22 +995,29 @@ user -.get_username( +, User.USERNAME_FIELD )%0A
cc300b1c0f6ccc4ca50b4f4d20f5f351af698cfc
Add files via upload
nthprime.py
nthprime.py
Python
0
@@ -0,0 +1,433 @@ +#encoding=utf8%0D%0A'''%0D%0AFind nth prime number%0D%0A'''%0D%0Afrom math import sqrt%0D%0Adef prime(maxn):%0D%0A n = 1%0D%0A while n %3C maxn:%0D%0A if is_prime(n):%0D%0A yield n%0D%0A n += 1%0D%0A %0D%0Adef is_prime(n):%0D%0A if n == 1:%0D%0A return False%0D%0A for i in range(2, int(sqrt(n))+1):%0D%0A if n %25 i == 0:%0D%0A return False%0D%0A return True%0D%0A%0D%0Afor i, n in enumerate(prime(100)):%0D%0A if i == 10:%0D%0A print(n)%0D%0A
b1316b3db89fbee6e6c1ad807e2e36b8b4dd1874
Add a script to fix garbled activities
Attic/act-fixup.py
Attic/act-fixup.py
Python
0.000001
@@ -0,0 +1,1109 @@ +from parliament.models import *%0Afrom django.db import transaction, reset_queries%0A%0Aif True:%0A with transaction.atomic():%0A print(%22Documents %25d%22 %25 Document.objects.count())%0A%0A for idx, doc in enumerate(Document.objects.all()):%0A if idx %25 1000 == 0:%0A reset_queries()%0A print(idx)%0A doc.keywords_changed = True%0A doc.save(update_fields=%5B'origin_id'%5D)%0A%0Aif True:%0A with transaction.atomic():%0A print(%22Signatures %25d%22 %25 DocumentSignature.objects.count())%0A%0A for idx, sign in enumerate(DocumentSignature.objects.all()):%0A if idx %25 1000 == 0:%0A reset_queries()%0A print(idx)%0A sign.keywords_changed = True%0A sign.save(update_fields=%5B'doc'%5D)%0A%0Aif True:%0A with transaction.atomic():%0A print(%22Statements %25d%22 %25 Statement.objects.count())%0A%0A for idx, st in enumerate(Statement.objects.all()):%0A if idx %25 1000 == 0:%0A reset_queries()%0A print(idx)%0A st.keywords_changed = True%0A st.save(update_fields=%5B'item'%5D)%0A
ad78abc4073cb26b192629aed9e9f8e3f5d9e94a
Test for GPI newline fix; for geneontology/go-site#1681
tests/test_gpiwriter.py
tests/test_gpiwriter.py
Python
0
@@ -0,0 +1,963 @@ +import io%0A%0Afrom ontobio.io import entitywriter, gafgpibridge%0A%0A%0Adef test_header_newline():%0A gpi_obj = %7B%0A 'id': %22MGI:MGI:1918911%22,%0A 'label': %220610005C13Rik%22, # db_object_symbol,%0A 'full_name': %22RIKEN cDNA 0610005C13 gene%22, # db_object_name,%0A 'synonyms': %5B%5D,%0A 'type': %5B%22gene%22%5D, # db_object_type,%0A 'parents': %22%22, # GAF does not have this field, but it's optional in GPI%0A 'xrefs': %22%22, # GAF does not have this field, but it's optional in GPI%0A 'taxon': %7B%0A 'id': %22NCBITaxon:10090%22%0A %7D%0A %7D%0A entity = gafgpibridge.Entity(gpi_obj)%0A%0A out = io.StringIO()%0A gpiwriter = entitywriter.GpiWriter(file=out)%0A gpiwriter.write_entity(entity)%0A outlines = out.getvalue().split(%22%5Cn%22)%0A%0A expected_lines = %5B%0A %22!gpi-version: 1.2%22,%0A %22MGI%5CtMGI:1918911%5Ct0610005C13Rik%5CtRIKEN cDNA 0610005C13 gene%5Ct%5Ctgene%5Cttaxon:10090%5Ct%5Ct%5Ct%22,%0A %22%22%0A %5D%0A assert expected_lines == outlines%0A
4d8dbf66bdee710e5b53863a4852e80c42a2c7a2
Add a sqlserver test
tests/test_sqlserver.py
tests/test_sqlserver.py
Python
0.000105
@@ -0,0 +1,2004 @@ +import unittest%0Aimport logging%0Afrom nose.plugins.attrib import attr%0A%0Afrom checks import gethostname%0Afrom tests.common import get_check%0A%0Alogging.basicConfig()%0A%0A%22%22%22%0ARun the following on your local SQL Server:%0A%0ACREATE LOGIN datadog WITH PASSWORD = '340$Uuxwp7Mcxo7Khy';%0ACREATE USER datadog FOR LOGIN datadog;%0AGRANT SELECT on sys.dm_os_performance_counters to datadog;%0AGRANT VIEW SERVER STATE to datadog;%0A%22%22%22%0A%0ACONFIG = %22%22%22%0Ainit_config:%0A custom_metrics:%0A - name: sqlserver.clr.execution%0A type: gauge%0A counter_name: CLR Execution%0A%0A - name: sqlserver.exec.in_progress%0A type: gauge%0A counter_name: OLEDB calls%0A instance_name: Cumulative execution time (ms) per second%0A%0A - name: sqlserver.db.commit_table_entries%0A type: gauge%0A counter_name: Log Flushes/sec%0A instance_name: ALL%0A tag_by: db%0A%0Ainstances:%0A - host: 127.0.0.1,1433%0A username: datadog%0A password: 340$Uuxwp7Mcxo7Khy%0A%22%22%22%0A%0A@attr('windows')%0Aclass SQLServerTestCase(unittest.TestCase):%0A def testSqlServer(self):%0A check, instances = get_check('sqlserver', CONFIG)%0A check.check(instances%5B0%5D)%0A metrics = check.get_metrics()%0A%0A # Make sure the base metrics loaded%0A base_metrics = %5Bm%5B0%5D for m in check.METRICS%5D%0A ret_metrics = %5Bm%5B0%5D for m in metrics%5D%0A for metric in base_metrics:%0A assert metric in ret_metrics%0A%0A # Check our custom metrics%0A assert 'sqlserver.clr.execution' in ret_metrics%0A assert 'sqlserver.exec.in_progress' in ret_metrics%0A assert 'sqlserver.db.commit_table_entries' in ret_metrics%0A%0A # Make sure the ALL custom metric is tagged%0A tagged_metrics = %5Bm for m in metrics%0A if m%5B0%5D == 'sqlserver.db.commit_table_entries'%5D%0A for metric in tagged_metrics:%0A for tag in metric%5B3%5D%5B'tags'%5D:%0A assert tag.startswith('db')%0A%0Aif __name__ == %22__main__%22:%0A unittest.main()
b70b51d1c43a344a3c408f3da30c6477b311241e
Create __init__.py
acitool/jsondata/Mpod/__init__.py
acitool/jsondata/Mpod/__init__.py
Python
0.000429
@@ -0,0 +1 @@ +%0A
9ec45d8b44a63bcd2652de30191b2bf0caf72ab8
Add tests for backrefs
tests/aggregate/test_backrefs.py
tests/aggregate/test_backrefs.py
Python
0
@@ -0,0 +1,2151 @@ +import sqlalchemy as sa%0Afrom sqlalchemy_utils.aggregates import aggregated%0Afrom tests import TestCase%0A%0A%0Aclass TestAggregateValueGenerationForSimpleModelPaths(TestCase):%0A def create_models(self):%0A class Thread(self.Base):%0A __tablename__ = 'thread'%0A id = sa.Column(sa.Integer, primary_key=True)%0A name = sa.Column(sa.Unicode(255))%0A%0A @aggregated('comments', sa.Column(sa.Integer, default=0))%0A def comment_count(self):%0A return sa.func.count('1')%0A%0A class Comment(self.Base):%0A __tablename__ = 'comment'%0A id = sa.Column(sa.Integer, primary_key=True)%0A content = sa.Column(sa.Unicode(255))%0A thread_id = sa.Column(sa.Integer, sa.ForeignKey('thread.id'))%0A%0A thread = sa.orm.relationship(Thread, backref='comments')%0A%0A self.Thread = Thread%0A self.Comment = Comment%0A%0A def test_assigns_aggregates_on_insert(self):%0A thread = self.Thread()%0A thread.name = u'some article name'%0A self.session.add(thread)%0A comment = self.Comment(content=u'Some content', thread=thread)%0A self.session.add(comment)%0A self.session.commit()%0A self.session.refresh(thread)%0A assert thread.comment_count == 1%0A%0A def test_assigns_aggregates_on_separate_insert(self):%0A thread = self.Thread()%0A thread.name = u'some article name'%0A self.session.add(thread)%0A self.session.commit()%0A comment = self.Comment(content=u'Some content', thread=thread)%0A self.session.add(comment)%0A self.session.commit()%0A self.session.refresh(thread)%0A assert thread.comment_count == 1%0A%0A def test_assigns_aggregates_on_delete(self):%0A thread = self.Thread()%0A thread.name = u'some article name'%0A self.session.add(thread)%0A self.session.commit()%0A comment = self.Comment(content=u'Some content', thread=thread)%0A self.session.add(comment)%0A self.session.commit()%0A self.session.delete(comment)%0A self.session.commit()%0A self.session.refresh(thread)%0A assert thread.comment_count == 0%0A
72e2a92522702af998dc599e3370346e22097603
Update threadedcomments/management/commands/migrate_threaded_comments.py
threadedcomments/management/commands/migrate_threaded_comments.py
threadedcomments/management/commands/migrate_threaded_comments.py
from django.core.management.base import NoArgsCommand from django.contrib.sites.models import Site from django.db import transaction, connection from django.conf import settings from threadedcomments.models import ThreadedComment USER_SQL = """ SELECT id, content_type_id, object_id, parent_id, user_id, date_submitted, date_modified, date_approved, comment, markup, is_public, is_approved, ip_address FROM threadedcomments_threadedcomment ORDER BY id ASC """ FREE_SQL = """ SELECT id, content_type_id, object_id, parent_id, name, website, email, date_submitted, date_modified, date_approved, comment, markup, is_public, is_approved, ip_address FROM threadedcomments_freethreadedcomment ORDER BY id ASC """ PATH_SEPARATOR = getattr(settings, 'COMMENT_PATH_SEPARATOR', '/') PATH_DIGITS = getattr(settings, 'COMMENT_PATH_DIGITS', 10) class Command(NoArgsCommand): help = "Migrates django-threadedcomments <= 0.5 to the new model structure" def handle(self, *args, **options): transaction.commit_unless_managed() transaction.enter_transaction_management() transaction.managed(True) site = Site.objects.all()[0] cursor = connection.cursor() cursor.execute(FREE_SQL) for row in cursor: (id, content_type_id, object_id, parent_id, name, website, email, date_submitted, date_modified, date_approved, comment, markup, is_public, is_approved, ip_address) = row tc = ThreadedComment( pk=id, content_type_id=content_type_id, object_pk=object_id, user_name=name, user_email=email, user_url=website, comment=comment, submit_date=date_submitted, ip_address=ip_address, is_public=is_public, is_removed=not is_approved, parent_id=parent_id, site=site, ) tc.save(skip_tree_path=True) cursor = connection.cursor() cursor.execute(USER_SQL) for row in cursor: (id, content_type_id, object_id, parent_id, user_id, date_submitted, date_modified, date_approved, comment, markup, is_public, is_approved, ip_address) = row tc = ThreadedComment( pk=id, content_type_id=content_type_id, object_pk=object_id, user_id=user_id, comment=comment, submit_date=date_submitted, ip_address=ip_address, is_public=is_public, is_removed=not is_approved, parent_id=parent_id, site=site, ) tc.save(skip_rtee_path=True) for comment in ThreadedComment.objects.all(): path = [str(comment.id).zfill(PATH_DIGITS)] current = comment while current.parent: current = current.parent path.append(str(current.id).zfill(PATH_DIGITS)) comment.tree_path = PATH_SEPARATOR.join(reversed(path)) comment.save(skip_tree_path=True) if comment.parent: ThreadedComment.objects.filter(pk=comment.parent.pk).update( last_child=comment) transaction.commit() transaction.leave_transaction_management()
Python
0.000002
@@ -2910,18 +2910,18 @@ ve(skip_ -r t +r ee_path=
8bf521bf26af93f13043ee6e0d70070d49f76f68
Implement the cipher map problem.
Home/cipherMap.py
Home/cipherMap.py
Python
0.00037
@@ -0,0 +1,1222 @@ +import operator%0Adef checkio(arr):%0A index = convertMapToTuples(arr%5B0%5D)%0A cube = convertCubeToList(arr%5B1%5D)%0A output = ''%0A%0A dimension = len(arr%5B0%5D)%0A for i in range(0, 4):%0A index.sort(key=operator.itemgetter(0, 1))%0A for idx in index:%0A output = '%7B0%7D%7B1%7D'.format(output, cube%5Bidx%5B0%5D%5D%5Bidx%5B1%5D%5D)%0A index = rotateCube(index, dimension)%0A return output%0A%0Adef convertCubeToList(arr):%0A result = %5B%5D%0A for i in range(len(arr)):%0A row = %5B%5D%0A for j in range(len(arr%5Bi%5D)):%0A row.append(arr%5Bi%5D%5Bj%5D)%0A result.append(row)%0A return result%0A%0Adef convertMapToTuples(arr):%0A result = %5B%5D%0A for i in range(len(arr)):%0A for j in range(len(arr%5Bi%5D)):%0A if arr%5Bi%5D%5Bj%5D != '.':%0A result.append((i, j))%0A return result%0A%0Adef rotateCube(tuples, dimension):%0A result = %5B%5D%0A for item in tuples:%0A result.append((item%5B1%5D, dimension - item%5B0%5D - 1))%0A return result%0A%0Aif __name__ == %22__main__%22:%0A assert checkio(%5B%5B%0A'X...',%0A'..X.',%0A'X..X',%0A'....'%5D,%5B%0A'itdf',%0A'gdce',%0A'aton',%0A'qrdi'%5D%0A%5D) == 'icantforgetiddqd', 'Test1'%0A%0A assert checkio(%5B%5B%0A'....',%0A'X..X',%0A'.X..',%0A'...X'%5D,%5B%0A'xhwc',%0A'rsqx',%0A'xqzz',%0A'fyzr'%5D%0A%5D) == 'rxqrwsfzxqxzhczy', %22Test2%22%0A
586a8ca10f1f492f9976df95fbe1fa3d187a6006
extend retries in wait for server to be ready (#4889)
Tests/scripts/wait_until_server_ready.py
Tests/scripts/wait_until_server_ready.py
"""Wait for server to be ready for tests""" import sys import json import ast import argparse from time import sleep import datetime import requests import demisto_client.demisto_api from typing import List, AnyStr import urllib3.util from Tests.test_utils import print_error, print_color, LOG_COLORS # Disable insecure warnings urllib3.disable_warnings() MAX_TRIES = 20 SLEEP_TIME = 45 def get_username_password(): parser = argparse.ArgumentParser(description='Utility for batch action on incidents') parser.add_argument('-c', '--confPath', help='The path for the secret conf file', required=True) parser.add_argument('-v', '--contentVersion', help='Content version to install', required=True) parser.add_argument("--non-ami", help="Do NOT run with AMI setting", action='store_true') options = parser.parse_args() conf_path = options.confPath with open(conf_path, 'r') as conf_file: conf = json.load(conf_file) if options.non_ami: return conf['username'], conf['username'], options.contentVersion return conf['username'], conf['userPassword'], options.contentVersion def is_correct_content_installed(ips, content_version, username, password): # type: (AnyStr, List[List], AnyStr) -> bool """ Checks if specific content version is installed on server list Args: username: Username of the service account password: Password of the service account ips: list with lists of [instance_name, instance_ip] content_version: content version that should be installed Returns: True: if all tests passed, False if one failure """ for ami_instance_name, ami_instance_ip in ips: host = "https://{}".format(ami_instance_ip) client = demisto_client.configure(base_url=host, username=username, password=password, verify_ssl=False) try: resp = demisto_client.generic_request_func(self=client, path='/content/installed/', method='POST', accept='application/json', content_type='application/json') resp_json = ast.literal_eval(resp[0]) if not isinstance(resp_json, dict): raise ValueError('Response from server is not a Dict, got [{}].\n' 'Text: {}'.format(type(resp_json), resp_json)) release = resp_json.get("release") notes = resp_json.get("releaseNotes") installed = resp_json.get("installed") if not (release and content_version in release and notes and installed): print_error("Failed install content on instance [{}]\nfound content version [{}], expected [{}]" "".format(ami_instance_name, release, content_version)) return False else: print_color("Instance [{instance_name}] content verified with version [{content_version}]".format( instance_name=ami_instance_name, content_version=release), LOG_COLORS.GREEN ) except ValueError as exception: err_msg = "Failed to verify content version on server [{}]\n" \ "Error: [{}]\n".format(ami_instance_name, str(exception)) if resp_json is not None: err_msg += "Server response: {}".format(resp_json) print_error(err_msg) return False print_color("Content was installed successfully on all of the instances! :)", LOG_COLORS.GREEN) return True def main(): username, password, content_version = get_username_password() ready_ami_list = [] with open('./Tests/instance_ips.txt', 'r') as instance_file: instance_ips = instance_file.readlines() instance_ips = [line.strip('\n').split(":") for line in instance_ips] for i in range(MAX_TRIES * SLEEP_TIME): if len(instance_ips) > len(ready_ami_list): for ami_instance_name, ami_instance_ip in instance_ips: if ami_instance_name not in ready_ami_list: host = "https://{}".format(ami_instance_ip) path = '/health' method = 'GET' res = requests.request(method=method, url=(host + path), verify=False) if res.status_code == 200: print("[{}] {} is ready to use".format(datetime.datetime.now(), ami_instance_name)) ready_ami_list.append(ami_instance_name) elif i % 30 == 0: # printing the message every 30 seconds print("{} is not ready yet - waiting for it to start".format(ami_instance_name)) if len(instance_ips) > len(ready_ami_list): sleep(1) else: break if len(ready_ami_list) != len(instance_ips): print_error("The server is not ready :(") sys.exit(1) if not is_correct_content_installed(instance_ips, content_version, username=username, password=password): sys.exit(1) if __name__ == "__main__": main()
Python
0
@@ -365,17 +365,17 @@ TRIES = -2 +3 0%0ASLEEP_
e583d977c7089f21841890b7eb50c824db153202
Test for unicode characters in grammars.
tests/functional/test_unicode.py
tests/functional/test_unicode.py
Python
0
@@ -0,0 +1,478 @@ +# -*- coding: utf-8 -*-%0Afrom __future__ import unicode_literals%0A%0Aimport pytest%0Afrom textx.metamodel import metamodel_from_str%0A%0A%0Adef test_unicode_grammar_from_string():%0A %22%22%22%0A Test grammar with unicode char given in grammar string.%0A %22%22%22%0A%0A grammar = %22%22%22%0A First:%0A 'first' a = Second%0A ;%0A%0A Second:%0A %22%E2%84%A6%22%7C%22%C2%B1%22%7C%22%E2%99%AA%22%0A ;%0A%0A %22%22%22%0A%0A metamodel = metamodel_from_str(grammar)%0A assert metamodel%0A%0A%0Adef test_unicode_grammar_from_file():%0A %22%22%22%0A%0A %22%22%22%0A