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
Cgruppo/oppia
core/domain/exp_domain_test.py
Python
apache-2.0
19,626
0.000357
# coding: utf-8 # # 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 requi...
exploration.param_specs = 'A string' with self.assertRaisesRegexp( utils.ValidationError, 'param_specs to be a dict'): exploration.validate() exploration.param_sp
ecs = { '@': param_domain.ParamSpec.from_dict({'obj_type': 'Int'}) } with self.assertRaisesRegexp( utils.ValidationError, 'Only parameter names with characters'): exploration.validate() exploration.param_specs = { 'notAParamSpec': param_domain...
ODiogoSilva/TriFusion
trifusion/ortho/OrthomclToolbox.py
Python
gpl-3.0
64,833
0.000586
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # # Copyright 2012 Unknown <diogo@arch> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your optio...
# Attribute containing the list of included species self.species_list = [] # Attribute tha
t will contain taxa to be excluded from analyses self.excluded_taxa = [] self.species_frequency = [] # Attributes that will store the number (int) of cluster after gene and # species filter self.all_clusters = 0 self.num_gene_compliant = 0 self.num_species_compli...
jbedorf/tensorflow
tensorflow/python/kernel_tests/where_op_test.py
Python
apache-2.0
8,003
0.010371
# Copyright 2015 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...
testRandom(np.float64) @test_util.run_deprecated_v1 def testRandomComplex64(self): self._testRandom(np.complex64) @test_util.run_deprecated_v1 def testRandomComplex128(self): self._testRandom(np.complex128) @test_util.run_deprecated_v1 def testRandomUint8(self): self._testRandom(np.uint8) ...
t_util.run_deprecated_v1 def testRandomInt16(self): self._testRandom(np.int16) @test_util.run_deprecated_v1 def testThreeArgument(self): x = np.array([[-2, 3, -1], [1, -3, -3]]) np_val = np.where(x > 0, x * x, -x) with self.session(use_gpu=True): tf_val = array_ops.where(constant_op.constan...
jamespcole/home-assistant
homeassistant/components/trafikverket_weatherstation/sensor.py
Python
apache-2.0
5,210
0
""" Weather information for air and road temperature, provided by Trafikverket. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.trafikverket_weatherstation/ """ import asyncio from datetime import timedelta import logging import aiohttp import vo...
MENTS = ['pytrafikverket==0.1.5.9'] _LOGGER = logging.getLogger(__name__) ATTRIBUTION = "Data provided by Trafikverket" ATTR_MEASURE_TIME = 'measure_time' ATTR_ACTIVE = 'active' CONF_STATION = 'station' MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=10) SCAN_INTERVAL
= timedelta(seconds=300) SENSOR_TYPES = { 'air_temp': [ 'Air temperature', TEMP_CELSIUS, 'air_temp', 'mdi:thermometer', DEVICE_CLASS_TEMPERATURE], 'road_temp': [ 'Road temperature', TEMP_CELSIUS, 'road_temp', 'mdi:thermometer', DEVICE_CLASS_TEMPERATURE], 'precipitation': [ ...
openmotics/gateway
tools/api-tester.py
Python
agpl-3.0
3,464
0.001443
import requests import ujson as json BASE_URL = 'http://localhost:8088/' # set the port and IP address correct USERNAME = '<Your username here>' PASSWD = '<Your password here>' TOKEN = '' # will be filled in by the login request VERBOSE = 1 # verbose 0 => No output, 1 => minimal output, 2 => full output def creat...
_indent += ' {}\n'.format(line) print('Response:\n code: {},\n headers:\n{} body:\n{}' .format(response.status_code, headers, body_indent)) print('--------------------------------------------') return response def login(verbose=None):
global TOKEN if verbose == None: verbose = VERBOSE params = {'username': USERNAME, 'password': PASSWD} resp = api_call('login', params=params, authenticated=False, verbose=verbose) resp_json = resp.json() if 'token' in resp_json: token = resp.json()['token'] TOKEN = token...
anhstudios/swganh
data/scripts/templates/object/draft_schematic/space/weapon/shared_wpn_heavy_disruptor.py
Python
mit
461
0.047722
#### NOTICE: THIS F
ILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Intangible() result.template = "object/draft_schematic/space/weapon/shared_wpn_heavy_disruptor.iff" result.attribute_template_id = -...
lt
bkjones/loghetti
test/apachelogs_test.py
Python
bsd-3-clause
930
0.005376
''' Simple test for apachelogs ''' import unittest from apachelogs import ApacheLogFile class apachelogs_test(unittest.TestCase): def test_foo(self): log = ApacheLogFile('test.log') line = iter(log).next() self.assertEquals(line.ip, '1
27.0.0.1') self.assertEquals(line.ident, '-') self.assertEquals(line.http_user, 'frank') self.assertEquals(line.time, '5/Oct/2000:13:55:36 -0700') self.assertEquals(line.request_line, 'GET /apache_pb.gif?foo=bar&baz=zip HTTP/1.0') self.assertEquals(line.
http_response_code, '200') self.assertEquals(line.http_response_size, '2326') self.assertEquals(line.referrer, 'http://www.example.com/start.html') self.assertEquals(line.user_agent, 'Mozilla/4.08 [en] (Win98; I ;Nav)') log.close() def setUp(self): pass if ...
FabianN/autopkg_recipies
AdobeReader/AdobeReaderUpdatesURLProvider.py
Python
mit
5,706
0.000526
#!/usr/bin/python # # Copyright 2014: wycomco GmbH ([email protected]) # 2015: modifications by Tim Sutton # # 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...
nses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for t
he specific language governing permissions and # limitations under the License. """See docstring for AdobeReaderURLProvider class""" # Disabling warnings for env members and imports that only affect recipe- # specific processors. #pylint: disable=e1101 import urllib2 import plistlib from autopkglib import Processor, ...
tfroehlich82/EventGhost
plugins/Mouse/__init__.py
Python
gpl-2.0
21,487
0.004328
# -*- coding: utf-8 -*- # # This file is part of EventGhost. # Copyright © 2005-2020 EventGhost Project <http://www.eventghost.net/> # # EventGhost 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 versio...
ceiveQueue.put([float(direction), float(initSpeed) / 1000, float(maxSpeed) / 1000, float(accelerationFactor) / 1000, useAlternateMethod]) eg.event.AddUpFunc(UpFunc) def Configure(self, direction=0, initSpeed = 60, maxSpeed = 7000, accelerationFactor = 3, useAlternateMet
hod=False): text = self.text panel = eg.ConfigPanel() direction = float(direction) valueCtrl = panel.SpinNumCtrl(float(direction), min=0, max=360) panel.AddLine(text.text1, valueCtrl, text.text2) initSpeedLabel = wx.StaticText(panel, -1, t
iLoop2/ResInsight
ThirdParty/Ert/devel/python/python/ert/enkf/enkf_main.py
Python
gpl-3.0
13,314
0.007736
# Copyright (C) 2012 Statoil ASA, Norway. # # The file 'ecl_kw.py' is part of ERT - Ensemble based Reservoir Tool. # # ERT 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 th...
return EnKFMain.cNamespace().iget_state(self, ensemble_member).setParent(self) def get_observations(self, user_key, obs_count, obs_x, obs_y, obs_std): EnKFMain.cNamespace().get_observations(self, user_key, obs_count, obs_x, obs_y, obs_std) def get_observation_count(self, user_key): return EnK...
: """ @rtype: EnkfSimulationRunner """ return self.__simulation_runner def getEnkfFsManager(self): """ @rtype: EnkfFsManager """ return self.__fs_manager def getWorkflowList(self): """ @rtype: ErtWorkflowList """ return EnKFMain.cNamespace().get_workflow_list(se...
akirakoyasu/ansible-modules-core
network/basics/uri.py
Python
gpl-3.0
19,263
0.006489
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, Romeo Theriault <romeot () hawaii.edu> # # 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 th...
uired: false default: null body: description: - The body of the http request/response to the web service. required: false default: null body_format: description: - The serialization format of the body. When set to json, encodes the body argument and automatically sets the Content-Typ...
- The HTTP method of the request or response. required: false choices: [ "GET", "POST", "PUT", "HEAD", "DELETE", "OPTIONS", "PATCH", "TRACE", "CONNECT", "REFRESH" ] default: "GET" return_content: description: - Whether or not to return the body of the request as a "content" key in the dic...
Nat-Lab/pac.py
lib/confParser.py
Python
mit
3,119
0
import string from pyparsing import ( Literal, White, Word, alphanums, CharsNotIn, Forward, Group, SkipTo, Optional, OneOrMore, ZeroOrMore, pythonStyleComment) class Parser(object): left_bracket = Literal("{").suppress() right_bracket = Literal("}").suppress() semicolon = Literal(";").suppress() ...
n self.parse().asList() class Dumper(object): def __init__(self, blocks, indentation=4):
self.blocks = blocks self.indentation = indentation def __iter__(self, blocks=None, current_indent=0, spacer=' '): blocks = blocks or self.blocks for key, values in blocks: if current_indent: yield spacer indentation = spacer * current_indent ...
Jumpscale/jumpscale6_core
apps/osis/logic/test_complextype/user/test_complextype_user_osismodelbase.py
Python
bsd-2-clause
5,069
0.00868
from JumpScale import j class test_complextype_user_osismodelbase(j.code.classGetJSRootModelBase()): """ group of users """ def __init__(self): pass self._P_id=0 self._P_organization="" self._P_name="" self._P_emails=list() self._P_groups=list() s...
ing(value): value = j.basetype.string.fromString(value) else: msg="p
roperty guid input error, needs to be str, specfile: /opt/jumpscale/apps/osis/logic/test_complextype/model.spec, name model: user, value was:" + str(value) raise TypeError(msg) self._P_guid=value @guid.deleter def guid(self): del self._P_guid @property def _meta(self):...
sunlaiqi/fundiy
src/shop/utils.py
Python
mit
2,973
0.006805
""" This file includes commonly used utilities for this app. """ from datetime import datetime today = datetime.now() year = today.year month = today.month day = today.day # Following are for images upload helper functions. The first two are used for product upload for the front and back. # The last two are used f...
duct_{1}/{2}/{3}/{4}/front/{5}'.format(instance.owner.id, instance.slug, year, month, day, filename) def back_image(instance, filename): # f
ile will be uploaded to MEDIA_ROOT/product_imgs/owner_<id>/product_<id>/Y/m/d/back/<filename> return 'product_imgs/owner_{0}/product_{1}/{2}/{3}/{4}/back/{5}'.format(instance.owner.id, instance.slug, year, month, day, filename) ''' def front_design_image(instance, filename): # file will be uploaded to MEDIA_RO...
terhorstd/nest-simulator
pynest/nest/tests/test_sp/test_disconnect_multiple.py
Python
gpl-2.0
10,751
0
# -*- coding: utf-8 -*- # # test_disconnect_multiple.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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 th...
dopamine_synapse_lbl', 'stdp_dopamine_synapse_hpc', 'stdp_dopamine_synapse_hpc_lbl', 'gap_junction', 'gap_junction_lbl', 'diffusion_connection', 'diffusion_connection_lbl', 'rate_connection_instantaneous', 'rate_connection_i...
tion_delayed_lbl', 'clopath_synapse', 'clopath_synapse_lbl' ] def test_multiple_synapse_deletion_all_to_all(self): for syn_model in nest.Models('synapses'): if syn_model not in self.exclude_synapse_model: nest.ResetKernel() nest.Co...
Koppermann/mod-mul-mersenne
mod_mul_mersenne/classes.py
Python
mit
2,433
0.000822
"""File holds the three classes Bit, DigitProduct, and PartialProduct.""" class Bit: """Class Bit represents a single bit of a digit-product.""" def __init__(self, identifier, absolute, relative): self.identifier = identifier self.absolute = absolute self.relative = relative def s...
self.msb = msb
def slice_block(self): """Slice digit-product in single bits.""" bit_list = [] for i in range(0, self.msb-self.lsb+1): bit_list.append(Bit(self.identifier, self.lsb+i, i)) return bit_list def print_info(self): """Print class info.""" print("identifie...
openpli-arm/enigma2-arm
RecordTimer.py
Python
gpl-2.0
26,731
0.033781
from enigma import eEPGCache, getBestPlayableServiceReference, \ eServiceReference, iRecordableService, quitMainloop from Components.config import config from Components.UsageConfig import defaultMoviePath from Components.TimerSanityCheck import TimerSanityCheck from Screens.MessageBox import MessageBox import Scree...
me from bisect import insort # ok, for descriptions etc we have: # service reference (to get the service name) # name (title) # description (d
escription) # event data (ONLY for time adjustments etc.) # parses an event, and gives out a (begin, end, name, duration, eit)-tuple. # begin and end will be corrected def parseEvent(ev, description = True): if description: name = ev.getEventName() description = ev.getShortDescription() if description ...
1iyiwei/pyml
code/ch13/theano_test.py
Python
mit
29
0
import
theano theano.tes
t()
audebert/alot
alot/foreign/urwidtrees/example4.filesystem.py
Python
gpl-3.0
4,462
0.002465
#!/usr/bin/python # Copyright (C) 2013 Patrick Totzke <[email protected]> # This file is released under the GNU GPL, version 3 or a later revision. import urwid import os from example1 import palette # example data from widgets import TreeBox from tree import Tree from decoration import CollapsibleArrowTree ...
size, key): return key # define Tree that can
walk your filesystem class DirectoryTree(Tree): """ A custom Tree representing our filesystem structure. This implementation is rather inefficient: basically every position-lookup will call `os.listdir`.. This makes navigation in the tree quite slow. In real life you'd want to do some caching. ...
CLVsol/clvsol_odoo_addons
clv_external_sync/models/external_sync_template.py
Python
agpl-3.0
2,540
0.001181
# -*- coding: utf-8 -*- # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class ExternalSyncTemplate(models.Model): _description =
'External Sync Template' _name = 'clv.external_sync.te
mplate' _order = 'name' name = fields.Char( string='Name', required=True, help='External Sync Template Name' ) external_host_id = fields.Many2one( comodel_name='clv.external_sync.host', string='External Host' ) external_max_task = fields.Integer( ...
cyli/volatility
volatility/plugins/mac/socket_filters.py
Python
gpl-2.0
3,566
0.00673
# Volatility # Copyright (C) 2007-2013 Volatility Foundation # # This file is part of Volatility. # # Volatility 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 o...
ommon.set_plugin_members(self) # get the symbols need to check for if rootkit or not (kernel_symbol_addresses, kmods) = common.get_kernel_addrs(self) members = ["sf_unregistered", "sf_attach", "sf_detach", "sf_notify", "sf_getpeername", "sf_getsockname"] members = members + ["s...
connect_out", "sf_bind", "sf_setoption"] members = members + ["sf_getoption", "sf_listen", "sf_ioctl"] sock_filter_head_addr = self.addr_space.profile.get_symbol("_sock_filter_head") sock_filter_list = obj.Object("socket_filter_list", offset = sock_filter_head_addr, vm = self.addr_space) ...
benosment/recipes
functional_tests/test_edit_recipe.py
Python
mit
8,273
0.00411
from selenium import webdriver from selenium.webdriver.common.keys import Keys from .base import FunctionalTest class RecipeEditTest(FunctionalTest): def test_can_add_a_recipe(self): # Ben goes to the recipe website homepage self.browser.get(self.server_url) # He notices the page title m...
self.assertIn('Add recipe', add_recipe_button.text) # He clicks on the link and new page appears add_recipe_button.click() # When he adds a new recipe,
he is taken to a new URL self.assertRegex(self.browser.current_url, '/users/.*/add_recipe') # He sees a form with a textbox for name, ingredients, directions and servings # along with a 'cancel' and 'add' button header_text = self.browser.find_element_by_tag_name('h1').text self...
jamestwebber/scipy
scipy/signal/wavelets.py
Python
bsd-3-clause
13,701
0.000292
from __future__ import division, print_function, absolute_import import numpy as np from numpy.dual import eig from scipy.special import comb from scipy.signal import convolve __all__ = ['daub', 'qmf', 'cascade', 'morlet', 'ricker', 'morlet2', 'cwt'] def daub(p): """ The coefficients for the FIR low-pass fi...
sqrt(3) return f * np.array([1 + c, 3 + c, 3 - c, 1 - c]) elif p == 3: tmp = 12 * sqrt(10) z1 = 1.5 + sqrt(15 + tmp) / 6 - 1j * (sqrt(15) + sqrt(tmp - 15)) / 6 z1c = np.conj(z1) f = sqrt(2) / 8 d0 = np.real((1 - z1) * (1 - z1c)) a0 = np.real(z1 * z1c) ...
a0 - 3 * a1 + 3, 3 - a1, 1]) elif p < 35: # construct polynomial and factor it if p < 35: P = [comb(p - 1 + k, k, exact=1) for k in range(p)][::-1] yj = np.roots(P) else: # try different polynomial --- needs work P = [comb(p - 1 + k, k, exact=1) /...
hl475/vispek
examples/run_raw_file_io.py
Python
apache-2.0
1,604
0.003117
# Copyright 2017 The Vispek Authors. All Rights Reserved. # # Licensed under the Apache License, Ve
rsion 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" ...
License. # ========================================================================== """ Example code about how to run raw_file_io python3 -m vispek.examples.run_raw_file_io \ --in_path /Users/huaminli/Downloads/data \ --out_path /Users/huaminli/Desktop/vispek/data """ import argparse from vispek.li...
openhatch/oh-mainline
vendor/packages/scrapy/scrapy/commands/version.py
Python
agpl-3.0
850
0.004706
import sys import platform import twisted import scrapy from scrapy.command import ScrapyCommand class Command(ScrapyCommand): def syntax(self): return "[-v]" def short_desc(self): return
"Print Scrapy version" def add_options(self, parser): ScrapyCommand.add_options(self, parser) parser.add_option("--verbose", "-v", dest="verbose", action="store_true", help="also display twisted/python/platform info (useful for bug reports)") def run(self, args, opts): if o...
n", "- ") print "Platform: %s" % platform.platform() else: print "Scrapy %s" % scrapy.__version__
tbenst/jupyter_webppl
jupyter_webppl/jupyter_webppl.py
Python
gpl-3.0
2,273
0.00132
# This code can be put in any Python module, it does not require IPython # itself to be running already. It only creates the magics subclass but # doesn't instantiate it yet. # from __future__ import print_function import json from IPython.core.magic import (Magics, magics_class, line_magic, ...
ss MUST call this class decorator at creation time @magics_class class WebpplMagics(Magics): def __init__(self, **kwargs): super(WebpplMagics, self).__init__(**kwargs) @line_magic def lmagic(self, line): "my line magic" print("Full access to the main IPython object:", self.shel...
: "my cell magic" code = json.dumps(cell) store = json.dumps(self.shell.user_ns['store']) h = """ <script> requirejs.config({ paths: { webppl: "//cdn.webppl.org/webppl-v0.9.1" } }); requi...
mylxiaoyi/mypyqtgraph-qt5
pyqtgraph/imageview/ImageViewTemplate_pyqt.py
Python
mit
8,950
0.003017
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ImageViewTemplate.ui' # # Created: Thu May 1 15:20:40 2014 # by: PyQt4 UI code generator 4.10.4 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets try: _fromUtf8 = QtCore.QString.f...
ormGroup) self.normFrameCheck.setObjectName(_fromUtf8("normFrameCheck")) self.gridLayout_2.addWidget(self.normFrameCheck, 1, 2, 1, 1) self.normTBlurSpin = QtWidgets.QDoubleSpinBox(self.normGroup) self.normTBlurSpin.setObjectName(_fromUtf8("normTBlurSpin")) self.gridLayout_2.add
Widget(self.normTBlurSpin, 2, 6, 1, 1) self.gridLayout_3.addWidget(self.normGroup, 1, 0, 1, 1) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): Form.setWindowTitle(_translate("Form", "Form", None)) self.roiBtn.setText(_tran...
flukiluke/eris
db.py
Python
mit
686
0.010204
import sqlite3 def cursor(): globa
l conn return conn.cursor() def commit(
): global conn conn.commit() def insert(table, data): global conn c = conn.cursor() keys = [*data] template_list = ','.join(['?'] * len(data)) query = "INSERT INTO {} ({}) VALUES ({})".format(table, ','.join(keys), template_list) c.execute(query, tuple(data[k] for k in keys)) conn.c...
thusoy/grunt-pylint
test/fixtures/test_package/camelcasefunc.py
Python
mit
144
0.006944
""" This modul
e should trigger a linting error for camelcase function name. """ def camelCaseFunc(): ""
" This function has a bad name. """
sahabi/keyman
main.py
Python
mit
33
0
fr
om ke
yman.interface import app
vileopratama/vitech
src/openerp/addons/base/tests/test_misc.py
Python
mit
1,108
0.000903
import unittest from openerp.tools import misc class test_countingstream(unittest.TestCase): def test_empty_stream(self): s = misc.CountingStream(iter([])) self.assertEqual(s.index, -1)
self.assertIsNone(next(s, None)) self.assertEqual(s.index, 0) def test_single(self): s = misc.CountingStream(xrange(1)) self.assertEqual(s.index, -1) self.assertEqual(next(s, None), 0) self.assertIsNone(next(s, None)) self.assertEqual(s.index, 1) def test_...
pass self.assertEqual(s.index, 42) def test_repeated(self): """ Once the CountingStream has stopped iterating, the index should not increase anymore (the internal state should not be allowed to change) """ s = misc.CountingStream(iter([])) self.assertIsNone(next(...
StSchulze/pymzML
tests/ms2_spec_test.py
Python
mit
2,583
0.003097
import sys import os import unittest sys.path.append(os.path.abspath(".")) import pymzml from pymzml.spec import PROTON import pymzml.run as run import test_file_paths import numpy as np class SpectrumMS2Test(unittest.TestCase): """ BSA test file Peptide @ Scan: 2548 RT [min] 28.96722412109...
t) self.assertIsInstance(selected_precursor[0]["charge"], int) self.assertEqual( selected_precursor, [{"mz": 443.711242675781, "i": 0.0, "charge
": 2}] ) @unittest.skipIf(pymzml.spec.DECON_DEP is False, "ms_deisotope was not installed") def test_deconvolute_peaks(self): charge = 3 test_mz = 430.313 arr = np.array([(test_mz, 100), (test_mz + PROTON / charge, 49)]) spec = self.Run[2548] spec.set_peaks(arr, ...
benoitbryon/xal
xal/dir/provider.py
Python
bsd-3-clause
895
0
# -*- coding: utf-8 -*- """Base stuff for providers that handle filesystem directories.""" from xal.provider import ResourceProvider from xal.dir.resource import Dir class DirProvider(ResourceProvider): """Base class for filesystem directori
es.""" def __init__(self, resource_factory=Dir): super(DirProvider, self).__init__(resource_factory=resource_factory) @property def home(self): raise NotImplementedError() @property def sep(self): if self.xal_session.sys.is_posix: return '/' elif self.xa...
return '\\' def join(self, *args): modified_args = args[:] for key, value in enumerate(modified_args): modified_args[key] = value.strip(self.sep) return self.sep.join(*modified_args) def abspath(self, path): raise NotImplementedError()
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_11_01/operations/_virtual_hubs_operations.py
Python
mit
26,953
0.004786
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
rameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._
serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(virtual_hub_parameters, 'VirtualHub') body_content_kwargs['content'] =...
mansonul/events
events/contrib/plugins/form_elements/fields/select_multiple_with_max/conf.py
Python
mit
1,127
0
from django.conf im
port settings from . import defaults __title__ = 'fobi.contrib.plugins.form_elements.fields.' \ 'select_multiple_with_max.conf' __author__ = 'Artur Barseghyan <artur.barseghya
[email protected]>' __copyright__ = '2014-2017 Artur Barseghyan' __license__ = 'GPL 2.0/LGPL 2.1' __all__ = ('get_setting',) def get_setting(setting, override=None): """Get setting. Get a setting from `fobi.contrib.plugins.form_elements.fields.select_multiple_with_max` conf module, falling back to the defa...
cycladesnz/chambersAndCreatures
src/effects/__init__.py
Python
gpl-2.0
175
0.005714
import os files = os.listdir(os.path.join('src','effects')) for file in files: if file[-3:] == '.py' and f
ile[:2] != '__': exec('from .%s
import *' % (file[:-3]))
Archman/felapps
tests/test2.py
Python
mit
8,381
0.022193
#!/usr/bin/env python import wx from wx.lib.agw import floatspin as fs import numpy as np class MyFrame(wx.Frame): def __init__(self, *args, **kws): super(self.__class__,self).__init__(*args, **kws) nb1 = MyNB(self) self.Show() class MyFrame1(wx.Frame): def __init__(self, *a...
AddPage(self.panel3, 'Third Tab') # events self.Bind(wx.EVT_BUTTON, self.onChooseColor, self.btn2) def onChooseColor(self, event)
: dlg = wx.ColourDialog(self) dlg.GetColourData().SetChooseFull(True) if dlg.ShowModal() == wx.ID_OK: color = dlg.GetColourData().GetColour() self.panel2.SetBackgroundColour(color) print color.GetAsString(wx.C2S_HTML_SYNTAX) dlg.Destroy() class MyFram...
NoahFlowa/CTC_Projects
Osterhout_Python/Kirby_Physics.py
Python
mit
1,794
0.043478
# Programmer: Noah Osterhout # Date: September 30th 2016 1:40PM EST # Project: Kirby_Physics.py #Ask what Problem they will be using print() print("This Program will find the mis
isng Variables using the three known ones and using PEMDAS") print() beetles_mem = input("What Beetles member will you be using? ") gravity_global = -9.8 if beetles_mem == "John": john_time = int(input("What is the Time in seconds? ")) new_john_time = john_time ** 2 john_Vi = int(input("What is the Initia...
? ")) #Calculate using John Formula john_formula = .5 * gravity_global * new_john_time print("The Distance would be", john_formula) elif beetles_mem == "Paul": paul_Vf = int(input("What is the Final Velocity? ")) paul_Vi = int(input("What is the Intial Velocity? ")) paul_time = int(input("What ...
ntt-pf-lab/backup_keystone
keystone/controllers/extensions.py
Python
apache-2.0
752
0.00133
from webob import Response from keystone import utils from keystone.common import template, wsgi class ExtensionsController(wsgi.Controller): """Controller for extensions related me
thods""" def __init__(self, options): super(ExtensionsController, self).__init__() self.options = options @utils.wrap_error def get_extensions_info(self, req, path): resp = Response() if utils.is_xml_response(req): resp_file = "%s.xml" % path mime_t...
"application/json" return template.static_file(resp, req, resp_file, root=utils.get_app_root(), mimetype=mime_type)
zhlinh/leetcode
0094.Binary Tree Inorder Traversal/test.py
Python
apache-2.0
874
0.006865
#!/usr/bin/env python # -*- coding: utf-8 -*- from solution imp
ort Solution from solution import TreeNode def constructOne(s): if s == '#': return None else: return TreeNode(int(s)) def createTree(tree): q = [] root = constructOne(tree[0]); q.append(root); idx =
1; while q: tn = q.pop(0) if not tn: continue if idx == len(tree): break left = constructOne(tree[idx]) tn.left = left q.append(left) idx += 1 if idx == len(tree): break right = constructOne(tree[idx]) ...
davogler/venus
opstel/urls/entries.py
Python
mit
1,232
0.018669
from django.conf.urls.defaults import * from django.views.generic.dates import YearArchiveView, MonthArchiveView, DayArchiveView, DateDetailView from tinymce.widgets import TinyMCE from tinymce.views import preview from opstel.models import Entry entry_info_dict = {'queryset':Entry.live.all(), 'date_field': 'pub_date'...
chive_index', ), #url(r'^preview/$', 'preview', name= "preview"), url(r'^(?P<year>\d{4})/$', YearArchiveView.as_view(**entry_info_dict), name= 'opstel_entry_archive_year'), url(r'^(?P<year>\d{4})/(?P<month>\w{3})/$', MonthArchiveView.as_view(**entry_info_dict), name= 'opstel_entry_archive_month'), url(r'^(?P<year>\...
})/(?P<month>\w{3})/(?P<day>\d{2})/$', DayArchiveView.as_view(**entry_info_dict), name= 'opstel_entry_archive_day'), url(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$', DateDetailView.as_view(**entry_info_dict), name= 'opstel_entry_detail'), )
SUSE/azure-sdk-for-python
azure-mgmt-resource/azure/mgmt/resource/policy/v2016_12_01/operations/policy_assignments_operations.py
Python
mit
30,831
0.002465
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
ssignment_name: The name of the policy assignment to delete. :type policy_assignment_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config:...
on configuration overrides<msrest:optionsforoperations>`. :rtype: :class:`PolicyAssignment <azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment>` :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true :raises: :class:`CloudError<ms...
lmccalman/spacerace
physics/engine.py
Python
mit
10,367
0.002026
""" Physics test sandbox for the space race game! Alistair Reid 2015 """ import matplotlib.pyplot as pl import matplotlib as mpl import numpy as np from numpy.linalg import norm from time import time, sleep import os def integrate(states, props, inp, walls, bounds, dt): """ Implementing 4th order Runge-Kutta f...
nt.height accessible fig.canvas.mpl_connect('key_press_event', press) fig.canvas.mpl_connect('key_release_event', unpress) fig.canvas.mpl_connect('resize_event', redo_background) print('Press Q to exit') while 'q' not in keys: # Advance the game state while t < next_draw: ...
100 # some forward thrust! # give the user control of ship 0 if 'right' in keys: inputs[0, 1] = -10. elif 'left' in keys: inputs[0, 1] = 10. else: inputs[0, 1] = 0. if 'up' in keys: inputs[0, 0]...
NicholasAsimov/courses
6.00.1x/final/p4-1.py
Python
mit
459
0.004357
def getSublists(L, n): subl
ists = [] for i in range(len(L)): next_sublist = L[i:i+n] if len(next_sublist) == n: sublists.append(next_sublist) return sublists # Test Cases L = [10, 4, 6, 8, 3, 4, 5, 7, 7, 2] print getSublists(L, 4) == [[10, 4, 6, 8], [4, 6, 8, 3], [6, 8, 3, 4], [8, 3, 4, 5], [3, 4, 5, 7], [...
s(L, 2) == [[1, 1], [1, 1], [1, 1], [1, 4]]
ShadauxCat/csbuild
UnitTests/Android/unit_test_android.py
Python
mit
622
0.016077
import csbuild #csbuild.SetActiveToolchain("android") @csbuild.project("AndroidTest_Basic", "AndroidTest_Basic") def AndroidTest_Basic(): csbuild.T
oolchain("android").SetCcCommand("gcc") csbuild.Toolchain("android").SetCxxCommand("g++") csbuild.Toolchain("android").SetPackageName("csbuild.UnitTest.AndroidBasic") csbuild.Toolchain("android").SetActivityName("CSBUnitTestAndroidBasic")
csbuild.DisablePrecompile() csbuild.SetOutput("AndroidTest_Basic", csbuild.ProjectType.Application) csbuild.Toolchain("android").AddLibraries("android", "m", "log", "dl", "c") csbuild.SetSupportedToolchains("msvc", "android")
kobejean/tensorflow
tensorflow/python/autograph/converters/asserts_test.py
Python
apache-2.0
1,319
0.002274
# Copyright 2017 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...
rom __future__ import print_function import gast from tensorflow.python.autograph.converters import asserts from tensorflow.python.autograph.core import converter_testing from tensorflow.python.platform import test class AssertsTest(converter_testing.TestCase): def test_t
ransform(self): def test_fn(a): assert a > 0 node, ctx = self.prepare(test_fn, {}) node = asserts.transform(node, ctx) self.assertTrue(isinstance(node.body[0].value, gast.Call)) if __name__ == '__main__': test.main()
masschallenge/impact-api
web/impact/impact/schema.py
Python
mit
482
0
# MIT License # Copyright (c) 2017 MassChallenge, Inc. from rest_framework import response, schemas from rest_framework.decorators import ( api_view,
renderer_classes, ) from drf_yasg.renderers import (
OpenAPIRenderer, SwaggerUIRenderer, ) @api_view() @renderer_classes([OpenAPIRenderer, SwaggerUIRenderer]) def schema_view(request): generator = schemas.SchemaGenerator(title='Impact API') return response.Response(generator.get_schema(request=request))
captainhungrykaboom/MTAT.TK.006
6. märts - 12. märts ülesanded/harjutus ülesanne 6.py
Python
mit
62
0.016129
a = "1" b = 1 print("A
rvud on " + 5 * a + " ja " + str(
5 * b))
mauroalberti/gsf
pygsf/utils/qt_utils/filesystem.py
Python
gpl-3.0
1,060
0.003774
from builtins import str from qgis.PyQt.QtCore import QFileInfo from qgis.PyQt.QtWidgets import QFileDialog def update_directory_key(settings, settings_dir_key, fileName): """ modified from module RASTERCALC by Barry Rowlingson """ path = QFileInfo(fileName).absolutePath() settings.setValue(se...
penFileName(parent, parent.tr(show_msg), filter_extension, filter_text) if not input_filename: return '' else: return in
put_filename
neharejanjeva/techstitution
venv/lib/python2.7/site-packages/pymongo/collection.py
Python
cc0-1.0
104,519
0.000287
# Copyright 2009-2015 MongoDB, 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 writin...
ad_preference, write_concern) salms = database.secondary_acceptable_latency_ms super(Collection, self).__init__( codec_options=opts, read_preference=mode, tag_sets=tags, secondary_acceptable_latency_ms=salms, slave_okay=database.slave_okay, ...
if not isinstance(name, basestring): raise TypeError("name must be an instance " "of %s" % (basestring.__name__,)) if not name or ".." in name: raise InvalidName("collection names cannot be empty") if "$" in name and not (name.startswith("oplog.$ma...
sidhart/antlr4
runtime/Python3/src/antlr4/atn/LexerATNSimulator.py
Python
bsd-3-clause
26,465
0.007255
# # [The "BSD license"] # Copyright (c) 2012 Terence Parr # Copyright (c) 2012 Sam Harwell # Copyright (c) 2014 Eric Vergnaud # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redis...
> #/ from antlr4.PredictionContext import PredictionContextCache, SingletonPredictionContext, PredictionContext from antlr4.InputStream import InputStream from antlr4.Token import Token from antlr4.atn.ATN import ATN from antlr4.atn.ATNConfig import LexerATNConfig from antlr4.atn.ATNSimulator import ATNSimulator from ...
TNState import RuleStopState, ATNState from antlr4.atn.LexerActionExecutor import LexerActionExecutor from antlr4.atn.Transition import Transition from antlr4.dfa.DFAState import DFAState from antlr4.error.Errors import LexerNoViableAltException, UnsupportedOperationException class SimState(object): def __init__(...
foer/linuxmuster-client-unity
tests/autopilot/unity/emulators/panel.py
Python
gpl-3.0
11,333
0.000794
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- # Copyright 2012 Canonical # Author: Marco Trevisan (Treviño) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundati...
menu_entries = self.menus.get_entries() if len(menu_entries) > 0: first_x = menu_entries[0].x last_x = menu_entries[-1].x + menu_entries[-1].width / 2 target_x = first_x + (last_x - first_x) / 2 logger.debug("Moving mouse to center of menu area.") self._mo...
rea for this panel.""" (x, y, w, h) = self.grab_area.geometry target_x = x + w / 2 target_y = y + h / 2 logger.debug("Moving mouse to center of grab area.") self._mouse.move(target_x, target_y) def move_mouse_over_window_buttons(self): """Move the mouse over the cen...
aqavi-paracha/coinsbazar
qa/pull-tester/pull-tester.py
Python
mit
8,761
0.007191
#!/usr/bin/python import json from urllib import urlopen import requests import getpass from string import Template import sys import os import subprocess class RunError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) def run(command, **kwar...
True, Fal
se, True, resultsurl) elif returncode != 0: print("Failed to test pull - sending comment to: " + comment_url) commentOn(comment_url, False, False, False, resultsurl) else: print("Successfully tested pull - sending comment to: " + comment_url) commentOn(comment_url, True, False, F...
tylertian/Openstack
openstack F/nova/nova/volume/nexenta/volume.py
Python
apache-2.0
11,026
0.001179
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2011 Nexenta Systems, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apa...
t='auto', help='Use http or https for REST connection (default auto)'), cfg.StrOpt('nexenta_user', default='admin', help='User name to connect to Nexenta SA'), cfg.StrOpt('nexenta_password', default='nexenta', help='Password to connect t...
help='Nexenta target portal port'), cfg.StrOpt('nexenta_volume', default='nova', help='pool on SA that will hold all volumes'), cfg.StrOpt('nexenta_target_prefix', default='iqn.1986-03.com.sun:02:nova-', help='IQN prefix for iSCSI targe...
sadanandb/pmt
src/pyasm/prod/biz/texture.py
Python
epl-1.0
5,425
0.00977
########################################################### # # Copyright (c) 2005, Southpaw Technology # All Rights Reserved # # PROPRIETARY INFORMATION. This software is proprietary to # Southpaw Technology, and is not to be reproduced, transmitted, # or disclosed in any way without written permi...
ject.set_value("category", category) if description != None
: sobject.set_value("description", description) sobject.commit() return sobject create = classmethod(create) def get(cls, texture_code, parent_code, project_code=None, is_multi=False): '''TODO: use search_type, id for the parent search''' if not project_code: ...
Shekharrajak/django-db-mailer
dbmail/management/commands/dbmail_test_send.py
Python
gpl-2.0
1,678
0.004172
import re import optparse from django.core.management.base import BaseCommand from dbmail.models import MailTemplate from dbmail.defaults import BACKEND from dbmail import db_sender def
send_test_msg(pk, email, user=None, **kwargs): template = MailTemplate.objects.get(pk=pk) slug = template.slug var_list = re.findall('\{\{\s?(\w+)\s?\}\}', template.message) context = {} for var in var_list: context[var] = '%s' % var.upper().replace('_', '-') return db_sender(slug, email...
ion_list + ( optparse.make_option('--email', dest='email', help='Recipients'), optparse.make_option('--pk', dest='pk', help='DBMail template id'), optparse.make_option('--without-celery', action='store_true', default=False, dest='celery', ...
QC-Technologies/HRMS
interview/admin/candidate.py
Python
gpl-3.0
1,067
0
from django.contrib import admin class CandidateAdmin(admin.ModelAdmin): fieldsets = [ (None, { 'fields': ['email', 'first_name', 'last_name', 'gender', 'cv'] }),
('Contact Information', { 'classes': ('collapse',), 'fields': ['mobile_phone'] }), ('Address Information', { 'classes': ('collapse',), 'fields': ['address', 'city'] }), ('Additional Information', { 'classes': ('collapse',), ...
None: self.fieldsets[0][1]['fields'] = ['email', 'first_name', 'last_name', 'gender', 'cv'] else: self.fieldsets[0][1]['fields'] = ['email', 'first_name', 'last_name', 'gender', 'cv', ...
Tasignotas/topographica_mirror
platform/ipython/profile_topo/ipython_notebook_config.py
Python
bsd-3-clause
4,652
0.003869
# Stripped down configuration file for ipython-notebook in Topographica. c = get_config() #------------------------------------------------------------------------------ # NotebookApp configuration #------------------------------------------------------------------------------ # NotebookApp will inherit config from:...
------- # A KernelManager that handles notebok mapping and HTTP error handling # MappingKernelManager will inherit config from: MultiKern
elManager # The max raw message size accepted from the browser over a WebSocket # connection. # c.MappingKernelManager.max_msg_size = 65536 # Kernel heartbeat interval in seconds. # c.MappingKernelManager.time_to_dead = 3.0 # Delay (in seconds) before sending first heartbeat. # c.MappingKernelManager.first_beat = 5....
common-workflow-language/cwl-upgrader
setup.py
Python
apache-2.0
2,104
0
#!/usr/bin/env python import os import sys from setuptools import setup SETUP_DIR = os.path.dirname(__file__) README = os.path.join(SETUP_DIR, "README.rst") NEEDS_PYTEST = {"pytest", "test", "ptr"}.intersection(sys.argv) PYTEST_RUNNER = ["pytest-runner", "pytest-cov"] if NEEDS_PYTEST else [] setup( name="cwl-u...
6, <4", classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Console", "Intended Audience :: Developers", "Intended Audience :: Healthcare Industry", "Intended Audience :: Science/Research", "License :: OSI Approved :: Apache Software L
icense", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language...
pdorrell/emacs-site-lisp
test/test-project/src/subdir_with_files/spaced dir name/hello.py
Python
gpl-2.0
45
0
def hello_again(): print("hello
again")
vorwerkc/pymatgen
pymatgen/command_line/bader_caller.py
Python
mit
22,902
0.002358
# Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """ This module implements an interface to the Henkelmann et al.'s excellent Fortran code for calculating a Bader charge analysis. This module depends on a compiled bader executable available in the path. Please download the ...
acuum_volume = float(toks[1]) el
if toks[0] == "NUMBER OF ELECTRONS": self.nelectrons = float(toks[1]) self.data = data if self.parse_atomic_densities: # convert the charge denisty for each atom spit out by Bader into Chgcar objects for easy parsing atom_chgcars = [ ...
AndreaMordenti/spotydowny
core/convert.py
Python
mit
2,314
0.001729
import subprocess import os """ What are the differences and similarities between ffmpeg, libav, and avconv? https://stackoverflow.com/questions/9477115 ffmeg encoders high to lower quality libopus > libvorbis >= libfdk_aac > aac > libmp3lame libfdk_aac due to copyrights needs to be compiled by end user on MacOS brew...
input_ext = input_song.split('.')[-1] output_ext = output_song.split('.')[-1] if input_ext == 'm4a': if out
put_ext == 'mp3': ffmpeg_params = '-codec:v copy -codec:a libmp3lame -q:a 2 ' elif output_ext == 'webm': ffmpeg_params = '-c:a libopus -vbr on -b:a 192k -vn ' elif input_ext == 'webm': if output_ext == 'mp3': ffmpeg_params = ' -ab 192k -ar 44100 -vn ' eli...
winnerineast/Origae-6
origae/dataset/text/classification/forms.py
Python
gpl-3.0
14,708
0.001904
from __future__ import absolute_import import os.path import requests import wtforms from wtforms import validators from ..forms import TextDatasetForm from origae import utils from origae.utils.forms import validate_required_iff, validate_greater_than class TextClassificationDatasetForm(TextDatasetForm): """ ...
method='folder', has_val_folder=True), ] ) folder_val_min_per_class = utils.forms.IntegerField( u'Minimum samples per class', default=2, validators=[ validators.Optional(), validators.NumberRange(min=1), ], tool...
s than the specified amount it will be ignored. ' 'Leave blank to ignore this feature.'), ) folder_val_max_per_class = utils.forms.IntegerField( u'Maximum samples per class', validators=[ validators.Optional(), validators.NumberRange(min=1), ...
ragupta-git/ImcSdk
imcsdk/__init__.py
Python
apache-2.0
1,616
0.001238
# Copyright 2016 Cisco Systems, 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 writin...
- %(name)s - %(levelname)s - %(message)s') console.setFormatter(formatter) def enable_file_logging(filename="imcsdk.log"): file_handler = logging.handlers.RotatingFileHandler( filename, maxBytes=10*1024*1024, backupCount=5) log.addHandler(file_handler) def set_log_level(level=logging.DEBUG): ...
Example: from imcsdk import set_log_level import logging set_log_level(logging.INFO) """ log.setLevel(level) console.setLevel(level) set_log_level(logging.DEBUG) log.addHandler(console) if os.path.exists('/tmp/imcsdk_debug'): enable_file_logging() __author__ = 'Cisco Sy...
Rajeshkumar90/ansible-modules-extras
source_control/bzr.py
Python
gpl-3.0
6,658
0.001954
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, André Paramés <[email protected]> # Based on the Git module by Michael DeHaan <[email protected]> # # 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 a...
self.parent = parent self.dest = dest self.version = ver
sion self.bzr_path = bzr_path def _command(self, args_list, cwd=None, **kwargs): (rc, out, err) = self.module.run_command([self.bzr_path] + args_list, cwd=cwd, **kwargs) return (rc, out, err) def get_version(self): '''samples the version of the bzr branch''' cmd = "%s ...
SpaceKatt/CSPLN
apps/scaffolding/win/web2py/gluon/contrib/mockimaplib.py
Python
gpl-3.0
10,569
0.002933
# -*- encoding: utf-8 -*- from imaplib import ParseFlags # mockimaplib: A very simple mock server module for imap client APIs # Copyright (C) 2014 Alan Etkin <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public Li...
: None | uid parts: "(ALL)" | "(RFC822 FLAGS)" | "(RFC822.HEADER FLAGS)"
"search", None, "(ALL)" -> ("OK", ("uid_1 uid_2 ... uid_<mailbox length>", None)) "search", None, "<query>" -> ("OK", ("uid_1 uid_2 ... uid_n", None)) "fetch", uid, parts -> ("OK", (("<id> ...", "<raw message as specified in parts>"), "<flags>") [0] [1][0][0] [...
PlanTool/plantool
wrappingPlanners/Deterministic/LAMA/seq-sat-lama/lama/translate/pddl/f_expression.py
Python
gpl-2.0
5,321
0.008081
####################################################################### # # Author: Gabi Roeger # Modified by: Silvia Richter ([email protected]) # (C) Copyright 2008: Gabi Roeger and NICTA # # This file is part of LAMA. # # LAMA is free software; you can redistribute it and/or # modify it under the terms of ...
me, arg.name)) for arg in self.args] pne = PrimitiveNumericExpression(sel
f.symbol, args) assert not self.symbol == "total-cost" # We know this expression is constant. Substitute it by corresponding # initialization from task. for fact in init_facts: if isinstance(fact, FunctionAssignment): if fact.fluent == pne: ...
inbloom/legacy-projects
lri-middleware/path_builder/form.py
Python
apache-2.0
1,107
0.001807
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You m
ay 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" B
ASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import web from web import form as webform import httpconfig class Form(object): """Form class""" def __init__(self, names=[...
christophreimer/pytesmo
pytesmo/time_series/plotting.py
Python
bsd-3-clause
6,133
0.000163
# Copyright (c) 2014,Vienna University of Technology, # Department of Geodesy and Geoinformation # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the...
idspec.GridSpec(nr_columns, 1, right=0.8) fig = plt.figure(num=None, figsize=(6, 2 * nr_columns), dpi=150, facecolor='w', edgecolor='k') last_axis = fig.add_subplot(gs[nr_columns - 1]) axes = [] for i, grid in enumerate(gs): if i < nr_columns - 1: ...
False) axes.append(last_axis) else: own_axis = False for i, column in enumerate(df): Ser = df[column] ax = axes[i] if clim is None: clima = anom.calc_climatology(Ser) else: clima = clim[column] anomaly = anom.calc_anomaly(Ser, cl...
mateoqac/unqTip
gui/views/boardOption.py
Python
gpl-3.0
3,726
0.002952
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'boardOptions.ui' # # Created: Fri Oct 4 12:27:03 2013 # by: PyQt4 UI code generator 4.9.1 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui from commons.i18n import * try: _fromUtf8 = QtCore...
)) self.horizontalLayout_3.addWidget(self.comboBox_3) self.verticalLayout.addLayout(self.horizontalLayout_3) self.retranslateUi(Dialog) QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), Dialog.accept) QtCore.QObject.connect(self.buttonBox, QtCore.SIG...
setWindowTitle(QtGui.QApplication.translate("Dialog", i18n('Options Board'), None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("Dialog", i18n("Balls"), None, QtGui.QApplication.UnicodeUTF8)) self.label_2.setText(QtGui.QApplication.translate("Dialog", i18n("Size"), No...
laputian/dml
mlp_test/test_compare_mlp_unit.py
Python
mit
1,003
0.004985
from compare_mlp import calculate_distance_pairs, load_models,get_fil
enames, plot_distance_pairs, plot_distances_from_target import unittest class DistanceTestCase(unittest.TestCase): def setUp(self): self.afiles = load_models(get_filenames("best_model_mlp", "zero_blur_a.pkl")) self.bfiles = load_models(get_filenames("best_model_mlp", "rand.pkl")) def te
stDistanceBetweenZeroAndRandModels(self): distances = calculate_distance_pairs(self.afiles, self.bfiles) plot_distance_pairs(distances) def testDistanceBetweenZeroModelsAndZeroTarget(self): plot_distances_from_target(self.afiles[-1], self.afiles) def testDistanceBetweenRandModelsAndRa...
metabrainz/acousticbrainz-server
db/api_key.py
Python
gpl-2.0
2,579
0.000775
import db import db.exceptions import sqlalchemy import string import random KEY_LENGTH = 40 def generate(owner_id): """Generate new key for a specified user. Doesn't check if user exists. Args: owner_id: ID of a user that will be associated with a key. Returns: Value of the new ke...
value, :owner) """), { "value": value, "owner": owner_id }) return value def get_active(owner_id): """Get active keys for a user. Doesn't check if user exists. Args: owner_id: ID of a user who owns the key. Returns: List of active API ...
db.engine.connect() as connection: result = connection.execute(sqlalchemy.text(""" SELECT value FROM api_key WHERE owner = :owner """), {"owner": owner_id}) return [row["value"] for row in result.fetchall()] def revoke(value): """Revoke key with a giv...
danielballan/scikit-xray
skbeam/io/avizo_io.py
Python
bsd-3-clause
10,337
0.000097
from __future__ import absolute_import, division, print_function import numpy as np import os import logging def _read_amira(src_file): """ Reads all information contained within standard AmiraMesh data sets. Separate the header information from the image/volume, data. Parameters ---------- s...
orrect ndarray dimensions # Note that resize is in-place whereas reshape is not flt_values.resize(Zdim, Ydim, Xdim) output = flt_values if flip_z: output = flt_values[::-1, ..., ...] return output def _clean_amira_header(header_li
st): """ Strip the string list of all "empty" characters,including new line characters ('\n') and empty lines. Splits each header line (which originally is stored as a single string) into individual words, numbers or characters, using spaces between words as the separating operator. The output o...
mattclay/ansible
lib/ansible/plugins/lookup/lines.py
Python
gpl-3.0
2,214
0.005872
# (c) 2012, Daniel Hokka Zakrisson <[email protected]> # (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = """ name: lines author: Daniel H...
for term in terms: p = subprocess.Popen(term, cwd=self._loader.get_basedir(), shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) (stdout, stderr) = p.communicate() if p.returncode == 0: ret.extend([to_text(l) for l in stdout.splitlines()]) else: ...
raise AnsibleError("lookup_plugin.lines(%s) returned %d" % (term, p.returncode)) return ret
zxl200406/minos
supervisor/supervisor/medusa/thread/thread_channel.py
Python
apache-2.0
3,713
0.01185
# -*- Mode: Python -*- VERSION_STRING = "$Id: thread_channel.py,v 1.3 2002/03/19 22:49:40 amk Exp $" # This will probably only work on Unix. # The disadvantage to this technique is that it wastes file # descriptors (especially when compared to select_trigger.py) # May be possible to do it on Win32, using TCP localh...
.start_new_thread ( self.func
tion, # put the output file in front of the other arguments (of,) + self.args ) def writable (self): return 0 def readable (self): return 1 def handle_read (self): data = self.recv (self.buffer_size) self.parent.push (data) ...
Kaushikpatnaik/LSTMChar2Char
train.py
Python
mit
5,431
0.019518
''' Training file with functions for 1) Taking in the inputs 2) Defining the model 3) Reading the input and generating batches 4) Defining the loss, learning rate and optimization functions 5) Running multiple epochs on training and testing ''' import argparse from read_input import * from model import * import tensor...
else: raise NotImplementedError("File extension not supported") train, val ,test = train_test_split(data, args.split_ratio) batch_train = BatchGenerator(train,args.batch_size,args.batch_len) batch_train.create_batches() max_batches_t
rain = batch_train.epoch_size # New chars seen in test time will have a problem args.data_dim = batch_train.vocab_size batch_val = BatchGenerator(val,args.batch_size,args.batch_len) batch_val.create_batches() max_batches_val = batch_val.epoch_size batch_test = BatchGenerator(test,args.batch_size,args.batc...
erbridge/NQr
src/export.py
Python
bsd-3-clause
834
0
import sqlite3 def main(): conn = sqlite3.connect("../database") cursor = conn.cursor() # I claim this gives the current score. Another formulation is # select trackid, score, max(scoreid) from scores group by trackid; # cursor.execute("""select trackid, score from scores # gro...
select score, path from tracks where score is not null and missing is not 1""") results = cursor.fetchall() f
or result in results: print(str(result[0]) + "\t" + result[1]) if __name__ == '__main__': main()
bwhitelock/garmon-ng
garmon/audi_codes.py
Python
gpl-3.0
34,868
0.000488
#!/usr/bin/python # -*- coding: iso-8859-15 -*- # # audi_codes.py # # Copyright (C) Ben Van Mechelen 2008-2009 <[email protected]> # # This file is part of Garmon # # Garmon 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 Fo...
_("Cyl.3-Fuel Inj.Circ. Short to B+"), "P1216": _("Cyl.4-Fuel Inj.Circ. Short to B+"), "P1217": _("Cyl.5-Fuel Inj.Circ. Short to B+"), "P1218": _("Cyl.6-F
uel Inj.Circ. Short to B+"), "P1219": _("Cyl.7-Fuel Inj.Circ. Short to B+"), "P1220": _("Cyl.8-Fuel Inj.Circ. Short to B+"), "P1221": _("Cylinder shut-off exhaust valves Short circuit to ground"), "P1222": _("Cylinder shut-off exhaust valves Short to B+"), "P1223": _
geotagx/geotagx-project-template
src/test_question.py
Python
agpl-3.0
2,076
0.010597
# This module is part of the GeoTag-X project builder. # Copyright (C) 2015 UNITAR. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option...
with this program. If not, see <http://www.gnu.org/licenses/>. import unittest from question import Question class TestQuestion(unittest.TestCase): def test_val
id_keys(self): self.assertTrue(Question.iskey("A")[0], "Single-character") self.assertTrue(Question.iskey("thisIsALongKey")[0], "Multi-character") self.assertTrue(Question.iskey("--")[0], "Hyphens") self.assertTrue(Question.iskey("--key")[0], "Leading hyphens") self.assertTrue(Question.iskey("_")[0], "Undersc...
FRC-RS/FRS
leaderboard/apps.py
Python
mit
98
0
from django.apps import AppConfig class Leader
boar
d2Config(AppConfig): name = 'leaderboard'
leppa/home-assistant
tests/util/test_json.py
Python
apache-2.0
2,695
0.000371
"""Test Home Assistant json utility functions.""" from json import JSONEncoder import os import sys from tempfile import mkdtemp import unittest from unittest.mock import Mock im
port pytest from homeassistant.exceptions import HomeAssistantError from homeassistant.util.json import SerializationError, load_json, save_json # Test data that can be saved as JSON TEST_JSON_A = {"a": 1, "B": "two"} TEST_JSON_B = {"a": "one", "B": 2} # Test data that can not be saved as JSON (keys must be strings) ...
TMP_DIR = mkdtemp() def teardown(): """Clean up after tests.""" for fname in os.listdir(TMP_DIR): os.remove(os.path.join(TMP_DIR, fname)) os.rmdir(TMP_DIR) def _path_for(leaf_name): return os.path.join(TMP_DIR, leaf_name + ".json") def test_save_and_load(): """Test saving and load...
s-hertel/ansible
lib/ansible/utils/display.py
Python
gpl-3.0
19,334
0.001914
# (c) 2014, Michael DeHaan <[email protected]> # # 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, or # (at your option) any lat...
# people like to make containers w/o actual valid passwd/shadow and use host uids username = 'uid=%s' % os.getuid() def filter(self, record): record.user = FilterUserInjector.username return True logger = None # TODO: make this a callback event instead if getattr(C, 'DEFAULT_LOG_PAT...
T_LOG_PATH if path and (os.path.exists(path) and os.access(path, os.W_OK)) or os.access(os.path.dirname(path), os.W_OK): # NOTE: level is kept at INFO to avoid security disclosures caused by certain libraries when using DEBUG logging.basicConfig(filename=path, level=logging.INFO, # DO NOT set to lo...
danstoner/python_experiments
playing_with_pygame/pygame-tutorial-series/part10.py
Python
gpl-2.0
3,658
0.020503
import pygame import time import random pygame.init() display_width = 800 display_height = 600 black = (0,0,0) white = (255,255,255) red = (255,0,0) block_color = (53,115,255) car_width = 73 gameDisplay = pygame.display.set_mode((display_width,display_height)) pygame.display.set_caption('A bit Racey') clock...
_RIGHT: x_change = 0 x += x_change gameDisplay.fill(white) # things(thingx, thingy, thingw, thingh, color) things(thing_startx, thing_starty, thing_width, thing_height, block_color) thing_starty += thing_speed car(x,y) things_d...
thing_starty = 0 - thing_height thing_startx = random.randrange(0,display_width) dodged += 1 thing_speed += 1 thing_width += (dodged * 1.2) if y < thing_starty+thing_height: print('y crossover') if x > thing_startx and x < th...
hbhzwj/GAD
gad/Experiment/EvalForBotnetDetection.py
Python
gpl-3.0
9,139
0.001532
#!/usr/bin/env python """ Evaluate the performance of detector get the statistical quantify for the hypotheis test like False Alarm Rate. """ from __future__ import print_function, division, absolute_import import copy, os import collections from ..Detector import MEM_FS from ..Detector import BotDetector from ..util i...
fpr = fp * 1.0 / (fp + tn) if (fp + tn) > 0 else float('nan') data_recorder.add(threshold=threshold, tp=tp, tn=tn, fp=fp, fn=fn, tpr=tpr, fpr=fpr, detect_result=result) data_frame = data_recorder.to_pandas_dataframe() data_frame...
'all_ips': ground_truth['all_ips'], } def run(self): self.desc = copy.deepcopy(self.args.config['DETECTOR_DESC']) update_not_none(self.desc, self.args.__dict__) self.detect() return self.eval() class TimeBasedBotnetDetectionEval(BotnetDetectionEval): """Cal...
google/tink
testing/cross_language/key_generation_consistency_test.py
Python
apache-2.0
15,388
0.004744
# 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 agreed to in writing, ...
def _test_case(key_size=32, hash_type=common_pb2.SHA256): return ('HkdfPrfKey(%d,%s)' % (key_size, common_pb2.HashType.Name(hash_type)), prf.prf_key_templates._create_hkdf_key_template( key_si
ze, hash_type)) for key_size in [15, 16, 24, 32, 64, 96]: yield _test_case(key_size=key_size) for hash_type in HASH_TYPES: yield _test_case(hash_type=hash_type) def aes_siv_test_cases() -> TestCasesType: for key_size in [15, 16, 24, 32, 64, 96]: yield ('AesSivKey(%d)' % key_size, daead.de...
codepanda/pycicl
tests/fixtures/parallel/tests/testfoo.py
Python
mit
2,035
0.064865
from unittest import TestCase class TestFoo( TestCase ): def test_foo_1( self ): self.assertTrue( True ) def test_foo_2( self ): self.assertTrue( True ) def t
est_foo_3( self ): self.assertTrue( True ) def test_foo_4( self ): self.assertTrue( True ) def test_foo_5( self ): self.assertTrue( True ) def test_foo_6
( self ): self.assertTrue( True ) def test_foo_7( self ): self.assertTrue( True ) def test_foo_8( self ): self.assertTrue( True ) def test_foo_9( self ): self.assertTrue( True ) def test_foo_10( self ): self.assertTrue( True ) def test_foo_11( self ): ...
sfstoolbox/sfs-python
sfs/fd/esa.py
Python
mit
11,543
0
"""Compute ESA driving functions for various systems. ESA is abbreviation for equivalent scattering approach. ESA driving functions for an edge-shaped SSD are provided below. Further ESA for different geometries might be added here. Note that mode-matching (such as NFC-HOA, SDM) are equivalent to ESA in their specif...
an2(n[1], n[0]) + _np.pi L = x0.shape[0] r = _np.linalg.norm(x0, axis=1) phi = _np.arct
an2(x0[:, 1], x0[:, 0]) phi = _np.where(phi < 0, phi + 2 * _np.pi, phi) if Nc is None: Nc = _np.ceil(2 * k * _np.max(r) * alpha / _np.pi) epsilon = _np.ones(Nc) # weights for series expansion epsilon[0] = 2 d = _np.zeros(L, dtype=complex) for m in _np.arange(Nc): nu = m * _np...
victorpoluceno/python_kinect_socketio
urls.py
Python
bsd-2-clause
349
0.005731
from django.conf.urls.defaults import patterns, include, url from singlecontrol.views import index, socketio ur
lpatterns = patterns('', url(r'^$', view=index, name='index'), url(r'^socket\.io', view=socketio, name='socketio'), ) from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns += staticfiles_urlpatt
erns()
diogocs1/comps
web/addons/l10n_be_coda/__init__.py
Python
apache-2.0
1,105
0.00181
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # # Copyright (c) 2011 Noviat nv/sa (www.noviat.be). All rights reserved. #
# This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hop
e that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this p...
emacsway/rope
ropetest/objectinfertest.py
Python
gpl-2.0
14,587
0
try: import unittest2 as unittest except ImportError: import unittest import rope.base.project import rope.base.builtins from rope.base import libutils from ropetest import testutils class ObjectInferTest(unittest.TestCase): def setUp(self): super(ObjectInferTest, self).setUp() self.proj...
): mod = 'class Sample(object):\n pass\n' \ 'sample_class = Sample\n' \ 'sample_class = sample_class\n' mod_scope = libutils.get_string_scope(self.project, mod) sample_class = mod_sc
ope['Sample'] sample_class_var = mod_scope['sample_class'] self.assertEquals(sample_class.get_object(), sample_class_var.get_object()) def test_function_returned_object_static_type_inference1(self): src = 'class Sample(object):\n pass\n' \ 'def a_f...
jaraco/aspen
tests/test_website.py
Python
mit
14,886
0.00477
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os import StringIO from pytest import raises from aspen.website import Website from aspen.http.response import Response from aspen.ex
ceptions import BadLocation simple_error_spt = """ [---] [---] text/plain via stdlib_format {response.body} """ # Tests # ===== def test_basic(): website = Website() expected = os.getcwd() actual = website.www_root assert actual == expected def test_normal_response_is_returned(harness): harnes...
splitlines()) actual = harness.client.GET()._to_http('1.1') assert actual == expected def test_fatal_error_response_is_returned(harness): harness.fs.www.mk(('index.html.spt', "[---]\nraise heck\n[---]\n")) expected = 500 actual = harness.client.GET(raise_immediately=False).code assert actual ==...
jarodwilson/atomic-reactor
tests/docker_mock.py
Python
bsd-3-clause
14,501
0.002
""" 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 os import docker from flexmock import flexmock import requests from atomic_reactor.constants...
'Official': False, 'Secure': False}, '172.17.0.2:5000': {'Mirrors': [], 'Name': '172.17.0.2:5000', ...
'172.17.0.3:5000': {'Mirrors': [], 'Name': '172.17.0.3:5000', 'Official': False, 'Secure': False}, ...
HumanExposure/factotum
dashboard/models/data_source.py
Python
gpl-3.0
1,472
0.002717
from django.db import models from .common_info import CommonInfo from django.utils import timezone from django.urls import reverse from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from django.core.validators import URLValidator def validate_nonzero(value): ...
url = models.CharField(max_length=150, blank=True, validators=[URLValidator()]) estimated_records = models.PositiveIntegerField( default=47, validators=[validate_nonzero], help_text="Estimated number of documents that the data source will eventually contain.", ) state = models.C...
gth=2, choices=STATE_CHOICES, default="AT") description = models.TextField(blank=True) priority = models.CharField(max_length=2, choices=PRIORITY_CHOICES, default="HI") def __str__(self): return self.title def get_absolute_url(self): return reverse("data_source_edit", kwargs={"pk": sel...
grimoirelab/perceval
tests/mocked_package/nested_package/nested_backend_b.py
Python
gpl-3.0
1,241
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright (C) 2015-2020 Bitergia # # Th
is program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option)
any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Pu...
apporc/nova
nova/tests/unit/image/test_glance.py
Python
apache-2.0
53,589
0.000187
# Copyright 2011 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...
ef test_get_remote_service_from_href(self, gcwi_mocked): id_or_uri = 'http://127.0.0.1/123' _ignored, image_id = glance.get_remote_image_service( mock.sentinel.ctx, id_or_uri) self.assertEqual('123', image_id) gcwi_mocked.assert_called_once_with(context=mock.sentinel.ctx,...
stCreateGlanceClient(test.NoDBTestCase): @mock.patch('oslo_utils.netutils.is_valid_ipv6') @mock.patch('glanceclient.Client') def test_headers_passed_glanceclient(self, init_mock, ipv6_mock): self.flags(auth_strategy='keystone') ipv6_mock.return_value = False auth_token = 'token' ...
GeKeShi/cluster-dp
cluster_image.py
Python
gpl-3.0
1,589
0.004405
# import os import numpy as np import matplotlib.pyplot as plt import
random # cluster_dp_GPU = "./cluster_dp_GPU" # os.system(cluster_dp_GPU) input_file = raw_input("enter the input file name:") result_file = raw_input("enter the result file nam
e:") location = [] # input_lable = [] for line in open("dataset/"+input_file, "r"): # line = line.replace('-','') items = line.strip("\n").split(",") # input_lable.append(int(items.pop())) tmp = [] for item in items: tmp.append(float(item)) location.append(tmp) location = np.array(locati...
skoslowski/gnuradio
gr-digital/python/digital/qa_clock_recovery_mm.py
Python
gpl-3.0
4,755
0.003785
#!/usr/bin/env python # # Copyright 2011-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # SPDX-License-Identifier: GPL-3.0-or-later # # import random import cmath from gnuradio import gr, gr_unittest, digital, blocks class test_clock_recovery_mm(gr_unittest.TestCase): def setUp(self):...
ed_result[le
n_e - Ncmp:] dst_data = dst_data[len_d - Ncmp:] #print expected_result #print dst_data self.assertFloatTuplesAlmostEqual(expected_result, dst_data, 1) if __name__ == '__main__': gr_unittest.run(test_clock_recovery_mm, "test_clock_recovery_mm.xml")
dana-i2cat/felix
ofam/src/src/ext/sfa/util/faults.py
Python
apache-2.0
11,639
0.01452
#---------------------------------------------------------------------- # Copyright (c) 2008 Board of Trustees, Princeton University # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and/or hardware specification (the "Work") to # deal in the Work without restriction, i...
faultString = "Invalid RPC Params: %(value)s, " % locals() SfaFault.__init__(self, 102, faultString, extra) def __str__(self): return repr(self.value) # SMBAKER exceptions follow class ConnectionKeyGIDMismatch(SfaFault): def __init__(self, value, extra = None): self.value = va...
Key GID mismatch: %(value)s" % locals() SfaFault.__init__(self, 102, faultString, extra) def __str__(self): return repr(self.value) class MissingCallerGID(SfaFault): def __init__(self, value, extra = None): self.value = value faultString = "Missing Caller GID: %(value)s" % loca...
Emmanu12/Image-Classification-using-SVM
predict.py
Python
apache-2.0
4,390
0.023235
import cv2 import numpy from PIL import Image import numpy as np import os from matplotlib import pyplot as plt bin_n = 16 #
Number of bins def hog(img): gx = cv2
.Sobel(img, cv2.CV_32F, 1, 0) gy = cv2.Sobel(img, cv2.CV_32F, 0, 1) mag, ang = cv2.cartToPolar(gx, gy) bins = np.int32(bin_n*ang/(2*np.pi)) # quantizing binvalues in (0...16) bin_cells = bins[:10,:10], bins[10:,:10], bins[:10,10:], bins[10:,10:] mag_cells = mag[:10,:10], mag[10:,:10], mag[:1...
norikra/norikra-client-python
setup.py
Python
mit
1,304
0.001534
# -*- coding: utf-8 -*- from setuptools import setup, find_packages import os, sys import pkg_resources import norikraclient long_description = open(os.path.join("README.rst")).read() classifiers = [ "Development Status :: 3 - Alpha", "Intended Audience :: System Administrators", "License :: OSI Approve...
pi/norikra-client-python', license='MIT License', packages=find_packages(), include_package_data=True, install_requir
es=requires, dependency_links=deplinks, entry_points={ 'console_scripts': [ 'norikra-client-py = norikraclient.command:main', ], } )