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
sdoran35/hate-to-hugs
venv/lib/python3.6/site-packages/nltk/test/gluesemantics_malt_fixt.py
Python
mit
302
0.003311
# -*- coding: utf-8 -*- from __future__ import absolute_import def setup_module(module): from nose import SkipTest
from nltk.parse.malt import MaltParser try: depparser = MaltParser('maltpar
ser-1.7.2') except LookupError: raise SkipTest("MaltParser is not available")
heschlie/taskbuster
functional_tests/test_allauth.py
Python
mit
2,343
0
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from
selenium.common.exceptions import TimeoutException from django.core.urlresolvers import reverse from django.contrib.staticfiles.testing import StaticLiveServerTestCase from django.utils.translation import activate class TestGoogleLogin(StaticLiveServerTestCase): fixtures = ['allauth_fixture'] def setUp(sel...
browser.implicitly_wait(3) self.browser.wait = WebDriverWait(self.browser, 10) activate('en') def tearDown(self): self.browser.quit() def get_element_by_id(self, element_id): return self.browser.wait.until(EC.presence_of_element_located( (...
hmpf/nav
tests/unittests/general/logengine_test.py
Python
gpl-3.0
7,207
0.003746
import datetime import pytest from mock import Mock from unittest import TestCase import random import logging logging.raiseExceptions = False from nav import logengine now = datetime.datetime.now() @pytest.fixture def loglines(): return """ Oct 28 13:15:06 10.0.42.103 1030: Oct 28 13:15:05.310 CEST: %LINEPROT...
def execute(sql, params=()): return sql % params database.execute = execute message = logengine.create_message(line) assert message, "unparseable: %s" % line logengine.insert_message(message, database, {}, {}, {}, {}, {}, {}) def test_swallow_generic_exceptions(): @log...
v.db import driver @logengine.swallow_all_but_db_exceptions def raiser(): raise driver.Error("This is an ex-database") with pytest.raises(driver.Error): raiser() def test_non_failing_function_should_run_fine(): @logengine.swallow_all_but_db_exceptions def nonraiser(input): ...
pytorch/vision
torchvision/models/quantization/shufflenetv2.py
Python
bsd-3-clause
5,067
0.002566
from typing import Any, Optional import torch import torch.nn as nn from torch import Tensor from torchvision.models import shufflenetv2 from ..._internally_replaced_utils import load_state_dict_from_url from .utils import _fuse_modules, _replace_relu, quantize_model __all__ = [ "Quant
izableShuffleNetV2", "shufflenet_v2_x0_5", "shufflenet_v2_x1_0", ] quant_model_urls = { "shufflenetv2_x0.5_fbgemm": "https://download.pytorch.
org/models/quantized/shufflenetv2_x0.5_fbgemm-00845098.pth", "shufflenetv2_x1.0_fbgemm": "https://download.pytorch.org/models/quantized/shufflenetv2_x1_fbgemm-db332c57.pth", } class QuantizableInvertedResidual(shufflenetv2.InvertedResidual): def __init__(self, *args: Any, **kwargs: Any) -> None: super...
tobspr/panda3d
direct/src/showbase/ShowBase.py
Python
bsd-3-clause
123,227
0.004764
""" This module contains ShowBase, an application framework responsible for opening a graphical display, setting up input devices and creating the scene graph. """ __all__ = ['ShowBase', 'WindowControls'] # This module redefines the builtin import function with one # that prints out every import it does in a hierarch...
a window-event. self.__oldAspectRatio = None ## This is set to the value of the window-type config variable, but may ## optionally be overridden in the Showbase constructor. Should either be ## 'onscreen' (the default), 'offscreen' or 'none'. self.windowType = windowType ...
ndow', 1) ## This is the main, or only window; see winList for a list of *all* windows. self.win = None self.frameRateMeter = None self.sceneGraphAnalyzerMeter = None self.winList = [] self.winControls = [] self.mainWinMinimized = 0 self.mainWinForeground...
JoGall/ubitrail
windowsBuild/share/glib-2.0/gdb/gobject.py
Python
gpl-3.0
9,374
0.014508
import gdb import glib import gdb.backtrace import gdb.command.backtrace # This is not quite right, as local vars may override symname def read_global_var (symname): return gdb.selected_frame().read_var(symname) def g_type_to_name (gtype): def lookup_fundamental_type (typenode): if typenode == 0: ...
True while type.code == gdb.TYPE_CODE_TYPEDEF: type = type.target() if type.code != gdb.TYPE_CODE_STRUCT: return False fields = type.fields() if len (fields) < 1: return False first_field = fields[0]
return is_g_type_instance_helper(first_field.type) type = val.type if type.code != gdb.TYPE_CODE_PTR: return False type = type.target() return is_g_type_instance_helper (type) def g_type_name_from_instance (instance): if long(instance) != 0: try: inst = instance.cast ...
devunt/hydrocarbon
board/migrations/0001_squashed_0022_auto_20141229_2347.py
Python
mit
10,743
0.003262
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.db.models.deletion import django.utils.timezone from django.conf import settings def siteconf_func(apps, schema_editor): Site = apps.get_model('sites', 'Site') db_alias = schema_editor.conne...
], options={ 'abstract': Fals
e, 'verbose_name_plural': 'users', 'verbose_name': 'user', }, bases=(models.Model,), ), migrations.RunPython( code=siteconf_func, reverse_code=None, atomic=False, ), migrations.CreateModel( ...
poliastro/poliastro
src/poliastro/core/angles.py
Python
mit
9,195
0.000545
import numpy as np from numba import njit as jit @jit def _kepler_equation(E, M, ecc): return E_to_M(E, ecc) - M @jit def _kepler_equation_prime(E, M, ecc): return 1 - ecc * np.cos(E) @jit def _kepler_equation_hyper(F, M, ecc): return F_to_M(F, ecc) - M @jit def _kepler_equation_prime_hyper(F, M, ec...
Notes ----- This uses a Newton iteration on the hyperbolic Kepler equation. """ F0 = np.arcsinh(M / ecc) F = _newton_hyperbolic(F0, args=(M, ecc), maxiter=100) return F @jit def M_to_D(M): """Parabolic anomaly from mean anomaly. Parameters ---------- M : float Mean an...
_. """ B = 3.0 * M / 2.0 A = (B + (1.0 + B**2) ** 0.5) ** (2.0 / 3.0) D = 2 * A * B / (1 + A + A**2) return D @jit def E_to_M(E, ecc): r"""Mean anomaly from eccentric anomaly. .. versionadded:: 0.4.0 Parameters ---------- E : float Eccentric anomaly in radians. e...
bstdenis/pymerra2
scripts/merra2_subdaily_download.py
Python
apache-2.0
1,774
0.000564
import logging from pathlib import Path from pymerra2 import download # Here we process multiple variables at a time
to avoid downloading # o
riginal data twice (all these variables are in the same files). # These variables names are user choices, their merra-2 equivalent are # specified below or in the default pymerra2_variables.py var_names = ["evspsbl", "huss", "prbc", "tas", "sic", "snw", "uas", "vas", "ps"] var_names = ["hur"] delete_temp_dir = False do...
Finntack/pootle
pootle/apps/accounts/managers.py
Python
gpl-3.0
3,836
0
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django.contrib.auth.models import BaseU...
if check_user_permission(default, permission_code, directory): return self.hide_meta().filter(is_active=True) user_filter = Q( permissionset__positive_permissions__codename=permission_code ) language_path = language.directory.pootle_path p
roject_path = project.directory.pootle_path user_filter &= ( Q(permissionset__directory__pootle_path=directory.pootle_path) | Q(permissionset__directory__pootle_path=language_path) | Q(permissionset__directory__pootle_path=project_path) ) user_filter |= Q(is_...
openstack/nova
nova/tests/functional/regressions/test_bug_1896463.py
Python
apache-2.0
9,311
0.000107
# 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...
_update_available_resource(self): # Create a server with a direct port to have PCI allocation server = self._create_server( name='test-server
-for-bug-1896463', networks=[{'port': self.neutron.sriov_port['id']}], host='host1' ) self._assert_pci_device_allocated(server['id'], self.compute1_id) self._assert_pci_device_allocated( server['id'], self.compute2_id, num=0) # stop and force down th...
elephantum/python-daemon
daemon/runner.py
Python
gpl-2.0
7,087
0.000424
# -*- coding: utf-8 -*- # daemon/runner.py # Part of python-daemon, an implementation of PEP 3143. # # Copyright © 2009 Ben Finney <[email protected]> # Copyright © 2007–2008 Robert Niederreiter, Jens Klein # Copyright © 2003 Clark Evans # Copyright © 2002 Noah Spurrier # Copyright © 2001 Jürgen Hermann # # T...
func(self) def emit_message(message, stream=None): """ Emit a message to the specified stream (default `sys.stderr`). """ if stream is None: stream = sys.stderr stream.write("%(message)s\n" % vars()) stream.flush() def make_p
idlockfile(path, acquire_timeout): """ Make a PIDLockFile instance with the given filesystem path. """ if not isinstance(path, basestring): error = ValueError("Not a filesystem path: %(path)r" % vars()) raise error if not os.path.isabs(path): error = ValueError("Not an absolute path:...
chaluemwut/fbserver
venv/lib/python2.7/site-packages/sklearn/cluster/tests/test_mean_shift.py
Python
apache-2.0
2,844
0
""" Testing for mean shift clustering methods """ import numpy as np from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_false from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_array_equal from sklearn.cluster import MeanShift from sklearn.clu...
ust 6 points in the plane X = np.array([[1., 1.], [1.5, 1.5], [1.8, 1.2], [2., 1.], [2.1, 1.1], [0., 0.]]) # With a bin coarseness of 1.0 and min_bin_freq of 1, 3 bins should be # found ground_truth = set([(1., 1.), (2., 1.), (0., 0.)]) test_bins = get_bin_seeds(X, 1, 1) test_...
sult = set([tuple(p) for p in test_bins]) assert_true(len(ground_truth.symmetric_difference(test_result)) == 0) # With a bin coarseness of 1.0 and min_bin_freq of 2, 2 bins should be # found ground_truth = set([(1., 1.), (2., 1.)]) test_bins = get_bin_seeds(X, 1, 2) test_result = set([tuple(p) ...
jackrzhang/zulip
zerver/tests/test_timestamp.py
Python
apache-2.0
1,871
0.003741
from django.utils.timezone import utc as timezone_utc from zerver.lib.test_classes import ZulipTestCase from zerver.lib.timestamp import floor_to_hour, floor_to_day, ceiling_to_hour, \ ceiling_to_day, timestamp_to_datetime, datetime_to_timestamp, \ TimezoneNotUTCException, convert_to_UTC from datetime import...
eplace(tzinfo=timezone_utc), parser.parse('2017-01-01 00:00:00.123').replace(tzinfo=pytz.utc)]: self.assertEqual(timestamp_to_datetime(timestamp), dt-timedelta(microseconds=123000)) self.assertEqual(datetime_to_ti
mestamp(dt), timestamp) for dt in [ parser.parse('2017-01-01 00:00:00.123+01:00'), parser.parse('2017-01-01 00:00:00.123')]: with self.assertRaises(TimezoneNotUTCException): datetime_to_timestamp(dt) def test_convert_to_UTC(self) -> None: ...
eldarion-gondor/pykube
pykube/exceptions.py
Python
apache-2.0
413
0
""" Exceptions. """ class KubernetesError(Exception): """ Base exception for all Kubernetes errors. """ pass class PyKubeError(KubernetesError): """ PyKube specific errors. """ pass class HTTPError(PyKubeError): def __in
it__(self, co
de, message): super(HTTPError, self).__init__(message) self.code = code class ObjectDoesNotExist(PyKubeError): pass
gnome-keysign/gnome-keysign
tests/test_bluetooth.py
Python
gpl-3.0
6,199
0.001936
import os import logging import select import socket from subprocess import check_call import tempfile import unittest import gi gi.require_version('Gtk', '3.0') from nose.twistedtools import deferred from nose.tools import * from twisted.internet import threads from twisted.internet.defer import inlineCallbacks try:...
key.fingerprint.encode('ascii'), file_key_data) # Start offering the key offer = BluetoothOffer(key) data = yield offer.allocate_code() # getting the code from "BT=code;...." code = data.split("=", 1)[1] code = code.split(";", 1)[0]
port = int(data.rsplit("=", 1)[1]) offer.start() receive = BluetoothReceive(port) msg_tuple = yield receive.find_key(code, hmac) downloaded_key_data, success, _ = msg_tuple assert_true(success) log.info("Checking with key: %r", downloaded_key_data) assert_equal(downloaded_key_data.encode("...
mikisvaz/rbbt-util
python/rbbt.py
Python
mit
109
0.009174
impo
rt warnings import sys import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' def rbbt(): print
("Rbbt")
cliftonmcintosh/openstates
billy_metadata/de.py
Python
gpl-3.0
3,486
0.00918
metadata = { 'name': 'Delaware', 'abbreviation': 'de', 'legislature_name': 'Delaware General Assembly', 'legislature_url': 'http://legis.delaware.gov/', 'capitol_timezone': 'America/New_York', 'chambers': { 'upper': {'name': 'Senate', 'title': 'Senator'}, 'lower': {'name': 'Hous...
ions': ['141'], }, { 'name
': '2003-2004', 'start_year': 2003, 'end_year': 2004, 'sessions': ['142'], }, { 'name': '2005-2006', 'start_year': 2005, 'end_year': 2006, 'sessions': ['143'], }, { 'name': '2007-2008', ...
rushiagr/keystone
keystone/contrib/federation/routers.py
Python
apache-2.0
9,192
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 # distributed under t...
rationExtension(wsgi.V3ExtensionRouter): """API Endpoints for the Federation extension. The API looks like:: PUT /OS-FEDERATION/identity_providers/$identity_provider GET /OS-FEDERATION/identity_providers GET /OS-FEDERATION/identity_providers/$identity_provider DELETE /OS-FEDERA...
oviders/$identity_provider PUT /OS-FEDERATION/identity_providers/ $identity_provider/protocols/$protocol GET /OS-FEDERATION/identity_providers/ $identity_provider/protocols GET /OS-FEDERATION/identity_providers/ $identity_provider/protocols/$protocol ...
steinitzu/aptfinder
aptfinder/web/__init__.py
Python
mit
249
0.004016
from flask import Flask from flask_compress
import Compress from .. import db app = Flask(__name__) app.config.from_pyfile('../config.py') from . import views Compress(app) @app.before_first_request def initialize_database():
db.init_db()
caseman/grease
test/entity_test.py
Python
mit
6,470
0.036012
import unittest import itertools class TestWorld(object): def __init__(self, **kw): self.__dict__.update(kw) self.components = self self.entities = set() self.new_entity_id = itertools.count().__next__ self.new_entity_id() # skip id 0 for comp in list(kw.values()): comp.world = self class TestComp...
self): from grease import Entity world = TestWorld() self.assertEqual(world.entities, set()) e
ntity1 = Entity(world) entity2 = Entity(world) self.assertEqual(world.entities, set([entity1, entity2])) self.assertTrue(entity1.exists) self.assertTrue(entity2.exists) entity1.delete() self.assertEqual(world.entities, set([entity2])) self.assertFalse(entity1.exists) self.assertTrue(entity2.exists) en...
pf4d/dolfin-adjoint
tests_dolfin/viscoelasticity/timings/unannotated.py
Python
lgpl-3.0
7,692
0.00533
__author__ = "Marie E. Rognes ([email protected])" __copyright__ = "Copyright (C) 2012 Marie Rognes" __license__ = "Distribute at will" """ Schematic drawing (starts with 1 springs, starts with 0 dashpots) | A10 --- A00 | ----- | | -------- | A11 | Standard linear solid (SLS) viscoelasti...
S) ic = Function(Z) ic_co
py = Function(ic) # Play forward run info_blue("Running forward ... ") z = main(ic, T=T, dt=dt)
morinim/vita
src/setversion.py
Python
mpl-2.0
2,950
0.004407
#!/usr/bin/env python3 # # Copyright (C) 2017-2020 EOS di Manlio Morini. # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/ # # A python program that helps to set up ...
\g<2>" + new_version + r"\g<4>\n[" + new_version + r"\g<2>\g<3>...v" + new_version
result = re.subn(regex, subst, result[0]) return result[0] if result[1] == 1 else None def doxygen_rule(data, args): regex = r"([\s]+)(\*[\s]+\\mainpage VITA v)([\d]+)\.([\d]+)\.([\d]+)([\s]*)" subst = r"\g<1>\g<2>" + version_str(args) + r"\g<6>" result = re.subn(regex, subst, data) return resu...
rg3/youtube-dl
youtube_dl/extractor/adobepass.py
Python
unlicense
41,407
0.000773
# coding: utf-8 from __future__ import unicode_literals import re import time import xml.etree.ElementTree as etree from .common import InfoExtractor from ..compat import ( compat_kwargs, compat_urlparse, ) from ..utils import ( unescapeHTML, urlencode_postdata, unified_timestamp, ExtractorErr...
ooperative Association' }, 'cns': { 'name': 'CNS'
}, 'com160': { 'name': 'Co-Mo Connect' }, 'coa020': { 'name': 'Coast Communications' }, 'coa030': { 'name': 'Coaxial Cable TV' }, 'mid055': { 'name': 'Cobalt TV (Mid-State Community TV)' }, 'col070': { 'name': 'Columbia Power & Water Systems...
hassanibi/erpnext
erpnext/patches/v7_1/move_sales_invoice_from_parent_to_child_timesheet.py
Python
gpl-3.0
853
0.029308
from __future__
import unicode_literals import frappe def execute(): frappe.reload_doc('projects', 'doctype', 'timesheet_detail') frappe.reload_doc('accounts', 'doctype', 'sales_invoice_timesheet')
frappe.db.sql(""" update `tabTimesheet` as ts, (select sum(billing_amount) as billing_amount, sum(billing_hours) as billing_hours, time_sheet from `tabSales Invoice Timesheet` where docstatus = 1 group by time_sheet ) as sit set ts.total_billed_amount = sit.billing_amount, ts.total_billed_hours =...
agry/NGECore2
scripts/object/tangible/wearables/bracelet/item_bracelet_r_set_officer_dps_01_01.py
Python
lgpl-3.0
1,158
0.022453
import sys def setup(core, object): object.setStfFilename('static_item_n') object.setStfName('item_bracelet_r_set_officer_dps_01_01') object.setDetailFilename('static_item_d') object.setDetailName('item_bracelet_r_set_officer_dps_01_01') object.setStringAttribute('class_required', 'Officer') object.setIntAttribu...
onus:set_bonus_officer_dps_3') object.setAtt
achment('setBonus', 'set_bonus_officer_dps') return
webdev1001/ansible
v2/ansible/plugins/connections/__init__.py
Python
gpl-3.0
1,420
0.000704
# (c) 2012-2014, Michael DeHaan <[email protected]> # # This file is part of Ansible # # Ans
ible 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. # # Ansible 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 P...
tcpcloud/contrail-controller
src/config/common/zkclient.py
Python
apache-2.0
14,983
0.00287
# # Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. # import os import gevent import logging import kazoo.client import kazoo.exceptions import kazoo.handlers.gevent import kazoo.recipe.election from kazoo.client import KazooState from kazoo.retry import KazooRetry from bitarray import bitarray from cfg...
= self._get_bit_from_zk_index(idx) if bit_idx >= 0: self._set_in_use(bit_idx) return id_val # end read def empty(self): return not self._in_use.any() # end empty @classmethod def delete_all(cls, zookeeper_client, path): try: zookeeper...
kazoo.exceptions.NotEmptyError: #TODO: Add retries for NotEmptyError zookeeper_client.syslog("NotEmptyError while deleting %s" % path) # end delete_all #end class IndexAllocator class ZookeeperClient(object): def __init__(self, module, server_list, logging_fn=None): # logging...
Tesora/tesora-tempest
tempest/api/compute/servers/test_create_server.py
Python
apache-2.0
14,903
0
# Copyright 2012 OpenStack Foundation # 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...
server_multi_nics['id']) waiters.wait_for_server_termination(self.client,
server_multi_nics['id']) self.addCleanup(cleanup_server) addresses =
kyleabeauchamp/pymbar
scripts/benchmark_covariance.py
Python
lgpl-2.1
2,091
0.015304
import pandas as pd import numpy as np import pymbar from pymbar.testsystems.pymbar_datasets import load_gas_data, load_8proteins_data import time def load_oscillators(n_states, n_samples): name = "%dx%d oscillators" % (n_states, n_samples) O_k = np.linspace(1, 5, n_states) k_k = np.linspace(1, 3, n_states...
illators.HarmonicOscillatorsTestCase(O_k, k_k) x_n, u_kn, N_k_output, s_n = test.sample(N_k, mode='u_kn') return name, u_kn, N_k_output, s_n def load_expone
ntials(n_states, n_samples): name = "%dx%d exponentials" % (n_states, n_samples) rates = np.linspace(1, 3, n_states) N_k = (np.ones(n_states) * n_samples).astype('int') test = pymbar.testsystems.exponential_distributions.ExponentialTestCase(rates) x_n, u_kn, N_k_output, s_n = test.sample(N_k, mode='...
joefutrelle/pocean-core
pocean/dsg/profile/om.py
Python
mit
7,029
0.001423
# -*- coding: utf-8 -*- from datetime import datetime from collections import namedtuple import netCDF4 as nc4 import numpy as np import pandas as pd from pygc import great_distance from shapely.geometry import Point, LineString from pocean.utils import unique_justseen, normalize_array, generic_masked from pocean.cf...
pocean import logger
class OrthogonalMultidimensionalProfile(CFDataset): """ If the profile instances have the same number of elements and the vertical coordinate values are identical for all instances, you may use the orthogonal multidimensional array representation. This has either a one-dimensional coordinate varia...
cevaris/python-consul-hiera
consul_hiera/utils.py
Python
mit
1,919
0.001042
import fnmatch import os import re import yaml from consul_hiera import ( HieraConfig, HIERARCHY, ) def find_files(directory, pattern='*'): if not os.path.exists(directory): raise ValueError("Directory not found {}".format(directory)) matches = [] for root, dirnames, filenames in os.walk...
pattern): matches.append(os.path.join(root, filename)) return matches def find_files_regex(directory, pattern='.+'): pattern = re.compile(pattern) if not os.path.exists(directory): raise ValueError("Directory not found {}".format(directory)) matches = [] for root, dirnames...
for filename in filenames: full_path = os.path.join(root, filename) if re.search(pattern, full_path): matches.append(os.path.join(root, filename)) return matches def find_yaml_files(directory): return find_files(directory, pattern='*.yaml') def parse_hiera_config(c...
mirimmad/LiveCam
_camera.py
Python
mit
325
0.049231
#Copyright
Mir Immad - RealTimeCam import cv2 import numpy as np class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) def __del__(self): self.video.release() def get_frame(self): success, image = self.video.read()
ret, jpeg = cv2.imencode('.jpg', image) return jpeg.tostring()
seatgeek/businesstime
businesstime/holidays/uk.py
Python
bsd-2-clause
2,093
0
import datetime import json import os from businesstime.holidays import Holidays __all__ = ( 'EnglandHolidays', 'WalesHolidays', 'ScotlandHolidays', 'NorthernIrelandHolidays', ) PWD = os.path.dirname(os.path.realpath(__file__)) DEFAULT_
HOLIDAYS_FILEPATH = os.path.join(PWD, 'data', 'uk-bank-holidays.json') class UKHolidays(Holidays): """ List from https://www.gov.uk/bank-holidays.json e.g. curl https://www.gov.uk/bank-holidays.json -o uk-bank-holidays.json """ DIVISION_CHOICES = ('england-and-wales', 'scotland', 'northern-irelan...
self.DIVISION_CHOICES: raise ValueError( "'division' class attribute must be one of {}. You picked: {}" .format(self.DIVISION_CHOICES, self.division) ) self.holidays = kwargs.pop('holidays', None) holidays_filepath = kwargs.pop('holidays_filepath'...
yeleman/snisi
snisi_reprohealth/aggregations.py
Python
mit
7,786
0.000257
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 nu from __future__ import (unicode_literals, absolute_import, division, print_function) import logging from django.utils import timezone from snisi_core.models.Reporting import (ExpectedReporting, ...
# "Vous devez le valider avant le 25.".format( # entity=agg.entity.display_full_name(), # period=agg.period, #
receipt=agg.receipt) # ) def generate_region_country_reports(period, ensure_correct_date=True): logger.info("Switching to {}".format(period)) if ensure_correct_date: now = timezone.now() if not period.following().includes(now) \ ...
8l/beri
cheritest/trunk/tests/mem/test_lh_unalign.py
Python
apache-2.0
2,215
0.004515
#- # Copyright (c) 2011 Robert N. M. Watson # All rights reserved. # # This software was developed by SRI International and the University of # Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237 # ("CTSRD"), as part of the DARPA CRASH research programme. # # @BERI_LICENSE_HEADER_START@ # # License...
able law or agreed to in writing, Work distributed # under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR # CONDITIONS OF ANY KIND, either express or implied. See the License for the # specific language governing permissions and limitations under the License. # # @BERI_LICENSE_HEADER_END@ # fro...
.a0, self.MIPS.a5, "Unexpected EPC") def test_returned(self): self.assertRegisterEqual(self.MIPS.a1, 1, "flow broken by lh instruction") def test_handled(self): self.assertRegisterEqual(self.MIPS.a2, 1, "lh exception handler not run") def test_exl_in_handler(self): self.assertRegi...
hastern/jelly
cli.py
Python
mit
3,654
0.000274
#!/usr/bin/env python # -*- coding:utf-8 -*- import sys import argparse import collections from functools import wraps import logging # We are assuming, that there is an already configured logger present logger = logging.getLogger(__name__) class CommandLine(object): """Create a command line interface for the...
d(call_buckets.keys()) for weight in call_order: for arg in call_buckets[weight]: params = getattr(args, arg.name.replace("-", "_")) method = getattr(core, arg.method) if params is not None and params != arg.default: if isinstance(p...
se: method() return not args.batch def __init__(self, name, *args, **flags): """The constructor for the CommandLine object. Accepts the same flags as the add_argument function of the ArgumentParser class. The *weight* flag can be used to reorder the e...
jdavidrcamacho/Tests_GP
01 - Trials and attempts/Cheat_attempt/Likelihood.py
Python
mit
3,613
0.036318
# -*- coding: utf-8 -*- """ Created on Mon Oct 10 17:27:49 2016 @author: camacho """ import Kernel;reload(Kernel);kl = Kernel import numpy as np from time import time import inspect as i ##### LIKELIHOOD def likelihood(kernel, x, xcalc, y, yerr): #covariance matrix calculations K = np.zeros((len(x),len(x)))...
dont need no calculation \n We dont need no optimization control' # Nao apliquei a mesma logica às kernels exponential e matern pois #até isto funcionar como deve ser não vale a pena fazer #funcionar como deve ser = saber se estou a calcular o gradiente bem #e arranjar maneira de isto
funcionar com somas e multiplicaçoes de kernels
legoktm/legoktm
icstalker/iclib/scrape.py
Python
mit
695
0.05036
#!usr/bin/python from BeautifulSou
p import BeautifulSoup as bs def schedul
e(text): soup = bs(text) l = soup.body.table.findAll('td', attrs={'class':'scheduleBody'}) final = [] for row in l: if 'portal' in str(row): if row: sp = bs(str(row)) url = sp.a['href'] name = sp.a.b.contents[0] final.append({'url':url,'name':name}) return final def classes(text): soup = bs...
Radagast-red/golem
tests/gui/controller/test_customizer.py
Python
gpl-3.0
1,855
0.001078
import unittest import tempfile import os from mock import Mock, patch from gui.controller.customizer import Customizer class TestCustomizer(unittest.TestCase): def test_init(self): customizer = Customizer(Mock(), Mock()) self.assertIsInstance(customizer, Customizer) @patch("gui.controller....
os.remove(file_name) @patch('gui.c
ontroller.customizer.QMessageBox') def test_show_warning_window(self, mock_messagebox): mock_messagebox.return_value = mock_messagebox customizer = Customizer(Mock(), Mock()) customizer.show_warning_window("Test warning message") assert mock_messagebox.exec_.called
applicationdevm/XlsxWriter
xlsxwriter/test/comparison/test_comment10.py
Python
bsd-2-clause
1,144
0
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2015, John McNamara, [email protected] # from ..excel_comparsion_test import ExcelComparisonTest from
...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.maxDiff = None filename = 'comment10.xlsx' test_dir = 'xlsxwriter/test/comparison/' self.got_f...
self.ignore_files = [] self.ignore_elements = {} def test_create_file(self): """Test the creation of a simple XlsxWriter file with comments.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() worksheet.write('A1', 'Foo') workshe...
mementum/backtrader
tests/test_ind_oscillator.py
Python
gpl-3.0
1,764
0
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2020 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
plot=main, chkind=chkind, chkmin=chkmin,
chkvals=chkvals) if __name__ == '__main__': test_run(main=True)
SpencerBelleau/glyptodon
modules/scanner.py
Python
mit
1,018
0.018664
import os, sys, hashlib, random, time from functions import * from helpers import * working_dir = os.getcwd() args = sys.argv package = 0 if(os.path.isfile(args[1])): package = open(args[1], 'rb') else: sys.exit(-1) IV = package.read(64) key = setupKey(args[2], IV) checksum = list(applyXOR(bytearray(package.read(1...
Index < len(directory)): fnLength = directory[dirIndex] dirIndex = dirIndex+1 name = "" for i in range(fnLength): name = name + chr(directory[dirIndex])
dirIndex = dirIndex+1 size = [] for i in range(4): size.append(directory[dirIndex]) dirIndex = dirIndex+1 size = readSizeBytes(size) print("> " + name)
UAVCAN/gui_tool
uavcan_gui_tool/widgets/bus_monitor/window.py
Python
mit
16,283
0.002211
# # Copyright (C) 2016 UAVCAN Development Team <uavcan.org> # # This software is distributed under the terms of the MIT License. # # Author: Pavel Kirienko <[email protected]> # import datetime import time import os from functools import partial import pyuavcan_v0 from pyuavcan_v0.driver import CANFrame from ...
ame == 'Data Hex': payload = bytes([int(x, 16) for x in item.split()]) if col_spec.name == 'Dir': direction = item.strip() assert all(map(lambda x: x is not None, [can_id, payload, extended, direction])) return CANFrame(can_id, payl
oad, extended, ts_monotonic=-1, ts_real=-1), direction class BusMonitorWindow(QMainWindow): DEFAULT_PLOT_X_RANGE = 120 BUS_LOAD_PLOT_MAX_SAMPLES = 50000 def __init__(self, get_frame, iface_name): super(BusMonitorWindow, self).__init__() self.setWindowTitle('CAN bus monitor (%s)' % iface_n...
zolyomiake/400
rle_coder.py
Python
gpl-3.0
3,975
0.000755
from operator import itemgetter import logging def test_coder(): # original = [1,2,3,3,3,4,18,18,2,3,4,4,4,5] # original = [1, 2, 3, 3, 3, 4, 18, 18, 2, 3, 4, 4, 4, 5, 44, 44, 45, 46, 46, 46, 49, 49, 49, 45] original = [1, 2, 0, 0, 0, 0, 3, 3, 3, 4, 18, 18, 2, 3, 4, 4, 4, 5, 44, 44, 45, 46, 46, 46, 49, 4...
har = chr(ord(char) - 182) if len(number_str) != 0: repeat = int(number_str) number_str = ''
for i in range(0, repeat): numbers.append(ord(char)) else: numbers.append(ord(char)) return numbers def rle_encode_as_str(memberships): last_member = None repeats = 0 rle_str = '' # work_array = memberships[:100] rep_dict = dict() ...
DevEd2/DevSound
demo/makegbs.py
Python
mit
508
0.007874
# makegbs.py - create GBS file from DevSound_GBS.gb # open files ROMFile = open("DevSound_GBS.gbc", "rb") # demo ROM OutFile = open("DevSound.gbs", "wb") # output file # f
ind end of data endpos = ROMFile.seek(-1,2) + 2 while endpos >= 0x4000: if ROMFile.read(1)[0] != 0xff: break; ROMFile.seek(-2,1) endpos -= 1 # copy song data RO
MFile.seek(0x3f90) OutFile.write(ROMFile.read(endpos - 0x3f90)) # write song data # close files ROMFile.close() OutFile.close()
tutorcruncher/morpheus
src/ext.py
Python
mit
3,555
0.003094
import json import logging from foxglove import glove from httpx import Response from .settings import Settings logger = logging.getLogger('ext') def lenient_json(v): if isinstance(v, (str, bytes)): try: return json.loads(v) except (ValueError, TypeError): pass return...
: def __init__(self, root_url, settings: Settings): self.settings = settings self.root = root_url.rstrip('/') + '/'
async def get(self, uri, *, allowed_statuses=(200,), **data) -> Response: return await self._request('GET', uri, allowed_statuses=allowed_statuses, **data) async def delete(self, uri, *, allowed_statuses=(200,), **data) -> Response: return await self._request('DELETE', uri, allowed_statuses=allowed...
carolFrohlich/nipype
nipype/interfaces/freesurfer/tests/test_auto_MRISPreproc.py
Python
bsd-3-clause
2,331
0.02145
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from ....testing import assert_equal from ..model import MRISPreproc def test_MRISPreproc_inputs(): input_map = dict(args=dict(argstr='%s', ), environ=dict(nohash=True, usedefault=Tru
e, ), fsgd_file=dict(argstr='--fsgd %s', xor=(u'subjects', u'fsgd_file', u'subject_file'), ), fwhm=dict(argstr='--fwhm %f', xor=[u'num_iter
s'], ), fwhm_source=dict(argstr='--fwhm-src %f', xor=[u'num_iters_source'], ), hemi=dict(argstr='--hemi %s', mandatory=True, ), ignore_exception=dict(nohash=True, usedefault=True, ), num_iters=dict(argstr='--niters %d', xor=[u'fwhm'], ), num_iters_source=dict(args...
acsone/knowledge
attachment_lock/tests/test_attachment_lock.py
Python
agpl-3.0
1,537
0
# -*- coding: utf-8 -*- # Copyright 2018 Therp BV <https://therp.nl> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from base64 import b64encode from openerp.tests.common import TransactionCase from openerp.exceptions import AccessError, ValidationError class TestAttachmentLock(TransactionCase)...
rtRaises(AccessError): testattachment.sudo(demo).lock() testattachment.unlock() self.assertTrue(testattachment.sudo(demo).can_lock) testattachment.sudo(demo).lock() self.assertTrue(testattachment.sudo(de
mo).can_lock) self.assertTrue(testattachment.sudo(demo).locked)
srfraser/services
src/releng_treestatus/releng_treestatus/config.py
Python
mpl-2.0
331
0
# -*- codin
g: utf-8 -*- # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from __future__ import absolute_import PROJECT_NAME = 'releng-treestatus' APP_NAME = 'releng_tre
estatus'
mozillazg/django-simple-projects
projects/pagination/hello/models.py
Python
mit
157
0
from django.db import models class Topic(models.Model):
title = models.CharField(max_length=200) def __unicode__(s
elf): return self.title
PARINetwork/pari
article/migrations/0010_add_show_modular_content_field.py
Python
bsd-3-clause
445
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import mig
rations, models class Migration(migrations.Migration): dependencies = [ ('article', '0009_add_stream_fields_for_modular_article_content'), ] operations = [ migrations.AddField( model_name='article', name='show_modular_content', field=models
.BooleanField(default=False), ), ]
aestrivex/PySurfer
examples/plot_label_foci.py
Python
bsd-3-clause
1,955
0.001023
""" ======================= Generate Surface Labels ======================= Define a label that is centered on a specific vertex in the surface mesh. Plot that label and the focus that defines its center. """ print __doc__ from surfer import Brain, utils subject_id = "fsaverage" """ Bring up the visualization. """...
white", coord_as_vert=True) brain.add_label('example_data/coord-lh.label', color='royalblue', alpha=.8) """ No
w we plot the foci on the inflated surface. We will map the foci onto the surface by finding the vertex on the "white" mesh that is closest to the coordinate of the point we want to display. """ brain.add_foci([coord], map_surface="white", coords_as_verts=True, color="mediumblue") """ Set the camera po...
GoogleCloudPlatform/cloud-opensource-python
compatibility_server/configs.py
Python
apache-2.0
9,653
0
# Copyright 2018 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, s...
, 'google-cloud-firestore', 'google-cloud-iam', 'google-cloud-iot',
# 'google-cloud-irm', # unreleased 'google-cloud-kms', 'google-cloud-language', 'google-cloud-logging', 'google-cloud-monitoring', 'google-cloud-os-login', # 'google-cloud-phishing-protection', # unreleased 'google-cloud-pubsub', 'google-cloud-redis', 'google-cloud-resource-manage...
antoinecarme/pyaf
tests/model_control/detailed/transf_None/model_control_one_enabled_None_MovingAverage_Seasonal_Second_AR.py
Python
bsd-3-clause
156
0.051282
import tests.model_control.test_ozone_custom_models_enabled as testmod testmod.build_model( ['None'] , ['MovingAverage'] , ['Seasonal_Second']
, ['AR'] );
OpusVL/Odoo-UK-Format-Reports
UK_Reports/__init__.py
Python
agpl-3.0
1,037
0
# -*- coding: utf-8 -*- ############################################################################## # # UK Report Template # Copyright (C) 2015 OpusVL (<http://opusvl.com/>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # pu...
u.org/licenses/>. # ############################################################################## import report import account_invoice import sale_order # vim:expandtab:sma
rtindent:tabstop=4:softtabstop=4:shiftwidth=4:
sjsucohort6/openstack
python/venv/lib/python2.7/site-packages/cinderclient/v2/qos_specs.py
Python
mit
4,789
0
# Copyright (c) 2013 eBay Inc. # Copyright (c) OpenStack 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 applicab...
""" return self._get("/qos-specs/%s" % base.getid(qos_specs), "qos_specs")
def delete(self, qos_specs, force=False): """Delete a specific qos specs. :param qos_specs: The ID of the :class:`QoSSpecs` to be removed. :param force: Flag that indicates whether to delete target qos specs if it was in-use. """ self._delete("/qos-spe...
osgee/django-web-demo
webdemo/views.py
Python
apache-2.0
1,352
0.005917
from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.core.urlresolvers import reverse from django.template import RequestContext, loader from django.views.decorators.csrf import csrf_exempt def index(request): template = loader.get_template('index.html') re...
xt)) @csrf_exempt def predict(request): result=5 try: img=request.POST['img'] except KeyError: # Redisplay the question voting form. # return render(request, 'polls/detail.html', { # 'question': p, # 'error_message': "You didn't select a choice.", ...
fully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. # return HttpResponseRedirect(reverse('polls:results', args=(p.id,))) return HttpResponse("Your predict is %s." % result) # pass # name = request.POST.get('name') ...
opennode/nodeconductor-assembly-waldur
src/waldur_core/server/base_settings.py
Python
mit
9,157
0.001092
""" Django base settings for Waldur Core. """ from datetime import timedelta import locale # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os import warnings from waldur_core.core import WaldurExtension from waldur_core.core.metadata import WaldurConfiguration from waldur_core.server.adm...
, }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] ANONYMOUS_USER_ID = None TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates',...
'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.i18n', ...
alfredgamulo/cloud-custodian
tests/test_cli.py
Python
apache-2.0
21,634
0.001433
# Copyright The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 import json import os import sys from argparse import ArgumentTypeError from datetime import datetime, timedelta from c7n import cli, version, commands from c7n.resolver import ValuesFrom from c7n.resources import aws from c7n.schema impor...
stdout, stderr = self.run_and_expect_success([ "custodian", "schema", "--outline", "--json", "aws"]) data = json.loads(stdout)
self.assertEqual(list(data.keys()), ["aws"]) self.assertTrue(len(data['aws']) > 100) self.assertEqual( sorted(data['aws']['aws.ec2'].keys()), ['actions', 'filters']) self.assertTrue(len(data['aws']['aws.ec2']['actions']) > 10) def test_schema_alias(self): stdout, st...
cjaymes/pyscap
src/scap/model/oval_5/defs/windows/Process58TestElement.py
Python
gpl-3.0
896
0.001116
# Copyright 2016 Casey Jaymes # This file is part of PySCAP. # # PySCAP 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. # # PySCAP 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 PySCAP. If not, see <http://www.gnu.org/licenses/>. import logging from...
futurecolors/gopython3
gopython3/api/tests/test_unit.py
Python
mit
7,904
0.006832
# coding: utf-8 import datetime import pytz from django.test import TestCase from httpretty import HTTPretty from api.pypi import PyPI from api.travis import TravisCI from api.github import Github class APITestCase(TestCase): def setUp(self): HTTPretty.reset() HTTPretty.enable() def tearDown(...
, ) assert Github().get_most_popular_repo('Fake_Requests') == 'kennethreitz/fake_requests' def test_get_repo_info(self): HTTPretty.register_uri(HTTPretty.GET, 'https://api.github.com/repos/coagulant/coveralls-python', '{"html_url": "https://github.com/coagulant/cover...
eralls-python') == { "html_url": "https://github.com/coagulant/coveralls-python", "updated_at": datetime.datetime(2013, 1, 26, 19, 14, 43, tzinfo=pytz.utc) } def test_crawl_py3_issues(self): HTTPretty.register_uri(HTTPretty.GET, 'https://api.github.com/repos/embe...
ssdi-drive/nuxeo-drive
nuxeo-drive-client/nxdrive/engine/next/processor.py
Python
lgpl-2.1
4,670
0.004497
# coding: utf-8 import os import shutil from nxdrive.client.base_automation_client import DOWNLOAD_TMP_FILE_PREFIX, \ DOWNLOAD_TMP_FILE_SUFFIX from nxdrive.engine.processor import Processor as OldProcessor from nxdrive.logging_config import get_logger log = get_logger(__name__) class Processor(OldProcessor): ...
._thread_id) # Postpone pair for watcher delay self._engine.get_queue_manager().postpone_pair(result, self._engine.get_local_watcher().get_scan_delay()) return None log.warning("Acquired: %r", result) return resul
t def _get_partial_folders(self): local_client = self._engine.get_local_client() if not local_client.exists('/.partials'): local_client.make_folder('/', '.partials') return local_client.abspath('/.partials') def _download_content(self, local_client, remote_client, doc_pair,...
TinghuiWang/ActivityLearning
actlearn/feature/sensorCount.py
Python
bsd-3-clause
1,358
0.002946
from .AlFeatureTemplate import AlFeatureTemplate from .sensorCountRoutine import AlFeatureSensorCountRoutine import numpy as np class AlFeatureSensorCount(AlFeatureTemplate): def __init__(self, normalize=False): """ Initialization of Template Class :return: """ AlFeatureTe...
name='senso
rCount', description='Number of Events in the window related to the sensor', per_sensor=True, enabled=True, routine=AlFeatureSensorCountRoutine()) # Normalize the number be...
d4rkl0rd3r3b05/Firewall
Firewall/syndelcnsl.py
Python
mit
5,853
0.075688
from Tkinter import * import os import tkMessageBox class syndelcnsl: def show(self,mainfrm): #-----------------------------------------This is mainframe-------------------------------------------- syndelfrm=Frame(mainfrm,relief=SOLID,borderwidth=1,bg="white") txtfont=("FreeSerif", 11,"bold") fnt=("Fre...
ck(expand=YES,fill=BOTH) #------------------------------------------Action-------------------------------------------------- #Action frame actfrm=Frame(syndelfrm,bg="white") #Action label actlbl=Label(actfrm,text="Action"+"\t"*4,font=fnt,relief=FLAT,wid
th=24,bg="white") actlbl.pack(side=LEFT,pady=4) #chain options self.act=StringVar() self.act.set("REJECT") actopt = OptionMenu(actfrm,self.act,"REJECT", "DROP", "LOG","ACCEPT","RETURN") actopt["bg"]="white" actopt["font"]=fntopt actopt["width"]=18 actopt.pack(side=RIGHT) actfrm.pack(e...
jeppeter/pytest
testing/test_core.py
Python
mit
21,642
0.002726
import pytest, py, os from _pytest.core import PluginManager from _pytest.core import MultiCall, HookRelay, varnames class TestBootstrapping: def test_consider_env_fails_to_import(self, monkeypatch): pluginmanager = PluginManager() monkeypatch.setenv('PYTEST_PLUGINS', 'nonexisting', prepend=",") ...
pp.getplugins() assert a1 in l assert a2 in l assert pp.getplugin('hello') == a2 pp.unregister(a1) assert not pp.isregistered(a1) pp.unregister(name="hello") assert not pp.isregistered(a2) def test_pm_ordering(self): pp = PluginManager() class...
ster(a2, "hello") l = pp.getplugins() assert l.index(a1) < l.index(a2) a3 = A() pp.register(a3, prepend=True) l = pp.getplugins() assert l.index(a3) == 0 def test_register_imported_modules(self): pp = PluginManager() mod = py.std.types.ModuleType("x.y...
rven/odoo
addons/sale_stock/wizard/stock_rules_report.py
Python
agpl-3.0
594
0.005051
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class StockRulesReport(models.TransientModel): _inherit = 'stock.rules.report' so_route_ids = fields.Many2many('stock.location.route', string='Apply specific routes', ...
data['so_route_ids'] = self.so_rou
te_ids.ids return data
PeachyPrinter/peachyinstaller
windows/test/test_application_remove.py
Python
apache-2.0
6,117
0.003923
import unittest import logging import os import sys from helpers import TestHelpers sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..',)) sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src')) from application_remove import RemoveApplication from action_handler import ActionHandlerExce...
ks = [arg[0][0] for arg in status_cb.call_args_list] self.assertEqual(expected_callbacks, callbacks) def test_start_does_not_delete_app_when_missing(self, mock_rmtree, mock_remove, mock_isdir, mock_isfile): app = self.get_application() mock_isdir.return_value = False mock_isfile.ret...
status_cb = MagicMock() expected_callbacks = ["Initializing", "Removing Application", "Application Not Found", "Removing Shortcut", "Cleaning up install history", "Finished Removing Files"] RemoveApplication(app, status_cb).start() mock_isdir.assert_called_once_with(app.installed_path) ...
davidbarkhuizen/sdmm
django_web_server/sitemodel/frp/interface.py
Python
gpl-2.0
7,900
0.035443
import random import json from django.db import connection from django.conf import settings from sitemodel.interface import SiteInterface, SiteModel, random_str from django.core.files import File from server.models import Site, TextUpload, BinaryUpload from sitemodel.frp.model import FRP_Category, FRP_Contact, FRP...
contact = contacts['contacts'][i] print(contact) db_contact = FRP_Contact(name=contact['name'], email=contact['email'], phone=contact['phone'], isprimary=contact['isprimary'], iscc=contact['iscc'] ) db_contact.save() for category in contact['categories']: db_category = FRP_...
ct.categories.add(db_category) db_contact.save() # PROPERTIES BY CATEGORY # for category in FRP_Category.objects.all(): # PROPERTIES try: to_import = load_as_json(category.name + '.json') except IOError as e: continue for prop in to_import['properties']: db_property = FRP_Property(catego...
clld/tsammalex
tsammalex/interfaces.py
Python
apache-2.0
139
0
from zope.inte
rface import Interface class IEcoregion(In
terface): """marker """ class IImage(Interface): """marker """
BillyAbildgaard/RackHD
test/fit_tests/tests/switch/test_rackhd11_switch_pollers.py
Python
apache-2.0
13,050
0.004291
''' Copyright 2016, EMC, Inc. Author(s): FIT test script template ''' import sys import subprocess import pprint # set path to common libraries sys.path.append(subprocess.check_output("git rev-parse --show-toplevel", shell=True).rstrip("\n") + "/test/fit_tests/common") import fit_common import test_api_utils # LOC...
m, subitem + ' field error') if fit_common.VERBOSITY >= 2: print "\nNode: ", node poller_dict = test_api_utils.get_supported_pollers(node) for poller in poller_dict: poller_id = poller_dict[poller]["poller_id"] poll_data = fit_common.ra...
1/pollers/" + poller_id) if fit_common.VERBOSITY >= 2: print "\nPoller: " + poller + " ID: " + str(poller_id) print fit_common.json.dumps(poll_data['json'], indent=4) def test_verify_poller_headers(self): if fit_common.VERBOSITY >= 2: msg ...
ooici/marine-integrations
mi/dataset/driver/ctdpf_ckl/wfp_sio_mule/driver.py
Python
bsd-2-clause
7,545
0.004374
""" @package mi.dataset.driver.ctdpf_ckl.wfp_sio_mule.driver @file marine-integrations/mi/dataset/driver/ctdpf_ckl/wfp_sio_mule/driver.py @author cgoodrich @brief Driver for the ctdpf_ckl_wfp_sio_mule Release notes: Initial Release """ __author__ = 'cgoodrich' __license__ = 'Apache 2.0' import os from mi.core.log i...
_WFP_SIO_MULE), self._data_callback, self._sample_exception_callback ) else: raise ConfigurationException('Bad Configuration: %s - Failed to build ctdpf_ckl_wfp parser', config) return parser def _build_harvester(self, driver_state): ...
harvesters = [] # list of harvesters to be returned # # Verify that the CTDPF_CKL_WFP harvester has been configured. # If so, build the CTDPF_CKL_WFP harvester and add it to the # list of harvesters. # if DataTypeKey.CTDPF_CKL_WFP in self._harvester_config: ...
h-2/seqan
core/apps/razers2/tests/run_tests.py
Python
bsd-3-clause
12,963
0.003857
#!/usr/bin/env python """Execute the tests for the razers2 program. The golden test outputs are generated by the script generate_outputs.sh. You have to give the root paths to the source and the binaries as arguments to the program. These are the paths to the directory that contains the 'projects' directory. Usage:...
program=path_to_program, redir_stdout=ph.outFile('se-adeno-reads%d_1-id.stdout' % rl), args=['--low-memory', '-id', ph.inFile('adeno-genome.fa'), ph.inFile('adeno-reads%d_1.fa' % rl), '-o', ph.outFile('se-adeno-reads%d_1-id.razers' ...
zers' % rl)), (ph.inFile('se-adeno-reads%d_1-id.stdout' % rl), ph.outFile('se-adeno-reads%d_1-id.stdout' % rl))]) conf_list.append(conf) # Compute forward/reverse matches only. for o in ['-r', '-f']: conf = app_tests.TestConf( ...
scottynomad/spoonerist
spoonerist/__init__.py
Python
apache-2.0
65
0
f
rom spoonerist.data impo
rt pairs from spoonerist.app import app
GabrieleNunez/fofix
fofix/game/Dialogs.py
Python
gpl-2.0
87,557
0.01125
##################################################################### # -*- coding: iso-8859-1 -*- # # # # Frets on Fire # # Copyright (C) 2006 Sami Kyöstilä ...
t("game", "drum_navigation") #MFH def shown(self): self.engine.input.addKeyListener(self, priority = True) self.engine.input.enableKeyRepeat() def hidden(self): self.engine.input.removeKeyListener(self) self.engine.input.disableKeyRepeat() def keyPressed(self, key, unic...
e.input.controls.getMapping(key) if key == pygame.K_BACKSPACE and not self.accepted: self.text = self.text[:-1] elif unicode and ord(unicode) > 31 and not self.accepted: self.text += unicode elif key == pygame.K_LSHIFT or key == pygame.K_RSHIFT: return True ...
wangjiaxi/django-dynamic-forms
dynamic_forms/fields.py
Python
bsd-3-clause
3,454
0.000579
# -*- coding: utf-8 -*- from __future__ import unicode_literals import six from django.core.exceptions import ValidationError from django.db import models from django.forms import CheckboxSelectMultiple from django.utils.text import capfirst from dynamic_forms.forms import MultiSelectFormField class TextMultiSelect...
ces=''): if not arr_choices: return False chces = [] for choice_selected in arr_choices: chces.append(choice_selected[0]) return chces def get_prep_value(self, value): return value def to_python(self, value): if value is not None: ...
ef validate(self, value, model_instance): """ :param callable convert: A callable to be applied for each choice """ arr_choices = self.get_choices_selected(self.get_choices_default()) for opt_select in value: if opt_select not in arr_choices: raise Val...
ryandub/skew
skew/resources/aws/elb.py
Python
apache-2.0
1,155
0
# Copyright (c) 2014 Scopely, Inc. # Copyright (c) 2015 Mitch Gar
naat # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at #
# http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. from sk...
aaxelb/osf.io
osf/migrations/0006_add_jsonb_index_for_fileversions.py
Python
apache-2.0
765
0.001307
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2017-04-03 20:50 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('osf', '0005_merge'), ] operations = [ migr
ations.RunSQL( [ """ CREATE INDEX fileversion_metadata_sha_arch_vault_index ON osf_fileversion ((osf_fileversion.metadata -> 'sha256'), (osf_fileversion.metadata -> 'archive'), ( osf_fileversion.metadata -> 'vault')); """ ...
; """ ] ) ]
tengqm/senlin-container
senlin/tests/tempest_tests/config.py
Python
apache-2.0
1,284
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 # distributed under...
title="Available OpenStack Services") ServiceAvailableGroup = [ cfg.BoolOpt("senlin", default=True,
help="Whether or not senlin is expected to be available"), ] clustering_group = cfg.OptGroup(name="clustering", title="Clustering Service Options") ClusteringGroup = [ cfg.StrOpt("catalog_type", default="clustering", help="Catalog type of th...
jokajak/itweb
data/env/lib/python2.6/site-packages/distribute-0.6.14-py2.6.egg/setuptools/tests/test_packageindex.py
Python
gpl-3.0
3,722
0.002149
"""Package Index Tests """ # More would be better! import sys import os, shutil, tempfile, unittest, urllib2 import pkg_resources import setuptools.package_index from server import IndexServer class TestPackageIndex(unittest.TestCase): def test_bad_urls(self): index = setuptools.package_index.PackageIndex...
e package page. - someone reuploads the package (with a different md5) - while easy_installing, an MD5 error occurs because the external link is used -> Distribute should use the link from pypi, not the external one. """ # start an index server server =
IndexServer() server.start() index_url = server.base_url() + 'test_links_priority/simple/' # scan a test index pi = setuptools.package_index.PackageIndex(index_url) requirement = pkg_resources.Requirement.parse('foobar') pi.find_packages(requirement) server.stop(...
jonaustin/advisoryscan
django/django/contrib/localflavor/jp/jp_prefectures.py
Python
mit
2,057
0
from django.utils.translation import gettext_lazy as gettext_lazy JP_PREFECTURES = ( ('hokkaido', gettext_lazy('Hokkaido'),), ('aomori', gettext_lazy('Aomori'),), ('iwate', gettext_lazy('Iwate'),), ('miyagi', gettext_lazy('Miyagi'),), ('akita', gettext_lazy('Akita'),), ('yamagata', gettext_lazy...
,), ('mie', gettext_lazy('Mie'),), ('shiga', gettext_lazy('Shiga'),), ('kyoto', gettext_lazy('Kyoto'),), ('osaka', gettext_lazy('Osaka'),), ('hyogo', gettext_lazy('Hyogo'),), ('nara', gettext_lazy('Nara'),), ('wakayama', gettext_lazy('Wakayama'),), ('tottori', gettext_lazy('Tottori'),), ...
ne'),), ('okayama', gettext_lazy('Okayama'),), ('hiroshima', gettext_lazy('Hiroshima'),), ('yamaguchi', gettext_lazy('Yamaguchi'),), ('tokushima', gettext_lazy('Tokushima'),), ('kagawa', gettext_lazy('Kagawa'),), ('ehime', gettext_lazy('Ehime'),), ('kochi', gettext_lazy('Kochi'),), ('fuk...
besm6/micro-besm
doc/opcodes/opcode.py
Python
mit
1,130
0.006195
#!/usr/bin/python # # Manage JSON database of Micro-BESM opcodes. # import sys, json, codecs # Check parameters. if len(sys.argv) != 2: print "Usage:" print " opcode [option] file.json" print "Options:" print " TODO" sys.exit(1) opcode = [] # List of all opcodes # # Proc...
ata(filename) write_results("output.json") # # Load opcode[] from JSON file. # def read_data(filename): global opcode try: file = open(filename) opcode = json.load(file) file.close() except: print "Fatal error: Cannot load file '" + filename + "'" sys.exit(1) ...
write_results(filename): file = codecs.open(filename, 'w', encoding="utf-8") json.dump(opcode, file, indent=4, sort_keys=True, ensure_ascii=False) file.close() print "Write file %s: %d opcodes" % (filename, len(opcode)) if __name__ == "__main__": main(sys.argv[1])
AstroTech/atlassian-python-api
atlassian/bitbucket/cloud/base.py
Python
apache-2.0
3,104
0.002255
# coding=utf-8 from ..base import BitbucketBase class BitbucketCloudBase(BitbucketBase): def __ini
t__(self, url, *args, **kwargs): """ Init the rest api wrapper :param url: string: The base url used for the rest api. :param *args: list: The fixed arguments for the AtlassianRestApi. :param **kwargs: dict: The keyword arguments for the AtlassianRestApi. :return:...
""" expected_type = kwargs.pop("expected_type", None) super(BitbucketCloudBase, self).__init__(url, *args, **kwargs) if expected_type is not None and not expected_type == self.get_data("type"): raise ValueError("Expected type of data is [{}], got [{}].".format(expected_type, se...
ESSolutions/ESSArch_Core
ESSArch_Core/api/forms/widgets.py
Python
gpl-3.0
605
0
from django import forms class Multipl
eTextWidget(forms.widgets.Widget): template_name = 'django/forms/widgets/text.html' def format_value(self, value): """Return selected values as a list.""" if value is None: return [] if not isinstance(value, (tuple, list)): value = [value] return [str(v) ...
try: getter = data.getlist except AttributeError: pass return getter(name)
gmalmquist/pants
tests/python/pants_test/pantsd/test_process_manager.py
Python
apache-2.0
16,494
0.01352
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import errno import ...
c, k), 'return_value', v) for k, v in kwargs.items()] return proc class TestProcessGroup(BaseTest): def setUp(self): super(TestProcessGroup, self).setUp() self.pg = ProcessGroup('test', metadata_base_dir=self.subprocess_dir) def test_swallow_psutil_exceptions(self): with swallow_psutil_exceptions()...
st') def test_iter_processes(self): with mock.patch('psutil.process_iter', **PATCH_OPTS) as mock_process_iter: mock_process_iter.return_value = [5, 4, 3, 2, 1] items = [item for item in self.pg.iter_processes()] self.assertEqual(items, [5, 4, 3, 2, 1]) def test_iter_processes_filtered(self):...
sniperganso/python-manilaclient
manilaclient/v2/share_instances.py
Python
apache-2.0
3,686
0
# Copyright 2015 Mirantis 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...
, instance, info=None, **kwargs): """Perform a share instnace 'action'. :param action: text with action name. :param instance: either share object or text with its ID. :param info: dict with data for specified 'action'. :param kwargs: dict with data to be provided for action hoo...
modify_body_for_action', body, **kwargs) url = '/share_instances/%s/action' % common_base.getid(instance) return self.api.client.post(url, body=body) def _do_force_delete(self, instance, action_name="force_delete"): """Delete a share instance forcibly - share status will be avoided. ...
miloszz/DIRAC
Resources/Computing/ARCComputingElement.py
Python
gpl-3.0
10,864
0.030836
######################################################################## # File : ARCComputingElement.py # Author : A.T. ######################################################################## """ ARC Computing Element """ __RCSID__ = "58c42fc (2013-07-07 22:54:57 +0200) Andrei Tsaregorodtsev <[email protected]>" ...
et the status information for the given list of jobs """ workingDirectory = self.ceParameters['WorkingDirectory'] fd, name = tempfile.mkstemp( suffix = '.list', prefix = 'StatJobs_', dir = workingDirectory ) jobL
istFile = os.fdopen( fd, 'w' ) jobTmpList = list( jobIDList ) if type( jobIDList ) in StringTypes: jobT
Schamnad/cclib
test/method/testpopulation.py
Python
bsd-3-clause
3,489
0.00172
# -*- coding: utf-8 -*- # # Copyright (c) 2016, the cclib development team # # This file is part of cclib (http://cclib.github.io) and is distributed under # the terms of the BSD 3-Clause License. """Test the various population analyses (MPA, LPA, CSPA) in cclib""" from __future__ import print_function im...
PA(self.data) self.analysis.logger.setLevel(0) self.analysis.calculate() def testsumcharges(self): """Do the Lowdin charges sum up to the total formal charge?""" formalcharge = sum(self.data.atomnos) - self.data.charge totalpopulation = sum(self.analysis.fragcharges) ...
ns(self): """Do the Lowdin spins sum up to the total formal spin?""" formalspin = self.data.homos[0] - self.data.homos[1] totalspin = sum(self.analysis.fragspins) self.assertAlmostEqual(totalspin, formalspin, delta=1.0e-3) class GaussianCSPATest(unittest.TestCase): """C-squ...
pekimmoche/AudioExperiment
tests/test_wave_generator.py
Python
gpl-3.0
413
0.002421
from unittest import TestCase import matplotlib.pyplot as plt from wave_generator import WaveGener
ator class TestWaveGenerator(TestCase): def test_sin(self): length = 44100 sin1000 = WaveGenerator.sin(10000, 1000, 0, length) self.assertEqual(0, sin1000[0]) self.assertEqual(9999.4290856537190, sin1000[44067]) self.assertEqual(len(
sin1000), length)
Metaswitch/calico-nova
nova/openstack/common/service.py
Python
apache-2.0
15,254
0
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2011 Justin Santa Barbara # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance wi...
status, signo = self._wait_for_exit_or_signal(ready_callback) if not _is_sighup_and_daemon(signo): return status self.restart() class ServiceWrapper(object): def __init__(self, service, workers): self.service = service self.workers = workers ...
essLauncher(object): def __init__(self, wait_interval=0.01): """Constructor. :param wait_interval: The interval to sleep for between checks of child process exit. """ self.children = {} self.sigcaught = None self.running = True s...
secnot/django-param-field
param_field/validators.py
Python
lgpl-3.0
1,141
0.003506
from django.core.exceptions import ValidationError from pyparsing import ParseBaseException from django.core.validators import MaxLengthValidator class ParamValidator(object): def __init__(self, file_support=False): self._file_support = file_support def __call__(self, value): # Impor...
except ParseBaseException as err: # Parser Error raise ValidationError(str(err)) except ValueError as err: # Error while creating Param raise Val
idationError(str(err)) class ParamLengthValidator(MaxLengthValidator): def clean(self, x): return len(str(x)) class ParamFormFieldValidator(object): def __init__(self, param): self._param = param def __call__(self, value): try: self._param.validate(value) ...
rohitw1991/latestadbwnf
core/doctype/workflow_state/test_workflow_state.py
Python
mit
104
0.009615
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
# MIT License. See license.txt test_records = [
]
gardiac2002/sunshine
sunshine/ext/html.py
Python
mit
207
0.009662
__author__ = 'sen' from bs4 import BeautifulSo
up def prettify_html(html_str): """ :param html_str: :return: """ soup = BeautifulSoup(html_str, 'html.parser') return soup.pret
tify()
tolimit/tp-qemu
qemu/tests/mq_change_qnum.py
Python
gpl-2.0
9,855
0.000304
import logging import re import aexpect from autotest.client import utils from autotest.client.shared import error from virttest import utils_net from virttest import utils_test from virttest import utils_misc @error.context_aware def run(test, params, env): """ MULTI_QUEUE chang queues number test 1)...
rt() if bg_stress_run_flag: utils_misc.wait_for(lambda: env.get(bg_stress_run_flag),
wait_time, 0, 5, "Wait %s start background" % bg_stress_test) if bg_ping == "yes": error.context("Ping guest from host", logging.info) args = (guest_ip, b_ping_time, b_ping_lost_ratio) bg_test = utils.Interrupte...
miguelgrinberg/Flask-Intro
07-ScalableStructure/app/forms.py
Python
mit
197
0.030457
from flask.ext.wtf import Form from wtforms import TextField from wtforms.validators import Required class NameForm(Form): name = TextField('What i
s your name?', validators = [ Required() ])
gopythongo/gopythongo
src/py/gopythongo/versioners/static.py
Python
mpl-2.0
1,614
0.001859
# -* encoding: utf-8 *- # This Source Code Form is subject to the terms of the Mozilla Public #
License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import configargparse from typing import Any, Type from gopythongo.utils import highlight, ErrorMessage from gopythongo.versioners import BaseVersioner class StaticVersioner(BaseVersi
oner): def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) @property def versioner_name(self) -> str: return u"static" def add_args(self, parser: configargparse.ArgumentParser) -> None: gp_static = parser.add_argument_group("Static Versioner...
aviau/python-pass
pypass/command.py
Python
gpl-3.0
13,445
0
# # Copyright (C) 2014 Alexandre Viau <[email protected]> # # This file is part of python-pass. # # python-pass 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 ...
(at yo
ur option) any later version. # # python-pass 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 c...
cgrice/django-staticblog
staticblog/urls.py
Python
mit
294
0.003401
from django.conf.urls import patterns # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns(
'staticblog.views', (r'^$', 'archive'), (r'^([\-\w]+)$', 'ren
der_post'), (r'^git/receive', 'handle_hook'), )
adijo/codeforces
287/AmrAndPins.py
Python
gpl-2.0
147
0.006803
imp
ort math r, x, y, x_p, y_p = map(int, raw_input().split()) dist = math.sqrt((x - x_p)**2 + (y - y_p)**2) print int(math.ceil(dist / (2
* r)))
fah-designs/feincms-blogs
blogs/views.py
Python
mit
3,343
0.001496
import datetime from django.views.generic.detail import SingleObjectMixin from django.views.generic.l
ist import ListView from django.views.generic.base import View
from django.utils.translation import ugettext as _ from django.http import Http404, HttpResponseRedirect from django.core.urlresolvers import reverse from feincms.module.mixins import ContentView from djapps.blogs.models import Blog, Post class PostPermalinkView(SingleObjectMixin, View): model = Post def g...