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
thgcode/soundrts
soundrts/res.py
Python
bsd-3-clause
4,481
0.001562
"""SoundRTS resource manager""" import os from lib.resource import ResourceLoader import config import options from paths import MAPS_PATHS def get_all_packages_paths(): """return the default "maps and mods" paths followed by the paths of the active packages""" return MAPS_PATHS # + package_manager.get_pack...
s.path.join("multi", n) w.append(Map(p, digest, official=True)) def _add_custom_multi(w): from mapfile import Map for mp in get_all_packages_pa
ths(): d = os.path.join(mp, "multi") if os.path.isdir(d): for n in os.listdir(d): p = os.path.join(d, n) if os.path.normpath(p) not in (os.path.normpath(x.path) for x in w): w.append(Map(p, None)) def _move_recommended_maps(w): from d...
golismero/golismero
tools/sqlmap/waf/knownsec.py
Python
gpl-2.0
511
0.003914
#!/usr/bin/env python """ Copyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission
""" import re from lib.core.settings import WAF_ATTACK_VECTORS __product__ = "KS-WAF (Knownsec)" def detect(get_page): retval = False for vector in WAF_ATTACK_VECTORS: page, headers, code = get_page(get=vector) retval = re.search(r"url\('/ks-waf-error\.png'\)", page, re.I) is not None ...
break return retval
carefree0910/MachineLearning
f_NN/Optimizers.py
Python
mit
3,492
0.002864
import os import sys root_path = os.path.abspath("../") if root_path not in sys.path: sys.path.append(root_path) import numpy as np from Util.Metas import TimingMeta class Optimizer: def __init__(self, lr=0.01, cache=None): self.lr = lr self._cache = cache def __str__(se...
a): def __init__(self, lr=0.01, cache=None, decay_rate=0.9, eps=1e-8): Optimizer.__init__(self, lr, cache) self.decay_rate, self.eps = decay_rate, eps def run(self, i, dw): self._cache[i] = s
elf._cache[i] * self.decay_rate + (1 - self.decay_rate) * dw ** 2 return self.lr * dw / (np.sqrt(self._cache[i] + self.eps)) class Adam(Optimizer, metaclass=TimingMeta): def __init__(self, lr=0.01, cache=None, beta1=0.9, beta2=0.999, eps=1e-8): Optimizer.__init__(self, lr, cache) se...
frappe/erpnext
erpnext/regional/doctype/e_invoice_request_log/test_e_invoice_request_log.py
Python
gpl-3.0
241
0.004149
#
-*- coding: utf-8 -*- # Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt from __future__ import unicode_literals # import frappe import unittest class TestEInvoiceRequestLog(unittest.TestCase): pass
GoogleCloudPlatform/cloud-data-quality
clouddq/log.py
Python
apache-2.0
3,052
0
# Copyright 2021 Google 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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
oggingHandler( client=client, name="clouddq", labels={ "name": APP_NAME,
"releaseId": APP_VERSION, }, ) handler.setFormatter(JSONFormatter()) logger.addHandler(handler) def get_json_logger(): json_logger = logging.getLogger("clouddq-json-logger") if not len(json_logger.handlers): json_logger.setLevel(LOG_LEVEL) logging_stream_handler = logging...
cxxgtxy/tensorflow
tensorflow/python/ops/linalg/linear_operator_kronecker.py
Python
apache-2.0
23,700
0.005148
# Copyright 2018 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...
` #### Performance The performance of `LinearOperatorKronecker` on any operation is equal to the sum of the individual operators' operations. #### Matrix property hints This `LinearOperator` is initialized with boolean flags of the form `is_X`, for `X = non_singular, self_adjoint, positive_definite, squ...
. These have the following meaning: * If `is_X == True`, callers should expect the operator to have the property `X`. This is a promise that should be fulfilled, but is *not* a runtime assert. For example, finite floating point precision may result in these promises being violated. * If `is_X == Fa...
Alecardv/College-projects
2048/Control.py
Python
gpl-3.0
1,336
0.026946
# -*- coding: utf-8 -*- """ Created on Tue Dec 08 13:25:40 2015 @author: J. Alejandro Cardona """ from Board import * import pygame UP, LEFT, DOWN, RIGHT = 1, 2, 3, 4 juego = Board() _2 = pygame.image.load("2.jpg"); _2re = _2.get_rect() _4 = pygame.image.load("4.jpg"); _4re = _4.get_rect() _8 = pygam...
pg"); _512re = _512.get_rect() _1024 = pygame.image.load("1024.jpg")
; _1024re = _1024.get_rect() _2048 = pygame.image.load("2048.jpg"); _2048re = _2048.get_rect() figs = {2:(_2, _2re), 4:(_4,_4re), 8:(_8,_8re), 16:(_16,_16re), 32:(_32,_32re), 64:(_64,_64re), 128:(_128,_128re), 256:(_256,_256re), 512:(_512,_512re), 1024:(_1024,_1024re), 2048:(_2048,_2048re)} def read_key(...
RussianPenguin/dailyprogrammer
easy/140.py
Python
gpl-2.0
1,049
0.042898
import re def readConversion(): string = '' conversion = [] try: # obtain conversion pattern raw = raw_input() while not raw: raw = raw_input() conversion = map(int, raw.split()) # obtain string string = raw_input() while not string: string = raw_input() finally: return conversion, string ...
rm].findall(string) outputData = outputCompiler[outForm](inputData) return outputData if __name__ == '__main_
_': while True: conversion, string = readConversion() if len(conversion) >= 1: print (conversion[::-1])[0] print converter(string, *(conversion[::-1])) else: break
pollen/pyrobus
pyluos/modules/servo.py
Python
mit
1,559
0
from __future__ import division from .module import Module, interact class Servo(Module): def __init__(self, id, alias, device): Module.__init__(self, 'Servo', id, alias, device) self._max_angle = 180.0 self._min_pulse = 0.0005 self._max_pulse = 0.0015 self._angle = 0.0 ...
self._push_value('parameters', param) @property def min_pulse(self): return self._min_pulse @min_pulse.setter def min_pulse(self, new): self._min_pulse = new param = [self._max_angle, self._min_pulse, self._max_pulse] self._push_value('parameters', param) @propert...
aram = [self._max_angle, self._min_pulse, self._max_pulse] self._push_value('parameters', param) def _update(self, new_state): Module._update(self, new_state) def control(self): def move(position): self.position = position return interact(move, position=(0, 180, 1)...
reeshupatel/demo
keystone/tests/test_revoke.py
Python
apache-2.0
17,990
0.000056
# 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 t...
rmissions and limitations # under the License.
import datetime import uuid import mock from keystone.common import dependency from keystone import config from keystone.contrib.revoke import model from keystone import exception from keystone.openstack.common import timeutils from keystone import tests from keystone.tests import test_backend_sql CONF = config.CO...
nkgilley/home-assistant
homeassistant/components/toon/const.py
Python
apache-2.0
11,757
0
"""Constants for the Toon integration.""" from datetime import timedelta from homeassistant.components.binary_sensor import ( DEVICE_CLASS_CONNECTIVITY, DEVICE_CLASS_PROBLEM, ) from homeassistant.components.sensor import DEVICE_CLASS_POWER from homeassistant.const import ( ATTR_DEVICE_CLASS, ATTR_ICON,...
O_WATT_HOUR, ATTR_DEVICE_CLASS: None, ATTR_ICON: "mdi:power-plug", ATTR_DEFAULT_ENABLED: False, }, "power_value": { ATTR_NAME: "Current Powe
r Usage", ATTR_SECTION: "power_usage", ATTR_MEASUREMENT: "current", ATTR_UNIT_OF_MEASUREMENT: POWER_WATT, ATTR_DEVICE_CLASS: DEVICE_CLASS_POWER, ATTR_ICON: "mdi:power-plug", ATTR_DEFAULT_ENABLED: True, }, "solar_meter_reading_produced": { ATTR_NAME: "Elect...
archesproject/arches
tests/models/mapped_csv_import_tests.py
Python
agpl-3.0
6,782
0.003096
""" ARCHES - a program developed to inventory and manage immovable cultural heritage. Copyright (C) 2013 J. Paul Getty Trust and World Monuments Fund 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 Founda...
TileModel.objects.count() BusinessDataImporte
r("tests/fixtures/data/csv/concept_label_import.csv").import_business_data() new_tile_count = TileModel.objects.count() tile_difference = new_tile_count - og_tile_count self.assertEqual(tile_difference, 1) def test_required_node_import(self): og_tile_count = TileModel.objects.count(...
mindnervestech/mnrp
openerp/service/server.py
Python
agpl-3.0
36,292
0.002618
#----------------------------------------------------------- # Threaded, Gevent and Prefork Servers #----------------------------------------------------------- import datetime import errno import logging import os import os.path import platform import psutil import random if os.name == 'posix': import resource els...
axError: py_errors.append(i) if py_errors
: _logger.info('autoreload: python code change detected, errors found') for i in py_errors: _logger.info('autoreload: SyntaxError %s', i) else: _logger.info('autoreload: python code updated, autoreload activated') restart() ...
Rostlab/nalaf
nalaf/features/relations/__init__.py
Python
apache-2.0
10,867
0.005245
import abc from nalaf.features import FeatureGenerator import re from nalaf import print_debug, print_verbose class EdgeFeatureGenerator(FeatureGenerator): """ Abstract class for generating features for each edge in the dataset. Subclasses that inherit this class should: * Be named [Name]FeatureGenera...
tal_feature
_present percentage_ne
Edraak/edraak-platform
lms/djangoapps/course_api/helpers.py
Python
agpl-3.0
2,431
0.002879
from urlparse import urljoin import requests from django.conf import settings from edxmako.shortcuts import marketing_link import logging from django.core.cache import cache import json log = logging.getLogger(__name__) def is_marketing_api_enabled(): """ Checks if the feature is enabled, while making some sa...
def get_marketing_data(course_key, language): """ This method gets the current marketing details for a specific course. :returns a course details from the mark
eting API or None if no marketing details found. """ CACHE_KEY = "MKTG_API_" + str(course_key) + str(language) if cache.get(CACHE_KEY): return cache.get(CACHE_KEY) marketing_root_format = marketing_link('COURSE_DETAILS_API_FORMAT') url = marketing_root_format.format(course_id=course_key)...
IotaMyriad/SmartMirror
Widgets/InstalledWidgets/WeatherWidget/ExpandedWeatherWidget.py
Python
gpl-3.0
3,751
0.005335
# user: smartmirror_elp # pw: 12345678 # API-key: 68a61abe6601c18b8288c0e133ccaafb import os import pyowm import datetime from datetime import datetime from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from Widgets.ExpandedWidget import ExpandedWidget API_key = "68a61abe6601c18b8288c0...
You MUST provide a valid API key fc = owm.daily_forecast(place) f = fc.get_forecast() i = 0 weather = f.get_weathers()[0] for weather in f: day = DailyWeather(weather.get_reference_time('iso')) day.setStyleSheet("background-color:black;");
self.layout.addWidget(day,0,i) i += 1 #self.layout.addWidget(self.widget) self.setLayout(self.layout) @staticmethod def name(): return "WeatherWidget"
kdart/pycopia
QA/pycopia/QA/jobrunner.py
Python
apache-2.0
5,084
0.00118
#!/usr/bin/python2.7 # -*- coding: utf-8 -*- # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # 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 ...
uments = testjob.parameters.split() else:
params = {} cf.argv = [testjob.suite.name] cf.comment = "Automated test job %s(%s)." % (testjob.name, testjob.id) cf.reportname = testjob.reportname cf.evalupdate(params) self.runner.set_options(params) ...
miketheman/opencomparison
grid/context_processors.py
Python
mit
430
0.002326
from itertools import izip, chain, r
epeat from grid.models import Grid def grouper(n, iterable, padvalue=None): "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')" return izip(*[chain(iterable, repeat(padvalue, n-1))]*n) def grid_headers(request): grid_headers = list(Grid.objects.filter(header=True)) grid_hea...
headers) return {'grid_headers': grid_headers}
arthurdarcet/aiohttp
aiohttp/multipart.py
Python
apache-2.0
32,819
0.000853
import base64 import binascii import json import re import uuid import warnings import zlib from collections import deque from types import TracebackType from typing import ( # noqa TYPE_CHECKING, Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple, Type, Union, ...
'BodyPartReader': return self async def __anext__(self) -> Any: part = await self.next() if part is None: raise StopAsyncIteration # NOQA return part async def next(self
) -> Any: item = await self.read() if not item: return None return item async def read(self, *, decode: bool=False) -> Any: """Reads body part data. decode: Decodes data following by encoding method from Content-Encoding header. If it missed ...
TomAugspurger/pandas
pandas/io/sql.py
Python
bsd-3-clause
62,333
0.000433
""" Collection of query wrappers / abstractions to both facilitate data retrieval and to reduce dependency on DB-specific API. """ from contextlib import contextmanager from datetime import date, datetime, time from functools import partial import re from typing import Iterator, Optional, Union, overload import warnin...
con, schema=None, index_col=No
ne, coerce_float=True, parse_dates=None, columns=None, chunksize: int = 1, ) -> Iterator[DataFrame]: ... def read_sql_table( table_name, con, schema=None, index_col=None, coerce_float=True, parse_dates=None, columns=None, chunksize: Optional[int] = None, ) -> Union[...
meyt/mehrcal
mehrcal/yapsy/PluginManager.py
Python
gpl-3.0
22,880
0.025481
#!/usr/bin/python # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t; python-indent: 4 -*- """ Role ==== The ``PluginManager`` loads plugins that enforce the `Plugin Description Policy`_, and offers the most simple methods to activate and deactivate the plugins once they are loaded. .. note:: It may also classif...
his behaviour is optional and if not specified elseway all plugins are stored in the same default category. .. no
te:: It is often more useful to have the plugin manager behave like singleton, this functionality is provided by ``PluginManagerSingleton`` Plugin Description Policy ========================= When creating a ``PluginManager`` instance, one should provide it with a list of directories where plugin...
Orav/kbengine
assets/scripts/login/kbemain.py
Python
lgpl-3.0
2,617
0.036195
# -*- coding: utf-8 -*- import os import KBEngine from KBEDebug import * """ loginapp进程主要处理KBEngine服务端登陆、创建账号等工作。 目前脚本支持几种功能: 1: 注册账号检查 2:登陆检查 3:自定义socket回调,参考interface中Poller实现 """ def onLoginAppReady(): """ KBEngine method. loginapp已经准备好了 """ INFO_MSG('onLoginAppReady: bootstrapGroupIndex=%...
_NAME; if len(password) > 64: errorno = KBEngine.SERVER_ERR_PASSWORD; return (errorno, accountName, password, datas) def onCreateAccountCallbackFromDB(accountName, errorno, datas): """
KBEngine method. 账号请求注册后db验证回调 errorno: KBEngine.SERVER_ERR_* """ INFO_MSG('onCreateAccountCallbackFromDB() accountName=%s, errorno=%s' % (accountName, errorno))
mxrrow/zaicoin
src/deps/boost/tools/build/v2/test/TestCmd.py
Python
mit
23,923
0.002424
""" TestCmd.py: a testing framework for commands and scripts. The TestCmd module provides a framework for portable automated testing of executable commands and scripts (in any language, not just Python), especially commands and scripts that require file system interaction. In addition to running tests and evaluating...
ense, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) from string import join, split __author__ = "Steven Knight <knight@baldmt.com>" __revision__ = "TestCmd.py 0.D002 2001/08/31 14:56:12 software" __version__ = "0.02" from types import * import o...
pfile import traceback tempfile.template = 'testcmd.' _Cleanup = [] def _clean(): global _Cleanup list = _Cleanup[:] _Cleanup = [] list.reverse() for test in list: test.cleanup() sys.exitfunc = _clean def caller(tblist, skip): string = "" arr = [] for file, line, name, tex...
apinsard/khango
khango/templatetags/khango.py
Python
mit
169
0
# -*- coding: utf-8 -*- from
django.template import Library register = Library() @register.simple_tag(name='getattr') def _getattr(*args):
return getattr(*args)
eustislab/horton
scripts/horton-esp-test.py
Python
gpl-3.0
3,917
0.004595
#!/usr/bin/env python # -*- coding: utf-8 -*- # HORTON: Helpful Open-source Research TOol for N-fermion systems. # Copyright (C) 2011-2015 The HORTON Development Team # # This file is part of HORTON. # # HORTON is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public Licens...
The location of the cost function in the form ' '"file.h5:group/cost". This argument must be the same as the ' 'output argument of the script horton-esp-cost.py.') parser.add_argument('charges', type=str, help='The atomic charges to be used in the form '
'"file.h5:group/charges". ') parser.add_argument('output', type=str, help='The output destination in the form file.h5:group. The colon and ' 'the group name are optional. When omitted, the root group of the ' 'HDF5 file is used.') parser.add_argument('--overwrite', ...
Aircollition/Aircollition
Python scripts/theta.py
Python
mit
378
0.02381
import numpy as np import matplotlib.p
yplot as plt npoint = 100 dec = 3 x = np.linspace(0,1,npoint) a = dec * np.linspace(0,1,npoint/2) b = dec * np.linspace(1,0,npoint/2) delta = np.concatenate((a,b)) delta1 = dec * np.linspace(0,1,npoint) delta2 = dec * np.ones(npoint) plt.figure() plt.plot(x, delta2) plt.f
igure() plt.plot(x, delta1) plt.figure() plt.plot(x, delta)
harmy/kbengine
kbe/res/scripts/common/Lib/test/test_profile.py
Python
lgpl-3.0
7,166
0.001535
"""Test suite for the profile module.""" import sys import pstats import unittest from difflib import unified_diff from io import StringIO from test.support import run_unittest import profile from test.profilee import testfunc, timer class ProfileTest(unittest.TestCase): profilerclass = profile....
line in output if mod_name in line] results.append('\n'.join(output)) return results def test_cprofile(self): results = self.do_profiling() expected = self.get_expected_output() self.assertEqual(results[0], 1000)
for i, method in enumerate(self.methodnames): if results[i+1] != expected[method]: print("Stats.%s output for %s doesn't fit expectation!" % (method, self.profilerclass.__name__)) print('\n'.join(unified_diff( resul...
pychess/pychess
lib/pychess/Variants/racingkings.py
Python
gpl-3.0
1,813
0.004413
""" The Racing Kings Variation""" from pychess.Utils.const import RACINGKINGSCHESS, V
ARIANTS_OTHER_NONSTANDARD, \
A8, B8, C8, D8, E8, F8, G8, H8 from pychess.Utils.Board import Board RACINGKINGSSTART = "8/8/8/8/8/8/krbnNBRK/qrbnNBRQ w - - 0 1" RANK8 = (A8, B8, C8, D8, E8, F8, G8, H8) class RacingKingsBoard(Board): """ :Description: The Racing Kings variation is where the object of the game is to bring your king to...
mikpin/plugin.video.italian-news
default.py
Python
gpl-2.0
1,928
0.028527
import sys, xbmcplugin, xbmcgui,xbmc _id = "plugin.video.italian-news" _resdir = "special://home/addons/" + _id + "/resources" _thisPlugin = int(sys.argv[1]) _icons = _resdir + "/icons/" sys.path.append( xbmc.translatePath(_resdir + "/lib/")) import rai _tg1Icon=xbmc.translatePath(_icons +"Tg1_logo.png") _tg2Icon=xb...
aram: (engine, title, eicon)=plugins[param['plugin']] for (name,url,icon) in engine().get(): if icon == '': icon = eicon _addItem(name,url,icon) xbmcplugin.endOfDirectory(_thisPlugin) else: for n in sorted(plugins.iterkeys()): (engine, title, icon)=plugins[n] ...
(name,url,icon) in tg1: # _addItem(name,url,icon) #xbmcplugin.endOfDirectory(_thisPlugin)
luotao1/Paddle
python/paddle/fluid/ir.py
Python
apache-2.0
22,516
0.000622
# Copyright (c) 2021 PaddlePaddle 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 ap...
relu_depthwise_conv and use_cuda: apply_pass("fuse_relu_depthwise_conv_pass") build_strategy.fuse_relu_depthwise_conv = False if build_strategy.fuse_bn_act_ops and use_cuda: apply_pass("fuse_bn_act_pass") build_strategy.fuse_bn_act_ops = False if build_strategy.fuse_bn_add_act_op...
s") build_strategy.fuse_bn_add_act_ops = False if build_strategy.enable_auto_fusion and use_cuda: apply_pass("fusion_group_pass") build_strategy.enable_auto_fusion = False if build_strategy.fuse_elewise_add_act_ops: apply_pass("fuse_elewise_add_act_pass") build_strategy.f...
smartscheduling/scikit-learn-categorical-tree
sklearn/cluster/tests/test_dbscan.py
Python
bsd-3-clause
10,974
0
""" Tests for DBSCAN clustering algorithm """ import pickle import numpy as np from scipy.spatial import distance from scipy import sparse from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing im...
core_sparse) assert_array_equal(labels_dense, labels_sparse) def test_dbscan_no_core_samples(): rng = np.random.RandomState(0) X = rng.rand(40, 10) X[X < .8] = 0 for X_ in [X, sparse.csr_matrix(X)]: db = DBSCAN(min_samples=6
).fit(X_) assert_array_equal(db.components_, np.empty((0, X_.shape[1]))) assert_array_equal(db.labels_, -1) assert_equal(db.core_sample_indices_.shape, (0,)) def test_dbscan_callable(): # Tests the DBSCAN algorithm with a callable metric. # Parameters chosen specifically for this task....
followthesheep/galpy
galpy/df_src/streamdf.py
Python
bsd-3-clause
117,381
0.021826
#The DF of a tidal stream import copy import numpy import multiprocessing import scipy from scipy import special, interpolate, integrate if int(scipy.__version__.split('.')[1]) < 10: #pragma: no cover from scipy.maxentropy import logsumexp else: from scipy.misc import logsumexp from galpy.orbit import Orbit fro...
: r'$X$', 'y': r'$Y$', 'z': r'$Z$', 'r': r'$R$', 'phi': r'$\phi$', 'vx':r'$V_X$', 'vy':r'
$V_Y$', 'vz':r'$V_Z$', 'vr':r'$V_R$', 'vt':r'$V_T$', 'll':r'$\mathrm{Galactic\ longitude\, (deg)}$', 'bb':r'$\mathrm{Galactic\ latitude\, (deg)}$', 'dist':r'$\mathrm{distance\, (kpc)}$', 'pmll':r'$\mu_l\,(\mathrm{mas\,yr}^{-1})$'...
datapythonista/datapythonista.github.io
docs/new-pandas-doc/generated/pandas-DataFrame-plot-bar-2.py
Python
apache-2.0
279
0
speed
= [0.1, 17.5, 40, 48, 52, 69, 88] lifespan = [2, 8, 70, 1.5, 25, 12, 28] index = ['snail', 'pig', 'elephant', 'rabbit', 'giraffe', 'coyote', 'horse'] df = pd.DataFrame({'speed': speed, 'lifespan': lifespan}, index=ind
ex) ax = df.plot.bar(rot=0)
prasanna08/oppia
core/controllers/reader_test.py
Python
apache-2.0
102,089
0.000431
# Copyright 2014 The Oppia 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 applicable ...
KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for the page that allows learners to play through an exploration.""" from __future__ import absolute_import # pylint: disable=import-only-modules from __future__ import uni...
ylint: disable=import-only-modules import logging from constants import constants from core.domain import collection_domain from core.domain import collection_services from core.domain import exp_domain from core.domain import exp_fetchers from core.domain import exp_services from core.domain import learner_progress_...
google-research/tf-slim
tf_slim/data/parallel_reader.py
Python
apache-2.0
11,775
0.002803
# coding=utf-8 # 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 requ...
ata_sources using n readers. It uses a ParallelReader to read from multiple files in parallel using multiple readers created using `reader_class` with `reader_kwargs'. If shuffle is True the common_queue would be a RandomShuffleQueue otherwise it would be a FIFOQueue. Usage: data_sources = ['path_to/...
/path/to/train@128, /path/to/train* or /tmp/.../train* reader_class: one of the io
alexiwamoto/django-rest-api
rest_api/admin.py
Python
mit
279
0
from django.contrib import admin from .models import Produto, Foto from r
est_framework.authtoken.admin import TokenAdmin TokenAdmin.raw_id_fields = ('user',) # Register your models here. # admin.site.register(Bucketlist) admin.site.register(P
roduto) admin.site.register(Foto)
rolandgeider/wger
wger/nutrition/tests/test_calories_calculator.py
Python
agpl-3.0
6,686
0.00015
# This file is part of wger Workout Manager. # # wger Workout Manager 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. # # wger W...
{'height': 180, 'weight': 80}) self.assertEqual(response.statu
s_code, 200) entry = WeightEntry.objects.filter(user=user).latest() self.assertEqual(entry.weight, 80) self.assertEqual(entry.date, datetime.date.today()) def test_bmr(self): """ Tests the BMR view """ self.user_login('test') response = self.client.p...
JaneliaSciComp/Neuroptikon
Source/documentation/__init__.py
Python
bsd-3-clause
747
0.008032
""" Documentation package """ import neuroptikon import wx, wx.html import os.path, sys, urllib _sharedFrame = None def baseURL(): if neuroptikon.runningFromSource: basePath = os.path.join(neuroptikon.rootDir, 'documentation', 'build', 'Documentation') else: basePath = os.path.join(neuropti...
ile:' + urllib.pathname2url(basePath) + '/' def showPage(page): pageURL = baseURL() + page # Try to open an embedded WebKit-based help browser. try: import documentation_frame documentation_frame.showPage(pageURL) except: # Fall back to using the user's default
browser outside of Neuroptikon. wx.LaunchDefaultBrowser(pageURL)
bitdeal/bitdeal
qa/rpc-tests/test_framework/test_framework.py
Python
mit
7,473
0.002141
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # Base class for RPC testing import logging import optparse import os import sys import shutil import te...
top bitdealds after the test execution") parser.add_option("--srcdir", dest="srcdir", default=os.path.normpath(os.path.dirname(os.path.realpath(__file__))+"/../.
./../src"), help="Source directory containing bitdeald/bitdeal-cli (default: %default)") parser.add_option("--tmpdir", dest="tmpdir", default=tempfile.mkdtemp(prefix="test"), help="Root directory for datadirs") parser.add_option("--tracerpc", dest="tra...
sandan/sqlalchemy
test/sql/test_compiler.py
Python
mit
148,745
0.00002
#! coding:utf-8 """ compiler tests. These tests are among the very first that were written when SQLAlchemy began in 2005. As a result the testing style here is very dense; it's an ongoing job to break these into much smaller tests with correct pep8 styling and coherent test organization. """ from sqlalchemy.testin...
hertable.otherid, myothertable.othername FROM mytable, " "myothertable") def test_invalid_col_argument(self): assert_raises(exc.ArgumentError, select, table1) assert_raises(exc.ArgumentError, select, table1.c.myid) def test_int_limit_offset_coercion(self): for given, exp in...
]: eq_(select().limit(given)._limit, exp) eq_(select().offset(given)._offset, exp) eq_(select(limit=given)._limit, exp) eq_(select(offset=given)._offset, exp) assert_raises(ValueError, select().limit, "foo") assert_raises(ValueError, select().offset...
hcs/mailman
src/mailman/commands/cli_control.py
Python
gpl-3.0
7,366
0.000543
# Copyright (C) 2009-2012 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman 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 you...
, Advanced Programming in # the UN
IX Environment, Chapter 13. pid = os.fork() if pid: # parent log(_("Starting Mailman's master runner")) return # child: Create a new session and become the session leader, but since # we won't be opening any terminal devices, don't do the # ult...
avinassh/simple-web-server
HTTPClientRequest.py
Python
mit
1,686
0.004745
""" This creates an HTTPClientRequest object. The constructor receives the JSON file which contains the request. Then it creates the o
bject with the data specified from the JSON, builds the appropriate GET/POST URL. When Execute method is called, the request is sent to server """ import urllib2 import sys import os import re import json from urllib import urlencode class HTTPClientRequest(object): """docstring for HTTPClientRequest""" de...
T_NAME, PORT_NUMBER): """ Initializes the object """ self.base_url = self._set_base_url(HOST_NAME, PORT_NUMBER) self.create_request(request_specs) def create_request(self, request_specs): """ Creates the request """ try: payload = self._convert_json_to_dict(r...
awolfe76/rural-with-mapbox
src/geojson/mk_geojson.py
Python
cc0-1.0
2,410
0.039419
#write one example for simplify by projecting; #write a different example for simplifying in DD (0.00001) #working off of downloaded uauc table #create working table of state #simplify polygon (perhaps project to GM, then try multiple distances) #check vertex count, visual polygon coarseness etc #use ogr2ogr to export ...
me.time()) print "start time:", time
.asctime(now) #variables myHost = "localhost" myPort = "5432" myUser = "feomike" db = "feomike" sch = "analysis" i_tbl = "tl_2015_us_uac10" o_tb = "uauc" r_tbl = "county_ru_dump" myDist = "10" #3, 5, 10, 13, 15 print "weeding at a distance of " + myDist #dissolve distance in dd must be smaller than 0.001 #in projecte...
wangqingbaidu/aliMusic
models/new_songs_incr.py
Python
gpl-3.0
38,314
0.012382
# -*- coding: UTF-8 -*- ''' Authorized by vlon Jang Created on Jul 3, 2016 Email:zhangzhiwei@ict.ac.cn From Institute of Computing Technology All Rights Reserved. ''' import pandas as pd import numpy as np import pymysql import matplotlib ...
)song_out where song_out.action_type=1 and song_out.ds >= "{me_from_date}" and song_out.ds <= "{toDate}" group by song_out.artist_id,song_out.ds )b group by artist_id; ''' return sqlTem...
ong_from_date, toDate = self.toDate, me_from_date = self.me_from_date, data2use = data2use[self.use_clean]) def genNewSongOutBaseline(self): sqlTemplate = ''' drop table if exists new_...
oVirt/imgbased
src/imgbased/plugins/openscap.py
Python
gpl-2.0
1,850
0
import logging from ..openscap import OSCAPScanner log = logging.getLogger(__package__) def init(app): app.hooks.connect("pre-arg-parse", add_argparse) app.hooks.connect("post-arg-parse", post_argparse) def add_argparse(app, parser, subparsers): s = subparsers.add_parser("openscap", help="Security man...
tered profile: %s" % os.profile) elif args.all: for id
_, desc in os.profiles().items(): print("Id: %s\n %s\n" % (id_, desc)) elif args.configure: os.configure() elif args.register: datastream, profile = args.register os.register(datastream, profile) elif args.unregister: os.unregist...
jsemple19/BSA_simulation
recombSim2.py
Python
gpl-2.0
10,746
0.020101
# last modified 20151215 changed sequencing selection to use sampling with # replacement for all populations sizes import numpy as np import random as rnd from itertools import groupby import os import random #mySeed=2015 #random.seed(mySeed) def encode(input_nparray): ''' converts a numpy boolean array to...
ental stain. contains method to create a founder genome of a single genotype (0 or 1) of a specified length ''' def __init__(self,haploidGenome): self
.numLoci=haploidGenome.numLoci self.mutRate=haploidGenome.mutRate self.recProb=haploidGenome.recProb self.useRLE=haploidGenome.useRLE def createFounder(self, genotype): if (genotype==1): self.setGenome(np.ones(self.numLoci,dtype=bool)) else: self.setG...
googleads/google-ads-python
google/ads/googleads/v10/services/types/campaign_service.py
Python
apache-2.0
6,174
0.00081
# -*- coding: utf-8 -*- # Copyright 2020 Google 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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
number=2, message="CampaignOperation", ) partial_failure = proto.Field(proto.BOOL, number=3,) validate_only = proto.Field(proto.BOOL, number=4,) response_content_type = proto.Field( proto.ENUM, number=5, enum=gage_response_content_type.ResponseContentTypeEnum.ResponseContentType...
ssage has `oneof`_ fields (mutually exclusive fields). For each oneof, at most one member field can be set at the same time. Setting any member of the oneof automatically clears all other members. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields...
barliant/fnc-id
django_project/old/hoaxdetector/hoaxdetector/wsgi.py
Python
apache-2.0
401
0
""" WSGI conf
ig for hoaxdetector 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/2.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODU...
ation()
nMustaki/python-slugify
setup.py
Python
bsd-3-clause
2,653
0.000754
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup import re import os import sys import codecs name = 'python-slugify' package = 'slugify' description = 'A Python Slugify application that handles Unicode' url = 'https://github.com/un33k/python-slugify' author = 'Val Neekman' author_email = '...
Return root package and all
sub-packages. """ return [dirpath for dirpath, dirnames, filenames in os.walk(package) if os.path.exists(os.path.join(dirpath, '__init__.py'))] def get_package_data(package): """ Return all files under the root package, that are not in a package themselves. """ walk...
nschaetti/EchoTorch
echotorch/nn/LiESN.py
Python
gpl-3.0
4,533
0.004853
# -*- coding: utf-8 -*- # # File : echotorch/nn/ESN.py # Description : An Echo State Network module. # Date : 26th of January, 2018 # # This file is part of EchoTorch. EchoTorch 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 Sof...
:param w_bias: :param sparsity: :param input_set: :param w_sparsity: :param nonlin_func: :param learning_algo: :param ridge_param: :param leaky_rate: :param train_leaky_rate: :param feedbacks: """ super(LiE
SN, self).__init__(input_dim, hidden_dim, output_dim, spectral_radius=spectral_radius, bias_scaling=bias_scaling, input_scaling=input_scaling, w=w, w_in=w_in, w_bias=w_bias, sparsity=sparsity, input_set=input_set, ...
mtambos/online-anomaly-detection
src/mgng/cdf_table.py
Python
mit
263,594
0
#!/usr/bin/env python CDF_TABLE = { -4.0: 3.1671241833119863e-05, -3.999: 3.1805340054201978e-05, -3.998: 3.1939975607705564e-05, -3.997: 3.2075150511550028e-05, -3.996: 3.2210866790657701e-05, -3.995: 3.2347126476975879e-05, -3.994: 3.2483931609498828e-05, -3.993: 3.2621284234289769e-0...
5388e-05, -3.917: 4.4828874401446823e-05, -3.916: 4.5015123775639811e-05, -3.915: 4.5202103932259478e-05, -3.914: 4.5389817550946242e-05, -3.913: 4.5578267320382521e-05, -3.912: 4.576745593831931e-05, -3.911: 4.5957386111604217e-05,
-3.91: 4.6148060556208749e-05, -3.909: 4.6339481997255854e-05, -3.908: 4.6531653169047459e-05, -3.907: 4.6724576815092721e-05, -3.906: 4.6918255688135439e-05, -3.905: 4.7112692550181989e-05, -3.904: 4.7307890172529221e-05, -3.903: 4.7503851335792433e-05, -3.902: 4.7700578829933875e-0...
homeworkprod/byceps
tests/unit/services/orga/test_birthday_service.py
Python
bsd-3-clause
1,509
0
""" :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from __future__ import annotations from datetime import date from freezegun import freeze_time from byceps.database import generate_uuid from byceps.services.orga import birthday_service from byceps.services.org...
) assert
actual == expected # helpers def create_user_and_birthday(date_of_birth: date) -> tuple[User, Birthday]: user = User( id=UserID(generate_uuid()), screen_name=f'born-{date_of_birth}', suspended=False, deleted=False, locale=None, avatar_url=None, ) birthday ...
wukong-m2m/NanoKong
tools/python/scripts/installer.py
Python
gpl-2.0
2,839
0.002113
#!/usr/bin/env python import sys, os sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../../master')) sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../../master/wkpf')) print os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../../master/wkpf') from...
_FEATURE_NATIVE_THRESHOLD, 0) comm.setLocation(13, "WuKong") comm.setFeature(14, WKPF_FEATURE_LIGHT_SENSOR, 0) comm.setFeature(14, WKPF_FEATURE_LIGHT_ACTUATOR, 1) comm.setFeature(14, WKPF_FEATURE_NUMERIC_CONTROLLER, 0) comm.setFeature(14, WKPF_FEATURE_NATIVE_THRESHOLD, 0) comm.setLocation(14, "WuKong") comm.setFeatur...
THRESHOLD, 0) comm.setLocation(15, "WuKong") comm.setFeature(10, WKPF_FEATURE_LIGHT_SENSOR, 0) comm.setFeature(10, WKPF_FEATURE_LIGHT_ACTUATOR, 1) comm.setFeature(10, WKPF_FEATURE_NUMERIC_CONTROLLER, 0) comm.setFeature(10, WKPF_FEATURE_NATIVE_THRESHOLD, 0) comm.setLocation(10, "WuKong") comm.setFeature(12, WKPF_FEATU...
greyside/errand-boy
tests/test_mock_transport.py
Python
bsd-3-clause
2,753
0.001816
import subprocess import errand_boy from errand_boy.exceptions import SessionClosedError from errand_boy.transports import base, mock as mock_transport from .base import mock, BaseTestCase from .data import get_command_data class MockTra
nsportSimTestCase(BaseTestCase): def test_run_cmd(self): transport = mock_transport.MockTransport() with self.multiprocessing_patcher as multiprocessing,\ self.subprocess_patcher as mock_subprocess: mock_subprocess.PIPE = subprocess.PIPE cmd, stdout, stderr,...
data('ls -al') process = mock.Mock() process.communicate.return_value = stdout, stderr process.returncode = returncode mock_subprocess.Popen.return_value = process mock_Pool = mock.Mock() mock_Pool.apply_async.side_effect = lambda f, args=(), kw...
fluxer/spm
nuitka/nuitka/nodes/BuiltinTypeNodes.py
Python
gpl-2.0
10,942
0.009048
# Copyright 2016, Kay Hayen, mailto:kay.hayen@gmail.com # # Part of "Nuitka", an optimizing Python compiler that is compatible and # integrates with CPython, but also works on its own. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in complianc...
dicted truth value of built-in bool argument" ) return ExpressionB
uiltinTypeBase.computeExpression(self, trace_collection) class ExpressionBuiltinIntLongBase(ChildrenHavingMixin, NodeBase, ExpressionSpecBasedComputationMixin): named_children = ("value", "base") # Note: Version specific, may be allowed or not. try: int(base = 2...
kuroneko1996/cyberlab
spritesheet.py
Python
mit
869
0.002301
import pygame as pg class Spritesheet: def __init__(self, filename, tile_size): self.sheet = pg.image.load(filename).convert_alpha() self.tile_size = tile_size def get_image(self, x, y, width, height): image = pg.Surface((width, height)) image.blit(self.sheet, (0, 0), (x, y, w...
ight)) return image
def get_image_alpha(self, x, y, width, height): image = pg.Surface((width, height), pg.SRCALPHA) image.blit(self.sheet, (0, 0), (x, y, width, height)) return image def get_image_at_col_row(self, col, row): return self.get_image(col * self.tile_size, row * self.tile_size, self...
googleapis/python-recommendations-ai
google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc.py
Python
apache-2.0
11,847
0.001857
# -*- coding: utf-8 -*- # Copyright 2022 Google 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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials i
dentify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if ``channel`` is provided. credentials_file (Optional[str]): A file with credentials that can ...
hcosta/escueladevideojuegos.net-backend-django
edv/reddit/migrations/0010_question_best_response.py
Python
gpl-3.0
628
0.001592
# -*- coding: utf-8 -*- # Generated by Dja
ngo 1.11.1 on 2017-05-27 16:28 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('reddit', '0009_auto_20170527_1814'), ] operations = [ migrations.AddField( ...
n.CASCADE, related_name='best_response', to='reddit.Response', verbose_name='Mejor Respuesta'), ), ]
ianstalk/Flexget
setup.py
Python
mit
2,280
0.000877
import sys from pathlib import Path from setuptools import find_packages, setup long_description = Path('README.rst').read_text() # Populates __version__ without importing the package __version__ = None with open('flexget/_version.py', encoding='utf-8') as ver_file: exec(ver_file.read()) # pylint: disable=W0122...
', 'Issue Tracker': 'https://github.com/Flexget/Flexget/issues', 'Forum': 'https://discuss.flexget.com', }, packages=find_packages(exclude=['flexget.tests']), include_package_data=True, zip_safe=False, install_requires=load_requirements('requirements.txt'), tests_require=['pytest...
entry_points={ 'console_scripts': ['flexget = flexget:main'], 'gui_scripts': [ 'flexget-headless = flexget:main' ], # This is useful on Windows to avoid a cmd popup }, python_requires='>=3.6', classifiers=[ "Development Status :: 5 - Production/Stable", ...
GbalsaC/bitnamiP
venv/lib/python2.7/site-packages/httpretty/__init__.py
Python
agpl-3.0
1,914
0
# #!/usr/bin/env python # -*- coding: utf-8 -*- # <HTTPretty - HTTP client mock for Python> # Copyright (C) <2011-2013> Gabriel Falcão <gabriel@nacaolivre.org> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to d...
WARE. from __future__ import unicode_literals __version__ = version = '0.8.3' from .core impo
rt httpretty, httprettified from .errors import HTTPrettyError from .core import URIInfo HTTPretty = httpretty activate = httprettified enable = httpretty.enable register_uri = httpretty.register_uri disable = httpretty.disable is_enabled = httpretty.is_enabled reset = httpretty.reset Response = httpretty.Response G...
fatherlinux/atomic-reactor
tests/plugins/test_check_and_set_rebuild.py
Python
bsd-3-clause
4,173
0.001198
""" Copyright (c) 2015 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ from __future__ import unicode_literals import pytest from atomic_reactor.core import DockerTasker from atomic_reactor.inner import DockerBu...
bel_value': value, 'url': '', }, }
]) return workflow, runner def test_check_rebuild_no_build_json(): workflow, runner = prepare('is_autorebuild', 'true') if "BUILD" in os.environ: del os.environ["BUILD"] with pytest.raises(PluginFailedException): runner.run() def test_check_no_buildconfi...
GeoMop/GeoMop
src/Analysis/pipeline/generator_actions.py
Python
gpl-3.0
11,140
0.006463
from .action_types import GeneratorActionType, ActionStateType from .data_types_tree import Ensemble, Struct, Float, DTT import copy from .code_formater import Formater class VariableGenerator(GeneratorActionType): name = "VariableGenerator" """Display name of action""" description = "Generator for cr...
"Can't determine valid output") return err def validate(self): """validate variables, inp
ut and output""" err = super(VariableGenerator, self).validate() return err class RangeGenerator(GeneratorActionType): name = "RangeGenerator" """Display name of action""" description = "Generator for generation parallel list" """Display description of action""" def __init__...
jfriedly/rethinkdb
scripts/nightly-test/launch_nightly_test.py
Python
agpl-3.0
1,755
0.015954
#!/usr/bin/env python # Copyright 2010-2012 RethinkDB, all rights reserved. #
Usage: ./launch_nightly_test.py # --test-host <hostname>[:<port>] # (--email <name>@<address>)* # [--title "<Title>"] # [-- <flags for full_test_driver.py>] import sys, subprocess, os, optparse if __name__ != "__main__": raise ImportError("It doesn't make any sense to i...
d_option("--email", action = "append", dest = "emailees") parser.add_option("--title", action = "store", dest = "title") parser.set_defaults(title = "Nightly test", emailees = []) (options, args) = parser.parse_args() if options.test_host is None: parser.error("You must specify --test-host.") def escape(arg): ...
Tunous/StringSheet
setup.py
Python
mit
977
0.001024
import os from io import open from setuptools import setup about = {} here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'stringsheet', '__init__.py'), encoding='utf-8') as f:
for line in f: if line.startsw
ith('__'): (key, value) = line.split('=') about[key.strip()] = value.strip().strip('\'') with open('README.rst', encoding='utf-8') as f: readme = f.read() setup( name=about['__title__'], version=about['__version__'], description=about['__description__'], long_description=re...
paulydboy/Quad-Vision
DroneControl/Camera.py
Python
apache-2.0
177
0.00565
from Sensor import Sensor i
mport cv2 class Camera(Sensor): def __init__(self): self._cap = cv2.VideoCapture(0) def read(self): r
eturn self._cap.read()
Videoclases/videoclases
videoclases/migrations/0014_auto_20150726_1441.py
Python
gpl-3.0
975
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('videoclases', '0013_tarea_profesor'), ]
operations = [ migrations.AddField( model_name='grupo', name='alternativa_2', field=models.CharField(max_length=100, null=True, blank=True), ), migrations.AddField( model_name='grupo', name='alternativa_3', field
=models.CharField(max_length=100, null=True, blank=True), ), migrations.AddField( model_name='grupo', name='alternativa_correcta', field=models.CharField(max_length=100, null=True, blank=True), ), migrations.AddField( model_name='grupo', ...
gepuro/csvkit
csvkit/utilities/csvsql.py
Python
mit
7,388
0.006091
#!/usr/bin/env python # -*- coding:utf-8 -*- import os import sys from csvkit import sql from csvkit import table from csvkit import CSVKitWriter from csvkit.cli import CSVKitUtility class CSVSQL(CSVKitUtility): description = 'Generate SQL statements for one or more CSV files, create execute those statements dir...
='If present, a sqlalchemy connection string to use to directly execute generated SQL on a database.') self.argparser.add_argument('--query', default=None, help='Execute one or more SQL queries delimited by ";" and output the result of the last query as CSV.') self.argparser.add_argument('--...
self.argparser.add_argument('--tables', dest='table_names', help='Specify one or more names for the tables to be created. If omitted, the filename (minus extension) or "stdin" will be used.') self.argparser.add_argument('--no-constraints', dest='no_constraints', action='store_true', ...
hardbyte/python-can
can/interfaces/pcan/pcan.py
Python
lgpl-3.0
21,138
0.001277
""" Enable basic CAN over a PCAN USB device. """ import logging import time from datetime import datetime import platform from typing import Optional from packaging import version from ...message import Message from ...bus import BusABC, BusState from ...util import len2dlc, dlc2len from ...exceptions import CanErr...
includes the :meth:`~can.interface.pcan.PcanBus.flash` and :meth:`~can.interface.pcan.PcanBus.status` methods. :param str channel: The can interface name. An example would be 'PCAN_USBBUS1'. Alternatively the value can be an int with the numerical v
alue. Default is 'PCAN_USBBUS1' :param can.bus.BusState state: BusState of the channel. Default is ACTIVE :param int bitrate: Bitrate of channel in bit/s. Default is 500 kbit/s. Ignored if using CanFD. :param bool fd: ...
Morbotic/pronto-distro
externals/libbot-drc/bot2-procman/python/src/bot_procman/printf_request_t.py
Python
lgpl-2.1
1,785
0.006162
"""LCM type definitions This file automatically generated by lcm. DO NOT MODIFY BY HAND!!!! """ try: import cStringIO.StringIO as BytesIO except ImportError: from io import BytesIO import struct class printf_request_t(object): __slots__ = ["sheriff_id"] def __init__(self): self.sheriff_id = 0...
self): buf = BytesIO() buf.write(printf_request_t._get_packed_fingerprint()) self._encode_one(buf) return buf.getvalue() def _encode_one(self, buf): buf.write(struct.pack(">i", self.sheriff_id)) def decode(data): if hasattr(data, 'read'): buf = data ...
rintf_request_t._decode_one(buf) decode = staticmethod(decode) def _decode_one(buf): self = printf_request_t() self.sheriff_id = struct.unpack(">i", buf.read(4))[0] return self _decode_one = staticmethod(_decode_one) _hash = None def _get_hash_recursive(parents): if...
edgedb/edgedb
edb/server/compiler/__init__.py
Python
apache-2.0
1,345
0
# # This source file is part of the EdgeDB open source project. # # Copyright 2018-present MagicStack Inc. and the EdgeDB authors. # # 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...
ma'
, 'new_compiler', 'new_compiler_context', )
codilime/cloudify-diamond-plugin
diamond_agent/tests/test_single_node.py
Python
apache-2.0
8,798
0.000114
import os import time import json import cPickle import tempfile from testtools import TestCase, ExpectedException import psutil from cloudify.workflows import local class TestSingleNode(TestCase): def setUp(self): super(TestSingleNode, self).setUp() os.environ['MANAGEMENT_IP'] = '127.0.0.1' ...
'TestCollector': { 'path': 'collectors/test.py', 'config': { 'name': 'metric', 'value': 42, }, }, }, } self.env = self._create_env(inputs) self.env.execute('in...
etric = cPickle.load(fh) metric_path = metric.path.split('.') collector_config = \ inputs['collectors_config']['TestCollector']['config'] self.assertEqual(collector_config['name'], metric_path[5]) self.assertEqual(collector_config['value'], metric.value) self.assertE...
CDNoyes/EDL-Py
Utils/progress.py
Python
gpl-3.0
521
0.011516
def progress(current, total, percent=10, iteration=None): """
Used in a loop to indicate progress """ current += 1 if current: previous = current - 1 else: previous = current # print out every percent frac = percent/100. value = max(1, frac*total) return not (int(current/value) == int(previous/value)) if __name__ ==...
print(r"Another 10% completed")
polyaxon/polyaxon
core/polyaxon/polypod/compiler/lineage/artifacts_collector.py
Python
apache-2.0
1,081
0.000925
#!/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 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 L
icense for the specific language governing permissions and # limitations under the License. import os from typing import Optional from polyaxon.polyboard.artifacts import V1ArtifactKind, V1RunArtifact from polyaxon.utils.fqn_utils import to_fqn_name def collect_lineage_artifacts_path(artifact_path: str) -> Optional...
pcbje/gransk
gransk/plugins/storage/tests/store_text_test.py
Python
apache-2.0
1,005
0.002985
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import os import unittest import shutil import gransk.core.helper as helper import gransk.cor
e.tests.test_helper as test_helper import gransk.core.document as document import gransk.plugins.storage.store_text as store_text class StoreTextTest(unittest.TestCase): def test_simple(self): mock_pipeline = test_helper.get_mock_pipeline([]) data_root = os.path.join('local_data', 'unittests') if os....
r.DATA_ROOT: data_root, 'workers': 1 }) doc = document.get_document('mock') doc.text = 'mock-mock-mock' _store_text.consume(doc, None) expected = 'local_data/unittests/text/17404a59-mock' actual = doc.meta['text_file'] self.assertEquals(expected, actual) if __name__ == '__main_...
aytuncbeken/Hp-Alm-Purge-Tool
PurgeWizard.py
Python
gpl-3.0
8,814
0.003744
#!/usr/bin/env python3 """ This Project is a Python based HP ALM Purge Wizard. This is the main file which do all stuff For detailed informatin please visit https://github.com/aytuncbeken/Hp-Alm-Purge-Tool Author:Aytunc BEKEN Python Version:3.6 License:GPL """ import threading from concurre...
lmPort:%s", alm_port) logging.info("AlmUserName:%s", alm_username) logging.info("AlmPassword:%s",
alm_password) logging.info("AlmDomain:%s", alm_domain) logging.info("AlmProject:%s", alm_project) logging.info("RecordLimitPerPage:%s", limit_per_page) logging.info("DeleteOlderThan:%s", date_limit) logging.info("SimulateDelete:%s", simulate_delete) logging.info("LogFileWithFullPath:%s", log_fi...
lesglaneurs/lesglaneurs
presentation/migrations/0016_auto_20160516_0806.py
Python
gpl-3.0
398
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from djang
o.db import migrations, models class Migration(migrati
ons.Migration): dependencies = [ ('presentation', '0015_auto_20160515_1658'), ] operations = [ migrations.RenameField( model_name='membership', old_name='membership', new_name='role', ), ]
mistercrunch/panoramix
superset/views/base_api.py
Python
apache-2.0
21,953
0.000957
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
plied. See the License for the # specific language governing permissions and limitations # under the License. import functools import l
ogging from typing import Any, Callable, cast, Dict, List, Optional, Set, Tuple, Type, Union from apispec import APISpec from apispec.exceptions import DuplicateComponentNameError from flask import Blueprint, g, Response from flask_appbuilder import AppBuilder, Model, ModelRestApi from flask_appbuilder.api import expo...
midonet/python-neutron-plugin-midonet
midonet/neutron/tests/unit/test_midonet_plugin.py
Python
apache-2.0
4,032
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (C) 2012 Midokura Japan K.K. # Copyright (C) 2013 Midokura PTE LTD # 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 th...
etUp(plugin=plugin) def tearDown(self): super(MidonetPluginV2TestCase, self).tearDown() self.module_patcher.stop() class TestMidonetNetworksV2(MidonetPluginV2TestCase, test_plugin.TestNetworksV2): pass cla
ss TestMidonetL3NatTestCase(MidonetPluginV2TestCase, test_l3_plugin.L3NatDBIntTestCase): def test_floatingip_with_invalid_create_port(self): self._test_floatingip_with_invalid_create_port(MIDONET_PLUGIN_NAME) class TestMidonetSecurityGroup(MidonetPluginV2TestCase, ...
callorico/django-rest-framework
tests/test_views.py
Python
bsd-2-clause
3,650
0
from __future__ import unicode_literals import copy import sys from django.test import TestCase from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.settings import api_settings from rest_framework.test import APIRequestFact...
nse.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual(response.data, expected) def test_function_based_view_exception_handler(self): view = error_view request = factory.get('/', content_type='application/json') response = view(request) expected = 'Error!' s...
, status.HTTP_400_BAD_REQUEST) self.assertEqual(response.data, expected)
kamal-gade/rockstor-core
src/rockstor/storageadmin/views/plugin.py
Python
gpl-3.0
1,928
0.004668
""" Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com> This file is part of RockStor. RockStor 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 (at your option) any la...
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/>. """ from rest_framework.renderers import JSONRenderer from rest_framework.response import Response import rest_framework_custom as rfc from storageadmin.util import handle_exception from storageadmin.models import (Plugin, InstalledPlugin) from storageadmin.serializers import PluginSerializer import t...
martenson/ansible-common-roles
paths/library/zfs_permissions.py
Python
mit
9,934
0.004832
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2015, Nate Coraor <nate@coraor.org> # # This file is part of Ansible # # Ansible 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...
tartswith('\tuser '): user, cur_perms = line.split()[1:3]
perms[reading]['u'][user] = cur_perms.split(',') elif line.startswith('\tgroup '): group, cur_perms = line.split()[1:3] perms[reading]['g'][group] = cur_perms.split(',') elif line.startswith('\teveryone '): perms[re...
Visrozar/DjangoRecommender
shop/migrations/0003_auto_20170217_1533.py
Python
mit
1,327
0.003014
# -*- coding: utf-8 -*- # Generated by D
jango 1.10.5 on 2017-02-17 10:03 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('shop', '0002_shops_longitude'), ] operations
= [ migrations.CreateModel( name='ShopsProducts', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), migrations.AddField( model_name='products', name='descri...
Juniper/nova
nova/virt/libvirt/volume/iscsi.py
Python
apache-2.0
3,538
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...
r express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Libvirt volume driver for iSCSI""" from os_brick import exception as os_brick_exception from os_brick.initiator import connector from oslo_log import log as logging import nova.conf fr...
e LOG = logging.getLogger(__name__) CONF = nova.conf.CONF class LibvirtISCSIVolumeDriver(libvirt_volume.LibvirtBaseVolumeDriver): """Driver to attach Network volumes to libvirt.""" def __init__(self, host): super(LibvirtISCSIVolumeDriver, self).__init__(host, ...
REANNZ/faucet
faucet/acl.py
Python
apache-2.0
33,575
0.001519
"""Configuration for ACLs.""" # Copyright (C) 2015 Brad Cowie, Christopher Lorier and Joe Stringer. # Copyright (C) 2015 Research and Education Advanced Network New Zealand Ltd. # Copyright (C) 2015--2019 The Contributors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file e...
alue
must be 0-2**16') elif rule_field == 'actions': test_config_condition( not rule_conf, 'Missing rule actions in ACL %s' % self._id) self._check_conf_types(rule_conf, self.actions_types) for action_...
josephmjoy/robotics
python_robotutils/robotutils/strmap_helper.py
Python
mit
3,444
0.003194
""" This module contains a helper to extract various kinds of primitive data types from a dictionary of strings. """ class StringDictHelper: """ Helper class to extract primitive types from a dictionary of strings. This is a port of Java robotutils class StringmapHelper. The special values 'true' an...
type(default) ret1 = t
ype_(val) valid = (minval is None or ret1 >= minval) and (maxval is None or ret1 <= maxval) ret = ret1 if valid else default except ValueError: ret = default return ret if __name__ == '__main__': D = dict(a='abc', b='true', c=42, d=1.5) H = ...
wubr2000/googleads-python-lib
examples/dfp/v201411/audience_segment_service/get_all_audience_segments.py
Python
apache-2.0
1,845
0.009214
#!/usr/bin/python # # Copyright 2014 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 b...
['size'])) statem
ent.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() main(dfp_client)
bendavis78/gnome-tweak-tool
gtweak/tweaks/tweak_group_shell_extensions.py
Python
gpl-3.0
13,162
0.004862
import os.path import zipfile import tempfile import logging import json from gi.repository import Gtk from gi.repository import GLib from gi.repository import Pango from operator import itemgetter from gtweak.utils import extract_zip_file, execute_subprocess from gtweak.gshellwrapper import GnomeShell, GnomeShellFac...
ame("emblem-system-symbolic", Gtk.IconSize.BUTTON) btn = Gtk.Button() btn.props.vexpand = False btn.props.valign = Gtk.Align.CENTER btn.add
(icon) btn.connect("clicked", self._on_configure_clicked, uuid) self.hbox.pack_start(btn, False, False, 0) btn = Gtk.Button(_("Remove")) btn.props.vexpand = False btn.props.valign = Gtk.Align.CENTER btn.set_sensitive(False) self.hbox.pack_start(bt...
skosukhin/spack
lib/spack/spack/cmd/gpg.py
Python
lgpl-2.1
6,389
0
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
l secret keys if unspecified') export.set_defaults(func=gpg_export) def gpg_create(args): if args.export: old_sec_keys = Gpg.signing_keys() Gpg.create(name=args.name, email=args.email, comment=args.comment, expires=args.expires) if args.export: new_sec_keys = set(Gpg.sig...
keys) Gpg.export_keys(args.export, *new_keys) def gpg_export(args): keys = args.keys if not keys: keys = Gpg.signing_keys() Gpg.export_keys(args.location, *keys) def gpg_list(args): Gpg.list(args.trusted, args.signing) def gpg_sign(args): key = args.key if key is None: ...
petrjasek/superdesk-core
superdesk/system/health.py
Python
agpl-3.0
1,753
0
"""Health Check API Use to check system status, will report "green" or "red" for each component plus overall for "status":: { "status": "green", "celery": "green", "elastic": "green", "mongo": "green", "redis": "green" } """ import logging import superdesk from typin...
("redis", redis_health), ] @bp.route("/system/health", methods=["GET", "OPTIONS"]) def health(): output = { "application_name": app.config.get("APPLICATION_NAME"), } status = True for key, check_func in checks: try: result = check_func() except Exception as er...
, key, err) result = False status = status and result output[key] = human(result) output["status"] = human(status) return output def init_app(app) -> None: superdesk.blueprint(bp, app)
DawudH/scrapy_real-estate
plot/print_progressbar.py
Python
mit
1,262
0.014286
# -*- coding: utf-8 -*- import sys def print_progress (iteration, total, prefix = '', suffix = '', decimals = 1, barLength = 100): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) ...
suffix - Optional : suffix string (Str) decimals - Optional : positive number of decimals in percent complete (Int) barLength - Optional : character length of bar (Int) copied from: http://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console With slight a...
just one iteration (total = 0) """ formatStr = "{0:." + str(decimals) + "f}" percent = formatStr.format(100 * (iteration / float(total))) if not total == 0 else formatStr.format(100) filledLength = int(round(barLength * iteration / float(total))) if not total == 0 else int(round(barLength)) bar = '...
mdblv2/joatu-django
application/joatu/local_settings.py
Python
apache-2.0
2,019
0.004458
DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( ('studio', 'mdbl@live.com'), # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': '/Users/studio...
et'] # Make this unique, and don't share it with anybody. SECRET_KEY = '@h8_wz=yshx96$%%tm$id#96gbllw3je7)%fhx@lja+_c%_(n&' # Additional locations of static fil
es STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ('common', '/Users/studio/Sites/joatu-master/static/img/common'), ('css', '/Users/studio/Sites/joatu-m...
zrzka/blackmamba
blackmamba/log.py
Python
mit
2,546
0.000393
#!python3 """Logging module. **This module must not introduce dependency on any other Black Mamba modules and must be importable on any other platform**. Why custom module instead of the bundled one? Several reasons: * not to interfere with Pythonista logging settings, * unable to convince Pythonista to use my colo...
" WARNING = 30 """Only warnings and errors are logged.""" INFO = 20 """Informational messages, warnings and errors are logged.""" DEBUG = 10 """Debug, information messages, warnings and errors are logged.""" NOTSET = 0 """All messages are logged.""" _level = INFO _COLORS = { WARNING: (1, 0.5, 0), ERROR: (...
_level(level: int): """Set effective log level. Args: level: Log level to set. """ global _level _level = level def _log(level, *args, **kwargs): if _level > level: return color = _COLORS.get(level, None) if console and color: console.set_color(*color) pr...
novas0x2a/ctypesgen
ctypesgencore/parser/cparser.py
Python
bsd-3-clause
6,868
0.00364
#!/usr/bin/env python ''' Parse a C source file. To use, subclass CParser and override its handle_* methods. Then instantiate the class with a string to parse. ''' __docformat__ = 'restructuredtext' import operator import os.path import re import sys import time import warnings import preprocessor import yacc imp...
name=%r, value=%r' % (name, value)
def handle_declaration(self, declaration, filename, lineno): print declaration if __name__ == '__main__': DebugCParser().parse(sys.argv[1], debug=True)
fredmorcos/attic
snippets/python/py-des/test_pydes.py
Python
isc
9,694
0.030638
from pyDes import * ############################################################################# # Examples # ############################################################################# def _example_triple_des_(): from time import time # Utility module from binascii import unhexlify as unhex # exam...
f k.decrypt(d) != unhex("000102030405060708FF8FDCB0408044"): print ("Test 4b: Error: Unencypted data block does not match start data") else: print ("Test 4: Successful") data = "String to Pad".encode('ascii') k = des("\r\n\tk
ey\r\n") d = k.encrypt(data, padmode=PAD_PKCS5) if k.decrypt(d, padmode=PAD_PKCS5) != data: print ("Test 5a: Error: decrypt does not match. %r != %r" % (data, k.decrypt(d))) # Try same with padmode set on the class instance. k = des("\r\n\tkey\r\n", padmode=PAD_PKCS5) d = k.encrypt(data) if k.decrypt(d) != data...
burgerdev/volumina
volumina/colorama/ansitowin32.py
Python
lgpl-3.0
7,363
0.001901
############################################################################### # volumina: volume slicing and editing library # # Copyright (C) 2011-2014, the ilastik developers # <team@ilastik.org> # # This program is free software; you can redistribute it and/or # modify it und...
ped stream, stripping any ANSI sequences from the text, and optionally converting them into win32 calls. ''' cursor = 0 for match in self.AN
SI_RE.finditer(text): start, end = match.span() self.write_plain_text(text, cursor, start) self.convert_ansi(*match.groups()) cursor = end self.write_plain_text(text, cursor, len(text)) def write_plain_text(self, text, start, end): if start < end: ...
glaudsonml/kurgan-ai
tools/sqlmap/thirdparty/clientform/clientform.py
Python
apache-2.0
126,378
0.001369
"""HTML form handling for web clients. ClientForm is a Python module for handling HTML forms on the client side, useful for parsing HTML forms, filling them in and returning the completed forms to the server. It has developed from a port of Gisle Aas' Perl module HTML::Form, from the libwww-perl library, but the inte...
rror', 'CheckboxControl', 'Cont
rol', 'ControlNotFoundError', 'FileControl', 'FormParser', 'HTMLForm', 'HiddenControl', 'IgnoreControl', 'ImageControl', 'IsindexControl', 'Item', 'ItemCountError', 'ItemNotFoundError', 'Label', 'ListControl', 'LocateError', 'Missing', 'ParseError', 'ParseFile', 'P...
cthGoman/shrdlite
cgi-bin/ajaxwrapper.py
Python
gpl-3.0
1,269
0.007092
#!/usr/bin/env python from __future__ import print_function import os import cgi from subprocess import Popen, PIPE, STDOUT # Java SCRIPTDIR = 'javaprolog' # SCRIPT = ['/usr/bin/java', '-cp', 'json-simple-1.1.1.jar:gnuprologjava-0.2.6.jar:.', 'Shrdlite'] import platform if pla
tform.system()=='Windows': SCRIPT = ['java', '-cp', 'json-simple-1.1.1.jar;gnuprologjava-0.2.6.jar;.', 'Shrdlite'] else: SCRIPT = ['java', '-cp', 'json-simple-1.1.1.jar:gnuprologjava-0.2.6.jar:.', 'Shrdlite'] # # SWI Prolog # SCRIPTDIR = 'javaprolog' # SCRIPT = ['/usr/local/bin/swipl', '-q', '-g', 'main,halt'...
ython' # SCRIPT = ['/usr/bin/python', 'shrdlite.py'] while not os.path.isdir(SCRIPTDIR): SCRIPTDIR = os.path.join("..", SCRIPTDIR) print('Content-type:text/plain') print() try: form = cgi.FieldStorage() data = form.getfirst('data') script = Popen(SCRIPT, cwd=SCRIPTDIR, stdin=PIPE, stdout=PIPE, stder...
DataDog/integrations-extras
calico/tests/test_e2e.py
Python
bsd-3-clause
492
0
# (C) Datadog, Inc. 2021-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) import pytest from datadog_checks.dev.utils i
mport get_metadat
a_metrics from . import common @pytest.mark.e2e def test_check_ok(dd_agent_check): aggregator = dd_agent_check(rate=True) metrics = common.FORMATTED_EXTRA_METRICS for metric in metrics: aggregator.assert_metric(metric) aggregator.assert_metrics_using_metadata(get_metadata_metrics())
nlloyd/SubliminalCollaborator
libs/twisted/trial/test/test_deferred.py
Python
apache-2.0
8,003
0.00025
from twisted.internet import defer from twisted.trial import unittest from twisted.trial import runner, reporter, util from twisted.trial.test import detests class TestSetUp(unittest.TestCase): def _loadSuite(self, klass): loader = runner.TestLoader() r = reporter.TestResult() s = loader.l...
loader.loadClass(klass) return r, s def test_setUp(self): self.failIf(detests.DeferredSetUpNeverFire.testCalled) result, suite = self._loadSuite(detests.DeferredSetUpNev
erFire) suite(result) self.failIf(result.wasSuccessful()) self.assertEqual(result.testsRun, 1) self.assertEqual(len(result.failures), 0) self.assertEqual(len(result.errors), 1) self.failIf(detests.DeferredSetUpNeverFire.testCalled) self.failUnless(result.errors[0]...
unioslo/cerebrum
Cerebrum/modules/pwcheck/__init__.py
Python
gpl-2.0
1,022
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2015-2016 University of Oslo, Norway # # This file is part of Cerebrum. # # Cerebrum 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...
heck sub-package implements mixins for password checks. Each module in this sub-package provides mixins
that can be used to check if a password is strong enough to be accepted for use. """