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
|
---|---|---|---|---|---|---|---|
0135ce760bb3bf8f2fd828fdb195bcdc4e4c3117 | Add sample.py | sample.py | sample.py | Python | 0.000001 | @@ -0,0 +1,777 @@
+from traitscli import TraitsCLIBase%0Afrom traits.api import Bool, Float, Int, Str, Enum, Event%0A%0A%0Aclass SampleCLI(TraitsCLIBase):%0A%0A %22%22%22Sample CLI using %60traitscli%60.%22%22%22%0A%0A not_configurable_from_cli = Bool%0A yes = Bool(config=True)%0A fnum = Float(config=True)%0A inum = Int(config=True)%0A string = Str(config=True)%0A choice = Enum(%5B'a', 'b', 'c'%5D, config=True)%0A%0A def do_run(self):%0A names = self.class_trait_names(%0A # Avoid 'trait_added' and 'trait_modified'%0A # (See also %60HasTraits.traits%60):%0A trait_type=lambda t: not isinstance(t, Event))%0A width = max(map(len, names))%0A for na in names:%0A print %22%7B0:%7B1%7D%7D : %7B2!r%7D%22.format(na, width, getattr(self, na))%0A%0A%0Aif __name__ == '__main__':%0A SampleCLI.cli()%0A
|
|
1706531082d75f7d6522b4f7d409df8d4fb2b3d7 | Create __init__.py | plantcv/plantcv/visualize/eCDF/__init__.py | plantcv/plantcv/visualize/eCDF/__init__.py | Python | 0.000429 | @@ -0,0 +1,84 @@
+from plantcv.plantcv.visualize.eCDF.obj_size import obj_size%0A__all__ = %5B%22obj_size%22%5D%0A
|
|
eb0163fe87454d634cb5ff34f6dbdded9181003b | Add Šteins as a valid globe due to usage on Wikidata | pywikibot/families/wikidata_family.py | pywikibot/families/wikidata_family.py | # -*- coding: utf-8 -*-
"""Family module for Wikidata."""
#
# (C) Pywikibot team, 2012-2016
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
__version__ = '$Id$'
from pywikibot import config
from pywikibot import family
# The Wikidata family
class Family(family.WikimediaFamily):
"""Family class for Wikidata."""
name = 'wikidata'
test_codes = ('test', )
def __init__(self):
"""Constructor."""
super(Family, self).__init__()
self.langs = {
'wikidata': 'www.wikidata.org',
'test': 'test.wikidata.org',
}
self.interwiki_forward = 'wikipedia'
# Subpages for documentation.
self.doc_subpages = {
'_default': ((u'/doc', ), ['wikidata']),
}
# Disable cosmetic changes
config.cosmetic_changes_disable.update({
'wikidata': ('wikidata', 'test')
})
def interface(self, code):
"""Return 'DataSite'."""
return 'DataSite'
def calendarmodel(self, code):
"""Default calendar model for WbTime datatype."""
return 'http://www.wikidata.org/entity/Q1985727'
def globes(self, code):
"""Supported globes for Coordinate datatype."""
return {
'ariel': 'http://www.wikidata.org/entity/Q3343',
'callisto': 'http://www.wikidata.org/entity/Q3134',
'ceres': 'http://www.wikidata.org/entity/Q596',
'deimos': 'http://www.wikidata.org/entity/Q7548',
'dione': 'http://www.wikidata.org/entity/Q15040',
'earth': 'http://www.wikidata.org/entity/Q2',
'enceladus': 'http://www.wikidata.org/entity/Q3303',
'eros': 'http://www.wikidata.org/entity/Q16711',
'europa': 'http://www.wikidata.org/entity/Q3143',
'ganymede': 'http://www.wikidata.org/entity/Q3169',
'gaspra': 'http://www.wikidata.org/entity/Q158244',
'hyperion': 'http://www.wikidata.org/entity/Q15037',
'iapetus': 'http://www.wikidata.org/entity/Q17958',
'io': 'http://www.wikidata.org/entity/Q3123',
'jupiter': 'http://www.wikidata.org/entity/Q319',
'lutetia': 'http://www.wikidata.org/entity/Q107556',
'mars': 'http://www.wikidata.org/entity/Q111',
'mercury': 'http://www.wikidata.org/entity/Q308',
'mimas': 'http://www.wikidata.org/entity/Q15034',
'miranda': 'http://www.wikidata.org/entity/Q3352',
'moon': 'http://www.wikidata.org/entity/Q405',
'oberon': 'http://www.wikidata.org/entity/Q3332',
'phobos': 'http://www.wikidata.org/entity/Q7547',
'phoebe': 'http://www.wikidata.org/entity/Q17975',
'pluto': 'http://www.wikidata.org/entity/Q339',
'rhea': 'http://www.wikidata.org/entity/Q15050',
'tethys': 'http://www.wikidata.org/entity/Q15047',
'titan': 'http://www.wikidata.org/entity/Q2565',
'titania': 'http://www.wikidata.org/entity/Q3322',
'triton': 'http://www.wikidata.org/entity/Q3359',
'umbriel': 'http://www.wikidata.org/entity/Q3338',
'venus': 'http://www.wikidata.org/entity/Q313',
'vesta': 'http://www.wikidata.org/entity/Q3030',
}
| Python | 0.000002 | @@ -2907,24 +2907,88 @@
ty/Q15050',%0A
+ 'steins': 'http://www.wikidata.org/entity/Q150249',%0A
|
4d4120d6982a02a01b8dd2a4853eab47d7fe6f83 | Create tests.py | polls/tests.py | polls/tests.py | Python | 0.000001 | @@ -0,0 +1,1320 @@
+import datetime%0A%0Afrom django.utils import timezone%0Afrom django.test import TestCase%0A%0Afrom .models import Question%0A%0A# Create your tests here.%0Aclass QuestionMethodTests(TestCase):%0A%0A def test_was_published_recently_with_future_question(self):%0A %22%22%22%0A was_published_recently() should return False for questions whose%0A pub_date is in the future.%0A %22%22%22%0A%0A time = timezone.now() + datetime.timedelta(days=30)%0A future_question = Question(pub_date=time)%0A self.assertEqual(future_question.was_published_recently(), False)%0A%0A def test_was_published_recently_with_old_question(self):%0A %22%22%22%0A was_published_recently() should return False for question whose%0A pub_date is older than 1 day.%0A %22%22%22%0A%0A time = timezone.now() - datetime.timedelta(days=30)%0A old_question = Question(pub_date=time)%0A self.assertEqual(old_question.was_published_recently(), False)%0A%0A def test_was_published_recently_with_recent_question(self):%0A %22%22%22%0A was_published_recently() should return True for question whose%0A pub_date is within the last day.%0A %22%22%22%0A%0A time = timezone.now() - datetime.timedelta(hours=1)%0A recent_question = Question(pub_date=time)%0A self.assertEqual(recent_question.was_published_recently(), True)%0A
|
|
15aa7efa3dfdade3001cdb6b5ac4c2f3c5cc2461 | Test Commit | raspberry/asip/RelationSemanticTag.py | raspberry/asip/RelationSemanticTag.py | Python | 0.000001 | @@ -0,0 +1,32 @@
+from SemanticTag import *%0A%0A#Test
|
|
95c34b9ad7ca6c425853642353a2d56282cc94d1 | add script | plugins/Scripts/Plugins/Convert_To_8bit.py | plugins/Scripts/Plugins/Convert_To_8bit.py | Python | 0.000001 | @@ -0,0 +1,434 @@
+# @DatasetIOService ds%0A# @ConvertService convert%0A# @UIService ui%0A%0Aimport os%0Afrom ij import IJ%0Afrom ij import ImagePlus%0A%0Ad = %22/home/hadim/Insync/Data/Microscopy/PSF/2016.04.12.T1/raw%22%0Afiles = os.listdir(d)%0A%0Afor fname in files:%0A fpath = os.path.join(d, fname)%0A print(fpath)%0A%0Aprint(fpath)%0Adataset = ds.open(fpath)%0Aui.show(dataset)%0A%0Aimp = convert.convert(dataset, ImagePlus)%0AIJ.run(%228-bit%22)%0A%0Ads.save(dataset, fpath) # DOES NOT WORK%0A
|
|
0b058198539195b5520687c744b5cd1eebae3d18 | predict all files in dir | predict_dir.py | predict_dir.py | Python | 0.998316 | @@ -0,0 +1,725 @@
+import argparse%0Aimport os%0A%0Afrom predict import main%0A%0A%0Adef run_dir(in_path, out_path):%0A for item in os.listdir(in_path):%0A if item.endswith('.wav'):%0A out_file_path = out_path + item.replace('.wav', '.TextGrid')%0A main(in_path + item, out_file_path)%0A%0A%0Aif __name__ == %22__main__%22:%0A # the first argument is the wav file path%0A # the second argument is the TextGrid path%0A # -------------MENU-------------- #%0A # command line arguments%0A parser = argparse.ArgumentParser()%0A parser.add_argument(%22in_dir%22, help=%22The input directory%22)%0A parser.add_argument(%22out_dir%22, help=%22The output directory%22)%0A args = parser.parse_args()%0A%0A # main function%0A run_dir(args.in_dir, args.out_dir)%0A
|
|
8cdbda5c0694f4137c1b8a92bafd7f33a6a84d78 | solve pep_751 | pe-solution/src/main/python/pep_751.py | pe-solution/src/main/python/pep_751.py | Python | 0.999969 | @@ -0,0 +1,822 @@
+from typing import Tuple%0Afrom decimal import Decimal, ROUND_FLOOR%0A%0A%0Adef b_a(b: Decimal) -%3E Tuple%5BDecimal, Decimal%5D:%0A a = b.to_integral_exact(ROUND_FLOOR)%0A b = a * (b %25 1 + 1)%0A return a, b%0A%0A%0Adef th_tau(th: Decimal, n: int) -%3E Decimal:%0A a1, b = b_a(th)%0A%0A l = %5B%5D%0A for _ in range(2, n + 1):%0A a, b = b_a(b)%0A l.append(a)%0A%0A return Decimal(f%22%7Ba1%7D.%22 + %22%22.join(map(str, l)))%0A%0A%0Adef solve():%0A n_max = 15%0A tau = 2%0A%0A for n in range(2, n_max + 1):%0A k = Decimal(10) ** (-n + 1)%0A for th in %5Btau + k * x for x in range(0, 10)%5D:%0A if (tau := th_tau(th, n)) %3C th:%0A break%0A%0A return f%22%7Btau:.24f%7D%22%0A%0A%0Aif __name__ == %22__main__%22:%0A theta = Decimal(%222.956938891377988%22)%0A tau = Decimal(%222.3581321345589%22)%0A assert th_tau(theta, 9) == tau%0A%0A print(solve())%0A
|
|
0428d4889b34568a5b5397532dfd0091029b64de | Create problem-10.py | problem-10.py | problem-10.py | Python | 0.00049 | @@ -0,0 +1,427 @@
+import math%0A%0Adef is_prime(next):%0A if n == 2:%0A return True%0A if n == 3:%0A return True%0A if n %25 2 == 0:%0A return False%0A if n %25 3 == 0:%0A return False%0A%0A i = 5%0A w = 2%0A%0A while math.pow(i, 2) %3C= n:%0A if n %25 i == 0:%0A return False%0A i += w%0A w = 6 - w%0A%0A return True%0A%0As = 0%0Amax = 2000000%0A%0Afor n in range(2, max-1):%0A if is_prime(n):%0A s += n%0A%0Aprint(s)%0A
|
|
4fe4cad49367b462c2201b98cce4382bff3a0206 | Add a script which use the iterative parsing to process the map file and find out not only what tags are there, but also how many, to get the feeling on how much of which data you can expect to have in the map. | DataWrangling/CaseStudy/mapparser.py | DataWrangling/CaseStudy/mapparser.py | Python | 0 | @@ -0,0 +1,1192 @@
+#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A%22%22%22%0AYour task is to use the iterative parsing to process the map file and%0Afind out not only what tags are there, but also how many, to get the%0Afeeling on how much of which data you can expect to have in the map.%0AFill out the count_tags function. It should return a dictionary with the%0Atag name as the key and number of times this tag can be encountered in%0Athe map as value.%0A%0ANote that your code will be tested with a different data file than the 'example.osm'%0A%22%22%22%0Aimport xml.etree.cElementTree as ET%0Aimport pprint%0Aimport os%0A%0A%0Adef count_tags(filename):%0A # YOUR CODE HERE%0A tags = %7B%7D%0A for event, elem in ET.iterparse(filename):%0A if elem.tag in tags:%0A tags%5Belem.tag%5D += 1%0A else:%0A tags%5Belem.tag%5D = 1%0A return tags%0A%0A%0Adef test():%0A os.chdir('./data')%0A tags = count_tags('example.osm')%0A pprint.pprint(tags)%0A assert tags == %7B'bounds': 1,%0A 'member': 3,%0A 'nd': 4,%0A 'node': 20,%0A 'osm': 1,%0A 'relation': 1,%0A 'tag': 7,%0A 'way': 1%7D%0A%0A%0A%0Aif __name__ == %22__main__%22:%0A test()
|
|
3d18f6e3ba3519422aa30bd25f3511f62361d5ca | Add test to ensure no mutable default arguments | tests/chainer_tests/test_chainer_objects.py | tests/chainer_tests/test_chainer_objects.py | Python | 0 | @@ -0,0 +1,2732 @@
+import importlib%0Aimport inspect%0Aimport pkgutil%0Aimport types%0A%0Aimport six%0Aimport unittest%0A%0Aimport chainer%0Afrom chainer import testing%0A%0A%0Adef walk_modules():%0A root = chainer.__path__%0A for loader, modname, ispkg in pkgutil.walk_packages(root, 'chainer.'):%0A # Skip modules generated by protobuf.%0A if '_pb2' in modname:%0A continue%0A%0A try:%0A mod = importlib.import_module(modname)%0A except ImportError:%0A continue%0A%0A yield mod%0A%0A%0Adef get_classes(module):%0A # Enumerate classes from a module%0A for name, o in module.__dict__.items():%0A if (inspect.isclass(o)%0A and o.__module__.startswith('chainer.')):%0A yield o%0A%0A%0Adef get_functions(module):%0A # Enumerate functions from a module%0A%0A # Normal functions%0A for k, o in module.__dict__.items():%0A if (isinstance(o, types.FunctionType)%0A and o.__module__.startswith('chainer.')):%0A yield o%0A%0A # Methods defined in a class%0A for cls in get_classes(module):%0A if cls.__module__.startswith('chainer.'):%0A for k, o in cls.__dict__.items():%0A if inspect.isfunction(o):%0A yield o%0A%0A%0Adef get_default_arguments(func):%0A # Retrieves the defaults arguments (names and values) of a function.%0A if six.PY2:%0A # Python 2%0A spec = inspect.getargspec(func)%0A if spec.defaults is not None:%0A n = len(spec.defaults)%0A for name, default_value in zip(spec.args%5B-n:%5D, spec.defaults):%0A yield name, default_value%0A else:%0A # Python 3%0A signature = inspect.signature(func)%0A for name, param in signature.parameters.items():%0A if param.default is not inspect.Parameter.empty:%0A yield name, param.default%0A%0A%0Aclass TestFunctions(unittest.TestCase):%0A%0A def test_no_mutable_default_args(self):%0A type_blacklist = (list, dict)%0A badlist = %5B%5D%0A # Collect mutable default arguments%0A for mod in walk_modules():%0A for func in get_functions(mod):%0A for arg_name, value in get_default_arguments(func):%0A if isinstance(value, type_blacklist):%0A badlist.append((func, arg_name, type(value)))%0A%0A if len(badlist) %3E 0:%0A # Report the error%0A s = six.StringIO()%0A s.write(%0A 'Some functions have mutable values as default values:%5Cn%5Cn')%0A for func, arg_name, value_type in badlist:%0A s.write('%7B%7D.%7B%7D: arg=%5C'%7B%7D%5C' type=%7B%7D%5Cn'.format(%0A func.__module__, func.__name__, arg_name, value_type))%0A assert False, s.getvalue()%0A%0A%0Atesting.run_module(__name__, __file__)%0A
|
|
fcb07c7cd94f96cd533c55d18a657673f9eeac7f | Move log related functions over to this file | SpicyTwitch/Log_tools.py | SpicyTwitch/Log_tools.py | Python | 0 | @@ -0,0 +1,1452 @@
+# Imports-----------------------------------------------------------------------%0Aimport logging%0Aimport os%0Afrom inspect import stack, getmodulename%0Afrom . import Storage%0A%0A%0A# Base setup--------------------------------------------------------------------%0Alog_to_stdout = True%0Alog_to_file = True%0Alogging_level = logging.DEBUG # TODO: Change this back to INFO!%0Alog_format = '%5B%25(asctime)s%5D %5B%25(levelname)s%5D %5B%25(module)s%5D (%25(funcName)s): ' %5C%0A '%25(message)s'%0Adate_format = '%25Y/%25m/%25d %25I:%25M:%25S %25p'%0Alog_formatter = logging.Formatter(log_format, datefmt=date_format)%0A%0Aconsole_handler = logging.StreamHandler()%0Aconsole_handler.setFormatter(log_formatter)%0A%0Alog_storage = os.path.join(Storage.primary_storage_directory, 'logs')%0A%0Aif not os.path.exists(log_storage):%0A os.mkdir(log_storage)%0A%0A# Functions---------------------------------------------------------------------%0Adef get_module_name() -%3E str:%0A return getmodulename(stack()%5B2%5D%5B1%5D)%0A%0Adef create_logger() -%3E logging.Logger:%0A python_module = get_module_name()%0A%0A module_logger = logging.getLogger(python_module)%0A%0A if log_to_stdout:%0A module_logger.addHandler(console_handler)%0A%0A if log_to_file:%0A file_path = os.path.join(log_storage, python_module + '.log')%0A file_handler = logging.FileHandler(file_path)%0A file_handler.setFormatter(log_formatter)%0A module_logger.addHandler(file_handler)%0A%0A module_logger.setLevel(logging_level)%0A return module_logger%0A
|
|
7ec36d0a1d0a757d0c914e4857ae06f4fece88f8 | Add HexTerrain | problem/pop_map/hexagon/hex_terrain.py | problem/pop_map/hexagon/hex_terrain.py | Python | 0.000012 | @@ -0,0 +1,2123 @@
+#! /usr/bin/env python%0A%0A# Copyright 2020 John Hanley.%0A#%0A# Permission is hereby granted, free of charge, to any person obtaining a%0A# copy of this software and associated documentation files (the %22Software%22),%0A# to deal in the Software without restriction, including without limitation%0A# the rights to use, copy, modify, merge, publish, distribute, sublicense,%0A# and/or sell copies of the Software, and to permit persons to whom the%0A# Software is furnished to do so, subject to the following conditions:%0A# The above copyright notice and this permission notice shall be included in%0A# all copies or substantial portions of the Software.%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%0A# the authors or copyright holders be liable for any claim, damages or%0A# other liability, whether in an action of contract, tort or otherwise,%0A# arising from, out of or in connection with the software or the use or%0A# other dealings in the software.%0A%0A%0A%22%22%22Implements a %22flat%22 hex grid, using invaluable advice from Amit Patel%0Ahttps://www.redblobgames.com/grids/hexagons%0A%22%22%22%0A# We choose flat-top rather than pointy-top hexes,%0A# with odd-q vertical layout. # , and doubleheight.%0A# We adopt Amit's %22origin at upper left%22 convention,%0A# which implies that angles resemble compass angles,%0A# with small positive angles in quadrant IV rather than I.%0A%0Afrom enum import Enum, auto%0A%0Aimport numpy as np%0A%0A%0Aclass Direction(Enum):%0A # (col, row) deltas%0A SE = (1, 0)%0A SOUTH = (0, 1)%0A SW = (-1, 0)%0A NW = (-1, -1)%0A NORTH = (0, -1)%0A NE = (1, -1)%0A%0A%0Aclass CellContent(Enum):%0A # breadcrumbs for a traversed path:%0A MARKED_SE = auto()%0A MARKED_SOUTH = auto()%0A MARKED_SW = auto()%0A MARKED_NW = auto()%0A MARKED_NORTH = auto()%0A MARKED_NE = auto()%0A%0A UNMARKED = auto() # like Path in a maze%0A CITY = auto() # a goal cell%0A MOUNTAIN = auto() # impassable, like Wall in a maz%0A%0A%0Aclass HexTerrain:%0A ''%0A%0A%0Aif __name__ == '__main__':%0A HexTerrain()%0A
|
|
4061e5db7097a680405282e371ab3bf07758648a | Add simple unit tests to validate all configs | projects/DensePose/tests/test_setup.py | projects/DensePose/tests/test_setup.py | Python | 0.000001 | @@ -0,0 +1,1727 @@
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.%0A%0Aimport os%0Aimport unittest%0A%0Afrom detectron2.config import get_cfg%0Afrom detectron2.engine import default_setup%0A%0Afrom densepose import add_densepose_config%0A%0A_CONFIG_DIR = %22configs%22%0A_QUICK_SCHEDULES_CONFIG_SUB_DIR = %22quick_schedules%22%0A_CONFIG_FILE_PREFIX = %22densepose_%22%0A_CONFIG_FILE_EXT = %22.yaml%22%0A%0A%0Adef _get_config_dir():%0A return os.path.join(os.path.dirname(os.path.realpath(__file__)), %22..%22, _CONFIG_DIR)%0A%0A%0Adef _collect_config_files(config_dir):%0A paths = %5B%5D%0A for entry in os.listdir(config_dir):%0A _, ext = os.path.splitext(entry)%0A if ext != _CONFIG_FILE_EXT:%0A continue%0A if not entry.startswith(_CONFIG_FILE_PREFIX):%0A continue%0A path = os.path.join(config_dir, entry)%0A paths.append(path)%0A return paths%0A%0A%0Adef _get_config_files():%0A config_dir = _get_config_dir()%0A return _collect_config_files(config_dir)%0A%0A%0Adef _get_quick_schedules_config_files():%0A config_dir = _get_config_dir()%0A config_dir = os.path.join(config_dir, _QUICK_SCHEDULES_CONFIG_SUB_DIR)%0A return _collect_config_files(config_dir)%0A%0A%0Aclass TestSetup(unittest.TestCase):%0A def _test_setup(self, config_file):%0A cfg = get_cfg()%0A add_densepose_config(cfg)%0A cfg.merge_from_file(config_file)%0A cfg.freeze()%0A default_setup(cfg, %7B%7D)%0A%0A def test_setup_configs(self):%0A config_files = _get_config_files()%0A for config_file in config_files:%0A self._test_setup(config_file)%0A%0A def test_setup_quick_schedules_configs(self):%0A config_files = _get_quick_schedules_config_files()%0A for config_file in config_files:%0A self._test_setup(config_file)%0A
|
|
d1bc6c3fd5741c5c8d3d6dd2ee5c5c28c2764ba3 | add Tumblr.py | TumblrResource/Tumblr.py | TumblrResource/Tumblr.py | Python | 0 | @@ -0,0 +1,37 @@
+#!/usr/bin/env python%0A# coding:utf-8%0A
|
|
30bb73da2b75b5cfcaadf743762bccb119b2c147 | First challenge converted to Python 3 | set1/ch1/hextob64.py | set1/ch1/hextob64.py | Python | 0.999736 | @@ -0,0 +1,679 @@
+#!/usr/bin/python3%0A%0A%22%22%22%0A The string:%0A%0A49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d%0A%0AShould produce:%0A%0ASSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t%0A%22%22%22%0A%0Aimport argparse%0Aimport base64%0Aimport sys%0A%0Adef hextobase64(hexstr):%0A return base64.b64encode(bytes(bytes.fromhex(hexstr).decode('utf-8'),'utf-8')).decode('utf-8')%0A%0Adef main(hexstring):%0A print(hextobase64(hexstring))%0A return 0%0A%0Aif __name__ == %22__main__%22:%0A parser = argparse.ArgumentParser(description='Convert a hex string to base64.')%0A parser.add_argument('hex', help='hex string')%0A args = parser.parse_args()%0A sys.exit(main(args.hex))%0A
|
|
3129819c7d2ff3b35dd0270c0a27ef694a7e4d9e | Add regularizers.py | seya/regularizers.py | seya/regularizers.py | Python | 0 | @@ -0,0 +1,815 @@
+from keras.regularizers import Regularizer%0A%0A%0Aclass GaussianKL(Regularizer):%0A def set_param(self, p):%0A self.p = p%0A%0A def set_layer(self, layer):%0A self.layer = layer%0A%0A def __call__(self, loss):%0A # See Variational Auto-Encoding Bayes by Kingma and Welling.%0A mean, sigma = self.layer.get_output(True)%0A kl = -.5 - self.logsigma + .5 * (mean**2%0A + T.exp(2 * self.logsigma))%0A loss += kl.mean()%0A return loss%0A%0A def get_config(self):%0A return %7B%22name%22: self.__class__.__name__%7D%0A%0A%0Aclass SimpleCost(Regularizer):%0A def set_param(self, cost):%0A self.cost = cost%0A%0A def __call__(self, loss):%0A loss += self.cost%0A return loss%0A%0A def get_config(self):%0A return %7B%22name%22: self.__class__.__name__%7D%0A
|
|
0a47253307d427c6e668d7cdf3bdf186dfc93858 | Fix the ConsolesController class doc string | nova/api/openstack/compute/contrib/consoles.py | nova/api/openstack/compute/contrib/consoles.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import webob
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova import compute
from nova import exception
from nova.openstack.common.gettextutils import _
authorize = extensions.extension_authorizer('compute', 'consoles')
class ConsolesController(wsgi.Controller):
def __init__(self, *args, **kwargs):
self.compute_api = compute.API()
super(ConsolesController, self).__init__(*args, **kwargs)
@wsgi.action('os-getVNCConsole')
def get_vnc_console(self, req, id, body):
"""Get text console output."""
context = req.environ['nova.context']
authorize(context)
# If type is not supplied or unknown, get_vnc_console below will cope
console_type = body['os-getVNCConsole'].get('type')
try:
instance = self.compute_api.get(context, id)
output = self.compute_api.get_vnc_console(context,
instance,
console_type)
except exception.InstanceNotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.format_message())
except exception.InstanceNotReady as e:
raise webob.exc.HTTPConflict(
explanation=_('Instance not yet ready'))
return {'console': {'type': console_type, 'url': output['url']}}
@wsgi.action('os-getSPICEConsole')
def get_spice_console(self, req, id, body):
"""Get text console output."""
context = req.environ['nova.context']
authorize(context)
# If type is not supplied or unknown, get_spice_console below will cope
console_type = body['os-getSPICEConsole'].get('type')
try:
instance = self.compute_api.get(context, id)
output = self.compute_api.get_spice_console(context,
instance,
console_type)
except exception.InstanceNotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.format_message())
except exception.InstanceNotReady as e:
raise webob.exc.HTTPConflict(explanation=e.format_message())
return {'console': {'type': console_type, 'url': output['url']}}
def get_actions(self):
"""Return the actions the extension adds, as required by contract."""
actions = [extensions.ActionExtension("servers", "os-getVNCConsole",
self.get_vnc_console),
extensions.ActionExtension("servers", "os-getSPICEConsole",
self.get_spice_console)]
return actions
class Consoles(extensions.ExtensionDescriptor):
"""Interactive Console support."""
name = "Consoles"
alias = "os-consoles"
namespace = "http://docs.openstack.org/compute/ext/os-consoles/api/v2"
updated = "2011-12-23T00:00:00+00:00"
def get_controller_extensions(self):
controller = ConsolesController()
extension = extensions.ControllerExtension(self, 'servers', controller)
return [extension]
| Python | 0.996907 | @@ -1205,35 +1205,61 @@
%22%22%22Get
-text console output
+vnc connection information to access a server
.%22%22%22%0A
@@ -2186,27 +2186,55 @@
Get
-text console output
+spice connection information to access a server
.%22%22%22
|
bdb75567519914386da7f1d598c6c7aaf96d8e02 | Add sql solution for 561. Array Partition I | py/array-partition-i.py | py/array-partition-i.py | Python | 0.999996 | @@ -0,0 +1,170 @@
+class Solution(object):%0A def arrayPairSum(self, nums):%0A %22%22%22%0A :type nums: List%5Bint%5D%0A :rtype: int%0A %22%22%22%0A return sum(sorted(nums)%5B::2%5D)%0A
|
|
7275a50343cba5073dc2fa77e2e964daec002c38 | move refactored OttTestCase to utils | ott/utils/tests/ott_test_case.py | ott/utils/tests/ott_test_case.py | Python | 0.000001 | @@ -0,0 +1,2121 @@
+import os%0Aimport sys%0Aimport unittest%0Aimport urllib%0Aimport contextlib%0A%0Afrom ott.utils import config_util%0Afrom ott.utils import file_utils%0A%0A%0Aclass OttTestCase(unittest.TestCase):%0A domain = %22localhost%22%0A port = %2233333%22%0A path = None%0A url_file = None%0A%0A def get_url(self, svc_name, params=None, lang=None):%0A # import pdb; pdb.set_trace()%0A if self.path:%0A ret_val = %22http://%7B%7D:%7B%7D/%7B%7D/%7B%7D%22.format(self.domain, self.port, self.path, svc_name)%0A else:%0A ret_val = %22http://%7B%7D:%7B%7D/%7B%7D%22.format(self.domain, self.port, svc_name)%0A if params:%0A ret_val = %22%7B0%7D?%7B1%7D%22.format(ret_val, params)%0A if lang:%0A ret_val = %22%7B0%7D&_LOCALE_=%7B1%7D%22.format(ret_val, lang)%0A if self.url_file:%0A url = ret_val.replace(%22 %22, %22+%22)%0A self.url_file.write(url)%0A self.url_file.write(%22%5Cn%22)%0A return ret_val%0A%0A def call_url(self, url):%0A ret_json = None%0A with contextlib.closing(urllib.urlopen(url)) as f:%0A ret_json = f.read()%0A return ret_json%0A%0A def setUp(self):%0A dir = file_utils.get_project_root_dir()%0A ini = config_util.ConfigUtil('development.ini', run_dir=dir)%0A%0A port = ini.get('ott.test_port', 'app:main')%0A if not port:%0A port = ini.get('ott.svr_port', 'app:main', self.port)%0A self.port = port%0A%0A url_file = ini.get('ott.test_urlfile', 'app:main')%0A if url_file:%0A self.url_file = open(os.path.join(dir, url_file), %22a+%22)%0A%0A test_domain = ini.get('ott.test_domain', 'app:main')%0A if test_domain:%0A self.domain = test_domain%0A%0A test_path = ini.get('ott.test_path', 'app:main')%0A if test_path:%0A self.path = test_path%0A%0A def tearDown(self):%0A if self.url_file:%0A url_file.flush()%0A url_file.close()%0A%0A def call_url_match_list(self, url, list):%0A u = self.call_url(url)%0A for l in list:%0A self.assertRegexpMatches(u, l)%0A%0A def call_url_match_string(self, url, str):%0A u = self.call_url(url)%0A self.assertRegexpMatches(u, str)%0A
|
|
e07c699caf699852c98b3396150b343553a386c4 | Add tests for language api | server/tests/api/test_language_api.py | server/tests/api/test_language_api.py | Python | 0 | @@ -0,0 +1,2275 @@
+import json%0Afrom server.tests.helpers import FlaskTestCase, fixtures%0A%0A%0Aclass TestLanguageAPI(FlaskTestCase):%0A%0A @fixtures('base.json')%0A def test_get_empty_languages(self):%0A %22%22%22Test GET /api/languages endpoint with no data%22%22%22%0A response, data = self.api_request('get', '/api/languages')%0A assert data%5B'num_results'%5D is 0%0A assert response.status_code == 200%0A%0A @fixtures('single_language.json')%0A def test_get_one_language(self):%0A %22%22%22Test GET /api/languages endpoint with a single language%22%22%22%0A response, data = self.api_request('get', '/api/languages')%0A assert data%5B'num_results'%5D is 1%0A assert response.status_code == 200%0A%0A @fixtures('many_languages.json')%0A def test_get_multiple_languages(self):%0A %22%22%22Test GET /api/languages endpoint with multple languages%22%22%22%0A response, data = self.api_request('get', '/api/languages')%0A assert data%5B'num_results'%5D %3E 0%0A assert response.status_code == 200%0A%0A @fixtures('many_languages.json')%0A def test_get_no_language_by_id(self):%0A %22%22%22Test GET /api/languages/(int:id) for missing language%22%22%22%0A response, data = self.api_request('get', '/api/languages/1000')%0A assert response.status_code == 404%0A%0A @fixtures('many_languages.json')%0A def test_language_by_id(self):%0A %22%22%22Test GET /api/languages(int:id) for existing language%22%22%22%0A response, data = self.api_request('get', '/api/languages/1')%0A assert data%5B'language'%5D == 'Python'%0A assert response.status_code == 200%0A%0A @fixtures('single_user.json')%0A def test_post_language(self):%0A %22%22%22Tests POST to /api/languages for an authorized user%22%22%22%0A self.login()%0A%0A data = %7B%0A 'language': 'some_value'%0A %7D%0A response = self.app.post(%0A '/api/languages',%0A data=json.dumps(data)%0A )%0A%0A assert response.status_code == 201%0A%0A @fixtures('base.json')%0A def test_post_language_unauthorized(self):%0A %22%22%22Tests POST to /api/languages for an unauthorized user%22%22%22%0A data = %7B%0A 'language': 'some_value'%0A %7D%0A response = self.app.post(%0A '/api/languages',%0A data=json.dumps(data)%0A )%0A%0A assert response.status_code == 401%0A
|
|
6e736a48f8c49b8257305125742d89cb7f729fbc | index Ansible source versions | shotglass/make_ver_ansible.py | shotglass/make_ver_ansible.py | Python | 0 | @@ -0,0 +1,783 @@
+#!/usr/bin/env python%0A%0A'''%0Amake_versions -- index many versions of a project%0A%0AALPHA code, will need modification for general use.%0A'''%0A%0Aimport re%0Aimport subprocess%0Aimport sys%0A%0Aimport git%0A%0A%0ANAME = 'ansible'%0A%0Abad_tag_re = re.compile(r'(rc%7Cbeta%7Calpha)')%0Arepos = git.Repo(NAME)%0Atags = %5Btag.name for tag in repos.tags%0A if tag.name.startswith('v') and not bad_tag_re.search(tag.name)%5D%0A%0Acheckout_cmd = 'cd %7Bname%7D ; git checkout %7Btag%7D'%0Aindex_cmd = './manage.py make_index --project=%7Bname%7D-%7Btag%7D %7Bname%7D'%0Afor tag in tags%5B:2%5D:%0A cmd = checkout_cmd.format(name=NAME, tag=tag)%0A print '%3E%3E%3E', cmd%0A if subprocess.call(cmd, shell=True):%0A sys.exit(0)%0A cmd = index_cmd.format(name=NAME, tag=tag)%0A print '%3E%3E%3E', cmd%0A out = subprocess.check_output(cmd, shell=True)%0A print out%0A
|
|
24e6a8a21ef61edbe00e6af8a1aea274394a23ed | Add a snippet (python/pygtk). | python/pygtk/minimal.py | python/pygtk/minimal.py | Python | 0.000036 | @@ -0,0 +1,1361 @@
+#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A%0A# Copyright (c) 2012 J%C3%A9r%C3%A9mie DECOCK (http://www.jdhp.org)%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%0A# all 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%0A# THE SOFTWARE.%0A%0Aimport pygtk%0Apygtk.require('2.0')%0Aimport gtk%0A%0Adef main():%0A %22%22%22Main function%22%22%22%0A%0A window = gtk.Window(gtk.WINDOW_TOPLEVEL)%0A window.show()%0A gtk.main()%0A%0Aif __name__ == '__main__':%0A main()%0A
|
|
08e4f449f0e871f996e9a265fd23a967a0377078 | Add bfx example | quant/example/ex_bfx.py | quant/example/ex_bfx.py | Python | 0 | @@ -0,0 +1,601 @@
+#!/usr/bin/env python%0A# -*- coding: UTF-8 -*-%0Aimport time%0A%0Afrom quant import config%0Afrom quant.api.bitfinex import PrivateClient%0A%0Aclient = PrivateClient(key=config.Bitfinex_SUB_API_KEY, secret=config.Bitfinex_SUB_SECRET_TOKEN)%0A# client = PrivateClient(key=config.Bitfinex_API_KEY, secret=config.Bitfinex_SECRET_TOKEN)%0A# print(client.ticker('eosbtc'))%0A# print(client.balances())%0A%0Aamount = '20.0'%0Aprice = '0.00015'%0Asymbol = 'eosbtc'%0Ar_id = client.buy(symbol=symbol, amount=amount, price=price)%0Aprint(r_id)%0A%0Aif r_id:%0A time.sleep(1)%0A client.cancel_order(r_id)%0A%0A# print(client.cancel_all_orders())%0A%0A%0A
|
|
800639fe381ec502e54a3fbd95241b460bd3e3c3 | add tests for shannon.py | dit/algorithms/tests/test_shannon.py | dit/algorithms/tests/test_shannon.py | Python | 0 | @@ -0,0 +1,1417 @@
+from __future__ import division%0A%0Afrom nose.tools import *%0A%0Afrom dit import Distribution as D, ScalarDistribution as SD%0Afrom dit.algorithms import (entropy as H,%0A mutual_information as I,%0A conditional_entropy as CH)%0A%0Adef test_H1():%0A d = SD(%5B1/2, 1/2%5D)%0A assert_almost_equal(H(d), 1.0)%0A%0Adef test_H2():%0A assert_almost_equal(H(1/2), 1.0)%0A%0Adef test_H3():%0A outcomes = %5B'00', '01', '10', '11'%5D%0A pmf = %5B1/4%5D*4%0A d = D(outcomes, pmf)%0A assert_almost_equal(H(d, %5B0%5D), 1.0)%0A assert_almost_equal(H(d, %5B1%5D), 1.0)%0A assert_almost_equal(H(d, %5B0,1%5D), 2.0)%0A assert_almost_equal(H(d), 2.0)%0A%0Adef test_H4():%0A d = SD(%5B1/10%5D*10)%0A d.set_base(10)%0A assert_almost_equal(H(d), 1.0)%0A%0Adef test_I1():%0A outcomes = %5B'00', '01', '10', '11'%5D%0A pmf = %5B1/4%5D*4%0A d = D(outcomes, pmf)%0A assert_almost_equal(I(d, %5B0%5D, %5B1%5D), 0.0)%0A%0Adef test_I2():%0A outcomes = %5B'00', '11'%5D%0A pmf = %5B1/2%5D*2%0A d = D(outcomes, pmf)%0A assert_almost_equal(I(d, %5B0%5D, %5B1%5D), 1.0)%0A%0Adef test_I3():%0A outcomes = %5B'000', '011', '101', '110'%5D%0A pmf = %5B1/4%5D*4%0A d = D(outcomes, pmf)%0A assert_almost_equal(I(d, %5B0,1%5D, %5B1,2%5D), 2.0)%0A%0Adef test_CH1():%0A outcomes = %5B'000', '011', '101', '110'%5D%0A pmf = %5B1/4%5D*4%0A d = D(outcomes, pmf)%0A assert_almost_equal(CH(d, %5B0%5D, %5B1,2%5D), 0.0)%0A assert_almost_equal(CH(d, %5B0,1%5D, %5B2%5D), 1.0)%0A assert_almost_equal(CH(d, %5B0%5D, %5B0%5D), 0.0)
|
|
8c1353537d0920d8137d5ea9d22843da67e41d9a | Add string_format pylint plugin. | test/sanity/pylint/plugins/string_format.py | test/sanity/pylint/plugins/string_format.py | Python | 0 | @@ -0,0 +1,2998 @@
+# (c) 2018, Matt Martz %[email protected]%3E%0A# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)%0A# -*- coding: utf-8 -*-%0Afrom __future__ import (absolute_import, division, print_function)%0A__metaclass__ = type%0A%0Aimport sys%0A%0Aimport six%0A%0Aimport astroid%0Afrom pylint.interfaces import IAstroidChecker%0Afrom pylint.checkers import BaseChecker%0Afrom pylint.checkers import utils%0Afrom pylint.checkers.utils import check_messages%0Afrom pylint.checkers.strings import parse_format_method_string%0A%0A_PY3K = sys.version_info%5B:2%5D %3E= (3, 0)%0A%0AMSGS = %7B%0A 'E9305': (%22Format string contains automatic field numbering %22%0A %22specification%22,%0A %22ansible-format-automatic-specification%22,%0A %22Used when a PEP 3101 format string contains automatic %22%0A %22field numbering (e.g. '%7B%7D').%22,%0A %7B'minversion': (2, 6)%7D),%0A 'E9390': (%22bytes object has no .format attribute%22,%0A %22ansible-no-format-on-bytestring%22,%0A %22Used when a bytestring was used as a PEP 3101 format string %22%0A %22as Python3 bytestrings do not have a .format attribute%22,%0A %7B'minversion': (3, 0)%7D),%0A%7D%0A%0A%0Aclass AnsibleStringFormatChecker(BaseChecker):%0A %22%22%22Checks string formatting operations to ensure that the format string%0A is valid and the arguments match the format string.%0A %22%22%22%0A%0A __implements__ = (IAstroidChecker,)%0A name = 'string'%0A msgs = MSGS%0A%0A @check_messages(*(MSGS.keys()))%0A def visit_call(self, node):%0A func = utils.safe_infer(node.func)%0A if (isinstance(func, astroid.BoundMethod)%0A and isinstance(func.bound, astroid.Instance)%0A and func.bound.name in ('str', 'unicode', 'bytes')):%0A if func.name == 'format':%0A self._check_new_format(node, func)%0A%0A def _check_new_format(self, node, func):%0A %22%22%22 Check the new string formatting %22%22%22%0A if (isinstance(node.func, astroid.Attribute)%0A and not isinstance(node.func.expr, astroid.Const)):%0A return%0A try:%0A strnode = next(func.bound.infer())%0A except astroid.InferenceError:%0A return%0A if not isinstance(strnode, astroid.Const):%0A return%0A%0A if _PY3K and isinstance(strnode.value, six.binary_type):%0A self.add_message('ansible-no-format-on-bytestring', node=node)%0A return%0A if not isinstance(strnode.value, six.string_types):%0A return%0A%0A if node.starargs or node.kwargs:%0A return%0A try:%0A fields, num_args, manual_pos = parse_format_method_string(strnode.value)%0A except utils.IncompleteFormatString:%0A return%0A%0A if num_args:%0A self.add_message('ansible-format-automatic-specification',%0A node=node)%0A return%0A%0A%0Adef register(linter):%0A %22%22%22required method to auto register this checker %22%22%22%0A linter.register_checker(AnsibleStringFormatChecker(linter))%0A
|
|
d6d21f6e7b8d2a44ff3406ddc9a050cc17372da8 | Add analyze_nir_intensity tests module | tests/plantcv/test_analyze_nir_intensity.py | tests/plantcv/test_analyze_nir_intensity.py | Python | 0.000001 | @@ -0,0 +1,844 @@
+import cv2%0Aimport numpy as np%0Afrom plantcv.plantcv import analyze_nir_intensity, outputs%0A%0A%0Adef test_analyze_nir(test_data):%0A # Clear previous outputs%0A outputs.clear()%0A # Read in test data%0A img = cv2.imread(test_data.small_gray_img, -1)%0A mask = cv2.imread(test_data.small_bin_img, -1)%0A%0A _ = analyze_nir_intensity(gray_img=img, mask=mask, bins=256, histplot=True)%0A assert int(outputs.observations%5B'default'%5D%5B'nir_median'%5D%5B'value'%5D) == 117%0A%0A%0Adef test_analyze_nir_16bit(test_data):%0A # Clear previous outputs%0A outputs.clear()%0A # Read in test data%0A img = cv2.imread(test_data.small_gray_img, -1)%0A mask = cv2.imread(test_data.small_bin_img, -1)%0A%0A _ = analyze_nir_intensity(gray_img=np.uint16(img), mask=mask, bins=256, histplot=True)%0A assert int(outputs.observations%5B'default'%5D%5B'nir_median'%5D%5B'value'%5D) == 117%0A
|
|
a9e387880dc8826bbe77decee7930d09b42ad59a | add private db uuid. | openerp/addons/base/ir/ir_config_parameter.py | openerp/addons/base/ir/ir_config_parameter.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2011 OpenERP SA (<http://www.openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
"""
Store database-specific configuration parameters
"""
import uuid
import datetime
from openerp import SUPERUSER_ID
from openerp.osv import osv, fields
from openerp.tools import misc, config
"""
A dictionary holding some configuration parameters to be initialized when the database is created.
"""
_default_parameters = {
"database.uuid": lambda: (str(uuid.uuid1()), []),
"database.create_date": lambda: (datetime.datetime.now().strftime(misc.DEFAULT_SERVER_DATETIME_FORMAT), ['base.group_user']),
"web.base.url": lambda: ("http://localhost:%s" % config.get('xmlrpc_port'), []),
}
class ir_config_parameter(osv.osv):
"""Per-database storage of configuration key-value pairs."""
_name = 'ir.config_parameter'
_rec_name = 'key'
_columns = {
'key': fields.char('Key', required=True, select=1),
'value': fields.text('Value', required=True),
'group_ids': fields.many2many('res.groups', 'ir_config_parameter_groups_rel', 'icp_id', 'group_id', string='Groups'),
}
_sql_constraints = [
('key_uniq', 'unique (key)', 'Key must be unique.')
]
def init(self, cr, force=False):
"""
Initializes the parameters listed in _default_parameters.
It overrides existing parameters if force is ``True``.
"""
for key, func in _default_parameters.iteritems():
# force=True skips search and always performs the 'if' body (because ids=False)
ids = not force and self.search(cr, SUPERUSER_ID, [('key','=',key)])
if not ids:
value, groups = func()
self.set_param(cr, SUPERUSER_ID, key, value, groups=groups)
def get_param(self, cr, uid, key, default=False, context=None):
"""Retrieve the value for a given key.
:param string key: The key of the parameter value to retrieve.
:param string default: default value if parameter is missing.
:return: The value of the parameter, or ``default`` if it does not exist.
:rtype: string
"""
ids = self.search(cr, uid, [('key','=',key)], context=context)
if not ids:
return default
param = self.browse(cr, uid, ids[0], context=context)
value = param.value
return value
def set_param(self, cr, uid, key, value, groups=[], context=None):
"""Sets the value of a parameter.
:param string key: The key of the parameter value to set.
:param string value: The value to set.
:param list of string groups: List of group (xml_id allowed) to read this key.
:return: the previous value of the parameter or False if it did
not exist.
:rtype: string
"""
ids = self.search(cr, uid, [('key','=',key)], context=context)
gids = []
for group_xml in groups:
res_id = self.pool['ir.model.data'].xmlid_to_res_id(cr, uid, group_xml)
if res_id:
gids.append((4, res_id))
vals = {'value': value}
if gids:
vals.update(group_ids=gids)
if ids:
param = self.browse(cr, uid, ids[0], context=context)
old = param.value
self.write(cr, uid, ids, vals, context=context)
return old
else:
vals.update(key=key)
self.create(cr, uid, vals, context=context)
return False
| Python | 0 | @@ -1298,24 +1298,110 @@
ameters = %7B%0A
+ %22database.uuid.private%22: lambda: (str(uuid.uuid1()), %5B'base.group_erp_manager'%5D),%0A
%22databas
|
9790fb109d59214ee016750307cd39b2f2780cf7 | solve increment counter | algo/incrementcounter.py | algo/incrementcounter.py | Python | 0.000124 | @@ -0,0 +1,1003 @@
+from datetime import datetime, timedelta%0Afrom time import sleep%0A%0Asecond = timedelta(seconds=1)%0Aday = timedelta(days=1)%0A%0Aclass Increment:%0A def __init__(self):%0A self.last_second_count = 0%0A self.last_day_count = 0%0A self.seconds_now = datetime.now()%0A self.days_now = datetime.now()%0A %0A def increment(self):%0A now = datetime.now()%0A%0A if (now - self.seconds_now) %3E= second:%0A self.last_second_count = 1%0A self.seconds_now = now%0A else:%0A self.last_second_count += 1%0A%0A if (now - self.days_now) %3E= day:%0A self.last_day_count = 1%0A self.days_now = now%0A else:%0A self.last_day_count += 1%0A %0A%0A def get_events_last_second(self):%0A return self.last_second_count%0A%0A def get_events_last_day(self):%0A return self.last_day_count%0A%0Ai = Increment()%0A%0Afor j in range(100):%0A sleep(0.01)%0A i.increment()%0A%0Aprint i.get_events_last_day()%0Aprint i.get_events_last_second()%0A
|
|
aa2b788c4d0b148ed9881da86de97965311b9cb4 | Add server.py | server.py | server.py | Python | 0.000001 | @@ -0,0 +1,506 @@
+import socket, sys%0Aimport datetime%0Aimport time, random%0ATCP_IP = '72.36.65.116'%0ATCP_PORT = 5005%0ABUFFER_SIZE = 1024%0A%0Aif len(sys.argv) %3C 2:%0A print (%22Enter the server id%22)%0A sys.exit(1)%0A%0Awhile True:%0A v = random.randint(1, 10)%0A ts = time.time()%0A MESSAGE = str(v) + %22;%22 + sys.argv%5B1%5D + %22;%22 + datetime.datetime.fromtimestamp(ts).strftime('%25Y-%25m-%25d %25H:%25M:%25S')%0A s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)%0A s.connect((TCP_IP, TCP_PORT))%0A s.send(MESSAGE)%0A s.close()%0A print (MESSAGE)%0A time.sleep(5)%0A
|
|
287c659ad35f5036ba2687caf73009ef455c7239 | update example | examples/plot_otda_linear_mapping.py | examples/plot_otda_linear_mapping.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 20 14:31:15 2018
@author: rflamary
"""
import numpy as np
import pylab as pl
import ot
from scipy import ndimage
##############################################################################
# Generate data
# -------------
n = 1000
d = 2
sigma = .1
# source samples
angles = np.random.rand(n, 1) * 2 * np.pi
xs = np.concatenate((np.sin(angles), np.cos(angles)),
axis=1) + sigma * np.random.randn(n, 2)
xs[:n // 2, 1] += 2
# target samples
anglet = np.random.rand(n, 1) * 2 * np.pi
xt = np.concatenate((np.sin(anglet), np.cos(anglet)),
axis=1) + sigma * np.random.randn(n, 2)
xt[:n // 2, 1] += 2
A = np.array([[1.5, .7], [.7, 1.5]])
b = np.array([[4, 2]])
xt = xt.dot(A) + b
##############################################################################
# Plot data
# ---------
pl.figure(1, (5, 5))
pl.plot(xs[:, 0], xs[:, 1], '+')
pl.plot(xt[:, 0], xt[:, 1], 'o')
##############################################################################
# Estimate linear mapping and transport
# -------------------------------------
Ae, be = ot.da.OT_mapping_linear(xs, xt)
xst = xs.dot(Ae) + be
##############################################################################
# Plot transported samples
# ------------------------
pl.figure(1, (5, 5))
pl.clf()
pl.plot(xs[:, 0], xs[:, 1], '+')
pl.plot(xt[:, 0], xt[:, 1], 'o')
pl.plot(xst[:, 0], xst[:, 1], '+')
pl.show()
##############################################################################
# Mapping Class between images
# ----------------------------
def im2mat(I):
"""Converts and image to matrix (one pixel per line)"""
return I.reshape((I.shape[0] * I.shape[1], I.shape[2]))
def mat2im(X, shape):
"""Converts back a matrix to an image"""
return X.reshape(shape)
def minmax(I):
return np.clip(I, 0, 1)
# Loading images
I1 = ndimage.imread('../data/ocean_day.jpg').astype(np.float64) / 256
I2 = ndimage.imread('../data/ocean_sunset.jpg').astype(np.float64) / 256
X1 = im2mat(I1)
X2 = im2mat(I2)
##############################################################################
# Estimate mapping and adapt
# ----------------------------
mapping = ot.da.LinearTransport()
mapping.fit(Xs=X1, Xt=X2)
xst = mapping.transform(Xs=X1)
xts = mapping.inverse_transform(Xt=X2)
I1t = minmax(mat2im(xst, I1.shape))
I2t = minmax(mat2im(xts, I2.shape))
# %%
##############################################################################
# Plot transformed images
# -----------------------
pl.figure(2, figsize=(10, 7))
pl.subplot(2, 2, 1)
pl.imshow(I1)
pl.axis('off')
pl.title('Im. 1')
pl.subplot(2, 2, 2)
pl.imshow(I2)
pl.axis('off')
pl.title('Im. 2')
pl.subplot(2, 2, 3)
pl.imshow(I1t)
pl.axis('off')
pl.title('Mapping Im. 1')
pl.subplot(2, 2, 4)
pl.imshow(I2t)
pl.axis('off')
pl.title('Inverse mapping Im. 2')
| Python | 0.000001 | @@ -1569,52 +1569,26 @@
#%0A#
-Mapping Class between images%0A# -------------
+Load image data%0A#
----
|
dcca93fbb66e5cd8bf0e0500aca3f187922e8806 | Add in team id spider | scrapy_espn/scrapy_espn/spiders/team_spider.py | scrapy_espn/scrapy_espn/spiders/team_spider.py | Python | 0 | @@ -0,0 +1,360 @@
+import scrapy%0A%0Aclass TeamSpider(scrapy.Spider):%0A%09name = %22team%22%0A%09start_urls = %5B%0A%09%09'http://www.espn.com/mens-college-basketball/teams',%0A%09%5D%0A%0A%09def parse(self, response):%0A%09%09for conf in response.css('ul'):%0A%09%09%09for team in conf.css('li'):%0A%09%09%09%09yield %7B%0A%09%09%09%09%09'team':team.css('h5 a::text').extract(),%0A%09%09%09%09%09'id':team.css('h5 a::attr(href)').extract()%5B0%5D.split('/')%5B7%5D%0A%09%09%09%09%7D
|
|
4eb6c05df9b8faf4492b23db1ef0e2aee141d24b | test case for tpt | emma2/msm/analysis/api_test.py | emma2/msm/analysis/api_test.py | Python | 0 | @@ -0,0 +1,800 @@
+'''%0ACreated on 18.10.2013%0A%0A@author: marscher%0A'''%0Aimport unittest%0A%0Aimport emma2.msm.analysis.api as api%0Aimport numpy as np%0A%0Aclass Test(unittest.TestCase):%0A%0A def testTPT(self):%0A A = np.ndarray(%5B1, 2, 3%5D, dtype=int)%0A B = np.ndarray(%5B4, 2%5D, dtype=int)%0A %0A T = np.ndarray(%5B%5B 0.5, 0, 0.5, 0%5D,%0A %5B0, 0.5, 0.5, 0%5D,%0A %5B1 / 3., 1 / 3., 0, 1 / 3.%5D,%0A %5B0, 0, 1, 0%5D%5D, shape=(4,4), dtype=np.double)%0A%0A itpt = api.tpt(T, A, B)%0A %0A print %22flux: %22, itpt.getFlux()%0A print %22net flux: %22, itpt.getNetFlux()%0A print %22total flux: %22, itpt.getTotalFlux()%0A print %22forward committor%22, itpt.getForwardCommittor()%0A print %22backward committor%22, itpt.getBackwardCommitor()%0A %0Aif __name__ == %22__main__%22:%0A unittest.main()%0A
|
|
458cf526a4ebb72b4fad84e8cd2b665e0f093c1b | Add functional test for cluster check recover | senlin/tests/functional/test_cluster_health.py | senlin/tests/functional/test_cluster_health.py | Python | 0.000009 | @@ -0,0 +1,2983 @@
+# Licensed under the Apache License, Version 2.0 (the %22License%22); you may%0A# not use this file except in compliance with the License. You may obtain%0A# a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS, WITHOUT%0A# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the%0A# License for the specific language governing permissions and limitations%0A# under the License.%0A%0Afrom senlin.tests.functional import api as test_api%0Afrom senlin.tests.functional import base%0Afrom senlin.tests.functional.utils import test_utils%0A%0A%0Aclass TestClusterHealth(base.SenlinFunctionalTest):%0A def setUp(self):%0A super(TestClusterHealth, self).setUp()%0A # Create profile%0A self.profile = test_api.create_profile(%0A self.client, test_utils.random_name('profile'),%0A test_utils.spec_nova_server)%0A%0A def tearDown(self):%0A # Delete profile%0A test_api.delete_profile(self.client, self.profile%5B'id'%5D)%0A super(TestClusterHealth, self).tearDown()%0A%0A def test_cluster_check_recover(self):%0A # Create cluster%0A desired_capacity = 3%0A min_size = 2%0A max_size = 5%0A cluster = test_api.create_cluster(self.client,%0A test_utils.random_name('cluster'),%0A self.profile%5B'id'%5D, desired_capacity,%0A min_size, max_size)%0A cluster = test_utils.wait_for_status(test_api.get_cluster, self.client,%0A cluster%5B'id'%5D, 'ACTIVE')%0A%0A # Check cluster health status%0A action_id = test_api.action_cluster(self.client, cluster%5B'id'%5D,%0A 'check')%0A test_utils.wait_for_status(test_api.get_action, self.client,%0A action_id, 'SUCCEEDED')%0A cluster = test_api.get_cluster(self.client, cluster%5B'id'%5D)%0A self.assertEqual('ACTIVE', cluster%5B'status'%5D)%0A%0A # Perform cluster recovering operation%0A action_id = test_api.action_cluster(self.client, cluster%5B'id'%5D,%0A 'recover')%0A test_utils.wait_for_status(test_api.get_action, self.client,%0A action_id, 'SUCCEEDED')%0A action_id = test_api.action_cluster(self.client, cluster%5B'id'%5D,%0A 'recover',%0A %7B'operation': 'REBUILD'%7D)%0A test_utils.wait_for_status(test_api.get_action, self.client,%0A action_id, 'SUCCEEDED')%0A%0A # Delete cluster%0A test_api.delete_cluster(self.client, cluster%5B'id'%5D)%0A cluster = test_utils.wait_for_delete(test_api.get_cluster, self.client,%0A cluster%5B'id'%5D)%0A
|
|
48c008b4ac08114e30f4bee7a208d5d3fb925296 | Add partial simple greedy algorithm (baseline). | problem1/steiner-simplegreedy.py | problem1/steiner-simplegreedy.py | Python | 0.000001 | @@ -0,0 +1,1091 @@
+import networkx as nx%0D%0Afrom sys import argv%0D%0A%0D%0Adef main():%0D%0A # G = nx.read_gml(argv%5B1%5D)%0D%0A G = nx.read_gml(%22steiner-small.gml%22)%0D%0A%09%0D%0A T = %5B%5D # terminals%0D%0A for v,d in G.nodes_iter(data=True):%0D%0A if d%5B'T'%5D == 1:%0D%0A T.append(v)%0D%0A%0D%0A U = T%5B:%5D # Steiner tree vertices%0D%0A F = %5B%5D # Steiner tree edges%0D%0A%0D%0A D = %5B%5D # candidate edge set%0D%0A%0D%0A for u in T:%0D%0A u_incident = G.edges(u)%0D%0A for i in u_incident:%0D%0A D.append(i)%0D%0A%0D%0A UF = nx.Graph()%0D%0A UF.add_nodes_from(T)%0D%0A%0D%0A while not nx.is_connected(UF):%0D%0A if len(D) == 0:%0D%0A print(%22Not sufficiently connected%22)%0D%0A return None%0D%0A%0D%0A min_f = float(%22inf%22)%0D%0A for f_i in D:%0D%0A f_cost = G.edge%5Bf_i%5B0%5D%5D%5Bf_i%5B1%5D%5D%5B'c'%5D%0D%0A if f_cost %3C min_f:%0D%0A min_f = f_cost%0D%0A f = f_i%0D%0A%0D%0A UF_f = UF.copy()%0D%0A UF_f.add_edge(f%5B0%5D, f%5B1%5D)%0D%0A if nx.has_no_cycles(UF_f):%0D%0A pass%0D%0A #F.append(f)%0D%0A #U.append(f%5B0%5D)%0D%0A #U.append(f%5B1%5D)%0D%0A%0D%0A #D.append(f.incident)%0D%0A #D.remove(f)%0D%0A%0D%0A return UF%0D%0A %0D%0A%0D%0Aif __name__ == '__main__':%0D%0A UF = main()%0D%0A print(%22UF nodes:%22,UF.nodes())%0D%0A print(%22UF edges:%22,UF.edges())%0D%0A
|
|
fca390e7dd0d806cd87fa3570ce23ad132d8c852 | add new example | examples/lineWithFocusChart.py | examples/lineWithFocusChart.py | Python | 0.000002 | @@ -0,0 +1,1496 @@
+#!/usr/bin/python%0A# -*- coding: utf-8 -*-%0A%0A%22%22%22%0AExamples for Python-nvd3 is a Python wrapper for NVD3 graph library.%0ANVD3 is an attempt to build re-usable charts and chart components%0Afor d3.js without taking away the power that d3.js gives you.%0A%0AProject location : https://github.com/areski/python-nvd3%0A%22%22%22%0A%0Afrom nvd3 import lineWithFocusChart%0Aimport random%0Aimport datetime%0Aimport time%0A%0A%0Astart_time = int(time.mktime(datetime.datetime(2012, 6, 1).timetuple()) * 1000)%0Anb_element = 100%0A%0A#Open File for test%0Aoutput_file = open('test_lineWithFocusChart.html', 'w')%0A#---------------------------------------%0Atype = %22lineWithFocusChart%22%0Achart = lineWithFocusChart(name=type, color_category='category20b', date=True)%0Achart.set_containerheader(%22%5Cn%5Cn%3Ch2%3E%22 + type + %22%3C/h2%3E%5Cn%5Cn%22)%0A%0Axdata = range(nb_element)%0Axdata = map(lambda x: start_time + x * 1000000000, xdata)%0Aydata = %5Bi + random.randint(-10, 10) for i in range(nb_element)%5D%0A%0Aydata2 = map(lambda x: x * 2, ydata)%0Aydata3 = map(lambda x: x * 3, ydata)%0Aydata4 = map(lambda x: x * 4, ydata)%0A%0Aextra_serie = %7B%22tooltip%22: %7B%22y_start%22: %22There is %22, %22y_end%22: %22 calls%22%7D%7D%0A#extra_serie = None%0Achart.add_serie(name=%22serie 1%22, y=ydata, x=xdata, extra=extra_serie)%0Achart.add_serie(name=%22serie 2%22, y=ydata2, x=xdata, extra=extra_serie)%0Achart.add_serie(name=%22serie 3%22, y=ydata3, x=xdata, extra=extra_serie)%0Achart.add_serie(name=%22serie 4%22, y=ydata4, x=xdata, extra=extra_serie)%0A%0Achart.buildhtml()%0A%0Aoutput_file.write(chart.htmlcontent)%0A%0A#close Html file%0Aoutput_file.close()%0A
|
|
0114173d508298d6e9f72fd7f344d9123e4a7e59 | Create wtospark.py | sparkgw/wtospark.py | sparkgw/wtospark.py | Python | 0 | @@ -0,0 +1,1492 @@
+from flask import Flask, request, abort%0Aimport json%0Aimport urllib2%0A%0Aapp = Flask(__name__)%0A%0A#Secret provided by%0A# fbabottemp99%0A# MmQ3YTA0MGUtNGI1Zi00MTI3LTlmZTMtMjQxNGJhYmRjMTI0MzI2ZDFlYWYtYzhh%0A%0A# curl -X POST -H %22X-Device-Secret: 12345%22 http://localhost:8080/report?temp=32%0A%0A%0AYOUR_DEVICE_SECRET = %2212345%22%0AYOUR_BOT_TOKEN = %22%22%0AYOUR_ROOM_ID = %22%22%0A%[email protected]('/report', methods =%5B'POST'%5D)%0A%0Adef inputArduino():%0A headers = request.headers%0A temperature = request.args.get('temp')%0A incoming_secret = headers.get('X-Device-Secret')%0A%0A if temperature is None:%0A abort(401)%0A%0A if incoming_secret is None:%0A abort(401)%0A%0A elif YOUR_DEVICE_SECRET == incoming_secret:%0A # we dont use it but for illustration%0A json_file = request.json%0A toSpark('**Temperature:** '+temperature)%0A return 'Ok'%0A else:%0A print %22Spoofed Hook%22%0A abort(401)%0A%0A%0A# POST Function that sends the commits & comments in markdown to a Spark room%0Adef toSpark(commits):%0A url = 'https://api.ciscospark.com/v1/messages'%0A headers = %7B'accept':'application/json','Content-Type':'application/json','Authorization': 'Bearer ' + YOUR_BOT_TOKEN%7D%0A values = %7B'roomId': YOUR_ROOM_ID, 'markdown': commits %7D%0A data = json.dumps(values)%0A req = urllib2.Request(url = url , data = data , headers = headers)%0A response = urllib2.urlopen(req)%0A the_page = response.read()%0A return the_page%0A%0Aif __name__ == '__main__':%0A app.run(host='0.0.0.0' , port=9090, debug=True)%0A
|
|
5432dd2ee2e1d20494d0b4cf8d816b298e70067c | Add test script. | protogeni/test/ma/lookup_keys.py | protogeni/test/ma/lookup_keys.py | Python | 0 | @@ -0,0 +1,2085 @@
+#! /usr/bin/env python%0A#%0A# Copyright (c) 2012-2014 University of Utah and the Flux Group.%0A# %0A# %7B%7B%7BGENIPUBLIC-LICENSE%0A# %0A# GENI Public License%0A# %0A# Permission is hereby granted, free of charge, to any person obtaining%0A# a copy of this software and/or hardware specification (the %22Work%22) to%0A# deal in the Work without restriction, including without limitation the%0A# rights to use, copy, modify, merge, publish, distribute, sublicense,%0A# and/or sell copies of the Work, and to permit persons to whom the Work%0A# is furnished to do so, subject to the following conditions:%0A# %0A# The above copyright notice and this permission notice shall be%0A# included in all copies or substantial portions of the Work.%0A# %0A# THE WORK IS PROVIDED %22AS IS%22, WITHOUT WARRANTY OF ANY KIND, EXPRESS%0A# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF%0A# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND%0A# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT%0A# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,%0A# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,%0A# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS%0A# IN THE WORK.%0A# %0A# %7D%7D%7D%0A#%0Aimport sys%0Aimport pwd%0Aimport getopt%0Aimport os%0Aimport re%0Aimport xmlrpclib%0Afrom M2Crypto import X509%0A%0Adef Usage():%0A print %22usage: %22 + sys.argv%5B 0 %5D + %22 %5Boption...%5D %3Cpublic%7Cprivate%7Cidentifying%3E %3Cuser_urn %5B...%5D%3E%22%0A print %22%22%22Options:%0A -d, --debug be verbose about XML methods invoked%0A -h, --help show options and usage%0A -r file, --read-commands=file specify additional configuration file%22%22%22%0A%0Aexecfile( %22test-common.py%22 )%0A%0Aauthority = %22geni-ma%22%0A%0Acallargs = %5B%0A %5B%7B%0A 'geni_type': 'geni_sfa',%0A 'geni_version': '3',%0A 'geni_value': get_self_credential()%7D%5D,%0A %7B%0A %7D%0A %5D%0A%0Atry:%0A response = do_method(authority, %22lookup_keys%22,%0A callargs,%0A response_handler=geni_am_response_handler)%0A print response%0Aexcept xmlrpclib.Fault, e:%0A Fatal(%22Could not obtain keys: %25s%22 %25 (str(e)))%0A
|
|
d1edac38e3402ebe03f96597500c3d39e49f299d | add run_pylint.py | run_pylint.py | run_pylint.py | Python | 0.000011 | @@ -0,0 +1,1214 @@
+#!/usr/bin/python%0A#%0A# wrapper script for pylint which just shows the errors and changes the return value if there's problems%0A# (enforcing a minscore and/or maxerrors - defaults to perfection)%0A#%0Aimport sys, re, subprocess, os%0A%0AMINSCORE = 10.0%0AMAXERRORS = 0%0A %0Acommand = 'pylint --rcfile=pylintrc --disable=W0511,W9911,W9913 %60find webui python_saml libs -name %22*py%22%60'%0A%0A# unbuffer *both* me and the pylint subprocess!%0Aos.environ%5B'PYTHONUNBUFFERED'%5D = '1'%0Ap = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,%0A shell=True, universal_newlines=True)%0Anum_errors = 0%0Ascore = 0%0Awhile True:%0A line = p.stdout.readline().strip()%0A if line is None:%0A break%0A match = re.search(r'%5E.+?:%5B0-9%5D+: %5C%5B.%5B0-9%5D+.+?%5C%5D ', line)%0A if match:%0A print line%0A num_errors += 1%0A continue%0A match = re.search(r'Your code has been rated at (%5B0-9.-%5D+)', line)%0A if match:%0A score = float(match.group(1))%0A break%0A%0Aif score %3C MINSCORE:%0A print %22scored %25.2f which is less than %25.2f - aborting%22 %25 (score, MINSCORE)%0A sys.exit(3)%0Aif num_errors %3C MAXERRORS:%0A print %22%25d errors which is more than %25d - aborting%22 %25 (num_errors, MAXERRORS)%0A sys.exit(4)%0A
|
|
a96c25cf46cd82716b397ba61c2b67acb8b7c2d7 | Add code reading. | micro.py | micro.py | Python | 0 | @@ -0,0 +1,137 @@
+#!/usr/bin/env python%0A%0Afrom sys import argv%0A%0Adef get_code():%0A%09return argv%5B1%5D%0A%0Aif __name__ == '__main__':%0A%09code = get_code()%0A%09print(code)%0A
|
|
084ebff19703c42c50621eb94ac070c6a471e983 | Solve the most wanted letter problem. | Home/mostWantedLetter.py | Home/mostWantedLetter.py | Python | 0.999816 | @@ -0,0 +1,694 @@
+def checkio(word):%0A word = word.lower()%0A arr = dict()%0A for i in range(len(word)):%0A char = word%5Bi%5D%0A if not str.isalpha(char):%0A continue%0A if not arr.__contains__(char):%0A arr%5Bchar%5D = 0%0A arr%5Bchar%5D = arr%5Bchar%5D + 1%0A result = %22%22%0A counter = 0%0A for k, v in arr.items():%0A if counter %3C v or (ord(k) %3C ord(result) and counter == v):%0A result = k%0A counter = v%0A return result%0A%0Aif __name__ == '__main__':%0A assert checkio(%22Hello World!%22) == %22l%22, %22First%22%0A assert checkio(%22How do you do?%22) == %22o%22, %22Second%22%0A assert checkio(%22One%22) == %22e%22, %22Third%22%0A assert checkio(%22%22) == %22%22, %22Final%22%0A print('All ok')%0A
|
|
d437f494db827c69da7aaec00a5acf1d133e16b2 | Add basic slash command example | examples/app_commands/basic.py | examples/app_commands/basic.py | Python | 0.009586 | @@ -0,0 +1,2925 @@
+from typing import Optional%0A%0Aimport discord%0Afrom discord import app_commands%0A%0AMY_GUILD = discord.Object(id=0) # replace with your guild id%0A%0A%0Aclass MyClient(discord.Client):%0A def __init__(self, *, intents: discord.Intents, application_id: int):%0A super().__init__(intents=intents, application_id=application_id)%0A # A CommandTree is a special type that holds all the application command%0A # state required to make it work. This is a separate class because it%0A # allows all the extra state to be opt-in.%0A # Whenever you want to work with application commands, your tree is used%0A # to store it and work with it.%0A # Note: When using commands.Bot instead of discord.Client, the bot will%0A # maintain its own tree instead.%0A self.tree = app_commands.CommandTree(self)%0A%0A # In this basic example, we just synchronize the app commands to one guild.%0A # Instead of specifying a guild to every command, we copy over our global commands instead.%0A # By doing so we don't have to wait up to an hour until they are shown to the end-user.%0A async def setup_hook(self):%0A # This copies the global commands over to your guild.%0A self.tree.copy_global_to(guild=MY_GUILD)%0A await self.tree.sync(guild=MY_GUILD)%0A%0A%0Aintents = discord.Intents.default()%0A%0A# In order to use a basic synchronization of the app commands in the setup_hook,%0A# you have replace the 0 with your bots application_id you find in the developer portal.%0Aclient = MyClient(intents=intents, application_id=0)%0A%0A%[email protected]%0Aasync def on_ready():%0A print(f'Logged in as %7Bclient.user%7D (ID: %7Bclient.user.id%7D)')%0A print('------')%0A%0A%[email protected]()%0Aasync def hello(interaction: discord.Interaction):%0A %22%22%22Says hello!%22%22%22%0A await interaction.response.send_message(f'Hi, %7Binteraction.user.mention%7D')%0A%0A%[email protected]()%0A@app_commands.describe(%0A first_value='The first value you want to add something to',%0A second_value='The value you want to add to the first value',%0A)%0Aasync def add(interaction: discord.Interaction, first_value: int, second_value: int):%0A %22%22%22Adds two numbers together.%22%22%22%0A await interaction.response.send_message(f'%7Bfirst_value%7D + %7Bsecond_value%7D = %7Bfirst_value + second_value%7D')%0A%0A%0A# To make an argument optional, you can either give it a supported default argument%0A# or you can mark it as Optional from the typing library. This example does both.%[email protected]()%0A@app_commands.describe(member='The member you want to get the joined date from, defaults to the user who uses the command')%0Aasync def joined(interaction: discord.Interaction, member: Optional%5Bdiscord.Member%5D = None):%0A %22%22%22Says when a member joined.%22%22%22%0A # If no member is explicitly provided then we use the command user here%0A member = member or interaction.user%0A%0A await interaction.response.send_message(f'%7Bmember%7D joined in %7Bmember.joined_at%7D')%0A%0A%0Aclient.run('token')%0A
|
|
235a7107ca0c6d586edd9f224b9ee9132111a842 | remove debug trace | toflib.py | toflib.py | import random
from datetime import datetime
# those commands directly trigger cmd_* actions
_simple_dispatch = set()
# those commands directly trigger confcmd_* actions
_simple_conf_dispatch = set()
def cmd(expected_args):
def deco(func):
name = func.__name__[4:]
_simple_dispatch.add(name)
def f(bot, chan, args):
if(len(args) == expected_args):
return func(bot, chan, args)
f.__doc__ = func.__doc__
return f
return deco
def confcmd(expected_args):
def deco(func):
name = func.__name__[8:]
_simple_conf_dispatch.add(name)
def f(bot, chan, args):
if(len(args) == expected_args):
return func(bot, chan, args)
f.__doc__ = func.__doc__
return f
return deco
def distance(string1, string2):
"""
Levenshtein distance
http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Levenshtein_distance#Python
"""
string1 = ' ' + string1
string2 = ' ' + string2
dists = {}
len1 = len(string1)
len2 = len(string2)
for i in range(len1):
dists[i, 0] = i
for j in range (len2):
dists[0, j] = j
for j in range(1, len2):
for i in range(1, len1):
if string1[i] == string2[j]:
dists[i, j] = dists[i-1, j-1]
else:
dists[i, j] = min(dists[i-1, j] + 1,
dists[i, j-1] + 1,
dists[i-1, j-1] + 1
)
return dists[len1-1, len2-1]
class RiddleTeller(object):
"""
A gentleman (and a scholar) who likes to entertain its audience.
"""
def __init__(self, riddle, channel, writeback, max_dist):
self.riddle, self.answer = riddle
self.channel = channel
self.writeback = writeback
self.remaining_msgs = 3
self.writeback(self.riddle)
self.max_dist = max_dist
def wait_answer(self, chan, msg):
"""
Called at each try.
Returns True iff the riddle is over.
"""
if chan != self.channel:
return False
if distance(msg.lower(), self.answer.lower()) < self.max_dist:
self.writeback("10 points pour Griffondor.")
return True
self.remaining_msgs -= 1
if self.remaining_msgs == 0:
self.writeback(self.answer)
return True
return False
class InnocentHand(object):
"""
A cute 6 years old girl, picking a random object
from a given pool of candidates
"""
def __init__(self, pool):
"""
pool: list of candidates
"""
self.pool = pool
def __call__(self, index=None):
if index:
return self.pool[index % len(self.pool)]
random.seed()
return random.choice(self.pool)
class Plugin(object):
def __init__(self, bot):
self.bot = bot
def say(self, msg):
self.bot.msg(self.bot.channels[0], msg)
class CronEvent:
def __init__(self, bot):
self.lastTick = datetime.min
self.period = timedelta(minutes=10)
self.bot = bot
def fire(self):
pass
class Cron:
def __init__(self):
self.events = []
def tick(self):
now = datetime.now ()
for ev in self.events:
print ev
if now > ev.lastTick + ev.period:
ev.fire()
ev.lastTick = now
def schedule(self, ev):
self.events.append(ev)
| Python | 0.000004 | @@ -36,16 +36,27 @@
datetime
+, timedelta
%0A%0A# thos
@@ -3383,29 +3383,8 @@
ts:%0A
- print ev%0A
|
8fb4df5367b5c03d2851532063f6fa781fe2f980 | Add Fibonacci Series Using Recursion | Maths/fibonacciSeries.py | Maths/fibonacciSeries.py | Python | 0.000003 | @@ -0,0 +1,367 @@
+# Fibonacci Sequence Using Recursion%0A%0Adef recur_fibo(n):%0A if n %3C= 1:%0A return n%0A else:%0A return(recur_fibo(n-1) + recur_fibo(n-2))%0A %0Alimit = int(input(%22How many terms to include in fionacci series:%22))%0A%0Aif limit %3C= 0:%0A print(%22Plese enter a positive integer%22)%0Aelse:%0A print(%22Fibonacci series:%22)%0A for i in range(limit):%0A print(recur_fibo(i))%0A
|
|
5f8e01f976d75eca651e29ebdd379c865aa5bda9 | update merge_two_binary_trees_617 | Python/merge_two_binary_trees_617.py | Python/merge_two_binary_trees_617.py | Python | 0.000004 | @@ -0,0 +1,1644 @@
+# Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.%0A%0A# You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node.%0A# Otherwise, the NOT null node will be used as the node of new tree.%0A%0A# Example 1:%0A# Input: %0A# %09Tree 1 Tree 2 %0A# 1 2 %0A# / %5C / %5C %0A# 3 2 1 3 %0A# / %5C %5C %0A# 5 4 7 %0A# Output: %0A# Merged tree:%0A# %09 3%0A# %09 / %5C%0A# %09 4 5%0A# %09 / %5C %5C %0A# %09 5 4 7%0A# Note: The merging process must start from the root nodes of both trees.%0A%0A# %E9%A2%98%E8%A7%A3:%0A# %E5%B0%B1%E6%98%AF%E5%90%88%E5%B9%B6%E4%B8%A4%E4%B8%AA%E4%BA%8C%E5%8F%89%E6%A0%91%EF%BC%8C%E6%9C%89%E7%9B%B8%E5%90%8C%E8%8A%82%E7%82%B9%E7%9A%84%EF%BC%8C%E5%88%99%E7%9B%B8%E5%8A%A0%E8%B5%B7%E6%9D%A5%EF%BC%8C%E8%BF%98%E6%94%BE%E5%9C%A8%E9%82%A3%E4%B8%AA%E8%8A%82%E7%82%B9%EF%BC%8C%0A# %E5%A6%82%E6%9E%9C%E4%B8%80%E4%B8%AA%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E4%B8%80%E4%B8%AA%E8%8A%82%E7%82%B9%E4%B8%8A%E6%9C%89%E8%80%8C%E5%8F%A6%E4%B8%80%E4%B8%AA%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E7%9B%B8%E5%90%8C%E8%8A%82%E7%82%B9%E4%B8%8A%E6%B2%A1%E6%9C%89%E6%95%B0%E6%8D%AE%E7%9A%84%E8%AF%9D%E5%B0%B1%E5%9C%A8%E9%82%A3%E4%B8%AA%E8%8A%82%E7%82%B9%E4%B8%8A%E4%BF%9D%E7%95%99%E6%9C%89%E7%9A%84%E5%8D%B3%E5%8F%AF%EF%BC%8C%0A# %E5%A6%82%E6%AD%A4%E9%81%8D%E5%8E%86%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9B%B4%E8%87%B3%E7%BB%93%E6%9D%9F%0A%0A# Definition for a binary tree node.%0A# class TreeNode(object):%0A# def __init__(self, x):%0A# self.val = x%0A# self.left = None%0A# self.right = None%0A%0Aclass Solution(object):%0A def mergeTrees(self, t1, t2):%0A %22%22%22%0A :type t1: TreeNode%0A :type t2: TreeNode%0A :rtype: TreeNode%0A %22%22%22%0A if t1 and t2:%0A root=TreeNode(t1.val + t2.val)%0A root.left=self.mergeTrees(t1.left, t2.left)%0A root.right=self.mergeTrees(t1.right, t2.right)%0A return root%0A else:%0A return t1 or t2%0A
|
|
8c6983656e550ebaf32ff714a3c22be276ba842b | Add ScribdDownloader.py | ScribdDownloader.py | ScribdDownloader.py | Python | 0 | @@ -0,0 +1,1497 @@
+#Scribd Downloader%0A#Adam Knuckey September 2015%0A%0Aprint (%22Starting Scribd Downloader%22)%0Aimport os%0Aimport re%0Aimport urllib, urllib2%0Aimport threading%0Afrom time import sleep%0A%0Adef download(link,destination):%0A%09#print link%0A%09urllib.urlretrieve(link,destination)%0A%0Aprint(%22Enter textbook link:%22)%0Awebsite = raw_input(%22 %3E %22)%0Arequest = urllib2.Request(website)%0Arequest.add_header('User-Agent','Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11')%0Aopener = urllib2.build_opener()%0Ahtml = opener.open(request).read()%0Aregex = re.compile(%22%3Ctitle%3E.+%3C/title%3E%22)%0Afor m in regex.finditer(html):%0A%09title = m.group().replace(%22%3Ctitle%3E%22,%22%22).replace(%22%3C/title%3E%22,%22%22)%0A%0Aprint (%22Download %22+title+%22?%22)%0Aproceed = raw_input(%22(y/n) %3E %22).lower()%0A%0Aif proceed == %22y%22:%0A%09print (%22Downloading textbook - %22+title+%22...%22)%0A%09index = html.index('pageParams.contentUrl = %22https://html2-f.scribdassets.com/')+len('pageParams.contentUrl = %22https://html2-f.scribdassets.com/')%0A%09ident = html%5Bindex:index+17%5D%0A%0A%09if not os.path.exists(title):%0A%09 os.makedirs(title)%0A%0A%09page = 1%0A%09regex = re.compile(ident)%0A%09for m in regex.finditer(html):#%0A%09%09link = html%5Bm.start()-len('https://html2-f.scribdassets.com/'):m.start()+23+len(str(page))+11%5D.replace(%22pages%22,%22images%22)+%22.jpg%22%0A%09%09t = threading.Thread(target=download,args=(link,title+%22/%22+str(page)+%22.jpg%22))%0A%09%09t.daemon = True%0A%09%09t.start()%0A%09%09sleep(0.05)%0A%09%09#print link%0A%09%09#urllib.urlretrieve(link,title+%22/%22+str(page)+%22.jpg%22)%0A%09%09page+=1%0A%09print (%22Downloaded %22+str(page-1)+%22 pages%22)%0A%0Aelse:%0A%09print (%22Exiting...%22)%0A%0A
|
|
97ae80b08958646e0c937f65a1b396171bf61e72 | Add a proper unit test for xreload.py. | Lib/test/test_xreload.py | Lib/test/test_xreload.py | Python | 0 | @@ -0,0 +1,1742 @@
+%22%22%22Doctests for module reloading.%0A%0A%3E%3E%3E from xreload import xreload%0A%3E%3E%3E from test.test_xreload import make_mod%0A%3E%3E%3E make_mod()%0A%3E%3E%3E import x%0A%3E%3E%3E C = x.C%0A%3E%3E%3E Cfoo = C.foo%0A%3E%3E%3E Cbar = C.bar%0A%3E%3E%3E Cstomp = C.stomp%0A%3E%3E%3E b = C()%0A%3E%3E%3E bfoo = b.foo%0A%3E%3E%3E b.foo()%0A42%0A%3E%3E%3E bfoo()%0A42%0A%3E%3E%3E Cfoo(b)%0A42%0A%3E%3E%3E Cbar()%0A42 42%0A%3E%3E%3E Cstomp()%0A42 42 42%0A%3E%3E%3E make_mod(repl=%2242%22, subst=%2224%22)%0A%3E%3E%3E xreload(x)%0A%3Cmodule 'x' (built-in)%3E%0A%3E%3E%3E b.foo()%0A24%0A%3E%3E%3E bfoo()%0A24%0A%3E%3E%3E Cfoo(b)%0A24%0A%3E%3E%3E Cbar()%0A24 24%0A%3E%3E%3E Cstomp()%0A24 24 24%0A%0A%22%22%22%0A%0ASAMPLE_CODE = %22%22%22%0Aclass C:%0A def foo(self):%0A print(42)%0A @classmethod%0A def bar(cls):%0A print(42, 42)%0A @staticmethod%0A def stomp():%0A print (42, 42, 42)%0A%22%22%22%0A%0Aimport os%0Aimport sys%0Aimport shutil%0Aimport doctest%0Aimport xreload%0Aimport tempfile%0Afrom test.test_support import run_unittest%0A%0Atempdir = None%0Asave_path = None%0A%0A%0Adef setUp(unused=None):%0A global tempdir, save_path%0A tempdir = tempfile.mkdtemp()%0A save_path = list(sys.path)%0A sys.path.append(tempdir)%0A%0A%0Adef tearDown(unused=None):%0A global tempdir, save_path%0A if save_path is not None:%0A sys.path = save_path%0A save_path = None%0A if tempdir is not None:%0A shutil.rmtree(tempdir)%0A tempdir = None%0A %0A%0Adef make_mod(name=%22x%22, repl=None, subst=None):%0A if not tempdir:%0A setUp()%0A assert tempdir%0A fn = os.path.join(tempdir, name + %22.py%22)%0A f = open(fn, %22w%22)%0A sample = SAMPLE_CODE%0A if repl is not None and subst is not None:%0A sample = sample.replace(repl, subst)%0A try:%0A f.write(sample)%0A finally:%0A f.close()%0A%0A%0Adef test_suite():%0A return doctest.DocTestSuite(setUp=setUp, tearDown=tearDown)%0A%0A%0Adef test_main():%0A run_unittest(test_suite())%0A%0Aif __name__ == %22__main__%22:%0A test_main()%0A
|
|
53e851f68f106bff919a591a3516f26d5b07c375 | add unit test case for FedMsgContext.send_message | fedmsg/tests/test_core.py | fedmsg/tests/test_core.py | Python | 0.000002 | @@ -0,0 +1,1190 @@
+import unittest%0A%0Aimport mock%0Aimport warnings%0Afrom fedmsg.core import FedMsgContext%0Afrom common import load_config%0A%0A%0Aclass TestCore(unittest.TestCase):%0A def setUp(self):%0A config = load_config()%0A config%5B'io_threads'%5D = 1%0A self.ctx = FedMsgContext(**config)%0A%0A def test_send_message(self):%0A %22%22%22send_message is deprecated%0A%0A It tests%0A - deprecation warning showing up appropriately%0A - that we call publish method behind the scene%0A %22%22%22%0A fake_topic = %22org.fedoraproject.prod.compose.rawhide.complete%22%0A fake_msg = %22%7B'arch'': 's390', 'branch': 'rawhide', 'log': 'done'%7D%22%0A self.ctx.publish = mock.Mock(spec_set=FedMsgContext.publish)%0A with warnings.catch_warnings(record=True) as w:%0A warnings.simplefilter(%22always%22)%0A self.ctx.send_message(topic=fake_topic, msg=fake_msg)%0A assert len(w) == 1%0A assert str(w%5B0%5D.message) == %22.send_message is deprecated.%22%0A assert self.ctx.publish.called%0A topic, msg, modname = self.ctx.publish.call_args%5B0%5D%0A assert topic == fake_topic%0A assert msg == fake_msg%0A assert modname is None%0A
|
|
7a7d597c771ba8100957b5ca00156d7147c695c5 | Add clear_db_es_contents tests | src/encoded/tests/test_clear_db_es_contents.py | src/encoded/tests/test_clear_db_es_contents.py | Python | 0.000002 | @@ -0,0 +1,1393 @@
+import pytest%0Afrom encoded.commands.clear_db_es_contents import (%0A clear_db_tables,%0A run_clear_db_es%0A)%0A%0Apytestmark = %5Bpytest.mark.setone, pytest.mark.working%5D%0A%0A%0Adef test_clear_db_tables(app, testapp):%0A # post an item and make sure it's there%0A post_res = testapp.post_json('/testing-post-put-patch/', %7B'required': 'abc'%7D,%0A status=201)%0A testapp.get(post_res.location, status=200)%0A clear_db_tables(app)%0A # item should no longer be present%0A testapp.get(post_res.location, status=404)%0A%0A%0Adef test_run_clear_db_envs(app):%0A # if True, then it cleared DB%0A assert run_clear_db_es(app, None, True) == True%0A prev_env = app.registry.settings.get('env.name')%0A%0A # should never run on these envs%0A app.registry.settings%5B'env.name'%5D = 'fourfront-webprod'%0A assert run_clear_db_es(app, None, True) == False%0A app.registry.settings%5B'env.name'%5D = 'fourfront-webprod2'%0A assert run_clear_db_es(app, None, True) == False%0A%0A # test if we are only running on specific envs%0A app.registry.settings%5B'env.name'%5D = 'fourfront-test-env'%0A assert run_clear_db_es(app, 'fourfront-other-env', True) == False%0A assert run_clear_db_es(app, 'fourfront-test-env', True) == True%0A%0A # reset settings after test%0A if prev_env is None:%0A del app.registry.settings%5B'env.name'%5D%0A else:%0A app.registry.settings%5B'env.name'%5D = prev_env%0A
|
|
28677132dbcacd7d348262007256b3e2a9e44da2 | add gate client module | server/Mars/Client/GateClient.py | server/Mars/Client/GateClient.py | Python | 0.000003 | @@ -0,0 +1,2606 @@
+#!/usr/bin/env python%0A# -*- encoding: utf-8 -*-%0A#%0A# Copyright (c) 2016 ASMlover. All rights reserved.%0A#%0A# Redistribution and use in source and binary forms, with or without%0A# modification, are permitted provided that the following conditions%0A# are met:%0A#%0A# * Redistributions of source code must retain the above copyright%0A# notice, this list ofconditions and the following disclaimer.%0A#%0A# * Redistributions in binary form must reproduce the above copyright%0A# notice, this list of conditions and the following disclaimer in%0A# the documentation and/or other materialsprovided with the%0A# distribution.%0A#%0A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS%0A# %22AS IS%22 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT%0A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS%0A# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE%0A# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,%0A# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,%0A# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;%0A# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER%0A# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT%0A# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN%0A# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE%0A# POSSIBILITY OF SUCH DAMAGE.%0A%0Aimport PathHelper as PH%0APH.addPathes('../')%0A%0Aimport sys%0Afrom bson import BSON%0Afrom msgpack.bMsgPack import msgPackExt, extHook%0Aimport msgpack%0A%0Afrom MarsLog.LogManager import LogManager%0Afrom MarsRpc.ChannelClient import ChannelClient%0Afrom MarsRpc.Compressor import Compressor%0A%0Afrom Utils.PyProto import ClientGate_pb2%0Afrom Utils.PyProto import Common_pb2%0Afrom Utils.EntityFactory import EntityFactory%0Afrom Utils.EntityManager import EntityManager%0Afrom Utils.IdCreator import IdCreator%0Afrom Utils.MessageCodec import Md5IndexDecoder, Md5IndexEncoder%0A%0Afrom ServerProxy import ServerProxy%0A%0AMARS_DEVICEID = str(IdCreator.genId())%0A%0Aclass GateClient(ClientGate_pb2.SGate2Client):%0A ST_INIT = 0%0A ST_CONNECTING = 1%0A ST_RECONNECTING = 3%0A ST_CONNECT_FAILED = 4%0A ST_CONNECT_SUCCESSED = 5%0A ST_DISCONNECTED = 6%0A%0A CB_ON_CONNECT_FAILED = 1%0A CB_ON_CONNECT_SUCCESSED = 2%0A CB_ON_DISCONNECTED = 3%0A CB_ON_CONNECT_REPLY = 4%0A CB_ON_RELIABLE_MSG_UNSENT = 5%0A%0A def __init__(self, host, port, clientConf, proto='BSON'):%0A super(GateClient, self).__init__(self)%0A self.client = ChannelClient(host, port, self)%0A
|
|
36fdfa89230fd08b6c28501f3f277bff642e36e3 | Create ipy_custom_action_button.py | pyside/pyside_basics/jamming/QAction/ipy_custom_action_button.py | pyside/pyside_basics/jamming/QAction/ipy_custom_action_button.py | Python | 0.000004 | @@ -0,0 +1,1201 @@
+from collections import OrderedDict%0Afrom functools import partial%0A%0Afrom PySide import QtCore%0Afrom PySide import QtGui%0A%0A##%0A%0Aclass CustomAction(QtGui.QAction):%0A def __init__(self, message, *args, **kwargs):%0A super(CustomAction, self).__init__(*args, **kwargs)%0A self.message = message%0A self.triggered.connect(self.callback)%0A %0A def callback(self):%0A print self.message, self.sender(), self.senderSignalIndex()%0A%0Aclass CustomButton(QtGui.QPushButton):%0A def __init__(self, *args, **kwargs):%0A super(CustomButton, self).__init__(*args, **kwargs)%0A self.clicked.connect(self.callback)%0A %0A def callback(self):%0A print self.text()%0A %0A for action in self.actions():%0A action.activate(QtGui.QAction.ActionEvent.Trigger)%0A%0A##%0A%0Amw = QtGui.QMainWindow()%0A%0AcustomAction1 = CustomAction(%22Action 1%22, mw)%0AcustomAction2 = CustomAction(%22Action 2%22, mw)%0A%0Abutton = CustomButton(%22Click me%22)%0A%0Aprint customAction1, button%0A%0Abutton.show()%0A%0A##%0A%0Abutton.addAction(customAction1)%0A%0A##%0A%0Abutton.addAction(customAction2)%0A%0A##%0A%0Abutton.removeAction(customAction1)%0A%0A##%0A%0Abutton.removeAction(customAction2)%0A%0A##%0A%0Abutton.addActions(%5BcustomAction1, customAction2%5D)%0A
|
|
c4625a3ea98da282d9cd77acc13bba996e9fa676 | Add refresh url param to dashboard page to allow on demand worker cache updates | flower/views/dashboard.py | flower/views/dashboard.py | from __future__ import absolute_import
import logging
from functools import partial
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
from tornado import web
from tornado import websocket
from tornado.ioloop import PeriodicCallback
from ..views import BaseHandler
logger = logging.getLogger(__name__)
class DashboardView(BaseHandler):
@web.authenticated
def get(self):
app = self.application
events = app.events.state
broker = app.capp.connection().as_uri()
workers = dict((k, dict(v)) for (k, v) in events.counter.items())
for name, info in workers.items():
worker = events.workers[name]
info.update(self._as_dict(worker))
info.update(status=worker.alive)
self.render("dashboard.html", workers=workers, broker=broker)
@classmethod
def _as_dict(cls, worker):
return dict((k, worker.__getattribute__(k)) for k in worker._fields)
class DashboardUpdateHandler(websocket.WebSocketHandler):
listeners = []
periodic_callback = None
workers = None
page_update_interval = 2000
def open(self):
app = self.application
if not app.options.auto_refresh:
self.write_message({})
return
if not self.listeners:
if self.periodic_callback is None:
cls = DashboardUpdateHandler
cls.periodic_callback = PeriodicCallback(
partial(cls.on_update_time, app),
self.page_update_interval)
if not self.periodic_callback._running:
logger.debug('Starting a timer for dashboard updates')
self.periodic_callback.start()
self.listeners.append(self)
def on_message(self, message):
pass
def on_close(self):
if self in self.listeners:
self.listeners.remove(self)
if not self.listeners and self.periodic_callback:
logger.debug('Stopping dashboard updates timer')
self.periodic_callback.stop()
@classmethod
def on_update_time(cls, app):
update = cls.dashboard_update(app)
if update:
for l in cls.listeners:
l.write_message(update)
@classmethod
def dashboard_update(cls, app):
state = app.events.state
workers = OrderedDict()
for name, worker in sorted(state.workers.items()):
counter = state.counter[name]
started=counter.get('task-started', 0)
processed=counter.get('task-received', 0)
failed=counter.get('task-failed', 0)
succeeded=counter.get('task-succeeded', 0)
retried=counter.get('task-retried', 0)
workers[name] = dict(
status=worker.alive,
active=started - succeeded - failed,
processed=processed,
failed=failed,
succeeded=succeeded,
retried=retried,
loadavg=worker.loadavg)
return workers
| Python | 0 | @@ -209,16 +209,40 @@
ort web%0A
+from tornado import gen%0A
from tor
@@ -340,16 +340,54 @@
Handler%0A
+from ..api.workers import ListWorkers%0A
%0A%0Alogger
@@ -476,16 +476,35 @@
ticated%0A
+ @gen.coroutine%0A
def
@@ -506,32 +506,106 @@
def get(self):%0A
+ refresh = self.get_argument('refresh', default=False, type=bool)%0A%0A
app = se
@@ -698,24 +698,99 @@
).as_uri()%0A%0A
+ if refresh:%0A yield ListWorkers.update_workers(app=app)%0A%0A
work
|
18f63b98bf7eefe3022dc4681e81ada9969d5228 | Create guess-the-word.py | Python/guess-the-word.py | Python/guess-the-word.py | Python | 0.999864 | @@ -0,0 +1,2936 @@
+# Time: O(n%5E2)%0A# Space: O(n)%0A%0A# This problem is an interactive problem new to the LeetCode platform.%0A#%0A# We are given a word list of unique words, each word is 6 letters long,%0A# and one word in this list is chosen as secret.%0A#%0A# You may call master.guess(word) to guess a word.%0A# The guessed word should have type string and must be from the original%0A# list with 6 lowercase letters.%0A#%0A# This function returns an integer type,%0A# representing the number of exact matches (value and position)%0A# of your guess to the secret word.%0A# Also, if your guess is not in the given wordlist, it will return -1 instead.%0A#%0A# For each test case, you have 10 guesses to guess the word.%0A# At the end of any number of calls, if you have made 10 or%0A# less calls to master.guess%0A# and at least one of these guesses was the secret, you pass the testcase.%0A#%0A# Besides the example test case below,%0A# there will be 5 additional test cases, each with 100 words in the word list.%0A# The letters of each word in those testcases were chosen independently at%0A# random from 'a' to 'z',%0A# such that every word in the given word lists is unique.%0A#%0A# Example 1:%0A# Input: secret = %22acckzz%22, wordlist = %5B%22acckzz%22,%22ccbazz%22,%22eiowzz%22,%22abcczz%22%5D%0A#%0A# Explanation:%0A#%0A# master.guess(%22aaaaaa%22) returns -1, because %22aaaaaa%22 is not in wordlist.%0A# master.guess(%22acckzz%22) returns 6, because %22acckzz%22 is secret%0A# and has all 6 matches.%0A# master.guess(%22ccbazz%22) returns 3, because %22ccbazz%22 has 3 matches.%0A# master.guess(%22eiowzz%22) returns 2, because %22eiowzz%22 has 2 matches.%0A# master.guess(%22abcczz%22) returns 4, because %22abcczz%22 has 4 matches.%0A#%0A# We made 5 calls to master.guess and one of them was the secret,%0A# so we pass the test case.%0A# Note: Any solutions that attempt to circumvent the judge will result%0A# in disqualification.%0A#%0A# %22%22%22%0A# This is Master's API interface.%0A# You should not implement it, or speculate about its implementation%0A# %22%22%22%0A# class Master(object):%0A# def guess(self, word):%0A# %22%22%22%0A# :type word: str%0A# :rtype int%0A# %22%22%22%0A%0Aimport collections%0Aimport itertools%0A%0Atry:%0A xrange # Python 2%0Aexcept NameError:%0A xrange = range # Python 3%0A%0A%0Aclass Solution(object):%0A def findSecretWord(self, wordlist, master):%0A %22%22%22%0A :type wordlist: List%5BStr%5D%0A :type master: Master%0A :rtype: None%0A %22%22%22%0A def match(a, b):%0A matches = 0%0A for i in xrange(len(a)):%0A if a%5Bi%5D == b%5Bi%5D:%0A matches += 1%0A return matches%0A%0A i, n = 0, 0%0A while i %3C 10 and n %3C 6:%0A count = collections.Counter(w1 for w1, w2 in%0A itertools.permutations(wordlist, 2)%0A if match(w1, w2) == 0)%0A guess = min(wordlist, key=lambda w: count%5Bw%5D)%0A n = master.guess(guess)%0A wordlist = %5Bw for w in wordlist if match(w, guess) == n%5D%0A i += 1%0A
|
|
803a2702a1330be1f51428f8d7533cfee27c3f90 | Add facebook_test_user support. | facepy/test.py | facepy/test.py | Python | 0 | @@ -0,0 +1,1381 @@
+import facepy%0A%0A%0Aclass FacebookTestUser(object):%0A def __init__(self, **kwargs):%0A fields = ('id', 'access_token', 'login_url', 'email', 'password')%0A for field in fields:%0A setattr(self, field, kwargs%5Bfield%5D)%0A self.graph = facepy.GraphAPI(self.access_token)%0A%0A%0Aclass TestUserManager(object):%0A def __init__(self, app_id, app_secret):%0A access_token = facepy.get_application_access_token(app_id, app_secret)%0A self.graph = facepy.GraphAPI(access_token)%0A self.app_id = app_id%0A%0A def create_user(self, **parameters):%0A %22%22%22 creates facebook test user%0A%0A Valid parameters (with default values):%0A installed = true%0A name = FULL_NAME%0A locale = en_US%0A permissions = read_stream%0A%0A %22%22%22%0A%0A url = %22%25s/accounts/test-users%22 %25 self.app_id%0A return FacebookTestUser(**self.graph.post(url, **parameters))%0A%0A def delete_user(self, user):%0A self.graph.delete(str(user.id))%0A%0A%0Aclass TestUser(object):%0A def __init__(self, manager, **user_params):%0A self.manager = manager%0A self.user_params = user_params%0A%0A def __enter__(self):%0A self._user = self.manager.create_user(**self.user_params)%0A return self._user%0A%0A def __exit__(self, exc_type=None, exc_value=None, traceback=None):%0A self.manager.delete_user(self._user)%0A
|
|
332f1fc67481432f6e8dd7cd9a35b02b12c9b6f6 | Create numpy.py | numpy.py | numpy.py | Python | 0.000319 | @@ -0,0 +1,152 @@
+# Best dimensions in each column of a matrix x.%0Afor i in range(x.shape%5B0%5D): %0A dims = x%5B:,i%5D.argsort()%5B-5:%5D%0A vals = x%5Bdims,i%5D%0A print dims, vals%0A
|
|
4d4904e69e030be3f2b0e30c957507626d58a50e | Teste nas listas | _Listas/sherlock.py | _Listas/sherlock.py | Python | 0.000002 | @@ -0,0 +1,639 @@
+# Quem %C3%A9 o culpado%0A%0Aperguntas = %5B%5D%0A%0Act = 0%0Apt = 0%0A%0Aquest = input(%22Voc%C3%AA telefonou a vitima: %22)%0Aperguntas.append(quest)%0Aquest = input(%22Voc%E1%BA%BD esteve no local do crime: %22)%0Aperguntas.append(quest)%0Aquest = input(%22Voc%C3%AA mora perto da vitima? %22)%0Aperguntas.append(quest)%0Aquest = input(%22Devia para a vitima? %22)%0Aperguntas.append(quest)%0Aquest = input(%22J%C3%A1 trabalhou com a vitima? %22)%0Aperguntas.append(quest)%0A%0Awhile ct %3C= len(perguntas) - 1:%0A%09if perguntas%5Bct%5D in %22sim%22:%0A%09%09pt += 1%0A%09ct += 1%0A%0Aif pt %3E= 1 and pt %3C= 2:%0A%09print(%22Voc%C3%AA %C3%A9 um suspeito%22)%0A%0Aelif pt %3E= 3 and pt %3C= 4:%0A%09print(%22Voc%C3%AA %C3%A9 cumplice!%22)%0A%0Aif pt == 5:%0A%09print(%22CULPADO,CULPADO, VOC%C3%8A SER%C3%81 PRESO!!!%22)%0A
|
|
47a0ebd7c5475f00299c967b9140b4025bba5f60 | Fix an issue when sending some options via ipc to a running daemon. fix #2344 | flexget/ipc.py | flexget/ipc.py | from __future__ import unicode_literals, division, absolute_import
import logging
import random
import string
import threading
import rpyc
from rpyc.utils.server import ThreadedServer
from flexget.scheduler import BufferQueue
from flexget.utils.tools import console
log = logging.getLogger('ipc')
# Allow some attributes from dict interface to be called over the wire
rpyc.core.protocol.DEFAULT_CONFIG['safe_attrs'].update(['items'])
IPC_VERSION = 0
AUTH_ERROR = 'authentication error'
AUTH_SUCCESS = 'authentication success'
class DaemonService(rpyc.Service):
# This will be populated when the server is started
manager = None
def on_connect(self):
"""Make sure the client version matches our own."""
client_version = self._conn.root.version()
if IPC_VERSION != client_version:
self.client_console('Incompatible client version. (daemon: %s, client: %s' % (IPC_VERSION, client_version))
self._conn.close()
return
def exposed_execute(self, options=None):
# Dictionaries are pass by reference with rpyc, turn this into a real dict on our side
if options:
options = dict(options.items())
if self.manager.scheduler.run_queue.qsize() > 0:
self.client_console('There is already a task executing. This task will execute next.')
log.info('Executing for client.')
cron = options and options.get('cron')
output = None if cron else BufferQueue()
tasks_finished = self.manager.scheduler.execute(options=options, output=output)
if output:
# Send back any output until all tasks have finished
while any(not t.is_set() for t in tasks_finished) or output.qsize():
try:
self.client_console(output.get(True, 0.5).rstrip())
except BufferQueue.Empty:
continue
def exposed_reload(self):
# TODO: Reload config
raise NotImplementedError
def exposed_shutdown(self, finish_queue=False):
log.info('Shutdown requested over ipc.')
self.client_console('Daemon shutdown requested.')
self.manager.scheduler.shutdown(finish_queue=finish_queue)
def client_console(self, text):
self._conn.root.console(text)
class ClientService(rpyc.Service):
def exposed_version(self):
return IPC_VERSION
def exposed_console(self, text):
console(text)
class IPCServer(threading.Thread):
def __init__(self, manager, port=None):
super(IPCServer, self).__init__(name='ipc_server')
self.daemon = True
self.manager = manager
self.host = '127.0.0.1'
self.port = port or 0
self.password = ''.join(random.choice(string.letters + string.digits) for x in range(15))
self.server = None
def authenticator(self, sock):
channel = rpyc.Channel(rpyc.SocketStream(sock))
password = channel.recv()
if password != self.password:
channel.send(AUTH_ERROR)
raise rpyc.utils.authenticators.AuthenticationError('Invalid password from client.')
channel.send(AUTH_SUCCESS)
return sock, self.password
def run(self):
DaemonService.manager = self.manager
self.server = ThreadedServer(
DaemonService, hostname=self.host, port=self.port, authenticator=self.authenticator, logger=log
)
# If we just chose an open port, write save the chosen one
self.port = self.server.listener.getsockname()[1]
self.manager.write_lock(ipc_info={'port': self.port, 'password': self.password})
self.server.start()
def shutdown(self):
self.server.close()
class IPCClient(object):
def __init__(self, port, password):
channel = rpyc.Channel(rpyc.SocketStream.connect('127.0.0.1', port))
channel.send(password)
response = channel.recv()
if response == AUTH_ERROR:
# TODO: What to raise here. I guess we create a custom error
raise ValueError('Invalid password for daemon')
self.conn = rpyc.utils.factory.connect_channel(channel, service=ClientService)
def close(self):
self.conn.close()
def __getattr__(self, item):
"""Proxy all other calls to the exposed daemon service."""
return getattr(self.conn.root, item)
| Python | 0 | @@ -430,16 +430,73 @@
items'%5D)
+%0Arpyc.core.protocol.DEFAULT_CONFIG%5B'allow_pickle'%5D = True
%0A%0AIPC_VE
@@ -1230,28 +1230,41 @@
s =
-dict(options.items()
+rpyc.utils.classic.obtain(options
)%0A
|
ceef4d18b414583cb39b83782c0fa24648b294db | make getters/setters private | periphery/gpio.py | periphery/gpio.py | import os
import select
class GPIOException(IOError):
pass
class GPIO(object):
def __init__(self, pin, direction):
self._fd = None
self._pin = None
self._open(pin, direction)
def __del__(self):
self.close()
def __enter__(self):
pass
def __exit__(self, t, value, traceback):
self.close()
def _open(self, pin, direction):
if not isinstance(pin, int):
raise TypeError("Invalid pin type, should be integer.")
if not isinstance(direction, str):
raise TypeError("Invalid direction type, should be string.")
if direction.lower() not in ["in", "out", "high", "low"]:
raise ValueError("Invalid direction, can be: \"in\", \"out\", \"high\", \"low\".")
gpio_path = "/sys/class/gpio/gpio%d" % pin
if not os.path.isdir(gpio_path):
# Export the pin
try:
f_export = open("/sys/class/gpio/export", "w")
f_export.write("%d\n" % pin)
f_export.close()
except IOError as e:
raise GPIOException(e.errno, "Exporting GPIO: " + e.strerror)
# Write direction
try:
direction = direction.lower()
f_direction = open("/sys/class/gpio/gpio%d/direction" % pin, "w")
f_direction.write(direction + "\n")
f_direction.close()
except IOError as e:
raise GPIOException(e.errno, "Setting GPIO direction: " + e.strerror)
# Open value
try:
self._fd = os.open("/sys/class/gpio/gpio%d/value" % pin, os.O_RDWR)
except OSError as e:
raise GPIOException(e.errno, "Opening GPIO: " + e.strerror)
self._pin = pin
def close(self):
if self._fd is None:
return
try:
os.close(self._fd)
except OSError as e:
raise GPIOException(e.errno, "Closing GPIO: " + e.strerror)
self._fd = None
# Methods
def read(self):
# Read value
try:
buf = os.read(self._fd, 2)
except OSError as e:
raise GPIOException(e.errno, "Reading GPIO: " + e.strerror)
# Rewind
try:
os.lseek(self._fd, 0, os.SEEK_SET)
except OSError as e:
raise GPIOException(e.errno, "Rewinding GPIO: " + e.strerror)
if buf[0] == b"0"[0]:
return False
elif buf[0] == b"1"[0]:
return True
raise GPIOException(None, "Unknown GPIO value: \"%s\"" % buf[0])
def write(self, value):
if not isinstance(value, bool):
raise TypeError("Invalid value type, should be bool.")
# Write value
try:
if value:
os.write(self._fd, b"1\n")
else:
os.write(self._fd, b"0\n")
except OSError as e:
raise GPIOException(e.errno, "Writing GPIO: " + e.strerror)
# Rewind
try:
os.lseek(self._fd, 0, os.SEEK_SET)
except OSError as e:
raise GPIOException(e.errno, "Rewinding GPIO: " + e.strerror)
def poll(self, timeout_ms):
if timeout_ms is not None and not isinstance(timeout_ms, int):
raise TypeError("Invalid timeout_ms type, should be integer or None.")
# Seek to the end
try:
os.lseek(self._fd, 0, os.SEEK_END)
except OSError as e:
raise GPIOException(e.errno, "Seeking to end of GPIO: " + e.strerror)
# Poll
p = select.poll()
p.register(self._fd, select.POLLPRI | select.POLLERR)
events = p.poll(timeout_ms)
# If GPIO edge interrupt occurred
if len(events) > 0:
# Rewind
try:
os.lseek(self._fd, 0, os.SEEK_SET)
except OSError as e:
raise GPIOException(e.errno, "Rewinding GPIO: " + e.strerror)
return True
return False
# Immutable properties
@property
def fd(self):
return self._fd
@property
def pin(self):
return self._pin
@property
def supports_interrupts(self):
return os.path.isfile("/sys/class/gpio/gpio%d/edge" % self._pin)
# Mutable properties
def get_direction(self):
# Read direction
try:
f_direction = open("/sys/class/gpio/gpio%d/direction" % self._pin, "r")
direction = f_direction.read()
f_direction.close()
except IOError as e:
raise GPIOException(e.errno, "Getting GPIO direction: " + e.strerror)
return direction.strip()
def set_direction(self, direction):
if not isinstance(direction, str):
raise TypeError("Invalid direction type, should be string.")
if direction.lower() not in ["in", "out", "high", "low"]:
raise ValueError("Invalid direction, can be: \"in\", \"out\", \"high\", \"low\".")
# Write direction
try:
direction = direction.lower()
f_direction = open("/sys/class/gpio/gpio%d/direction" % self._pin, "w")
f_direction.write(direction + "\n")
f_direction.close()
except IOError as e:
raise GPIOException(e.errno, "Setting GPIO direction: " + e.strerror)
direction = property(get_direction, set_direction)
def get_edge(self):
# Read edge
try:
f_edge = open("/sys/class/gpio/gpio%d/edge" % self._pin, "r")
edge = f_edge.read()
f_edge.close()
except IOError as e:
raise GPIOException(e.errno, "Getting GPIO edge: " + e.strerror)
return edge.strip()
def set_edge(self, edge):
if not isinstance(edge, str):
raise TypeError("Invalid edge type, should be string.")
if edge.lower() not in ["none", "rising", "falling", "both"]:
raise ValueError("Invalid edge, can be: \"none\", \"rising\", \"falling\", \"both\".")
# Write edge
try:
edge = edge.lower()
f_edge = open("/sys/class/gpio/gpio%d/edge" % self._pin, "w")
f_edge.write(edge + "\n")
f_edge.close()
except IOError as e:
raise GPIOException(e.errno, "Setting GPIO edge: " + e.strerror)
edge = property(get_edge, set_edge)
# String representation
def __str__(self):
if self.supports_interrupts:
return "GPIO %d (fd=%d, direction=%s, supports interrupts, edge=%s)" % (self._pin, self._fd, self.direction, self.edge)
return "GPIO %d (fd=%d, direction=%s, no interrupts)" % (self._pin, self._fd, self.direction)
| Python | 0.000004 | @@ -4296,24 +4296,25 @@
es%0A%0A def
+_
get_directio
@@ -4669,24 +4669,25 @@
()%0A%0A def
+_
set_directio
@@ -5362,24 +5362,25 @@
= property(
+_
get_directio
@@ -5382,16 +5382,17 @@
ection,
+_
set_dire
@@ -5407,16 +5407,17 @@
def
+_
get_edge
@@ -5735,16 +5735,17 @@
def
+_
set_edge
@@ -6366,16 +6366,17 @@
roperty(
+_
get_edge
@@ -6377,16 +6377,17 @@
t_edge,
+_
set_edge
|
235bfc6db908b6701de77df11e00e89a307d738e | Create tinymongo.py | tinymongo/tinymongo.py | tinymongo/tinymongo.py | Python | 0.000621 | @@ -0,0 +1 @@
+%0A
|
|
b351e5106684b0af8b862bb6ba5375671c1f431d | include getcomments.py | getcomments.py | getcomments.py | Python | 0.000001 | @@ -0,0 +1,1276 @@
+import urllib2%0Aimport json%0Aimport datetime%0Aimport time%0Aimport pytz%0Aimport pandas as pd%0Afrom pandas import DataFrame%0A%0Ats = str(int(time.time()))%0Adf = DataFrame()%0AhitsPerPage = 1000%0Arequested_keys = %5B%22author%22, %22comment_text%22, %22created_at_i%22, %22objectID%22, %22points%22%5D%0A%0Ai = 0%0A%0Awhile True:%0A%09try:%0A%09%09url = 'https://hn.algolia.com/api/v1/search_by_date?tags=comment&hitsPerPage=%25s&numericFilters=created_at_i%3C%25s' %25 (hitsPerPage, ts)%0A%09%09req = urllib2.Request(url)%0A%09%09response = urllib2.urlopen(req)%0A%09%09data = json.loads(response.read())%0A%09%09last = data%5B%22nbHits%22%5D %3C hitsPerPage%0A%09%09data = DataFrame(data%5B%22hits%22%5D)%5Brequested_keys%5D%0A%09%09df = df.append(data,ignore_index=True)%0A%09%09ts = data.created_at_i.min()%0A%09%09print i%0A%09%09if (last):%0A%09%09%09break%0A%09%09time.sleep(3.6)%0A%09%09i += 1%0A%0A%09except Exception, e:%0A%09%09print e%0A%0Adf%5B%22comment_text%22%5D = df%5B%22comment_text%22%5D.map(lambda x: x.translate(dict.fromkeys(%5B0x201c, 0x201d, 0x2011, 0x2013, 0x2014, 0x2018, 0x2019, 0x2026, 0x2032%5D)).encode('utf-8').replace(',',''))%0Adf%5B%22created_at%22%5D = df%5B%22created_at_i%22%5D.map(lambda x: datetime.datetime.fromtimestamp(int(x), tz=pytz.timezone('America/New_York')).strftime('%25Y-%25m-%25d %25H:%25M:%25S'))%0A%0Aordered_df = df%5B%5B%22comment_text%22,%22points%22,%22author%22,%22created_at%22,%22objectID%22%5D%5D%0A%0Aordered_df.to_csv(%22hacker_news_comments.csv%22,encoding='utf-8', index=False)
|
|
74ecac2dbca41d737f62325955fd4d0dc393ac16 | Rename flots.py to plots.py | plots.py | plots.py | Python | 0.999997 | @@ -0,0 +1,417 @@
+import json%0Aimport re%0A%0Aclass plot(object):%0A%0A def get_data(self,fn,col1,col2):%0A y = ''%0A for line in open(fn, 'rU'):%0A # don't parse comments%0A if re.search(r'#',line): continue%0A x = line.split()%0A if not re.search(r'%5BA-Za-z%5D%7B2,%7D%5Cs+%5BA-Za-z%5D%7B2,%7D',line):%0A y += '%5B ' + x%5Bcol1%5D + ', ' + x%5Bcol2%5D + '%5D, ' %0A str = %22%5B %25s %5D%22 %25 y%0A return str%0A
|
|
f13da24b8fb4cf6d8fff91e88afb1507528c2c2a | Add `.ycm_extra_conf.py` for https://github.com/Valloric/ycmd | android/.ycm_extra_conf.py | android/.ycm_extra_conf.py | Python | 0.000002 | @@ -0,0 +1,954 @@
+import os%0A%0AbasePath = os.path.dirname(os.path.realpath(__file__))%0A%0Adef FlagsForFile(filename, **kwargs):%0A return %7B%0A 'flags': %5B%0A '-std=c++11',%0A '-DFOLLY_NO_CONFIG=1',%0A '-DFOLLY_USE_LIBCPP',%0A '-I' + basePath + '/ReactAndroid/../ReactCommon/cxxreact/..',%0A '-I' + basePath + '/ReactAndroid/../ReactCommon/jschelpers/..',%0A '-I' + basePath + '/ReactAndroid/src/main/jni/first-party/fb/include',%0A '-I' + basePath + '/ReactAndroid/build/third-party-ndk/folly',%0A '-I' + basePath + '/ReactAndroid/build/third-party-ndk/jsc',%0A '-I' + basePath + '/ReactAndroid/build/third-party-ndk/glog/..',%0A '-I' + basePath + '/ReactAndroid/build/third-party-ndk/glog/glog-0.3.3/src/',%0A '-I' + basePath + '/ReactAndroid/build/third-party-ndk/boost/boost_1_63_0',%0A '-I' + basePath + '/ReactAndroid/build/third-party-ndk/double-conversion',%0A '-I' + basePath + '/ReactAndroid/../ReactCommon/cxxreact',%0A %5D,%0A %7D%0A%0A
|
|
0b51d460aab9a01135af9ba5279a5f321f0981f0 | Fix missing power monitor call on FakePlatform | tools/perf/measurements/smoothness_unittest.py | tools/perf/measurements/smoothness_unittest.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import sys
from measurements import smoothness
from telemetry.core import wpr_modes
from telemetry.page import page
from telemetry.page import page_measurement_unittest_base
from telemetry.unittest import options_for_unittests
class FakePlatform(object):
def IsRawDisplayFrameRateSupported(self):
return False
class FakeBrowser(object):
def __init__(self):
self.platform = FakePlatform()
self.category_filter = None
def StartTracing(self, category_filter, _):
self.category_filter = category_filter
class FakeTab(object):
def __init__(self):
self.browser = FakeBrowser()
def ExecuteJavaScript(self, js):
pass
class SmoothnessUnitTest(
page_measurement_unittest_base.PageMeasurementUnitTestBase):
"""Smoke test for smoothness measurement
Runs smoothness measurement on a simple page and verifies
that all metrics were added to the results. The test is purely functional,
i.e. it only checks if the metrics are present and non-zero.
"""
def testSyntheticDelayConfiguration(self):
test_page = page.Page('http://dummy', None)
test_page.synthetic_delays = {
'cc.BeginMainFrame': { 'target_duration': 0.012 },
'cc.DrawAndSwap': { 'target_duration': 0.012, 'mode': 'alternating' },
'gpu.SwapBuffers': { 'target_duration': 0.012 }
}
tab = FakeTab()
measurement = smoothness.Smoothness()
measurement.WillRunActions(test_page, tab)
expected_category_filter = [
'DELAY(cc.BeginMainFrame;0.012000;static)',
'DELAY(cc.DrawAndSwap;0.012000;alternating)',
'DELAY(gpu.SwapBuffers;0.012000;static)',
'benchmark',
'webkit.console'
]
actual_category_filter = tab.browser.category_filter.split(',')
actual_category_filter.sort()
if expected_category_filter != actual_category_filter:
sys.stderr.write("Expected category filter: %s\n" %
repr(expected_category_filter))
sys.stderr.write("Actual category filter filter: %s\n" %
repr(actual_category_filter))
self.assertEquals(expected_category_filter, actual_category_filter)
def setUp(self):
self._options = options_for_unittests.GetCopy()
self._options.browser_options.wpr_mode = wpr_modes.WPR_OFF
def testSmoothness(self):
ps = self.CreatePageSetFromFileInUnittestDataDir('scrollable_page.html')
measurement = smoothness.Smoothness()
results = self.RunMeasurement(measurement, ps, options=self._options)
self.assertEquals(0, len(results.failures))
frame_times = results.FindAllPageSpecificValuesNamed('frame_times')
self.assertEquals(len(frame_times), 1)
self.assertGreater(frame_times[0].GetRepresentativeNumber(), 0)
mean_frame_time = results.FindAllPageSpecificValuesNamed('mean_frame_time')
self.assertEquals(len(mean_frame_time), 1)
self.assertGreater(mean_frame_time[0].GetRepresentativeNumber(), 0)
jank = results.FindAllPageSpecificValuesNamed('jank')
self.assertEquals(len(jank), 1)
self.assertGreater(jank[0].GetRepresentativeNumber(), 0)
mostly_smooth = results.FindAllPageSpecificValuesNamed('mostly_smooth')
self.assertEquals(len(mostly_smooth), 1)
self.assertGreaterEqual(mostly_smooth[0].GetRepresentativeNumber(), 0)
mean_mouse_wheel_latency = results.FindAllPageSpecificValuesNamed(
'mean_mouse_wheel_latency')
if mean_mouse_wheel_latency:
self.assertEquals(len(mean_mouse_wheel_latency), 1)
self.assertGreater(
mean_mouse_wheel_latency[0].GetRepresentativeNumber(), 0)
mean_touch_scroll_latency = results.FindAllPageSpecificValuesNamed(
'mean_touch_scroll_latency')
if mean_touch_scroll_latency:
self.assertEquals(len(mean_touch_scroll_latency), 1)
self.assertGreater(
mean_touch_scroll_latency[0].GetRepresentativeNumber(), 0)
def testCleanUpTrace(self):
self.TestTracingCleanedUp(smoothness.Smoothness, self._options)
| Python | 0.000573 | @@ -473,16 +473,67 @@
n False%0A
+ def CanMonitorPowerAsync(self):%0A return False%0A
%0A%0Aclass
|
654f21b39a68aa461b6457199403e7d89781cc79 | add migration | students/migrations/0010_auto_20161010_1345.py | students/migrations/0010_auto_20161010_1345.py | Python | 0.000001 | @@ -0,0 +1,754 @@
+# -*- coding: utf-8 -*-%0A# Generated by Django 1.10.2 on 2016-10-10 11:45%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations, models%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('students', '0009_auto_20161005_1820'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterField(%0A model_name='student',%0A name='want_exam',%0A field=models.BooleanField(default=False, help_text='Die Klausur ist eine Simulation einer Uniklausur, um die Unteschiede zwischen einer Schul- und einer Universit%C3%A4tsklausr zu zeigen. Abgefragt werden haupts%C3%A4chlich Informationen aus der Ophase. Es ist nicht verpflichtend die Klausur zu bestehen.', verbose_name='Klausur mitschreiben?'),%0A ),%0A %5D%0A
|
|
b90b43ceefb78e1a94ba898ed23443567786cf25 | Add /monitoring/status handler | app/monitoring/handlers.py | app/monitoring/handlers.py | Python | 0.000002 | @@ -0,0 +1,928 @@
+from __future__ import unicode_literals, absolute_import, division%0Aimport json%0A%0Afrom structlog import get_logger%0A%0A%0Aclass StatusHandler:%0A def __init__(self):%0A self.logger = get_logger()%0A%0A def on_get(self, req, res):%0A %22%22%22%0A @type req: falcon.request.Request%0A @type res: falcon.response.Response%0A %22%22%22%0A rv = dict(%0A status='OK',%0A settings=%7B%7D, # TODO pass some/all settings here%0A content_type=req.content_type,%0A url=req.url,%0A remote_addr='', # TODO Use falcon or wgsi API to get remote addr%0A headers=req.headers,%0A cookies=req.cookies,%0A context=req.context)%0A res.body = json.dumps(dict(result=rv))%0A%0A%0Aclass AppRoutesHandler:%0A def __init__(self):%0A self.logger = get_logger()%0A%0A def on_get(self, req, res):%0A # TODO return result: routes?: %5Bhandler, url, methods%5D%0A pass
|
|
95c71727bf340f55e17a15d475aba54438eb0b8e | add solution for Partition List | src/partitionList.py | src/partitionList.py | Python | 0 | @@ -0,0 +1,750 @@
+# Definition for singly-linked list.%0A# class ListNode:%0A# def __init__(self, x):%0A# self.val = x%0A# self.next = None%0A%0A%0Aclass Solution:%0A # @param head, a ListNode%0A # @param x, an integer%0A # @return a ListNode%0A%0A def partition(self, head, x):%0A head1, head2 = ListNode(0), ListNode(0)%0A last1, last2 = head1, head2%0A while head:%0A if head.val %3C x:%0A last1.next = head%0A head = head.next%0A last1 = last1.next%0A last1.next = None%0A else:%0A last2.next = head%0A head = head.next%0A last2 = last2.next%0A last2.next = None%0A last1.next = head2.next%0A return head1.next%0A
|
|
5bff284204a1397dbc63e83363d865213a35efe6 | add a new test file test_begin_end.py | tests/unit/selection/modules/test_begin_end.py | tests/unit/selection/modules/test_begin_end.py | Python | 0.000016 | @@ -0,0 +1,1339 @@
+# Tai Sakuma %[email protected]%3E%0Aimport pytest%0A%0Atry:%0A import unittest.mock as mock%0Aexcept ImportError:%0A import mock%0A%0Afrom alphatwirl.selection.modules import Not, NotwCount%0A%0A##__________________________________________________________________%7C%7C%0Anot_classes = %5BNot, NotwCount%5D%0Anot_classe_ids = %5Bc.__name__ for c in not_classes%5D%0A%[email protected]('NotClass', not_classes, ids=not_classe_ids)%0Adef test_not_begin(NotClass):%0A selection = mock.Mock()%0A obj = NotClass(selection)%0A event = mock.Mock()%0A obj.begin(event)%0A assert %5Bmock.call(event)%5D == selection.begin.call_args_list%0A%[email protected]('NotClass', not_classes, ids=not_classe_ids)%0Adef test_not_begin_absent(NotClass):%0A selection = mock.Mock()%0A del selection.begin%0A obj = NotClass(selection)%0A event = mock.Mock()%0A obj.begin(event)%0A%[email protected]('NotClass', not_classes, ids=not_classe_ids)%0Adef test_not_end(NotClass):%0A selection = mock.Mock()%0A obj = NotClass(selection)%0A obj.end()%0A assert %5Bmock.call()%5D == selection.end.call_args_list%0A%[email protected]('NotClass', not_classes, ids=not_classe_ids)%0Adef test_not_end_absent(NotClass):%0A selection = mock.Mock()%0A del selection.end%0A obj = NotClass(selection)%0A obj.end()%0A%0A##__________________________________________________________________%7C%7C%0A
|
|
7655fe94decf2fc9c3a07104f8fa76cf39442ddb | implement rectified drive | rectifieddrive.py | rectifieddrive.py | Python | 0.000001 | @@ -0,0 +1,1210 @@
+import navx%0Aimport subsystems%0A%0A%0Aclass RectifiedDrive:%0A %22%22%22%0A This class implemented the rectifiedDrive function, which sets the motor outputs%0A given a desired power and angular velocity using the NavX and a PID controller.%0A %22%22%22%0A%0A def __init__(self, kp, ki, kd, period=0.05):%0A self.kp = kp%0A self.ki = ki%0A self.kd = kd%0A self.period = period%0A%0A self.prev_error = 0.0%0A%0A def rectifiedDrive(self, power, angular_vel):%0A error = angular_vel - navx.ahrs.getRate()%0A output = self.calc_pid(error)%0A left_output = power - output%0A if abs(left_output) %3E 1.0: # normalize if magnitude greater than 1%0A left_output /= abs(left_output)%0A right_output = power + output%0A if abs(right_output) %3E 1.0: # normalize if magnitude greater than 1%0A right_output /= abs(right_output)%0A subsystems.motors.robot_drive.setLeftRightMotorOutputs(left_output, right_output)%0A%0A def calc_pid(self, error):%0A e_deriv = (error - self.prev_error) / self.period%0A e_int = (error + self.prev_error) / 2 * self.period%0A self.prev_error = error%0A return self.kp * error + self.kd * e_deriv + self.ki * e_int%0A
|
|
feed8beb23fa1b1b4703e86b147f8bff84dab87a | Version bump. This ought to be the latest before 2.1 final. | src/robot/version.py | src/robot/version.py | # Automatically generated by 'package.py' script.
VERSION = 'trunk'
RELEASE = '20090415'
TIMESTAMP = '20090415-015729'
def get_version(sep=' '):
if RELEASE == 'final':
return VERSION
return VERSION + sep + RELEASE
if __name__ == '__main__':
import sys
print get_version(*sys.argv[1:])
| Python | 0 | @@ -80,17 +80,17 @@
'2009041
-5
+9
'%0ATIMEST
@@ -107,16 +107,16 @@
9041
-5-015729
+9-030634
'%0A%0Ad
|
dd1d0893823561efec203cdfbb927b8edac7a72a | Add a coupld tests to create exception classes from error code names | tests/unit/beanstalk/test_exception.py | tests/unit/beanstalk/test_exception.py | Python | 0 | @@ -0,0 +1,2084 @@
+# Copyright (c) 2014 Amazon.com, Inc. or its affiliates.%0A# All Rights Reserved%0A#%0A# Permission is hereby granted, free of charge, to any person obtaining a%0A# copy of this software and associated documentation files (the%0A# %22Software%22), to deal in the Software without restriction, including%0A# without limitation the rights to use, copy, modify, merge, publish, dis-%0A# tribute, sublicense, and/or sell copies of the Software, and to permit%0A# persons to whom the Software is furnished to do so, subject to the fol-%0A# lowing conditions:%0A#%0A# The above copyright notice and this permission notice shall be included%0A# in all copies or substantial portions of the Software.%0A#%0A# THE SOFTWARE IS PROVIDED %22AS IS%22, WITHOUT WARRANTY OF ANY KIND, EXPRESS%0A# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-%0A# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT%0A# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,%0A# 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%0A# IN THE SOFTWARE.%0A%0Afrom boto.beanstalk.exception import simple%0Afrom boto.compat import unittest%0A%0A%0Aclass FakeError(object):%0A def __init__(self, code, status, reason, body):%0A self.code = code%0A self.status = status%0A self.reason = reason%0A self.body = body%0A%0A%0Aclass TestExceptions(unittest.TestCase):%0A def test_exception_class_names(self):%0A # Create exception from class name%0A error = FakeError('TooManyApplications', 400, 'foo', 'bar')%0A exception = simple(error)%0A self.assertEqual(exception.__class__.__name__, 'TooManyApplications')%0A%0A # Create exception from class name + 'Exception' as seen from the%0A # live service today%0A error = FakeError('TooManyApplicationsException', 400, 'foo', 'bar')%0A exception = simple(error)%0A self.assertEqual(exception.__class__.__name__, 'TooManyApplications')%0A%0A # Make sure message body is present%0A self.assertEqual(exception.message, 'bar')%0A
|
|
de38b3e7b3d8458920b913316b06bb10b886df9f | Implement ArgumentSelector for overload disambiguation | thinglang/symbols/argument_selector.py | thinglang/symbols/argument_selector.py | Python | 0 | @@ -0,0 +1,1978 @@
+import collections%0Aimport copy%0A%0Afrom thinglang.compiler.errors import NoMatchingOverload%0Afrom thinglang.lexer.values.identifier import Identifier%0A%0ASymbolOption = collections.namedtuple('SymbolOption', %5B'symbol', 'remaining_arguments'%5D)%0A%0A%0Aclass ArgumentSelector(object):%0A %22%22%22%0A Aids in disambiguating overloaded method symbols contained in MergedSymbol objects.%0A Managed state regarding arguments already observed, and filters out overloads and all arguments are processed.%0A If a matching overload exists, it is returned - otherwise, an exception is thrown.%0A %22%22%22%0A%0A def __init__(self, symbols):%0A self.symbols = symbols%0A self.collected_arguments = %5B%5D%0A self.options = %5BSymbolOption(symbol, copy.deepcopy(symbol.arguments)) for symbol in symbols%5D%0A%0A def constraint(self, resolved):%0A %22%22%22%0A Filters out option groups that do not expect to see the resolved type as their next argument%0A %22%22%22%0A self.collected_arguments.append(resolved)%0A%0A new_options = %5B%5D%0A%0A for option in self.options:%0A if option.remaining_arguments and self.type_match(resolved, option.remaining_arguments.pop(0)):%0A new_options.append(option)%0A%0A self.options = new_options%0A%0A if not self.options:%0A raise NoMatchingOverload(self.symbols, self.collected_arguments)%0A%0A def disambiguate(self):%0A %22%22%22%0A Selects the best matching overload%0A %22%22%22%0A option_group = %5Boption for option in self.options if not option.remaining_arguments%5D%0A%0A if len(option_group) != 1:%0A raise NoMatchingOverload(self.symbols, self.collected_arguments)%0A%0A return option_group%5B0%5D.symbol%0A%0A @staticmethod%0A def type_match(resolved, expected_type):%0A %22%22%22%0A Checks if two types match (TODO: take inheritance chains into account)%0A %22%22%22%0A if expected_type == Identifier('object'):%0A return True%0A%0A return resolved.type == expected_type%0A
|
|
609bd2a0712ee488dd76bb3619aef70343adb304 | add test__doctests.py | greentest/test__doctests.py | greentest/test__doctests.py | Python | 0.000009 | @@ -0,0 +1,956 @@
+import os%0Aimport re%0Aimport doctest%0Aimport unittest%0Aimport eventlet%0A%0Abase = os.path.dirname(eventlet.__file__)%0Amodules = set()%0A%0Afor path, dirs, files in os.walk(base):%0A package = 'eventlet' + path.replace(base, '').replace('/', '.')%0A modules.add((package, os.path.join(path, '__init__.py')))%0A for f in files:%0A module = None%0A if f.endswith('.py'):%0A module = f%5B:-3%5D%0A if module:%0A modules.add((package + '.' + module, os.path.join(path, f)))%0A%0Asuite = unittest.TestSuite()%0Atests_count = 0%0Amodules_count = 0%0Afor m, path in modules:%0A if re.search('%5E%5Cs*%3E%3E%3E ', open(path).read(), re.M):%0A s = doctest.DocTestSuite(m)%0A print '%25s (from %25s): %25s tests' %25 (m, path, len(s._tests))%0A suite.addTest(s)%0A modules_count += 1%0A tests_count += len(s._tests)%0Aprint 'Total: %25s tests in %25s modules' %25 (tests_count, modules_count)%0Arunner = unittest.TextTestRunner(verbosity=2)%0Arunner.run(suite)%0A
|
|
2885adb781ba5179e0dcc7645644bcb182e7bfe7 | Create hacks/eKoomerce/__init__.py | hacks/eKoomerce/__init__.py | hacks/eKoomerce/__init__.py | Python | 0.000004 | @@ -0,0 +1,11 @@
+import bs4%0A
|
|
d9cce6f06503f1527d56d40d3037f46344c517d4 | Add PerUserData utility. | src/librement/utils/user_data.py | src/librement/utils/user_data.py | Python | 0 | @@ -0,0 +1,1803 @@
+from django.db import models%0Afrom django.db.models.signals import post_save, pre_delete%0Afrom django.contrib.auth.models import User%0A%0Adef PerUserData(related_name=None):%0A %22%22%22%0A Class factory that returns an abstract model attached to a %60%60User%60%60 object%0A that creates and destroys concrete child instances where required.%0A%0A Example usage::%0A%0A class ToppingPreferences(PerUserData('toppings')):%0A pepperoni = models.BooleanField(default=True)%0A anchovies = models.BooleanField(default=False)%0A%0A %3E%3E%3E u = User.objects.create_user('test', '[email protected]')%0A %3E%3E%3E u.toppings # ToppingPreferences created automatically%0A %3CToppingPreferences: user=test%3E%0A %3E%3E%3E u.toppings.anchovies%0A False%0A %22%22%22%0A%0A class UserDataBase(models.base.ModelBase):%0A def __new__(cls, name, bases, attrs):%0A model = super(UserDataBase, cls).__new__(cls, name, bases, attrs)%0A%0A if model._meta.abstract:%0A return model%0A%0A def on_create(sender, instance, created, *args, **kwargs):%0A if created:%0A model.objects.create(user=instance)%0A%0A def on_delete(sender, instance, *args, **kwargs):%0A model.objects.filter(pk=instance).delete()%0A%0A post_save.connect(on_create, sender=User, weak=False)%0A pre_delete.connect(on_delete, sender=User, weak=False)%0A%0A return model%0A%0A class UserData(models.Model):%0A user = models.OneToOneField(%0A 'auth.User',%0A primary_key=True,%0A related_name=related_name,%0A )%0A%0A __metaclass__ = UserDataBase%0A%0A class Meta:%0A abstract = True%0A%0A def __unicode__(self):%0A return 'user=%25s' %25 self.user.username%0A%0A return UserData%0A
|
|
e58d30a64ae2ce2962dbaaf119e5e4c4ee33e4e7 | Create pub.py | cloud/mqtt_server/pub.py | cloud/mqtt_server/pub.py | Python | 0.000001 | @@ -0,0 +1,726 @@
+#!/usr/bin/env python%0Aimport asyncio%0A%0Afrom hbmqtt.client import MQTTClient%0Afrom hbmqtt.mqtt.constants import QOS_0, QOS_1, QOS_2%0A%0Aasync def publish_test():%0A try:%0A C = MQTTClient()%0A ret = await C.connect('mqtt://192.168.0.4:1883/')%0A message = await C.publish('server', 'MESSAGE-QOS_0'.encode(), qos=QOS_0)%0A message = await C.publish('server', 'MESSAGE-QOS_1'.encode(), qos=QOS_1)%0A message = await C.publish('gateway', 'MESSAGE-QOS_2'.encode(), qos=QOS_2)%0A print(%22messages published%22)%0A await C.disconnect()%0A except ConnectException as ce:%0A print(%22Connection failed: %25s%22 %25 ce)%0A asyncio.get_event_loop().stop()%0A%0Aif __name__ == '__main__':%0A asyncio.get_event_loop().run_until_complete(publish_test())%0A
|
|
8551c56a9fea5d21ea9dc6761eff8e93d451f6b3 | Add pip setup.py | setup.py | setup.py | Python | 0.000002 | @@ -0,0 +1,1749 @@
+%22%22%22Setup script for gin-config.%0A%0ASee:%0A%0Ahttps://github.com/google/gin-config%0A%0A%22%22%22%0A%0Aimport codecs%0Afrom os import path%0Afrom setuptools import find_packages%0Afrom setuptools import setup%0A%0Ahere = path.abspath(path.dirname(__file__))%0A%0A# Get the long description from the README file%0Awith codecs.open(path.join(here, 'README.md'), encoding='utf-8') as f:%0A long_description = f.read()%0A%0A%0Asetup(%0A name='gin-config',%0A version='0.1',%0A include_package_data=True,%0A packages=find_packages(exclude=%5B'contrib', 'docs', 'tests'%5D), # Required%0A extras_require=%7B # Optional%0A 'tf': %5B'tensorflow'%5D,%0A 'test': %5B'coverage'%5D,%0A %7D,%0A description='Gin-config: a lightweight configuration library for Python',%0A long_description=long_description,%0A url='https://github.com/google/gin-config', # Optional%0A author='The Gin-Config Team', # Optional%0A classifiers=%5B # Optional%0A 'Development Status :: 3 - Alpha',%0A%0A # Indicate who your project is intended for%0A 'Intended Audience :: Developers',%0A 'Topic :: Software Development :: ML Tools',%0A%0A # Pick your license as you wish%0A 'License :: OSI Approved :: Apache License',%0A%0A # Specify the Python versions you support here. In particular, ensure%0A # that you indicate whether you support Python 2, Python 3 or both.%0A 'Programming Language :: Python :: 2.7',%0A 'Programming Language :: Python :: 3',%0A 'Programming Language :: Python :: 3.4',%0A 'Programming Language :: Python :: 3.5',%0A 'Programming Language :: Python :: 3.6',%0A %5D,%0A project_urls=%7B # Optional%0A 'Bug Reports': 'https://github.com/google/gin-config/issues',%0A 'Source': 'https://github.com/google/gin-config',%0A %7D,%0A)%0A
|
|
379c5e73d767753142a62ba57f5928acf754b508 | Add simple setup.py for ease of system-installing | setup.py | setup.py | Python | 0 | @@ -0,0 +1,224 @@
+from setuptools import setup, find_packages%0A%0Asetup(%0A name=%22crow2%22,%0A version=%220.1.dev0%22,%0A packages=find_packages(),%0A scripts=%5B%22bin/crow2%22%5D,%0A install_requires=%5B%22twisted%22, %22zope.interface%22%5D%0A)%0A
|
|
c2d14b8c3beaee3cff498fc02106751fce8e8e1c | Add setup.py | setup.py | setup.py | Python | 0.000001 | @@ -0,0 +1,1100 @@
+import sys%0Afrom setuptools import setup, find_packages%0Afrom setuptools.command.test import test as TestCommand%0A%0Aimport pb2df%0A%0A%0Aclass PyTest(TestCommand):%0A user_options = %5B('pytest-args=', 'a', %22Arguments to pass to py.test%22)%5D%0A%0A def initialize_options(self):%0A TestCommand.initialize_options(self)%0A self.pytest_args = %5B%5D%0A%0A def finalize_options(self):%0A TestCommand.finalize_options(self)%0A self.test_args = %5B%5D%0A self.test_suite = True%0A%0A def run_tests(self):%0A # import here, cause outside the eggs aren't loaded%0A import pytest%0A errno = pytest.main(self.pytest_args)%0A sys.exit(errno)%0A%0A%0Asetup(%0A name='pb2df',%0A version=pb2df.__version__,%0A author=pb2df.__author__,%0A author_email='',%0A description='Convert ProtoBuf objects to Spark DataFrame.',%0A long_description=__doc__,%0A url='https://github.com/jason2506/pb2df',%0A license=pb2df.__license__,%0A packages=find_packages(),%0A zip_safe=False,%0A platforms='any',%0A install_requires=%5B'protobuf'%5D,%0A tests_require=%5B'pytest'%5D,%0A cmdclass=%7B'test': PyTest%7D,%0A)%0A
|
|
a7bf54f417576bfc355e1851258e711dadd73ad3 | Add python trove classifiers | setup.py | setup.py | from setuptools import setup, find_packages
from taggit import VERSION
f = open('README.rst')
readme = f.read()
f.close()
setup(
name='django-taggit',
version=".".join(map(str, VERSION)),
description='django-taggit is a reusable Django application for simple tagging.',
long_description=readme,
author='Alex Gaynor',
author_email='[email protected]',
url='http://github.com/alex/django-taggit/tree/master',
packages=find_packages(),
zip_safe=False,
package_data = {
'taggit': [
'locale/*/LC_MESSAGES/*',
],
},
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
test_suite='runtests.runtests',
)
| Python | 0.000327 | @@ -867,16 +867,254 @@
ython',%0A
+ 'Programming Language :: Python',%0A 'Programming Language :: Python :: 2.6',%0A 'Programming Language :: Python :: 2.7',%0A 'Programming Language :: Python :: 3.2',%0A 'Programming Language :: Python :: 3.3',%0A
|
b751598da9cb43b537ab5990a9c15995bba298df | Allow lxml 3.6 | setup.py | setup.py | from setuptools import setup, find_packages
from codecs import open
import os
import sys
# Based on https://github.com/pypa/sampleproject/blob/master/setup.py
# and https://python-packaging-user-guide.readthedocs.org/
here = os.path.abspath(os.path.dirname(__file__))
from mitmproxy import version
with open(os.path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name="mitmproxy",
version=version.VERSION,
description="An interactive, SSL-capable, man-in-the-middle HTTP proxy for penetration testers and software developers.",
long_description=long_description,
url="http://mitmproxy.org",
author="Aldo Cortesi",
author_email="[email protected]",
license="MIT",
classifiers=[
"License :: OSI Approved :: MIT License",
"Development Status :: 5 - Production/Stable",
"Environment :: Console",
"Environment :: Console :: Curses",
"Operating System :: MacOS :: MacOS X",
"Operating System :: POSIX",
"Operating System :: Microsoft :: Windows",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
"Topic :: Security",
"Topic :: Internet",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: Proxy Servers",
"Topic :: Software Development :: Testing"
],
packages=find_packages(include=[
"mitmproxy", "mitmproxy.*",
"pathod", "pathod.*",
"netlib", "netlib.*"
]),
include_package_data=True,
entry_points={
'console_scripts': [
"mitmproxy = mitmproxy.main:mitmproxy",
"mitmdump = mitmproxy.main:mitmdump",
"mitmweb = mitmproxy.main:mitmweb",
"pathod = pathod.pathod_cmdline:go_pathod",
"pathoc = pathod.pathoc_cmdline:go_pathoc"
]
},
# https://packaging.python.org/en/latest/requirements/#install-requires
# It is not considered best practice to use install_requires to pin dependencies to specific versions.
install_requires=[
"backports.ssl_match_hostname>=3.5.0.1, <3.6",
"blinker>=1.4, <1.5",
"click>=6.2, <7.0",
"certifi>=2015.11.20.1", # no semver here - this should always be on the last release!
"configargparse>=0.10, <0.11",
"construct>=2.5.2, <2.6",
"cryptography>=1.2.2, <1.3",
"Flask>=0.10.1, <0.11",
"h2>=2.1.2, <3.0",
"hpack>=2.1.0, <3.0",
"html2text==2016.1.8",
"hyperframe>=3.2.0, <4.0",
"Pillow>=3.1, <3.2",
"passlib>=1.6.5, <1.7",
"pyasn1>=0.1.9, <0.2",
"pyOpenSSL>=0.15.1, <0.16",
"pyparsing>=2.1,<2.2",
"pyperclip>=1.5.22, <1.6",
"requests>=2.9.1, <2.10",
"six>=1.10, <1.11",
"tornado>=4.3, <4.4",
"urwid>=1.3.1, <1.4",
"watchdog>=0.8.3, <0.9",
],
extras_require={
':sys_platform == "win32"': [
"lxml==3.4.4", # there are no Windows wheels for newer versions, so we pin this.
"pydivert>=0.0.7, <0.1",
],
':sys_platform != "win32"': [
"lxml>=3.5.0, <3.6",
],
# Do not use a range operator here: https://bitbucket.org/pypa/setuptools/issues/380
# Ubuntu Trusty and other still ship with setuptools < 17.1
':python_version == "2.7"': [
"enum34>=1.0.4, <2",
"ipaddress>=1.0.15, <1.1",
],
'dev': [
"coveralls>=1.1, <1.2",
"mock>=1.3.0, <1.4",
"pytest>=2.8.7, <2.9",
"pytest-cov>=2.2.1, <2.3",
"pytest-timeout>=1.0.0, <1.1",
"pytest-xdist>=1.14, <1.15",
"sphinx>=1.3.5, <1.4",
"sphinx-autobuild>=0.5.2, <0.7",
"sphinxcontrib-documentedlist>=0.3.0, <0.4",
],
'contentviews': [
"cssutils>=1.0.1, <1.1",
"protobuf>=2.6.1, <2.7",
"pyamf>=0.8.0, <0.9",
],
'examples': [
"beautifulsoup4>=4.4.1, <4.5",
"harparser>=0.2, <0.3",
"pytz==2015.7.0",
]
}
)
| Python | 0 | @@ -3346,25 +3346,25 @@
%3E=3.5.0, %3C3.
-6
+7
%22,%0A %5D
|
2b1146a1741262a9c5acec9a56dfa3e45202f1df | set version 1.0 | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name='aleph',
version='0.2',
description="Document sifting web frontend",
long_description="",
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"Programming Language :: Python",
],
keywords='',
author='Friedrich Lindenberg',
author_email='[email protected]',
url='http://grano.cc',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'test']),
namespace_packages=[],
include_package_data=True,
zip_safe=False,
install_requires=[],
test_suite='nose.collector',
entry_points={
'aleph.ingestors': [
'skip = aleph.ingest.dummy:SkipIngestor',
'pdf = aleph.ingest.text:PDFIngestor',
'doc = aleph.ingest.document:DocumentIngestor',
'ppt = aleph.ingest.document:PresentationIngestor',
'html = aleph.ingest.html:HtmlIngestor',
'img = aleph.ingest.image:ImageIngestor',
'email = aleph.ingest.email:EmailFileIngestor',
'pst = aleph.ingest.email:OutlookIngestor',
'messy = aleph.ingest.tabular:MessyTablesIngestor',
'dbf = aleph.ingest.dbf:DBFIngestor',
'rar = aleph.ingest.packages:RARIngestor',
'zip = aleph.ingest.packages:ZipIngestor',
'tar = aleph.ingest.packages:TarIngestor',
'gz = aleph.ingest.packages:GzipIngestor',
'bz2 = aleph.ingest.packages:BZ2Ingestor'
],
'aleph.analyzers': [
'lang = aleph.analyze.language:LanguageAnalyzer',
'emails = aleph.analyze.regex:EMailAnalyzer',
'urls = aleph.analyze.regex:URLAnalyzer',
'regex = aleph.analyze.regex_entity:RegexEntityAnalyzer',
'polyglot = aleph.analyze.polyglot_entity:PolyglotEntityAnalyzer'
],
'aleph.crawlers': [
# 'stub = aleph.crawlers.stub:StubCrawler',
'opennames = aleph.crawlers.opennames:OpenNamesCrawler',
'idrequests = aleph.crawlers.idashboard:IDRequests',
'idfiles = aleph.crawlers.idashboard:IDFiles',
'blacklight = aleph.crawlers.blacklight:BlacklightCrawler',
'sourceafrica = aleph.crawlers.documentcloud:SourceAfricaCrawler'
],
'aleph.init': [
],
'console_scripts': [
'aleph = aleph.manage:main',
]
},
tests_require=[
'coverage', 'nose'
]
)
| Python | 0.000002 | @@ -80,11 +80,11 @@
on='
-0.2
+1.0
',%0A
|
733289636661f3c0034a66eaa8763058ef43796d | update setup.py | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
from codecs import open
setup(name='Open Tamil',
version='0.1-dev',
description='Tamil language text processing tools',
author='Muthiah Annamalai',
author_email='[email protected]',
url='https://github.com/arcturusannamalai/open-tamil',
packages=['tamil'],
license='GPLv3',
platforms='PC,Linux,Mac',
classifiers='Natural Language :: Tamil',
long_description=open('README.md','r','UTF-8').read(),
download_url='https://github.com/arcturusannamalai/open-tamil/archive/latest.zip',#pip
)
| Python | 0.000001 | @@ -90,17 +90,17 @@
me='Open
-
+-
Tamil',%0A
|
d8aff370378d7af39797fc03e184f2572d52bfc6 | Remove the restriction for pylons. | setup.py | setup.py | # -*- coding: utf-8 -*-
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
import os
import sys
# Taken from kennethreitz/requests/setup.py
package_directory = os.path.realpath(os.path.dirname(__file__))
def get_file_contents(file_path):
"""Get the context of the file using full path name."""
content = ""
try:
full_path = os.path.join(package_directory, file_path)
content = open(full_path, 'r').read()
except:
print >> sys.stderr, "### could not open file: %r" % file_path
return content
def get_debian_package():
"""
returns the slash, if we do a debian installation
Set the environment variable PRIVACYIDEA_DEBIAN_PACKAGE_PREFIX
"""
check_file = os.path.join(package_directory, "PRIVACYIDEA_DEBIAN_PACKAGE")
print
print check_file
print
if os.path.isfile(check_file):
return "/"
return ""
setup(
name='privacyIDEA',
version='1.2dev0',
description='privacyIDEA: identity, multifactor authentication, authorization, audit',
author='privacyidea.org',
license='AGPL v3',
author_email='[email protected]',
url='http://www.privacyidea.org',
install_requires=[
"WebOb>=1.2,<1.4",
# repoze.who is not compatible with the pylons 1.0.1 tests.
# it will run with 1.0.1 but the tests will fail!
"Pylons>=0.9.7,<=1.0",
"SQLAlchemy>=0.6",
"docutils>=0.4",
"simplejson>=2.0",
"pycrypto>=1.0",
"repoze.who<=1.1",
"pyrad>=1.1",
"netaddr",
"qrcode>=2.4",
"configobj>=4.6.0",
"httplib2",
"pyyaml",
"python-ldap",
"Pillow"
],
scripts=['tools/privacyidea-convert-token',
'tools/privacyidea-create-pwidresolver-user',
'tools/privacyidea-create-sqlidresolver-user',
'tools/privacyidea-pip-update',
'tools/privacyidea-create-enckey',
'tools/privacyidea-create-auditkeys',
'tools/privacyidea-create-certificate',
'tools/privacyidea-create-database',
'tools/privacyidea-fix-access-rights',
'tools/totp-token',
'tools/privacyidea-create-ad-users',
],
setup_requires=["PasteScript>=1.6.3"],
packages=find_packages(exclude=['ez_setup']),
include_package_data=True,
test_suite='nose.collector',
data_files=[(get_debian_package()+'etc/privacyidea/', ['config/privacyidea.ini.example',
'config/privacyideaapp.wsgi',
'config/dictionary',
'config/dummy-encKey'] ),
(get_debian_package()+'etc/apache2/sites-available/',['config/privacyidea',
] ),
(get_debian_package()+'etc/init.d/',['config/privacyidea-paster']),
# ('share/doc/privacyidea/', ["tools/README-migrate.txt"]),
('share/man/man1', ["tools/privacyidea-convert-token.1",
"tools/privacyidea-create-pwidresolver-user.1",
"tools/privacyidea-create-sqlidresolver-user.1",
"tools/totp-token.1",
"tools/privacyidea-pip-update.1",
"tools/privacyidea-create-enckey.1",
"tools/privacyidea-create-auditkeys.1",
"tools/privacyidea-create-certificate.1",
"tools/privacyidea-create-database.1",
"tools/privacyidea-fix-access-rights.1",
]),
],
classifiers=[
"Framework :: Pylons",
"License :: OSI Approved :: GNU Affero General Public License v3",
"Programming Language :: Python",
"Development Status :: 5 - Production/Stable",
"Topic :: Internet",
"Topic :: Security",
"Topic :: System :: Systems Administration :: Authentication/Directory"
],
message_extractors={'privacyidea': [
('**.py', 'python', None),
('templates/**.mako', 'mako', {'input_encoding': 'utf-8'}),
('lib/tokens/*.mako', 'mako', {'input_encoding': 'utf-8'}),
('public/**', 'ignore', None)]},
zip_safe=False,
paster_plugins=['PasteScript', 'Pylons'],
entry_points="""
[paste.app_factory]
main = privacyidea.config.middleware:make_app
[paste.app_install]
main = pylons.util:PylonsInstaller
[nose.plugins]
pylons = pylons.test:PylonsPlugin
""",
long_description=get_file_contents('DESCRIPTION')
)
| Python | 0 | @@ -1339,120 +1339,8 @@
4%22,%0A
-%09# repoze.who is not compatible with the pylons 1.0.1 tests.%0A%09# it will run with 1.0.1 but the tests will fail!%0A
@@ -1361,14 +1361,8 @@
.9.7
-,%3C=1.0
%22,%0A
|
231d050fe611adb201cd7ae55f52212d0b84caa1 | Check for pandoc. add pyandoc to setup_requires | setup.py | setup.py | from setuptools import setup, find_packages, Command
from setuptools.command.build_py import build_py as _build_py
from distutils.spawn import find_executable
import os.path
import imp
import pandoc.core
pandoc.core.PANDOC_PATH = find_executable('pandoc')
ROOT = os.path.abspath(os.path.dirname(__file__))
def read(fname):
return open(os.path.join(ROOT, fname)).read()
def read_md_as_rest(fname):
doc = pandoc.Document()
doc.markdown = read(fname)
return doc.rst
def version():
file, pathname, description = imp.find_module('sparts', [ROOT])
return imp.load_module('sparts', file, pathname, description).__version__
class gen_thrift(Command):
user_options=[]
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
self.mkpath(os.path.join(ROOT, 'sparts', 'gen'))
for f in os.listdir(os.path.join(ROOT, 'thrift')):
self.spawn(['thrift', '-out', os.path.join(ROOT, 'sparts', 'gen'),
'-v', '--gen', 'py:new_style',
os.path.join(ROOT, 'thrift', f)])
class build_py(_build_py):
def run(self):
self.run_command('gen_thrift')
_build_py.run(self)
setup(
name="sparts",
version=version(),
packages=find_packages(),
description="Build services in python with as little code as possible",
long_description=read_md_as_rest("README.md"),
install_requires=[],
author='Peter Ruibal',
author_email='[email protected]',
license='ISC',
keywords='service boostrap daemon thrift tornado',
url='http://github.com/fmoo/sparts',
test_suite="tests",
cmdclass={'gen_thrift': gen_thrift,
'build_py': build_py},
)
| Python | 0 | @@ -251,16 +251,205 @@
andoc')%0A
+assert pandoc.core.PANDOC_PATH is not None, %5C%0A %22'pandoc' is a required system binary to generate documentation.%5Cn%22 %5C%0A %22Please install it somewhere in your PATH to run this command.%22%0A%0A
ROOT = o
@@ -1641,16 +1641,48 @@
res=%5B%5D,%0A
+ setup_requires=%5B'pyandoc'%5D,%0A
auth
|
e458733b0aa1cbb142fc6818ae1f7cf84bef6518 | Add setup | setup.py | setup.py | Python | 0.000001 | @@ -0,0 +1,1265 @@
+import setuptools%0A%0Aif __name__ == %22__main__%22:%0A setuptools.setup(%0A name='friendly_computing_machine',%0A version=%220.1.1%22,%0A description='A starting template for Python programs',%0A author='CHENXI CAI',%0A author_email='[email protected]',%0A url=%22https://github.com/xiaohaiguicc/friendly-computing-machine%22,%0A license='BSD-3C',%0A packages=setuptools.find_packages(),%0A install_requires=%5B%0A 'numpy%3E=1.7',%0A %5D,%0A extras_require=%7B%0A 'docs': %5B%0A 'sphinx==1.2.3', # autodoc was broken in 1.3.1%0A 'sphinxcontrib-napoleon',%0A 'sphinx_rtd_theme',%0A 'numpydoc',%0A %5D,%0A 'tests': %5B%0A 'pytest',%0A 'pytest-cov',%0A 'pytest-pep8',%0A 'tox',%0A %5D,%0A %7D,%0A%0A tests_require=%5B%0A 'pytest',%0A 'pytest-cov',%0A 'pytest-pep8',%0A 'tox',%0A %5D,%0A%0A classifiers=%5B%0A 'Development Status :: 4 - Beta',%0A 'Intended Audience :: Science/Research',%0A 'Programming Language :: Python :: 2.7',%0A 'Programming Language :: Python :: 3',%0A %5D,%0A zip_safe=True,%0A )%0A
|
|
bc17ea522b0120ec7308ba0309d87b18ba9163d9 | Add setup.py | setup.py | setup.py | Python | 0.000001 | @@ -0,0 +1,731 @@
+import sys%0Afrom setuptools import setup%0A%0Asetup(%0A name='pingdombackup',%0A version=%220.1.0%22,%0A description='Backup Pingdom logs',%0A long_description='Backup Pingdom result logs to a SQLite database.',%0A author='Joel Verhagen',%0A author_email='[email protected]',%0A install_requires=%5B'requests%3E=2.1.0'%5D,%0A url='https://github.com/joelverhagen/PingdomBackup',%0A packages=%5B'pingdombackup'%5D,%0A license='MIT',%0A classifiers=%5B%0A 'Development Status :: 3 - Alpha',%0A 'Intended Audience :: Developers',%0A 'Intended Audience :: System Administrators',%0A 'License :: OSI Approved :: MIT License',%0A 'Operating System :: OS Independent',%0A 'Topic :: System :: Monitoring'%0A %5D%0A)%0A
|
|
1dd8a34cba565f70a30a6c8ab4604a489377e752 | Add template remove script | src/utils/remove_templates.py | src/utils/remove_templates.py | Python | 0 | @@ -0,0 +1,1353 @@
+def remove_templates(text):%0A %22%22%22Remove all text contained between '%7B%7B' and '%7D%7D', even in the case of%0A nested templates.%0A%0A Args:%0A text (str): Full text of a Wikipedia article as a single string.%0A%0A Returns:%0A str: The full text with all templates removed.%0A%0A %22%22%22%0A start_char = 0%0A while '%7B%7B' in text:%0A depth = 0%0A prev_char = None%0A open_pos = None%0A close_pos = None%0A%0A for pos in xrange(start_char, len(text)):%0A char = text%5Bpos%5D%0A # Open Marker%0A if char == '%7B' and prev_char == '%7B':%0A if depth == 0:%0A open_pos = pos-1%0A # When we scan the string again after removing the chunk%0A # that starts here, we know all text before is template%0A # free, so we mark this position for the next while%0A # iteration%0A start_char = open_pos%0A depth += 1%0A # Close Marker%0A elif char == '%7D' and prev_char == '%7D':%0A depth -= 1%0A if depth == 0:%0A close_pos = pos%0A # Remove all text between the open and close markers%0A text = text%5B:open_pos%5D + text%5Bclose_pos+1:%5D%0A break%0A prev_char = char%0A%0A return text%0A
|
|
ad714cbf92d2984c9cc855e99e31bf622c38a220 | add setup file | setup.py | setup.py | Python | 0.000001 | @@ -0,0 +1,165 @@
+#!/usr/bin/env python%0Afrom distutils.core import setup%0A%0Asetup(%0A name = 's7n-menu',%0A version = %221a1%22,%0A packages = %5B's7n', 's7n.menu'%5D,%0A )%0A
|
|
e9832b7b3bb028170562cacde3dbb52f13adba85 | Set version number | setup.py | setup.py | #!/usr/bin/env python
#
# Copyright (C) 2007 SIOS Technology, Inc.
# Copyright (C) 2011 Umea Universitet, Sweden
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
#import here, cause outside the eggs aren't loaded
import pytest
errno = pytest.main(self.test_args)
sys.exit(errno)
install_requires = [
# core dependencies
'decorator',
'requests >= 1.0.0',
'paste',
'zope.interface',
'repoze.who',
'pycrypto', #'Crypto'
]
tests_require = [
'mongodict',
'pyasn1',
'pymongo',
'python-memcached == 1.51',
'pytest',
'mako',
#'pytest-coverage',
]
# only for Python 2.6
if sys.version_info < (2, 7):
install_requires.append('importlib')
setup(
name='pysaml2',
version='1.1.0',
description='Python implementation of SAML Version 2 to be used in a WSGI environment',
# long_description = read("README"),
author='Roland Hedberg',
author_email='[email protected]',
license='Apache 2.0',
url='https://github.com/rohe/pysaml2',
packages=['saml2', 'xmldsig', 'xmlenc', 's2repoze', 's2repoze.plugins',
"saml2/profile", "saml2/schema", "saml2/extension",
"saml2/attributemaps", "saml2/authn_context",
"saml2/entity_category", "saml2/userinfo"],
package_dir={'': 'src'},
package_data={'': ['xml/*.xml']},
classifiers=["Development Status :: 4 - Beta",
"License :: OSI Approved :: Apache Software License",
"Topic :: Software Development :: Libraries :: Python Modules"],
scripts=["tools/parse_xsd2.py", "tools/make_metadata.py",
"tools/mdexport.py"],
tests_require=tests_require,
extras_require={
'testing': tests_require,
},
install_requires=install_requires,
zip_safe=False,
test_suite='tests',
cmdclass={'test': PyTest},
)
| Python | 0.000032 | @@ -1550,19 +1550,23 @@
sion='1.
-1
+2
.0
+beta
',%0A d
|
73d9b80d6fa1cf75dba73e396d1f5d3bd4963df6 | Create setup.py | setup.py | setup.py | Python | 0.000001 | @@ -0,0 +1,541 @@
+from distutils.core import setup%0Asetup(%0A name = 'wthen',%0A packages = %5B'wthen'%5D, # this must be the same as the name above%0A version = '0.1',%0A description = 'A simple rule engine with YAML format',%0A author = 'Alex Yu',%0A author_email = '[email protected]',%0A url = 'https://github.com/sevenbigcat/wthen', # use the URL to the github repo%0A download_url = 'https://github.com/sevenbigcat/wtehn/archive/0.1.tar.gz', # I'll explain this in a second%0A keywords = %5B'rule engine', 'ECA', 'YAML'%5D, # arbitrary keywords%0A classifiers = %5B%5D,%0A)%0A
|
|
62e126908e08544f8595be368d300b0abaca82d3 | support old setuptools versions | setup.py | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
# Get the version
version_regex = r'__version__ = ["\']([^"\']*)["\']'
with open('h2/__init__.py', 'r') as f:
text = f.read()
match = re.search(version_regex, text)
if match:
version = match.group(1)
else:
raise RuntimeError("No version number found!")
# Stealing this from Kenneth Reitz
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
packages = [
'h2',
]
setup(
name='h2',
version=version,
description='HTTP/2 State-Machine based protocol implementation',
long_description=open('README.rst').read() + '\n\n' + open('HISTORY.rst').read(),
author='Cory Benfield',
author_email='[email protected]',
url='http://hyper.rtfd.org',
packages=packages,
package_data={'': ['LICENSE', 'README.rst', 'CONTRIBUTORS.rst', 'HISTORY.rst', 'NOTICES']},
package_dir={'h2': 'h2'},
include_package_data=True,
license='MIT License',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
],
install_requires=[
'hyperframe~=3.1',
'hpack~=2.0',
],
extras_require={
':python_version<"3.4"': ['enum34~=1.0.4'],
}
)
| Python | 0 | @@ -1802,13 +1802,17 @@
rame
-~
+%3E
=3.1
+, %3C4
',%0A
@@ -1828,13 +1828,17 @@
pack
-~
+%3E
=2.0
+, %3C3
',%0A
@@ -1892,13 +1892,43 @@
sion
-%3C%223.4
+ == %222.7%22 or python_version == %223.3
%22':
@@ -1939,15 +1939,21 @@
um34
-~
+%3E
=1.0.4
+, %3C1.1
'%5D,%0A
|
4d16ae6d1ad8b308c14c23e802349001b81ae461 | Add Python-based opcode enum parser | thinglang/compiler/opcodes.py | thinglang/compiler/opcodes.py | Python | 0.001332 | @@ -0,0 +1,683 @@
+import os%0A%0Aimport re%0A%0ABASE_DIR = os.path.dirname(os.path.abspath(__file__))%0AENUM_PARSER = re.compile(r'(.*)%5Cs*?=%5Cs*?(%5Cd+)')%0A%0Adef read_opcodes():%0A with open(os.path.join(BASE_DIR, '..', '..', 'thingc', 'execution', 'Opcode.h')) as f:%0A for line in f:%0A if 'enum class Opcode' in line:%0A break%0A%0A for decl in f:%0A decl = decl.strip()%0A%0A if not decl:%0A continue%0A%0A if '%7D' in decl:%0A break%0A%0A groups = ENUM_PARSER.search(decl).groups()%0A yield (groups%5B0%5D.strip(), int(groups%5B1%5D))%0A%0AOPCODES = dict(read_opcodes())%0A%0Aassert set(range(len(OPCODES))) == set(OPCODES.values())%0A
|
|
ac823e61fd214f9818bb7a893a8ed52a3bfa3af4 | Add utils for graph visualization. | neurokernel/conn_utils.py | neurokernel/conn_utils.py | Python | 0 | @@ -0,0 +1,1974 @@
+#!/usr/bin/env python%0A%0Aimport itertools%0Aimport os%0Aimport tempfile%0A%0Aimport conn%0Aimport matplotlib.pyplot as plt%0Aimport networkx as nx%0A%0Adef imdisp(f):%0A %22%22%22%0A Display the specified image file using matplotlib.%0A %22%22%22%0A %0A im = plt.imread(f)%0A plt.imshow(im)%0A plt.axis('off')%0A plt.draw()%0A return im%0A%0Adef show_pydot(g):%0A %22%22%22%0A Display a networkx graph using pydot.%0A %22%22%22%0A %0A fd = tempfile.NamedTemporaryFile()%0A fd.close()%0A p = nx.to_pydot(g)%0A p.write_jpg(fd.name)%0A imdisp(fd.name)%0A os.remove(fd.name)%0A%0Adef show_pygraphviz(g, prog='dot', graph_attr=%7B%7D, node_attr=%7B%7D, edge_attr=%7B%7D):%0A %22%22%22%0A Display a networkx graph using pygraphviz.%0A %22%22%22%0A %0A fd = tempfile.NamedTemporaryFile(suffix='.jpg')%0A fd.close()%0A p = nx.to_agraph(g)%0A p.graph_attr.update(graph_attr)%0A p.node_attr.update(node_attr)%0A p.edge_attr.update(edge_attr)%0A p.draw(fd.name, prog=prog)%0A imdisp(fd.name)%0A os.remove(fd.name)%0A%0Adef conn_to_bipartite(c):%0A %22%22%22%0A Convert a Connectivity object into a bipartite NetworkX multigraph.%0A %22%22%22%0A%0A g = nx.MultiDiGraph()%0A src_nodes = %5B'src_%25i' %25 i for i in xrange(c.N_src)%5D%0A dest_nodes = %5B'dest_%25i' %25 i for i in xrange(c.N_dest)%5D%0A g.add_nodes_from(src_nodes)%0A g.add_nodes_from(dest_nodes)%0A%0A for key in c._data.keys():%0A syn, dir, name = key.split('/')%0A syn = int(syn)%0A if name == 'conn':%0A if dir == '+':%0A for src, dest in itertools.product(xrange(c.N_src), xrange(c.N_dest)):%0A if c%5Bsrc, dest, syn, dir, name%5D == 1:%0A g.add_edge('src_%25i' %25 src, 'dest_%25i' %25 dest)%0A elif dir == '-':%0A for src, dest in itertools.product(xrange(c.N_src), xrange(c.N_dest)):%0A if c%5Bsrc, dest, syn, dir, name%5D == 1:%0A g.add_edge('dest_%25i' %25 dest, 'src_%25i' %25 src)%0A else:%0A raise ValueError('invalid direction')%0A return g%0A
|
|
e663394d1dc4de7b8e3a877f0c9870a804e804f2 | Make tests runnable from lifelines.tests | lifelines/tests/__main__.py | lifelines/tests/__main__.py | Python | 0.00001 | @@ -0,0 +1,107 @@
+import unittest%0Afrom . import test_suite%0A%0A%0Aif __name__ == '__main__':%0A unittest.main(module=test_suite)%0A
|
|
525a8438bd601592c4f878ca5d42d3dab8943be0 | Test that specific Failures are caught before parent Failures | ooni/tests/test_errors.py | ooni/tests/test_errors.py | Python | 0.000001 | @@ -0,0 +1,719 @@
+from twisted.trial import unittest%0A%0Aimport ooni.errors%0A%0Aclass TestErrors(unittest.TestCase):%0A%0A def test_catch_child_failures_before_parent_failures(self):%0A %22%22%22%0A Verify that more specific Failures are caught first by%0A handleAllFailures() and failureToString().%0A%0A Fails if a subclass is listed after it's parent Failure.%0A %22%22%22%0A%0A # Check each Failure against all subsequent failures%0A for index, (failure, _) in enumerate(ooni.errors.known_failures):%0A for sub_failure, _ in ooni.errors.known_failures%5Bindex+1:%5D:%0A%0A # Fail if subsequent Failure inherits from the current Failure%0A self.assertNotIsInstance(sub_failure(None), failure)%0A
|
|
90d079928eaf48e370d21417e4d6e649ec0f5f6f | Update tasks and evaluate viewports on saving | taskwiki/taskwiki.py | taskwiki/taskwiki.py | import sys
import re
import vim
from tasklib.task import TaskWarrior, Task
# Insert the taskwiki on the python path
sys.path.insert(0, vim.eval("s:plugin_path") + '/taskwiki')
from regexp import *
from task import VimwikiTask
from cache import TaskCache
"""
How this plugin works:
1.) On startup, it reads all the tasks and syncs info TW -> Vimwiki file. Task is identified by their
uuid.
2.) When saving, the opposite sync is performed (Vimwiki -> TW direction).
a) if task is marked as subtask by indentation, the dependency is created between
"""
tw = TaskWarrior()
cache = TaskCache(tw)
def update_from_tw():
"""
Updates all the incomplete tasks in the vimwiki file if the info from TW is different.
"""
cache.load_buffer()
cache.update_tasks()
cache.update_buffer()
cache.evaluate_viewports()
def update_to_tw():
"""
Updates all tasks that differ from their TaskWarrior representation.
"""
cache.reset()
cache.load_buffer()
cache.save_tasks()
cache.update_buffer()
if __name__ == '__main__':
update_from_tw()
| Python | 0 | @@ -999,32 +999,57 @@
e.load_buffer()%0A
+ cache.update_tasks()%0A
cache.save_t
@@ -1081,16 +1081,47 @@
uffer()%0A
+ cache.evaluate_viewports()%0A
%0A%0Aif __n
|
f2e9f2adbc81a37847bbe27401dd852317243486 | add a test for the session tables | test/sessionstest.py | test/sessionstest.py | Python | 0 | @@ -0,0 +1,1197 @@
+#!/usr/bin/python2.4%0A#%0A# Copyright (c) 2004-2005 rpath, Inc.%0A#%0A%0Aimport time%0Aimport testsuite%0Atestsuite.setup()%0A%0Aimport sqlite3%0Aimport rephelp %0Afrom mint_rephelp import MintRepositoryHelper%0A%0Afrom mint import dbversion%0Afrom mint import sessiondb%0A%0Aclass SessionTest(MintRepositoryHelper):%0A def testSessions(self):%0A st = sessiondb.SessionsTable(self.db)%0A%0A # create a session%0A st.save(%22abcdefg123456%22, %7B'_data': 'data',%0A '_accessed': time.time() - 20,%0A '_timeout': 10%7D%0A )%0A%0A # load and check data%0A d = st.load(%22abcdefg123456%22)%0A assert(d%5B'_data'%5D == 'data')%0A%0A # clean up expired sessions%0A st.cleanup()%0A%0A # confirm that expired session went away%0A d = st.load(%22abcdefg123456%22)%0A assert(not d)%0A %0A def setUp(self):%0A rephelp.RepositoryHelper.setUp(self)%0A try:%0A os.unlink(self.reposDir + %22/db%22)%0A except:%0A pass%0A self.db = sqlite3.connect(self.reposDir + %22/db%22)%0A self.versionTable = dbversion.VersionTable(self.db)%0A self.db.commit()%0A%0Aif __name__ == %22__main__%22:%0A testsuite.main()%0A
|
|
eb71a3d3319480b3f99cb44f934a51bfb1b5bd67 | Add abstract class for HAP channels | pyatv/auth/hap_channel.py | pyatv/auth/hap_channel.py | Python | 0 | @@ -0,0 +1,2522 @@
+%22%22%22Base class for HAP based channels (connections).%22%22%22%0Afrom abc import ABC, abstractmethod%0Aimport asyncio%0Aimport logging%0Afrom typing import Callable, Tuple, cast%0A%0Afrom pyatv.auth.hap_pairing import PairVerifyProcedure%0Afrom pyatv.auth.hap_session import HAPSession%0Afrom pyatv.support import log_binary%0A%0A_LOGGER = logging.getLogger(__name__)%0A%0A%0Aclass AbstractHAPChannel(ABC, asyncio.Protocol):%0A %22%22%22Abstract base class for connections using HAP encryption and segmenting.%22%22%22%0A%0A def __init__(self, output_key: bytes, input_key: bytes) -%3E None:%0A %22%22%22Initialize a new AbstractHAPChannel instance.%22%22%22%0A self.buffer = b%22%22%0A self.transport = None%0A self.session: HAPSession = HAPSession()%0A self.session.enable(output_key, input_key)%0A%0A def connection_made(self, transport) -%3E None:%0A %22%22%22Device connection was made.%22%22%22%0A sock = transport.get_extra_info(%22socket%22)%0A dstaddr, dstport = sock.getpeername()%0A _LOGGER.debug(%22Connected to %25s:%25d%22, dstaddr, dstport)%0A%0A self.transport = transport%0A%0A def data_received(self, data: bytes) -%3E None:%0A %22%22%22Message was received from device.%22%22%22%0A assert self.transport is not None%0A%0A decrypt = self.session.decrypt(data)%0A log_binary(_LOGGER, %22Received data%22, Data=data)%0A self.buffer += decrypt%0A self.handle_received()%0A%0A @abstractmethod%0A def handle_received(self) -%3E None:%0A %22%22%22Handle received data that was put in buffer.%22%22%22%0A%0A def send(self, data: bytes) -%3E None:%0A %22%22%22Send message to device.%22%22%22%0A assert self.transport is not None%0A%0A encrypted = self.session.encrypt(data)%0A log_binary(_LOGGER, %22Sending data%22, Encrypted=encrypted)%0A self.transport.write(encrypted)%0A%0A def connection_lost(self, exc) -%3E None:%0A %22%22%22Device connection was dropped.%22%22%22%0A _LOGGER.debug(%22Connection was lost to remote%22)%0A%0A%0Aasync def setup_channel(%0A factory: Callable%5B%5Bbytes, bytes%5D, AbstractHAPChannel%5D,%0A verifier: PairVerifyProcedure,%0A address: str,%0A port: int,%0A salt: str,%0A output_info: str,%0A input_info: str,%0A) -%3E Tuple%5Basyncio.BaseTransport, AbstractHAPChannel%5D:%0A %22%22%22Set up a new HAP channel and enable encryption.%22%22%22%0A out_key, in_key = verifier.encryption_keys(salt, output_info, input_info)%0A%0A loop = asyncio.get_event_loop()%0A transport, protocol = await loop.create_connection(%0A lambda: factory(out_key, in_key),%0A address,%0A port,%0A )%0A return transport, cast(AbstractHAPChannel, protocol)%0A
|
|
0089de0eccae27bf4cd5a2f9166e8418d64171c3 | Create XOR.py | XOR.py | XOR.py | Python | 0.000027 | @@ -0,0 +1,334 @@
+'''%0AImplement XOR operation%0A'''%0A%0Adef XOR(a,b):%0A result = 0%0A power = 1%0A while a%3E0 or b%3E0:%0A m = a%252%0A n = b%252%0A if m+n==1:%0A result = result+power%0A %0A power *=2%0A a = a/2%0A b = b/2%0A %0A return result%0A %0Aif __name__=='__main__':%0A a = 123%0A b = 230%0A print XOR(a,b)%0A
|
|
bd01797f18012927202b87872dc33caf685306c0 | Add GDB plugin for printing ABC values | gdb.py | gdb.py | Python | 0 | @@ -0,0 +1,2385 @@
+deadbeef = 0xdeadbeefdeadbeef%0A%0Aabc_any = gdb.lookup_type(%22union any%22)%0A%0Adef color(s, c):%0A return %22%5Cx1b%5B%22 + str(c) + %22m%22 + s + %22%5Cx1b%5B0m%22%0A%0Adef gray(s):%0A return color(s, 90)%0A%0Adef red(s):%0A return color(s, %221;31%22)%0A%0Adef p(indent, tag, value):%0A print(%22 %22 * indent + tag + %22: %22 + str(value))%0A%0Adef print_abc(i, v):%0A v = v.cast(abc_any)%0A vt = v%5B'as_tagged'%5D%0A if vt == 0xdeadf00ddeadf00d:%0A p(i, %22Unit%22, %22Unit%22)%0A elif vt == deadbeef:%0A p(i, %22Dead%22, %22Beef%22)%0A elif vt == 0:%0A p(i, red(%22!!!NULL POINTER!!!%22), %22This should never happen%22)%0A elif (vt & 0xfff0000000000000) != 0:%0A p(i, %22Number%22, (~vt).cast(abc_any)%5B'as_num'%5D)%0A elif vt %3C 0x00007f0000000000: # FIXME should get actual mappings -- don't know how to.%0A block = gdb.block_for_pc(int(vt))%0A if block == None:%0A name = str(v%5B'as_indirect'%5D)%0A else:%0A name = str(block.function)%0A p(i, %22Block%22, name)%0A else:%0A tag = vt & 0x3%0A ptr = vt & ~0x3%0A hexptr = gray(hex(int(ptr)))%0A v = ptr.cast(abc_any)%0A try:%0A if tag == 0:%0A pair = v%5B'as_pair'%5D.dereference()%0A if pair%5B'snd'%5D%5B'as_tagged'%5D == deadbeef:%0A p(i, %22Left%22, hexptr)%0A print_abc(i+4, pair%5B'fst'%5D)%0A else:%0A p(i, %22Pair%22, hexptr)%0A print_abc(i+4, pair%5B'fst'%5D)%0A print_abc(i+4, pair%5B'snd'%5D)%0A elif tag == 1:%0A pair = v%5B'as_comp_block'%5D.dereference()%0A if pair%5B'yz'%5D%5B'as_tagged'%5D == deadbeef:%0A p(i, %22Right%22, hexptr)%0A print_abc(i+4, pair%5B'xy'%5D)%0A else:%0A p(i, %22Composed%22, hexptr)%0A print_abc(i+4, pair%5B'xy'%5D)%0A print_abc(i+4, pair%5B'yz'%5D)%0A elif tag == 2:%0A p(i, %22Quoted%22, hexptr)%0A print_abc(i+4, v%5B'as_indirect'%5D.dereference())%0A else:%0A p(i, %22INVALID TAG%22, hexptr)%0A except gdb.MemoryError:%0A p(i, red(%22!!!INVALID POINTER!!!%22), hexptr)%0A%0Aclass PrintABCValue(gdb.Command):%0A def __init__(self):%0A super(PrintABCValue, self).__init__('print-abc-value', gdb.COMMAND_DATA, gdb.COMPLETE_SYMBOL)%0A%0A def invoke(self, arg, tty):%0A print_abc(0, gdb.parse_and_eval(arg))%0A%0APrintABCValue()%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.