prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
def diff_int(d=0.01*u.cm,a=0.001*u.cm,wl=400*u.nm): '''
function that returns the intensity of a double slit interference pattern ''' theta = arange(-10,10,1e-5)*u.degree x = pi*a*sin(theta)/wl*u.radian xnew = x.decompose() i_single = (sin(xnew)/xnew)**2 y = pi*d*sin(theta)/wl*u.radian ynew = y.decompose() i_double = (cos(ynew))**2 ...
e plot(theta,I) return
files.append(bw.parser.file_from_string('\\x00FOOBAR\\xFF', display_name='My custom signature')) bw.scan('firmware.bin') All magic files generated by this class will be deleted when the class deconstructor is called. ''' BIG_ENDIAN = 'big' LITTLE_ENDIAN = 'little' MAGIC_STRING_FORMAT...
try: self.fd.close() except KeyboardInterrupt as e: raise e
except Exception: pass try: self.raw_fd.close() except KeyboardInterrupt as e: raise e except Exception: pass def cleanup(self): ''' Cleans up any tempfiles created by the class instance. Returns None. ...
ave to match level # to decode. # # See zconf.h, deflate.cc, inflate.cc of zlib library, and zlibmodule.c of # Python. See also RFC1950 (ZLIB 3.3). class _Deflater(object): def __init__(self, window_bits): self._logger = get_class_logger(self) self._compress = zlib.compressobj( zlib....
ger = get_class_logger(self) self._unconsumed = '' self.reset() def decompress(self, size): if not (size == -1 or size > 0): raise Exception('size must be -1 or positive') data = '' while True: if size == -1: data += self._decompre...
tp://bugs.python.org/issue12050 to # understand why the same code cannot be used for updating # self._unconsumed for here and else block. self._unconsumed = '' else: data += self._decompress.decompress( self._unconsumed, siz...
# Claire Jaja # 11/1/2014 # # Project Euler # Problem 2 #
Even Fibonacci numbers # # Each new term in the Fibonacci sequence is generated by adding # the previous two terms. # By starting with 1 and 2, the first 10 terms will be: # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By
considering the terms in the Fibonacci sequence # whose values do not exceed four million, # find the sum of the even-valued terms. def main(): max_value = 4000000 # set up first three terms previous_previous_term = 1 previous_term = 1 current_term = 2 my_sum = 0 while current_term < max_...
list[int]]] = { ATTR_CONDITION_CLEAR_NIGHT: [33, 34, 37], ATTR_CONDITION_CLOUDY: [7, 8, 38], ATTR_CONDITION_EXCEPTIONAL: [24, 30, 31], ATTR_CONDITION_FOG: [11], ATTR_CONDITION_HAIL: [25], ATTR_CONDITION_LIGHTNING: [15], ATTR_CONDITION_LIGHTNING_RAINY: [16, 17, 41, 42], ATTR_CONDITION_PAR...
4], ATTR_CONDITION_SNOWY_RAINY: [29], ATTR_CONDITION_SUNNY: [1, 2, 5], ATTR_CONDITION_WINDY: [32], } FORECAST_SENSOR_TYPES: Final[di
ct[str, SensorDescription]] = { "CloudCoverDay": { ATTR_DEVICE_CLASS: None, ATTR_ICON: "mdi:weather-cloudy", ATTR_LABEL: "Cloud Cover Day", ATTR_UNIT_METRIC: PERCENTAGE, ATTR_UNIT_IMPERIAL: PERCENTAGE, ATTR_ENABLED: False, }, "CloudCoverNight": { ATTR_...
from setuptools import setup import py2exe import os import glob __import__('gtk') __import__('jinja2') __import__('docutils') setup_dict = dict( name='regenerate', version='1.0.0', license='License.txt', author='Donald N. Allingham', author_email='dallingham@gmail.com', description='Re...
"data/ui/*.ui", "data/media/*", "data/help/*.rst", "data/extra/*", "data/*.*", "writers/templates/*" ] }, include_package_data=True, url="https://github.com/dallingham/regenerate", scripts=[ "bin/regenerate", "bin/reg...
, "bin/regxref", "bin/regdiff" ], classifiers=[ 'Operating System :: POSIX', 'Programming Language :: Python :: 2.7', 'License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)', 'Topic :: Scientific/Engineering :: Electronic Design Automation (EDA)' ...
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
me_avg = "{0}_{1}".format(parent.__name__, "avg") cls_name_sqrt = "{0}_{1}".format(parent.__name__, "sqrt") TestSeqPoolAvgCase.__name__ = cls_name_avg TestSeqPoolSqrtCase.__name__ = cls_name_sqrt globals()[cls_name_avg] = TestSeqPoolAvgCase globals()[cls_name_sqrt] = TestSeqPoolSqrtCase create_tes...
_avg_sqrt_class(TestFusionSeqPoolCVMConcatOpCase1) create_test_avg_sqrt_class(TestFusionSeqPoolCVMConcatOpCase2) create_test_avg_sqrt_class(TestFusionSeqPoolCVMConcatOpCase3) create_test_avg_sqrt_class(TestFusionSeqPoolCVMConcatOpCase4) if __name__ == '__main__': unittest.main()
""" SignalHound related detector functions extracted from pycqed/measurement/detector_functions.py commit 0da380ad2adf2dc998f5effef362cdf264b87948 """ import logging import time from packaging import version import qcodes as qc from pycqed.measurement.det_fncs.Base import Soft_Detector, Hard_Detector from pycqed.me...
ratio, skewness, self.f_mod) self.pulsar.AWG.start() time.sleep(self.delay) return self.SH.get_power_at_freq(Navg=self.Navg) def generate_a
wg_seq(self, QI_ratio, skewness, f_mod): SSB_modulation_el = element.Element('SSB_modulation_el', pulsar=self.pulsar) cos_pulse = pulse.CosPulse(channel=self.I_ch, name='cos_pulse') sin_pulse = pulse.CosPulse(channel=self.Q_ch, name='sin_pulse') ...
import logging class Error(Exception): def __init__(self, message, data = {}): self.message = message self.data
= data def __str__(self): return self.message + ": " + repr(self.data) @staticmethod def die(code, error, message = None):
if isinstance(error, Exception): e = error error = '{0}.{1}'.format(type(e).__module__, type(e).__name__) message = str(e) print 'Error: ' + error if message: print message #logging.exception(message) exit(code)
) -> None: """Instantiates the specialist pool service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none ...
he ``request`` instance; if ``request`` is provided, this should not be set. s
pecialist_pool (:class:`google.cloud.aiplatform_v1.types.SpecialistPool`): Required. The SpecialistPool to create. This corresponds to the ``specialist_pool`` field on the ``request`` instance; if ``request`` is provided, this should not b...
from ConfigParser import DEFAULTSECT from cmd import Cmd import logging import sys import subprocess import argparse import datetime from fibbing import FibbingManager import fibbingnode from fibbingnode.misc.utils import dump_threads import signal log = fibbingnode.log CFG = fibbingnode.CFG class FibbingCLI(Cmd): ...
ine=''): """Print information about the fibbing routes""" self.fibbing.print_routes() def do_exit(self, line=''): """Exit the prompt""" return True def do_cfg(self, line=''): part = line.split(' ') val = part.pop() key = part.pop() sect = part.po...
line): """Execute a command on a node""" items = line.split(' ') try: node = self.fibbing[items[0]] node.call(*items[1:]) except KeyError: log.error('Unknown node %s', items[0]) def do_add_route(self, line=''): """Setup a fibbing route ...
end_url=end_url ), region, **kwargs ) def get_all_champions(self, region=None, free_to_play=False): return self._champion_request('', region, freeToPlay=free_to_play) def get_champion(self, champion_id, region=None): return self._champi...
return self._static_request('item', region, locale=locale, version=version, itemListData=item_list_data) def static_get_item(self, item_id, region=None, locale=None, version=None, item_data=None): return self._static_request( 'item/{id}'.format(id=item_id), region, ...
: return self._static_request( 'mastery', region, locale=locale, version=version, masteryListData=mastery_list_data ) def static_get_mastery(self, mastery_id, region=None, locale=None, version=None, mastery_data=None): return self....
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2012-2021 SoftBank Robotics. All rights reserved. # Use of this source code is governed by a BSD-style license (see the COPYING file). """ Test QiBuild Find """ from __future__ import absolute_import from __future__ import unicode_literals from __future__ im...
qibuild_action("find", "world", "-c", "foo") assert record_messages.find(find.library_name("world")) record_messages.reset() qibuild_action("find", "hello", "-c", "foo")
assert record_messages.find(find.binary_name("hello")) rc = qibuild_action("find", "libeggs", "-c", "foo", retcode=True) assert rc == 1
#!/usr/bin/python import getpass import snmp_helper from snmp_helper import snmp_get_oid,snmp_extract import yaml DeviceIp1 = '184.105.247.70' DeviceIp2 = '184.105.247.71' SnmpPort = 161 sysNameOID = '.1.3.6.1.2.1.1.5.0' sysDescOID = '.1.3.6.1.2.1.1.1.0' #Connecting to the devices, using methods from getpass librar...
Printing results to a yaml file SmpFileOutput = 'SnmpInformation.txt' with open(SmpFileOutput, "a") as f: f.write(yaml.safe_dump(SnmpDescOutput, default_flow_
style=False)) print "\nResults printed to a yaml file.\n"
, onlyOne=False): """ list of fields valid to load the table as layer in QGis canvas. QGis automatically search for a valid unique field, so it's needed only for queries and views. """ ret = [] # add the pk pkcols = filter(lambda x: x.primaryKey, self.fields()) ...
fier, QPyNullVariant): self.modifier = None else: self.modifier = int(self.modifier) if self.notNull.upper() == u"Y": self.notNull = False else: self.notNull = True if isinstance(self.comment, QPyNullVariant): self.comment = u...
.constraints(): if (con.type == ORTableConstraint.TypePrimaryKey and self.name == con.column): self.primaryKey = True break def type2String(self): if (u"TIMESTAMP" in self.dataType or self.dataType in [u"DATE", u"SDO_GEOMETRY", ...
import glob import os import shutil from distutil
s import sysconfig from setuptools import setup, Command from setuptools.command.install import install here=os.path.dirname(os.path.abspath(__file__)) site_packages_path = sysconfig.get_python_lib() class CleanCommand(Command): """Custom clean command to tidy up the project root.""" CLEAN_FILES = './build ./...
lit(' ') user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): global here for path_spec in self.CLEAN_FILES: # Make paths absolute and relative to this path abs_paths = glob.glob(os.path.normpa...
import os import tempfile import unittest import logging from pyidf import ValidationLevel import pyidf from pyidf.idf import IDF from pyidf.compliance_objects import ComplianceBuilding log = logging.getLogger(__name__) class TestComplianceBuilding(unittest.TestCase): def setUp(self): self.fd, self.path ...
tation_for_appendix_g idf = IDF() idf.add(obj) idf.save(self.path, check=False) with open(self.path, mode='r') as f: for line in f: log.debu
g(line.strip()) idf2 = IDF(self.path) self.assertAlmostEqual(idf2.compliancebuildings[0].building_rotation_for_appendix_g, var_building_rotation_for_appendix_g)
#!/usr/bin/env python3 """ Open csv file with each a list. All the row-lists are contained in a list. In preparation for entry into the database the data is cleaned. This includes validating the headers and striping and lowering the values. """ import csv HEADERS = ['case number', 'case occurred from date', 'case oc...
se subject type', 'reporting district'] def open_csv(path): # Open the csv file lower and strip all the values. Make sure the csv is # expect format. with open(path) as csvfile: reader = list(csv.reader(csvfile, delimiter=',')) rows = [[val.strip().lower() for val in row] for row in reader...
he receipt to csv file. with open(f'{path}/receipt.csv', 'w') as f: writer = csv.writer(f) writer.writerows(rows) def main(): pass if __name__ == '__main__': main()
from django import forms from registration.forms import RegistrationForm from django.contrib.auth.models import User from models import UserProfile from models import * class Registration(RegistrationForm): picture = forms.ImageField(required=False) bio = forms.CharField(widget=forms.Textarea(),required=False)...
rms.CharField(max_length=200, help_text="Write your paragraph!") choices = ( (True, 'yes'), (False, 'no')) end = forms.ChoiceField(choices=choices, widget=forms.RadioSelect) class Meta: model = Paragraph exclude = ('story', 'parent', 'author','created_datetime') class StoryForm(for...
help_text = "Category", required = True) cat = forms.CharField(required = True) text = forms.CharField(max_length=140, help_text="First Paragraph", required = True) class Meta: model = Story exclude = ('created_datetime', 'author', 'slug', 'category')
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the #...
@mock.patch('airflow.contrib.hooks.azure_data_lake_hook.core.AzureDLFileSystem', autospec=True) @mock.patch('airflow.contrib.hooks.azure_data_lake_hook.lib', autospec=True) def test_list_walk(self, mock_lib, mock_fs): from airflow.contrib.hooks.azure_data_lake_hook import AzureData...
k(azure_data_lake_conn_id='adl_test_key') hook.list('file_path/some_folder/') mock_fs.return_value.walk.assert_called_with('file_path/some_folder/') if __name__ == '__main__': unittest.main()
import json import re import requests from_cmdline = False try: __file__ from_cmdline = True except NameError: pass if not from_cmdline: import vim METHOD_REGEX = re.compile('^(GET|POST|DELETE|PUT|HEAD|OPTIONS|PATCH) (.*)$') HEADER_REGEX = re.compile('^([^()<>@,;:\<>/\[\]?={}]+):\\s*(.*)$') VAR_REGEX...
def is_comment(s): return s
.startswith('#') def do_request(block, buf): variables = dict((m.groups() for m in (GLOBAL_VAR_REGEX.match(l) for l in buf) if m)) variables.update(dict((m.groups() for m in (VAR_REGEX.match(l) for l in block) if m))) block = [line for line in block if not is_comment(line) and line.strip() != ''] if...
# Copyright (C) 2010-2011 Richard Lincoln # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish...
= e2 self.e1 = e1 self.kn = kn self.vamin = vamin self.kr = kr self.efdn = efdn super(ExcitationSystemsExcAC3A, self).__init__(*args, **kw_arg
s) _attrs = ["ta", "ka", "kd", "se1", "kc", "se2", "te", "tf", "tb", "tc", "vamax", "kf", "vemin", "ke", "vfemax", "tr", "e2", "e1", "kn", "vamin", "kr", "efdn"] _attr_types = {"ta": float, "ka": float, "kd": float, "se1": float, "kc": float, "se2": float, "te": float, "tf": float, "tb": float, "tc": float, "v...
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2017, Anaconda, Inc. All rights reserved. # # Powered by the Bokeh Development Team. # # The full license is in the file LICENSE.txt, distributed with this software. #---------------------------------------------------...
''' Create a new HSL color by converting from this color. *Subclasses must implement this method.* Returns: :class:`~bokeh.colors.rgb.RGB` ''' raise NotImplementedError #--------
--------------------------------------------------------------------- # Internal API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #-------------------------------------------------------------...
# -*- coding: utf-8 -*- from .. import server, utils class Memcached(server.Server): binary = 'memcached' def init(self, **kwargs): self.binary = utils.find_binary(kw
args.get('memcached_bin', self.binary)) assert 'ip' in kwargs, "memcached servers requires <ip> option" self.ip = kwargs['ip
'] assert 'port' in kwargs, "memcached server require <port> option" self.port = kwargs['port'] self.command = [ self.binary, '-l', self.ip, '-p', self.port ]
""" The Watchdog Factory instantiates a given Watchdog based on a quick determination of
the local operating system. """ __RCSID__ = "$Id$" import re import platform from DIRAC import S_OK, S_ERROR, gLogger class WatchdogFactory( object ): ############################################################################# def __init__(self): """ Standard constructor """ self.version = platf...
) self.watchDogsLocation = 'DIRAC.WorkloadManagementSystem.JobWrapper' ############################################################################# def getWatchdog( self, pid, exeThread, spObject, jobCPUTime, memoryLimit, processors = 1, jobArgs = {} ): """ This method returns the CE instance correspondi...
# -*- coding: utf-8 -*- # © 2017 Didotech srl (www.didotech.com) { "name": "BoM Warning", "version": "4.0.1.2", "depends": [ "mrp", "base", "product", "warning" ], "author": "Didotech srl", "description": """ This mo
dule is aim to track the warning on Bills of Material. """, "website": "https://www.didotech.com", "category": "Manufacture Resource Planning", "data": [ 'views/product_view.xml', 'views/mrp_bom_view.xml' ], "demo": [], "act
ive": False, "installable": True, }
#!/usr/bin/env python3 print("this is a test program to see if") print("we can make a new file in gith
ub") print("and push it t
o the hub.")
from distutils.core import setup import os from teams import get_version # Compile the list of packages available, because distutils doesn't have # an easy way to do this. packages, data_files = [], [] root_dir = os.path.dirname(__file__) if root_dir: os.chdir(root_dir) for dirpath, dirnames, filenames in os.wa...
se', 'Operating System :: OS Independent',
'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Utilities'], )
ctx=ctx, dtype=dtype) else: raise ValueError("Unexpected length of input tuple: " + str(arg_len)) else: # construct a csr matrix from a sparse / dense one if isinstance(arg1, CSRNDArray) or (spsp and isinstance(arg1, spsp.csr.csr_matrix...
t dtype is float32. Pa
rameters ---------- arg1: NDArray, numpy.ndarray, RowSparseNDArray, tuple of int or tuple of array_like The argument to help instantiate the row sparse ndarray. See above for further details. shape : tuple of int, optional The shape of the row sparse ndarray. ctx : Context, optional ...
pe=smartos_type) elif smartos_type == SMARTOS_ENV_LX_BRAND: return JoyentMetadataSocketClient(socketpath=metadata_sockfile, smartos_type=smartos_type) raise ValueError("Unknown value for smartos_type: %s" % smartos_type) def write_boot_content(content, conten...
mi_data("system-product-name") else: system_type = product_name if system_type and 'smartdc' in system_type.lower(): return SMARTOS_ENV_KVM return None # Convert SMARTOS 'sdc:nics' data to network_config yaml def convert_smartos_network_data(network_data=None, ...
SMARTOS sdc:nics configuration data sdc:nics data is a dictionary of properties of a nic and the ip configuration desired. Additional nic dictionaries are appended to the list. Converting the format is straightforward though it does include duplicate information as well as data which appears to...
# # CDR-Stats License # http://www.cdr-stats.org # # This S
ource 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/. # # Copyright (C) 2011-2015 Star2Billing S.L. # # The Initial Developer of the Original Code is # Arezqui Belaid <info@star2billi...
k.permissions import IsAuthenticatedOrReadOnly from rest_framework.authentication import BasicAuthentication, SessionAuthentication from rest_framework import viewsets from apirest.user_serializers import UserSerializer #from permissions import CustomObjectPermissions class UserViewSet(viewsets.ReadOnlyModelViewSet):...
import requests import json import yaml import pandas as pd import pprint from jsonld_processor import jsonld2nquads, fetchvalue from utils import int2str class SmartAPIHandler: def __init__(self): # description info about endpoint, bioentity and api self.endpoint_info = {} self.bioentity_i...
results[_para['name']] = _template['template'].replace('{{input}}', value) elif uri == _template['valueType']: results[_para['name']] = _template['template'].rep
lace('{{input}}', value) else: results[_para['name']] = value if type(value) != list: data = requests.get(endpoint_name, params=results) else: data = requests.post(endpoint_name, data=results) return data ''' parse th...
import galaxy.model from galaxy.model.orm import * from base.twilltestcase import TwillTestCase class TestMetadataEdit( TwillTestCase ): def test_00_metadata_edit( self ): """test_metadata_edit: Testing metadata editing""" self.logout() self.login( email='test@bx.psu.edu' ) self.ne...
y.model.HistoryDatasetAssociation.table.c.create_time ) ).first() self.home() # Due to twill not being able to handle the permissions forms, we'll eliminate # DefaultHistoryPermissions prior to upload
ing a dataset so that the permission # form will not be displayed on ted edit attributes page. for dp in latest_hda.dataset.actions: dp.delete() dp.flush() latest_hda.dataset.refresh() self.check_history_for_string( '1.bed' ) self.check_metadata_for_string...
import os import subprocess import pytest import flask_resize from .decorators import requires_redis, slow @pytest.fixture def env(tmpdir, redis_cache): basedir = tmpdir conffile = tmpdir.join('flask-resize-conf.py') conffile.write( """ RESIZE_URL = 'https://example.com' RESIZE_ROOT = '{root}' ...
es_empty(env): assert run(env, 'flask-resize', 'list', 'images') == [] @slow def test_bin_list_has_images( env, resizetarget_opts, image1_name, image1_data, image1_key ): resize_target = flask_resize.ResizeTarget(**resizetarget_opts) resize_target.image_store.save(image1_name, image1_...
list', 'images') == [image1_key] @requires_redis @slow def test_bin_list_cache_empty(env, redis_cache): assert run(env, 'flask-resize', 'list', 'cache') == [] @requires_redis @slow def test_bin_list_has_cache(env, redis_cache): redis_cache.add('hello') redis_cache.add('buh-bye') assert set(run(env, ...
from __futur
e__ import unicode_literals from frappe import _ def get
_data(): return { 'fieldname': 'therapy_session', 'transactions': [ { 'label': _('Assessments'), 'items': ['Patient Assessment'] } ] }
#!/usr/bin/python # # Copyright 2012 Anthony Campbell (anthonycampbell.co.uk) # # 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 re...
le, str(verbose)], stdout=subprocess.PIPE) output, stderr = process.communicate() process.wait() except exceptions.Exception as error: print "\n Unabl
e to execute clojure-imdb-parser.jar!" print "\n " + str(error) sys.exit(1) else: print "\n Unable to find latest clojure-imdb-parser.jar!" sys.exit(1) # Where we at? print output # If we're being run directly if __name__ == "__main__": main()
# JEB sample script # http://www.android-decompiler.com/ # # AlertMarker.py # Set(unset) alert marker to focued method. # # Copyright (c) 2013 SecureBrain from jeb.api import IScript from jeb.api.dex import Dex from jeb.api.ui import View import string
class AlertMarker(IScript): def run(self, jeb): self.jeb = jeb self.dex = jeb.getDex() self.ui = jeb.getUI() success = self.start() def start(self): view = self.ui.getView
(View.Type.ASSEMBLY) msig = view.getCodePosition().getSignature() md = self.dex.getMethodData(msig) if not md: print 'caret is not in method.' return f = md.getUserFlags() print 'target:' + msig if (f & Dex.FLAG_ALERT) == 0: ...
onnect(dummy_request) dummy_request.json_body = {"conn_id": str(test_uuids[1]), "channels": ["a"]} result = unsubscribe(dummy_request) assert len(result["channels"]) == 0 assert result["channels_info"]["users"] == [] assert result["channels_info"]["channels"] == {} @pytest.mark...
d_json(self, dummy_request, test_uuids): from channelstream.wsgi_views.server import connect, info, message dummy_request.json_body = { "username": "test1", "conn_id": str(test_uuids[1]), "fresh_user_state": {"key": "foo"}, "user_state": {"bar": "baz", "p...
s": ["bar"], "channels": ["a", "aB", "c", "D"], "channel_configs": {"a": {"store_history": True, "history_size": 2}}, } connect(dummy_request) dummy_request.json_body = [ { "type": "message", "user": "test1", "ch...
list of all spaz. #Therefore, I am making the list here so I can get which spaz belongs #to the player supplied by HitMessage. self.spazList.append(spaz) # we want a bigger area-of-interest in co-op mode # if isinstance(self.getSession(),bs.CoopSession): spaz.node.areaOfInterest...
ate, repeat=True) def _getTotalTeamLives(self,team): return sum(player.gameData['lives'] for player in team.players) def handleMessage(self,m): if isinstance(m,bs.PlayerSpazDeathMessage): bs.TeamGameActivity.handleMessage(self, m) # augment standard behavior ...
player = m.spaz.getPlayer() respawnPoints = None print([player, m.spaz.hitPoints, "killed by", m.killerPlayer]) if m.killerPlayer is None: pass #Don't take away a life for non-violent death elif m.killerPlayer == m.spaz.getPlayer(): pass ...
from Crypto.Cipher import AES import xml.etree.cElementTree as ET import win32con, win32api, win32crypt import base64, hashlib, os import binascii, struct from config.constant import * from config.write_output import print_output, print_debug from config.header import Header from config.moduleInfo import Module...
nc_binary[d])[0] ^ struct.unpack('B', aes_key[d])[0]) # cast the result byte tmp = '' for dec in decrypted
: tmp = tmp + struct.pack(">I", dec).strip('\x00') # byte to hex return binascii.hexlify(tmp) def dictionary_attack(self, login, md5): wordlist = get_dico() for word in wordlist: hash = hashlib.md5('%s\nskyper\n%s' % (login, word)).hexdigest() if hash == md5: return word return F...
from . import adaptVor_driver from .adaptVor_driver import Adapti
veVoronoiDr
iver
return (c for c in self.choices if c.lower().startswith(prefix.lower())) # Override the choices completer with one that is case insensitive argcomplete.completers.ChoicesCompleter = CaseInsensitiveChoicesCompleter def enable_autocomplete(parser): argcomplete.autocomplete = argcomplete.CompletionFinder() ...
options) else: try: param = command_parser.add_argument( *arg.options_list, **arg.options) except argparse.ArgumentError: dest = arg.o
ptions['dest'] if dest in ['no_wait', 'raw']: pass else: raise param.completer = arg.completer command_parser.set_defaults( func=metadata, command=command_...
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2019 Manas.Tech # License granted by Canonical Limited # # 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 Foundation. # # ...
ame, options, project): super().__init__(name, options, project) if project._get_build_base() not in ("core", "core16", "core18"): raise errors.PluginBaseError( part_name=self.name, base=project._get_build_base()
) self.build_snaps.append("crystal/{}".format(self.options.crystal_channel)) self.build_packages.extend( [ "gcc", "pkg-config", "libpcre3-dev", "libevent-dev", "libyaml-dev", "libgmp-dev", ...
import numpy as np import h5py f = h5py.File('hdf5/data_streaming.h5', 'w') ADSL_2008 = f.create_group("ADSL_Montsouris_2008_07_01") # retreve: ADSL_2008 = f['ADSL_Montsouris_2008_07_01'] gvb_adsl_2008 = np.load('python_flows/flows_marked_GVB_juill_2008_ADSL_cut_BGP_AS.npy') ADSL_2008.create_dataset('GVB', data=gvb_...
B_nov_2009_ADSL_BGP_AS.npy') ADSL_nov_2009.create_dataset('GVB'
, data=gvb_adsl_nov_2009) dipcp_adsl_nov_2009 = np.load('python_flows/dipcp_flows_ADSL_nov_2009.npy') ADSL_nov_2009.create_dataset('dipcp', data=dipcp_adsl_nov_2009) FTTH_nov_2009 = f.create_group("FTTH_Montsouris_2009_11_26") gvb_ftth_nov_2009 = np.load('python_flows/flows_marked_GVB_nov_2009_FTTH_BGP_AS.npy') FTTH_...
fr
om task19_PageObject.MainPage import MainPage def test_adding_and_deleting_from_cart(driver): main_page = MainPage(driver) main_page.open() #
Add 3 ducks to the cart in a loop for i in range(1, 4): # Click at the i-d duck product_page = main_page.click_to_product_number(i) product_page.put_product_into_cart() main_page = product_page.go_to_home_page() cart_page = main_page.go_to_checkout() cart_page.remove_all_...
from charmhelpers.core.hookenv import ( config, unit_get, ) from charmhelpers.contrib.network.ip import ( get_address_in_network, is_address_in_network, is_ipv6, get_ipv6_addr, ) fr
om charmhelpers
.contrib.hahelpers.cluster import is_clustered PUBLIC = 'public' INTERNAL = 'int' ADMIN = 'admin' _address_map = { PUBLIC: { 'config': 'os-public-network', 'fallback': 'public-address' }, INTERNAL: { 'config': 'os-internal-network', 'fallback': 'private-address' }, ...
# 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...
name) def test_convert_entity_to_ast_class_hierarchy(self): class TestBase(object): def __init__(self, x='base'): self.x = x def foo(self): return self.x def bar(self): return self.x class TestSubclass(TestBase):
def __init__(self, y): super(TestSubclass, self).__init__('sub') self.y = y def foo(self): return self.y def baz(self): return self.y program_ctx = self._simple_program_ctx() with self.assertRaisesRegex(NotImplementedError, 'classes.*whitelisted'): convers...
ght 2008-2015 Nokia Networks # Copyright 2016- Robot Framework Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unle...
err.message), warn_on_skipped) def _log_failed_parsing(self, message, warn): if warn: LOGGER.warn(message) else: LOGGER.info(message) def _get_include_suites(self, path, incl_suites): if not isinstance(incl_suites, SuiteNamePatterns): incl_suites = S...
_suites(incl_suites)) if not incl_suites: return incl_suites # If a directory is included, also all its children should be included. if self._directory_is_included(path, incl_suites): return SuiteNamePatterns() return incl_suites def _create_included_suites(s...
"""Tests for the USB Discovery integration.""" from homeassistant.components.usb.m
odels import USBDevice conbee_device = USBDevice( device="/dev/cu.usbmodemDE24338801", vid="1CF1", pid="0030", serial_number="DE2433880", manufacturer="dresden elektronik ingenieurtechnik GmbH", description="ConBee II", ) slae_sh_device = USBDevice( device="/dev/cu.usbserial-110", vid="...
_22_98_88_7F", manufacturer="Silicon Labs", description="slae.sh cc2652rb stick - slaesh's iot stuff", ) electro_lama_device = USBDevice( device="/dev/cu.usbserial-110", vid="1A86", pid="7523", serial_number=None, manufacturer=None, description="USB2.0-Serial", )
from bambu_mail.shortcuts import subscribe def newsletter_optin(sender, user, **kwargs): subscribe
( user.email, list_id = 'signup', double_optin = False, send_welcome = False
)
'''Doc build con
stants''' from django.conf import settings from django.utils.translation import ugettext_lazy as _ DOCKER_SOCKET = getattr(settings, 'DOCKER_SOCKET', 'unix:///var/run/docker.sock') DOCKER_VERSION = getattr(settings, 'DOCKER_VERSION', 'auto') DOCKER_IMAGE = getattr(settings, 'DOCKER_IMAGE', 'rtfd-build') DOCKER_LIMIT...
42 DOCKER_OOM_EXIT_CODE = 137
from typing import KeysView from baby_steps import given, then, when from district42
import optional, schema def test_dict_empty_keys(): with given: sch = schema.dict with when: res = sch.keys() with then: assert res == KeysView([]) def test_dict_keys(): with given: sch = schema.dict({ "id": schema.int, "name": schema.
str, optional("email"): schema.str, }) with when: res = sch.keys() with then: assert res == KeysView(["id", "name", "email"])
go.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields....
'django.db.models.fields.TextField', [], {'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'site': ('django.db.models.fields.related.ForeignKey
', [], {'to': "orm['sites.Site']"}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '255', 'db_index': 'True'}), 'template': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '200'}), ...
from __future__ import division, print_function, absolute_import import pytest import numpy as np from numpy.testing import assert_, assert_equal, assert_allclose import scipy.special as sc from scipy.special._testutils import assert_func_equal def test_wrightomega_nan(): pts = [complex(np.nan, 0), c...
versions of # numpy, assert_equal doesn't check the sign of the real and imaginary # parts when comparing complex zeros. It does check the sign when the # arguments are *real* scalars. assert_equal(res.real, expected.real) assert_equal(res.imag, expected.imag) def test_wrighto...
complex(-np.inf, 10), complex(10, np.inf), complex(10, -np.inf)] for p in pts: assert_equal(sc.wrightomega(p), p) def test_wrightomega_singular(): pts = [complex(-1.0, np.pi), complex(-1.0, -np.pi)] for p in pts: res = sc.wrightomega(p) ass...
model is based on Fullertons algorithm for superlattices as described in Phys. Rev. B vol. 45 p. 9292 (1992). ''' # Programmed by Matts Bjorck 20091215 import numpy as np import genx.models.sxrd from genx.models.utils import f, rho import time from genx.models.sxrd import UnitCell, AtomGroup, Instrument, Slab, SymT...
'''Calculate the strucutre factor for a a layer n is the thickness of the bilayer in units of slabs''' pass def calc_fb(self, n, h, k, l): '''Calcualte the structure factor for a b layer
n is the thickness of the bilayer in units of slabs''' pass def calc_fsl(self, unit_cell, h, k, l): '''Calculate the strucutre factor for the entire superlattice. ''' raise NotImplementedError('calc_fsl has to be implemented in ' '...
#!/usr/bin/python import sys sys.path.append('..') from bcert_pb2 import * import binascii # fill out a minimal bitcoin cert cert = BitcoinCert() # first the data part (the part is later signed by the "higher level cert" or "the blockchain") cert.data.version = '0.1' cert.data.subjectname = 'Foo Inc.' email = cert....
AIL email.value = 'foo@fooinc.com' url = cert.data.contacts.add() url.type = url.URL url.value = 'http://www.fooinc.com' paykey = cert.data.paymentkeys.add() paykey.usage = paykey.PAYMENT paykey.algorithm.type = paykey.algorithm.STATIC_BTCADDR # is default anyway key = paykey.value.append("mrMyF68x19kAc2byGKqR9MLfdAe1t...
) from bitcoin import hash_160 # add signature to cert #sig = cert.signatures.add() #sig.algorithm.type = sig.algorithm.BCPKI #sig.algorithm.version = "0.3" #sig.value = "foo1" # for signatures of type BCPKI the alias IS the value, # other types place the signature of BitcoinCertDataToHash(certDat...
import csv import random import cassandra from nose.tools import assert_items_equal class DummyColorMap(object): def __getitem__(self, *args): return '' def csv_rows(filename, delimiter=None): """ Given a filename, opens a csv file and yields it line by line. """ reader_opts = {} i...
t_csvs_items_equal(filename1, filename2): with open(filename1, 'r') as x, open(filename2, 'r') as y: assert_items_equal(list(x.readlines()), list(y.readlines())) def random_list(gen=None, n=None): if gen is None: def gen(): return random.randint(-1000, 1000) if n is None: ...
h(): return random.randint(1, 5) else: def length(): return n return [gen() for _ in range(length())] def write_rows_to_csv(filename, data): with open(filename, 'wb') as csvfile: writer = csv.writer(csvfile) for row in data: writer.writerow(row)...
class StoreChangeLogger: def __init__(self, store_name, context)
-> None: self.topic = f'{context.application_id}-{store_name}-changelog' self.context = context
self.partition = context.task_id.partition self.record_collector = context.state_record_collector def log_change(self, key: bytes, value: bytes) -> None: if self.record_collector: self.record_collector.send(self.topic, key, value, self.context.timestamp, partition=self.partitio...
# -*- coding: utf-8 -*- """ /*************************************************************************** GeobricksTRMM A QGIS plugin Download TRMM daily data. ------------------- begin : 2015-10-06 copyright : (C) ...
**************************************/ This script initializes the plugin, making it known to QGIS. """ # noinspection PyPep8Naming def classFactory(iface): # pylint: disable=invalid-name """Load GeobricksTRMM class from file GeobricksTRMM. :param iface: A QGIS interface instance. :type iface: QgsInte...
.geobricks_trmm_qgis import GeobricksTRMM return GeobricksTRMM(iface)
from datetime import datetime, timedelta import re import types from unittest import TestCase from django.core.exceptions import ValidationError from django.core.validators import ( BaseValidator, EmailValidator, MaxLengthValidator, MaxValueValidator, MinLengthValidator, MinValueValidator, RegexValidator, URL...
), NOW, None), (MinValueValidator(NOW), NOW + timedelta(days=1), None), (MinValueValidator(0), -1, ValidationError), (MinValueVali
dator(NOW), NOW - timedelta(days=1), ValidationError), (MaxLengthValidator(10), '', None), (MaxLengthValidator(10), 10 * 'x', None), (MaxLengthValidator(10), 15 * 'x', ValidationError), (MinLengthValidator(10), 15 * 'x', None), (MinLengthValidator(10), 10 * 'x', None), (MinLengthValidator(10...
#!/usr/bin/env python # Install the Python helper library from twilio.com/docs/python/install import os from twilio.rest import Client # To set up envir
onmental variables, see http://twil.io/secure ACCOUNT_SID = os.environ['TWILIO_ACCOUNT_SID'] AUTH_TOKEN = os.environ['TWILIO_AUTH_TOKEN'] client = Client(ACCOUNT_SID, AUTH_TOKEN) notification = client.notify.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .notifications.create(identity='0000000
1', body='Hello Bob') print(notification.sid)
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # yo
u may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR ...
or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Load plugin assets from disk.""" from __future__ import absolute_import from __future__ import division from __future__ ...
# -*- coding:utf-8 -*- # @author yuding # 2017-09-23 import re import os import shutil import msvcrt import traceback def mkdir(path): # 去除首位空格 path = path.strip() # 去除尾部 \ 符号 path = path.rstrip("\\") isExists = os.path.exists(path) if not isExists: os.makedirs(path) ...
不要 content = tf.read() #从第二行开始 # 删除头部和换行符 content = re.sub(r'\n', '', content) tf.close() return content def getAllData2(
dirname, fname, name): (dic, geneDic) = getTargetData(fname) content = getContent(fname) fl = open(dirname + '\\' + name + '.txt', 'wb') length = len(content) for unit in dic: pt = '' for k in dic[unit]: pt = pt + k + ',' lh = len(p...
""" .. module:: area_attribute The **Area Attribute** Model. PostgreSQL Definition --------------------- The :code:`area_attribute` table is defined in the MusicBrainz Server as: .. code-block:: sql CREATE TABLE area_attribute ( -- replicate (verbose) id SERIAL, -- PK ...
null=True) area_attribute_text = models.TextField(null=True) def
__str__(self): return 'Area Attribute' class Meta: db_table = 'area_attribute' models.signals.pre_save.connect(pre_save_model_attribute, sender=area_attribute)
# -*- coding: utf-8 -*- import time import requests import json import logging import threading from .exceptions import ClientError from
.utils import to_unixtime from .compat import to_unicode logger = logging.getLogger(__name__) class Credentials(object): def __init__(self, access_key_id="", access_key_secret="", security_token=""): self.access_key_id = access_key_id self.access_key_secret = access_key_secret self.securi...
ecret(self): return self.access_key_secret def get_security_token(self): return self.security_token DEFAULT_ECS_SESSION_TOKEN_DURATION_SECONDS = 3600 * 6 DEFAULT_ECS_SESSION_EXPIRED_FACTOR = 0.85 class EcsRamRoleCredential(Credentials): def __init__(self, access_key_id, ...
GnuXzPackage
('clutter', '1.10.6', sources = [ 'http://source.clutter-project.org/sources/clut
ter/1.10/%{name}-%{version}.tar.xz' ], )
#!/usr/bin/env python import sys from manticore import issymbolic from manticore.native import Manticore """ Replaces a variable that controls program flow with a tainted symbolic value. This in turn explores all possible states under that variable's influence, and reports the specific cmp/test instructions can be i...
ainted data. Usage: $ gcc -static -g src/state_explore.c -o state_explore # -static is optional $ ADDRESS=0x$(objdump -S state_explore | grep -A 1 '((value & 0xff) != 0)' | tail
-n 1 | sed 's|^\s*||g' | cut -f1 -d:) $ python ./introduce_symbolic_bytes.py state_explore $ADDRESS Tainted Control Flow: introducing symbolic value to 7ffffffffd44 400a0e: test eax, eax 400a19: cmp eax, 0x3f 400b17: test eax, eax 400b1e: cmp eax, 0x1000 400b63: test eax, eax 400a3e: cmp eax, 0x41 400a64: cm...
# Fabric file for the health monitor. # # This should only be used for deployment tasks. make should be # sufficient for development. import os from fabric.api import env, task, roles, lcd, local, run, put BASE_DIR = os.path.dirname(__file__) env.path = ":".join([ '/home/forcer/bin/', os.path.join(BASE_DIR,...
put("compressed_cache.tar.gz") local("rm compressed_cache.tar.gz") run("tar -C health.jorgenschaefer.de/static/ -xzf compressed_cache.tar.gz") run("rm compressed_cache.tar.gz") run("venv/bin/pip install -qr lib/requirements.txt") run("venv/bin/django-admin migrate --noinput " "--setting...
ion") run("venv/bin/django-admin collectstatic --noinput " "--settings=healthmonitor.settings_production") run("sudo /usr/bin/supervisorctl restart healthmonitor")
# This file is part of PyEMMA. # # Copyright (c) 2015, 2014 Computational Molecular Biology Group, Freie Universitaet Berlin (GER) # # PyEMMA is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either vers...
return self._max_centers @max_centers.setter def max_centers(self, value): value = int(value) if value < 0: raise ValueError("max_centers has to be positive") self._max_centers = value @property def n_clusters(self): return self.max_centers @n_cl...
self.max_centers = val def _estimate(self, iterable, **kwargs): ######## # Calculate clustercenters: # 1. choose first datapoint as centroid # 2. for all X: calc distances to all clustercenters # 3. add new centroid, if min(distance to all other clustercenters) >= dmin ...
# -*- coding: utf-8 -*- """ Created on Tue Jan 12 11:57:45 2016 @author: katerinailiakopoulou """ import gensim import logging import sys logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) """ The Finder finds which words are similar to the one given based on the word2vec wo...
self.n = topn def get_most_similar(self,input): self.output_file.write('---Similar words to:' + input + '---\n') try: self.output_file.write(str(self.m.most_similar([input], topn=self.n))) except KeyError as e: self.output_file.write(str(e)) self.outp...
lar(self,input): self.output_file.write('--- Similar words to: ' + input + '---\n') pos_negs = input.split('NOT') pos = pos_negs[0] neg = pos_negs[1] poss = pos.split('AND') negs = neg.split(',') positives = [] for p in poss: positives.append(p...
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware 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 ...
DB
behaves # differently in Python 2 vs 3. Additionally, serializing a bytes to JSON behaves differently # in Python 2 vs 3. So, just keep it as a unicode (or ordinary Python 2 str). realTermsHash = hashlib.sha256(collection['terms'].encode('utf-8')).hexdigest() if termsHash != realTermsHash: # Thi...
# -*- coding: utf-8 -*- from p
yload.plugin.Crypter import Crypter class Dereferer(SimpleDereferer): __name = "Dereferer" __type = "crypter" __version = "0.11" __pattern = r'https?://([^/]+)/.*?(?P<LINK>(ht|f)tps?(://|%3A%2F%2F).+)' __config = [("use_subfolder" , "bool", "Save package to subfolder" , True),...
__authors = [("zoidberg", "zoidberg@mujmail.cz")]
#!/usr/bin/env vpython # Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import subprocess import sys import unittest import mock import merge_lib as merger class MergeLibTest(unittest.TestCase...
invalid_profraw_files = [] counter_overflows = [] merger._validate_and_convert_profraw( 'mock.profraw', output_profdata_files, invalid_profraw_files, counter_overflows, '/usr/bin/llvm-cov') self.assertEqual( expected_results, [output_profdata_files, invalid_pro...
main()
"Need to setup communication first before attempting any BitBox02 calls" ) coin = self._get_coin() tx_script_type = None # Build BTCInputType list inputs = [] for txin in tx.inputs(): my_pubkey, full_path = keystore.find_my_pubkey_in_txinout...
address # check for change if txout.is_change: my_pubkey, change_pubkey_path = keystore.find_my_pubkey_in_txinout(txout) outputs.append( bitbox02.BTCOutputInternal( keypath=change_pubkey_path, value=txout.value, script_c...
if addrtype == OnchainOutputType.P2PKH: output_type = bitbox02.btc.P2PKH elif addrtype == OnchainOutputType.P2SH: output_type = bitbox02.btc.P2SH elif addrtype == OnchainOutputType.WITVER0_P2WPKH: output_type = bitbox02...
#----------------------------------------------------------------------------- # Copyright (c) 2005-2020, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License (version 2 # or later) with exception for distributing the bootloader. # # The full license is in the file COPYING.txt...
---------------------------
----- """ Import hook for PyGObject's "gi.repository.Champlain" package. """ from PyInstaller.utils.hooks import get_gi_typelibs binaries, datas, hiddenimports = get_gi_typelibs('Champlain', '0.12')
# -*- coding: utf-8 -*- """ @author: kevinhikali @email: hmingwei@gmail.com """ import tensorflow as tf A = [[1, 2, 3, 4]] B = [[2, 2,
3, 4]] casted = tf.cast(tf.equal(A, B), dtype='float32') with tf.Session() as sess:
print(sess.run(casted))
from unittest2 import TestCase, skip from bsPlugins.Annotate import AnnotatePlugin import os path = 'testing_files/' class Test_AnnotatePlugin(TestCase): def setUp(self): self.plugin = AnnotatePlugin() def test_with_signals(self): self.plugin(**{'track':path+'KO50.bedGraph', 'assembly':'mm9',...
'promoter':0, 'intergenic':0, 'UTR':0}) with open(self.plugin.output_files[0][0],'rb') as f: content = f.readlines() self.assertEqual(len(content),50) def tearDown(self): for f in os.listdir('.'): if f.startswith('tmp'):
os.system("rm -rf %s" % f) # nosetests --logging-filter=-tw2 test_Annotate.py
idth=220,checkHeight=150) self.chkbutton[4]= xbmcgui.ControlButton(imgX+pw,imgY+ph, pw, ph, '5', font='font1');#,focusTexture=check_image ,noFocusTexture=uncheck_image);#,checkWidth=220,checkHeight=150) self.chkbutton[5]= xbmcgui.ControlButton(imgX+pw+pw,imgY+ph, pw, ph, '6', font='font1');#,focusTextur...
ontrol(self.cancelbutton) self.chkbutton[6].controlDown(self.cancelbutton); self.chkbutton[6].controlUp(self.chkbutton[3]) self.chkbutton[7].controlDown(self.cancelbutton); self.chkbutton[7].controlUp(self.chkbutton[4]) self.chkbutton[8].
controlDown(self.okbutton); self.chkbutton[8].controlUp(self.chkbutton[5]) self.chkbutton[6].controlLeft(self.chkbutton[8]);self.chkbutton[6].controlRight(self.chkbutton[7]); self.chkbutton[7].controlLeft(self.chkbutton[6]);self.chkbutton[7].controlRight(self.chkbutton[8]); ...
# Auto-clustering, suggested by Matt Terry from skimage import io, color, exposure from sklearn import cluster, preprocessing import numpy as np import matplotlib.pyplot as plt url = 'http://blogs.mathworks.com/images/steve/2010/mms.jpg' import os if not os.path.exists('mm.jpg'): print("Downloading M&M's...") ...
left, right = -100, 100 bins = np.arange(left, right) H, x_edges, y_edges = np.histogram2d(a.flatten(), b.flatten(), bins, normed=True) ax = plt.subplot2grid((2, N), (0, 2)) H_bright = exposure.rescale_intensity(H, in_range=(0, 5e-4)) ax.imshow(H_bright, extent=[left, ri...
5 L = len(mid_bins) yy, xx = np.meshgrid(mid_bins, mid_bins) Z = kmeans.predict(np.column_stack([xx.ravel(), yy.ravel()])) Z = Z.reshape((L, L)) ax = plt.subplot2grid((2, N), (0, 3)) ax.imshow(Z, interpolation='nearest', extent=[left, right, right, left], cmap=plt.cm.Spectral, alpha=0.8) ax.imshow...
from allennlp.modules.encoder_base import _EncoderBase from allennlp.common import Registrable class Seq2VecEncoder(_EncoderBase, Registrable): """ A `Seq2VecEncoder` is a `Module` that takes as input a sequence of vectors and returns a single vector. Input shape : `(batch_size, sequence_length, input_di...
et_input_dim()` and `get_output_dim()`. You might need this if y
ou want to construct a `Linear` layer using the output of this encoder, or to raise sensible errors for mis-matching input dimensions. """ def get_input_dim(self) -> int: """ Returns the dimension of the vector input for each element in the sequence input to a `Seq2VecEncoder`. This...
from .main import main # run the progra
m if __name__ == '__
main__': main()
def s
um_diagonal_principal(matrix): return sum(matrix[i][i] for i in range(len(matrix))) def sum_diagonal_secondary(matrix): return sum(matrix[i][-i-1] for i in range(len(matrix))) def diagonal(matrix): s1 = sum_diagonal_principal(matrix) s2 = sum_diagonal_secondary(matrix) return "Princip
al Diagonal win!" if s1 > s2 else "Secondary Diagonal win!" if s1 < s2 else "Draw!"
AUTH_URL = "h
ttps://quality.hubwoo.com/rest/auth/latest/sessio
n"
o_system,units,rssi_alarm,cap_alarm,unused1,osd_item_count,alt_alarm", "osd_items", "stats_item_count", "stats_items", "timer_count", "timer_items", "legacy_warnings,warnings_count,ena...
== 0: break s.append(b) self.msp_name['name'] = s.decode("utf-8") elif cmd == self.MSP_ACC_CALIBRATION: x = None elif cmd == self.MSP_MAG_CALIBRATION: x = None elif cmd == self.MSP_BOX: x = None ...
None elif cmd == self.MSP_SERVO_CONF: x = None elif cmd == self.MSP_DEBUGMSG: x = None elif cmd == self.MSP_DEBUG: x = None else: print("Unhandled command ", cmd, dataSize) def parseMspData(self, buf): for c in buf:...
from setuptools import set
up, find_packages setup( name="gevent-websocket", version="0.3.6", description="Websocket handler for the gevent pywsgi server, a P
ython network library", long_description=open("README.rst").read(), author="Jeffrey Gelens", author_email="jeffrey@noppo.pro", license="BSD", url="https://bitbucket.org/Jeffrey/gevent-websocket", download_url="https://bitbucket.org/Jeffrey/gevent-websocket", install_requires=("gevent", "gree...
def
ault_app_
config = 'forked_apps.catalogue.config.CatalogueConfig'
Device']: warn("Only import of data from NIRScout devices have been " "thoroughly tested. You are using a %s device. " % hdr['GeneralInfo']['Device']) # Parse required header fields # Extract frequencies of light used by machine fnirs_wavelengths =...
, line) for line in fid]
onset = np.zeros(len
# 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) from pants.subsystem...
# All checks have this option. register('--skip', default=False, action='store_true', help='If enabled, skip this style checker.') def get_plugin(self, python_file): return self.get_plugin_type()(self.get_options(), python_file) def get_plugin_type(self): raise NotImplementedError('get_p...
at(type(self)))
import logging logging.basicConfig() logger = logging.getLogger(__name__) import maya.cmds as cmds import constants as const import rigBuildLib as complib reload(complib) class Component(object): def __init__(self): self.cmpdata = {} self.compName = None self.compSide = None self....
lib.createDefaultMetaData(inputGrp, self.name, self.side, 'componentGroup') complib.parentTo(inputGrp, self.cmpdata['input']) self.cmpdata[name] = inputGrp
def addCustomPartsGroup(self, name): grpName = "{}_{}".format(name, const.GROUP_SUFFIX['master']) inputGrp = complib.createGroup(grpName, self.name, self.side) complib.createDefaultMetaData(inputGrp, self.name, self.side, 'componentGroup') complib.parentTo(inputGrp, self.cmpdata['parts...
ert p.type == 'a' def test_module_parameters_members(self): args = dict( partition='Common', members=[ dict( server='foo', virtual_server='bar' ) ] ) p = ModuleParameters(params=args)...
True]) tm.update_on_device = Mock(return_value=True) tm.read_current_from_device = Mock(return_value=current) # Override methods to force specific logic in the module to happen mm = ModuleManager(module=module) mm.version_is_less_than_12 = Mock(return_value=True) mm.get_...
ert results['preferred_lb_method'] == 'topology' assert results['alternate_lb_method'] == 'drop-packet' assert results['fallback_lb_method'] == 'cpu' def test_delete_pool(self, *args): set_module_args(dict( name='foo', state='absent', password='password',...
import sys from deriva.transfer import DerivaBackupCLI DESC = "Deriva Catalog Backup Utility - CLI" INFO = "For more information see
: https://github.com/informatics-isi-edu/deriva-py" def main(): cli = DerivaBackupCLI(DESC, INFO, hostname_required=True, co
nfig_file_required=False) return cli.main() if __name__ == '__main__': sys.exit(main())
etdate, formatdate, get_first_day, date_diff, add_years, get_timestamp, nowdate, flt) from frappe.contacts.doctype.address.address import (get_address_display, get_default_address, get_company_address) from frappe.contacts.doctype.contact.contact import get_contact_details, get_default_contact from erpnext.exceptions...
arty.get("sales_team")] return out def set_address_details(out, p
arty, party_type, doctype=None, company=None): billing_address_field = "customer_address" if party_type == "Lead" \ else party_type.lower() + "_address" out[billing_address_field] = get_default_address(party_type, party.name) if doctype: out.update(get_fetch_values(doctype, billing_address_field, out[billing_add...
# -*- coding: utf-8 -*- """ .. module:: djstripe.utils. :synopsis: dj-stripe - Utility functions related to the djstripe app. .. moduleauthor:: @kavdev, @pydanny, @wahuneke """ from __future__ import absolute_import, division, print_function, unicode_literals import datetime from django.conf import settings from...
rn response # Overrides the
set timezone to UTC - I think... tz = timezone.utc if settings.USE_TZ else None return datetime.datetime.fromtimestamp(response, tz) # TODO: Finish this. CURRENCY_SIGILS = { "CAD": "$", "EUR": "€", "GBP": "£", "USD": "$", } def get_friendly_currency_amount(amount, currency): currency =...
bject): def __init__(self, *args): self.bytes_read = 0 tarfile.ExFileObject.__init__(self, *args) def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): try: self.close() except Exception: pass def read(self...
astore_freespace = ds.summary.freeSpace if datastore: self.datastore = datastore else: self.datastore = self.find_datasto
re_by_name(self.params['datastore'], self.datacenter) if not self.datastore: self.module.fail_json(msg='%(datastore)s could not be located' % self.params) if self.params['cluster']: resource_pools = [] cluster = self.find_cluster_by_name(self.params['cluster'], data...
''' main tuning script, LCLS ''' import numpy as np from ocelot.mint.mint import Optimizer, Action from ocelot.mint.flash1_interface import FLASH1MachineInterface, FLASH1DeviceProperties, TestInterface mi = FLASH1MachineInterface() dp = FLASH1DeviceProperties() #opt = Optimizer(mi, dp) opt = Optimizer(TestInterfac...
042831, 0.318743893708, 0.15280311903, 0.130996600233, -0.831909116508]) currents = np.array([ -0.0229914523661, 0.0250000003725, 0.985000014305, 0.0, -1.17299997807, 0.0, 0.148000001907]) bump = {"correctors":cors, "dI": dI, "currents":currents} alpha = 0.1 seq_bump = [Action(func=opt.max_sase_bump, args=[ bump, alp...
l = MagneticLattice(lattice) setup.load_lattice("init.txt", lat_all) orbit["bpms"] = get_dict(lat, bpms) seq_min_orb = [Action(func=opt.min_orbit, args=[orbit, 'simplex' ] )] opt.eval(seq_bump) apply_bump(cors, currents, dI, alpha=0.1) """
# -*- coding: utf-8 -*- """ :created: 27 Aug 2014 :author: Éric Piel :copyright: © 2014 Éric Piel, Delmic This file is part of Odemis. .. license:: Odemis is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software ...
rot, iscale_xy, ishear, resa, resb, hfwa, scaleshift) conf.set_sh_calib(shid, *orig_calib) # read back from memory back_calib = conf.get_sh_calib(shid) for o, b in zip(orig_calib, back_calib): if isinstance(o, tuple): test.assert_tuple_a...
nf = gui.conf.get_calib_conf() back_calib = conf.get_sh_calib(shid) for o, b in zip(orig_calib, back_calib): if isinstance(o, tuple): test.assert_tuple_almost_equal(o, b) else: self.assertAlmostEqual(o, b) if __name__ == "__main__": unittest.m...
# -*- coding: utf-8 -*- import xbmc, xbmcgui, xbmcplugin import urllib2,urllib,cgi, re import HTMLParser import xbmcaddon import json import traceback import os import cookielib from BeautifulSoup import BeautifulStoneSoup, BeautifulSoup, BeautifulSOAP import datetime import sys import time import CustomPlayer import c...
cept: traceback.print_exc(file=sys.stdout) return True def shouldforceLogin(cookieJar=None): try: url="http://www.livetv.tn/index.php" if not cookieJar: cookieJar=getCookieJar() html_txt=getUrl(url,cookieJar) if '<a href="http://www.liv...
return False except: traceback.print_exc(file=sys.stdout) return True class InputWindow(xbmcgui.WindowDialog): def __init__(self, *args, **kwargs): self.cptloc = kwargs.get('captcha') self.img = xbmcgui.ControlImage(335,30,624,60,self.cptloc) self.addControl(self.img) ...
""" Definition of TreeNode: class TreeNode: def __init__(self, val):
self.val = val self.left, self.right = None, None """ class Solution: """ @param root: The root of binary tree. @return: True if this Binary tree is Balanced, or false. """ def isBalanced(self, root): # write your code here isbalanced, h = self.isBalancedandHeight(root) ...
None: return True, 0 l, r = root.left, root.right l_balanced, l_h = self.isBalancedandHeight(l) if not l_balanced: return False, 0 r_balanced, r_h = self.isBalancedandHeight(r) if not r_balanced: return False, 0 if abs(l_h - r_h) < ...
# This script will check http://services.scribus.net for broken asset
s import lxml.html url = "http://services.scribus.net" doc = lxml.html.parse(url) # pattern matching for relative urls: <a href="scribus_fonts.xml"> content_parsed = doc.xpath('href') # also ignore scribusversions.xml # Create a scraper class to feed .xml page results to # Cr
eate a function that mails an admin when a result 404s
import numpy as np import pytest import pandas as pd from pandas import DataFrame, Index, Series, Timestamp, date_range import pandas._testing as tm class TestDatetimeIndex: def test_indexing_with_datetime_tz(self): # GH#8260 # support datetime64 with tz idx = Index(date_range("20130101...
tm.assert_series_equ
al(result, exp, check_index_type=True) keys = [ Timestamp("2011-01-02"), Timestamp("2011-01-02"), Timestamp("2011-01-01"), ] if to_period: keys = [x.to_period("D") for x in keys] exp = Series( [0.2, 0.2, 0.1], index=Index(keys,...