prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.exception import SqlmapUnsupportedFeatureException from plugins.generic.filesystem import Filesystem as GenericFilesystem class Filesystem(GenericFilesystem): ...
GenericFilesystem.__init__(self) def readFile(self, rFile): errMsg = "File system read access not yet implemented for " errMsg += "Oracle" raise SqlmapUnsupportedFeatureException(errMsg) def writeFile(self, wFile, dFile, fileType=None, forceCheck=False): errMsg = "File sy...
te access not yet implemented for " errMsg += "Oracle" raise SqlmapUnsupportedFeatureException(errMsg)
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from datetime import datetime from django.http import HttpResponse from GarageWarden import status, settingHelper, settingView, config, settings as gw_settings import RPi.GPIO as GPIO settings = None settings_loaded = Fa...
recipients = get_setting('recipients') msg = MIMEMultipart("alternative") msg['Subject'] = subject msg['From'] = _from msg['To'] = recipients if text: msg.attach(MIMEText(text, "plain")) if html: msg.attach(MIMEText(html, "html")) smtp.sendmail(_from, [r.strip() for r in re...
state, color, date): if get_setting('Status Notification'): send_mail("Garage " + state, make_text(state, date), make_html(state, color, date)) else: print('status emails not enabled') def make_html(state, color, date): return "Garage was <span style='color: " + color + "'><strong>" + stat...
INFRINGEMENT. IN NO EVENT SHALL THE #* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #* THE SOFTWARE. # #include <osgViewer/Viewer> ...
ight1.setAmbient(osg.Vec4(1.0,0.0,0.0,1.0)) myLight1.setDiffuse(osg.Vec4(1.0,0.0,0.0,1.0)) myLight1.setSpotCutoff(20.0) myLight1.setSpotExponent(50.0) myLight1.setDirection(osg.Vec3(1.0,1.0,-1.0)) lightS1 = osg.LightSource() lightS1.setLight(myLight1) lightS1.setLocalStateS
etModes(osg.StateAttribute.ON) lightS1.setStateSetModes(*rootStateSet,osg.StateAttribute.ON) lightGroup.addChild(lightS1) # create a local light. myLight2 = osg.Light() myLight2.setLightNum(1) myLight2.setPosition(osg.Vec4(0.0,0.0,0.0,1.0)) myLight2.setAmbient(osg.Vec4(0.0,1.0,1.0,1.0)) ...
ve = False imageNode = avg.ImageNode(parent=self, opacity=1, href=href, size=size, ) imageNode.pos = util.vectorMult(size, -0.5) self.image = imageNode ...
it = None self
.unlink(True) self.__edit = avg.WordsNode(size=(self.size.x, self.size.y // 8), parent=self, fontsize=self.size.y // 8, alignment="center") self.__edit.pos = (self.size.x // 2, 0) s...
# Copyright 2017 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 o...
a_groups') op.drop_constraint(constraint_name=primary_key['name'], table_name='cisco_router_ha_groups', type_='primary') op.create_primary_key( constraint_name='pk_cisco_router_ha_groups', table_name='cisco_router_ha_groups',...
op.create_foreign_key('cisco_router_ha_groups_ibfk_1', source_table='cisco_router_ha_groups', referent_table='ports', local_cols=['ha_port_id'], remote_cols=['id'], ...
from fancypa
ges.templatetags.fp_con
tainer_tags import *
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2015-12-23 15:08 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('django_ca', '0001_initial'), ] operations = [ migrations.AlterField( ...
name='csr', field=models.TextField(verbose_name='CSR'), ),
migrations.AlterField( model_name='certificate', name='pub', field=models.TextField(verbose_name='Public key'), ), migrations.AlterField( model_name='certificate', name='revoked_date', field=models.DateTimeField(blank=True, null=T...
# Copyright (c) 2017 Civic Knowledge. This file is licensed under the terms of the # MIT, included in this distribution as LICENSE """ """ from rowgenerators.appurl.file.file import FileUrl from rowgenerators.exceptions import AppUrlError class ZipUrlError(AppUrlError): pass class ZipUrl(FileUrl): """Zip ...
e names = [] zf = ZipFile(str(url.fspath)) nl = list(ZipUrl.real_files_in_zf(zf)) # Old way, but maybe gets links? : list(zf.namelist()) tf = url.target_file ts = url.target_segment if not nl: # sometimes
real_files_in_zf doesn't work at all. I don't know why it does work, # so I certainly don't know why it does not. nl = list(zf.namelist()) # the target_file may be a string, or a regular expression if tf: names = list([e for e in nl if re.search(tf, e) ...
""" This module is used to select features or proposals """ def select_preceding(features, k): """ select preced
ing k features or proposals for each image :param k: preceding k features or proposals for each image are selected :type k: integer :return: selected features or proposals :rtype: list. Each element is a k'-by-m ndarray, where m is feature dimension or 4 for pr
oposals. If there are enough features or proposals for selection, then k' = k, else all features or proposals are selected. """ return [i[:k] for i in features]
__version__ = "1.4.3" import sys import os # verify that pygame is on the machine try: import pygame except Exception: print("Pygame doesn't seem to be installed on this machine.") # add thorpy folder to Windows and Python search paths THORPY_PATH = os.path.abspath(os.path.dirname(__file__)) try: os.env...
y.elements.image import Image from thorpy.elements.box import Box, BarBox from thorpy.elements.browserlight import Browser
Light from thorpy.elements.browser import Browser from thorpy.elements.checker import Checker from thorpy.elements.clickable import Clickable from thorpy.elements._wrappers import make_button, make_text from thorpy.elements.colorsetter import ColorSetter from thorpy.elements.ddlf import DropDownListFast as DropDownList...
title = str(self._metadata['title']) description = str(self._metadata.get('description', '')) mime_type = str(self._metadata['mime_type']) if not mime_type: mime_type = mime.get_for_file(file_name) filetransfer.start_transfer(buddy, file_name, title, description, ...
present(): menu_item = MenuItem(text_label=friend.get_nick(), icon_name='computer-xo', xo_color=friend.get_color()) menu_item.connect('activate', self.__item_activate_cb, ...
em) menu_item.show() if not self.get_children(): menu_item = MenuItem(_('No friends present')) menu_item.set_sensitive(False) self.append(menu_item) menu_item.show() else: menu_item = MenuItem(_('No vali...
#coding=utf-8 import argparse import json import os from smartqq import start_qq, list_messages, create_db def load_pluginconfig(configjson): config = None if configjson is not None: if os.path.isfile(configjson): with open(configjson, "r") as f: config = json.load(f) ...
action="store_true", default=False, help="Logout old user first(by clean the cookie file.)" ) parser.add_argument( "--debug", action="store_true", default=False, help="Switch to DEBUG mode for better view of requests and responses." ) parser.add_argu...
parser.add_argument( "--cookie", default="cookie.data", help="Specify the storage path for cookie." ) parser.add_argument( "--vpath", default="./v.jpg", help="Specify the storage path for login bar code." ) parser.add_argument( "--list", ...
.id, self.f2, self.f3 ) self.row2 = '%s %s "syn12" "syn123;https://www.example.com" provName2 bar\n' % ( self.f2, self.folder.id ) self.row3 = '%s %s "syn12" prov2 False baz\n' % (self.f3, self.folder.id) self.row4 = '%s %s %s act 2\n' % (s...
fest) def test_syncToSynapse(test_state): # Test upload of accurate manifest manifest = _makeManifest( test_state.header + test_state.row1 + test_state.row2 + test_state.row3, test_state.schedule_for_cleanup ) synapseutils.syncToSynapse(test_state.syn, manifest, sendMessages=False, ret...
# syn.getChildren() used by syncFromSynapse() may intermittently have timing issues time.sleep(3) # Download using syncFromSynapse tmpdir = tempfile.mkdtemp() test_state.schedule_for_cleanup(tmpdir) synapseutils.syncFromSynapse(test_state.syn, test_state.project, path=tmpdir) orig_df = pd.re...
_pre_init(natom=natom) set_calculator(self, kind, self._kind_opts) ref_compress_state='P0' ref_thermal_state='T0' ref_energy_type = 'E0' refstate.set_calculator(self, ref_compress_state=ref_compress_state, ref_thermal_state=ref_thermal_state, ...
*(V_a/V0)**q return gamma_a def _calc_gamma_deriv(self, V_a): q, = self.eos_mod.get_param_values(param_names=['q']) gamma_a = self._calc_gamma(V_a) gamma_deriv_a = q*gamma_a/V_a return gamma_deriv_a def _calc_tem
p(self, V_a, T0=None): if T0 is None: T0 = self.eos_mod.refstate.ref_temp() # T0, = self.eos_mod.get_param_values(param_names=['T0'], overrides=[T0]) gamma0, q = self.eos_mod.get_param_values( param_names=['gamma0','q']) gamma_a = self._calc_gamma(V_a) T_...
# -*- coding: utf-8 -*- """ Creat
ed on Fri Dec 23 15:22:48 2011 @author: moritz """ __all__ = [
"bslip"]
""" Utilities for testing trajectories. """ # Copyright (C) 2009-2011 University of Edinburgh # # This file is part of IMUSim. # # IMUSim 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...
eRotations): """ Check the outputs of a trajectory model agree with truth values. @param T: Trajectory to check. @param truePositions: L{TimeSeries} of true position values. @param trueRotations: L{TimeSeries} of true rotation values. """ # Get time indices at which position comparisons va...
(t >= T.startTime) & (t <= T.endTime) t = t[validity] dt = np.gradient(t) p = truePositions.values[:,validity] # Check position assert_vectors_correlated(T.position(t), p) # Check velocity v = np.array(map(np.gradient, p)) / dt assert_vectors_correlated(T.velocity(t[2:-2]), v[:,2:-2]) ...
from tests.base import ApiDBTestCase from zou.app.models.entity import Entity class BreakdownTestCase(ApiDBTestCase): def setUp(self): super(BreakdownTestCase, self).setUp() self.generate_fixture_project_status() self.generate_fixture_project() self.generate_fixture_asset_type() ...
e() self.generate_fixture_shot() self.generate_fixture_asset() self.generate_fixture_asset_character() def test_update_casting(self): self.project_id = str(self.project.id) self.shot_id = str(self.shot.id) self.asset_id = str(self.asset.i
d) self.asset_character_id = str(self.asset_character.id) self.asset_type_character_id = str(self.asset_type_character.id) self.shot_name = self.shot.name self.sequence_name = self.sequence.name self.episode_name = self.episode.name casting = self.get( "/data...
**{'initiator-group-name': igroup, 'initiator': initiator}) self.connection.invoke_successfully(igroup_add, True) def do_direct_resize(self, path, new_size_bytes, force=True): """Resize the LUN.""" seg = path.split("/") LOG.info(_LI("Resizing LUN %s directly t...
luns_mapped_to_initiator(self, initiator): """Checks whether any LUNs are mapped to the given initiator.""" lun_list_api = netapp_api.NaElement('lun-initiator-list-map-info') lun_list_api.add_new_child('initiator', initiator) result = self.connection.invoke_successfully(lun_list_api, Tru...
apped_to_initiators(self, initiator_list): """Checks whether any LUNs are mapped to the given initiator(s).""" for initiator in initiator_list: if self._has_luns_mapped_to_initiator(initiator): return True return False def get_lun_by_args(self, **args): "...
# -*- coding: utf-8 -*- from module.plugins.internal.SimpleCrypter import SimpleCrypter class NosvideoCom(SimpleCrypter): __name__ = "NosvideoCom" __type__ = "crypter" __version__ = "0.07" __status__ = "testing" __pattern__ = r'http://(?:www\.)?nosvideo\.com/\?v=\w+' __config__ = [("activate...
ate folder for each package", "Default"), ("max_wait", "int", "Reconnect if waiting time is greater than minutes", 10)] __description__ = """Nosvideo.com decrypter plug
in""" __license__ = "GPLv3" __authors__ = [("igel", "igelkun@myopera.com")] LINK_PATTERN = r'href="(http://(?:w{3}\.)?nosupload\.com/\?d=\w+)"' NAME_PATTERN = r'<[tT]itle>Watch (?P<N>.+?)<'
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
dify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # 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 PARTICUL...
more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack im...
import sys # --- ROBOT DYNAMIC SIMULATION ------------------------------------------------- from dynamic_graph.sot.hrp2_14.robot import Robot robot = Robot( 'robot' ) # --- LINK ROBOT VIEWER ------------------------------------------------------- from dynamic_graph.sot.core.utils.viewer_helper import addRobotViewer ad...
e.gyrometer = gyr.sout robot.device.forceLLEG.value = (0,0,284,0,0,0) robot.device.forceRLEG.value = (0,0,284,0,0,0) # --- MAIN LOOP ---------------------------------------------------------------- from dynamic_graph.sot.core.utils.thread_interruptible_loop import loopInThread,optionalparentheses,loopShortcuts re...
ts(runner) @optionalparentheses def iter(): print 'iter = ',robot.device.state.time @optionalparentheses def status(): print runner.isPlay # ---------------------------------------------------------------------- for scripts in sys.argv[1:]: if scripts[0]!='+': raw_input('Enter when you are ...
ct_ins.linkedAccountUuid else: project_login_session_uuid = plain_user_session_uuid conditions = res_ops.gen_query_conditions('category', '=', 'Public') l3_pub_uuid = res_ops.query_resource(res_ops.L3_NETWORK, conditions)[0].uuid vm_creation_option = test_util.VmOpti...
h_pf_service_from_l3network(l3_net_uuid, pf_service_providor_uuid) acc_ops.revok
e_resources([project_linked_account_uuid], [l3_pub_uuid, l3_net_uuid, image_uuid, instance_offering_uuid]) return self.judge(True) else: try: net_ops.delete_port_forwarding(pf_rule_uuid, session_uuid=project_login_session_uuid) test_util.test_logger("delet...
from .base_reader import BaseReader, InvalidDataDirectory # noqa from .object_detection import ObjectDetectionReader # noqa from .ob
ject_detection import ( COCOReader, CSVReader, FlatReader, ImageNetReader, OpenImagesReader, PascalVOCReader, TaggerineReader ) READERS = { 'coco': COCOReader, 'csv': CSVReader, 'flat': FlatReader, 'imagenet': ImageNetReader, 'openima
ges': OpenImagesReader, 'pascal': PascalVOCReader, 'taggerine': TaggerineReader, } def get_reader(reader): reader = reader.lower() if reader not in READERS: raise ValueError('"{}" is not a valid reader'.format(reader)) return READERS[reader]
# Copyright (c) 2015, Nordic Semiconductor # 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 above copyright notice, this # list of conditions ...
emiconductor ASA nor the names of its # contributors may be used to endorse o
r promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PU...
t.requests.r.test_requests_pb2' _RESPONSES_PB2 = 'beta_grpc_plugin_test.responses.test_responses_pb2' _SERVICE_PB2 = 'beta_grpc_plugin_test.service.test_service_pb2' # Identifiers of entities we expect to find in the generated module. SERVICER_IDENTIFIER = 'BetaTestServiceServicer' STUB_IDENTIFIER = 'BetaTestServiceSt...
esponses_pb2 = responses_pb2 @contextlib.contextmanager def pause(self): # pylint: disable=invalid-name with self._condition: self._paused = True yield with
self._condition: self._paused = False self._condition.notify_all() @contextlib.contextmanager def fail(self): # pylint: disable=invalid-name with self._condition: self._fail = True yield with self._condition: self._fail = False def ...
2": "Holy Nova", "CS1_130": "Holy Smite", "DS1_070": "Houndmaster", "NEW1_034": "Huffer", "EX1_360": "Humility", "CS2_084": "Hunter's Mark", "EX1_169": "Innervate", "CS2_232": "Ironbark Protector", "CS2_141": "Ironforge Rifleman", "CS2_125": "Ironfur Grizzly", "EX1_539": "Kill Co...
_006": "NOOOOOOOOOOOO", "EX1_593": "Nightblade", "CS2_235": "
Northshire Cleric", "EX1_015": "Novice Engineer", "CS2_119": "Oasis Snapjaw", "CS2_197": "Ogre Magi", "CS2_022": "Polymorph", "CS2_004": "Power Word: Shield", "CS2_122": "Raid Leader", "CS2_196": "Razorfen Hunter", "CS2_213": "Reckless Rocketeer", "CS2_120": "River Crocolisk", "C...
m.choice(string.ascii_uppercase + "9") for _ in range(81)) return seed def check_transaction(self,transaction): transaction_hash = transaction['bundle'].hash inclusion_states = self.iota_api.get_latest_inclusion([transaction_hash]) return inclusion_states['states'][transaction_hash]...
,balance) #Checks if the user has at least the given amount def check_balance(self,reddit_username,amount): entry = self.db.ex
ecute("SELECT * FROM users WHERE redditUsername=?",(reddit_username,)).fetchone() if entry: balance = entry[1] if amount > balance: return False else: return True else: return False #Gets the balance for the speici...
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
he IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation,...
####################################################### from spack import * class LlvmLld(CMakePackage): """lld - The LLVM Linker lld is a new set of modular code for creating linker tools.""" homepage = "http://lld.llvm.org" url = "http://llvm.org/releases/3.4/lld-3.4.src.tar.gz" version...
__class__() for name in self._get_base_attributes(): setattr(new_me, name, getattr(self, name)) new_me._loader = self._loader new_me._variable_manager = self._variable_manager # if the ds value was set on the object, copy it to the new copy too if hasattr...
get_base_attributes()): if name in data: setattr(self, name, data[name]) else: setattr(self, name, attribute.default) # restore the UUID field setattr(self, '_uuid', data.get('uuid')) def _load_vars(self, attr, ds): ''' Vars i...
cified either as a dictionary directly, or as a list of dictionaries. If the later, this method will turn the list into a single dictionary. ''' def _validate_variable_keys(ds): for key in ds: if not isidentifier(key): raise TypeError("%s ...
# Copyright 2018 - TODAY Serpent Consulting Services Pvt. Ltd. # (<http://www.serpentcs.com>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { 'name': 'Search Partner Phone/Mobile/Email', 'version': '11.0.1.
0.1', 'category': 'Extra Tools', 'summary': 'Partner Search by Phone/Mobile/Email', 'auth
or': "Serpent Consulting Services Pvt. Ltd.," "Odoo Community Association (OCA)", 'website': 'https://github.com/OCA/partner-contact', 'license': 'AGPL-3', 'depends': [ 'base', ], 'installable': True, 'auto_install': False, }
import tensorflow as tf import numpy as np import scipy.io vgg_layers = [ 'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1', 'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2', 'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3', 'relu3_3', 'conv3_4', 'relu3_4', 'pool3', 'conv4_1', 'relu4_1', 'con...
mean = np.mean(pretrained_net['normalization'][0][0][0], axis = (0, 1)) layers = pretrained_net['layers'][0] convnet = {} current = input_image for i, name in enumerate(vgg_layers): if vgg_layer_types[i] == 'conv': # Convolution layer kernel, bias = layers[i][0][0][0]...
kernels = np.transpose(kernel, (1, 0, 2, 3)) bias = bias.reshape(-1) conv = tf.nn.conv2d(current, tf.constant(kernel), strides = (1, 1, 1, 1), padding = 'SAME') current = tf.nn.bias_add(conv, bias) elif vgg_layer_types[i] == 'relu': # Relu layer cur...
''' primepalCodeEval.py - Solution to Problem Prime Palindrome (Category - Easy) Copyright (C) 2013, Shubham Verma This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of th...
ope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, s...
te a program to determine the biggest prime palindrome under 1000. Input sample: None Output sample: Your program should print the largest palindrome on stdout. i.e. 929 ''' from math import sqrt def isPrime(num): if num%2 == 0: return False else: for i in xrange(3, int(sqrt(num)), 2): if num % i =...
#!/usr/bin/python -tt """Helper functions.""" from dns import resolver #
Exceptions class CouldNotResolv(Exception): """Exception for unresolvable hostname.""" pass def resolv(hostname): """Select and query DNS servers. Args: hostna
me: string, hostname Returns: ips: list, list of IPs """ ips = list() # Create resolver object res = resolver.Resolver() # Choose the correct DNS servers # Blue DNS servers if hostname.startswith('b-'): res.nameservers = ['172.16.2.10', '172.16.2.11'] # Green DNS servers elif hostname.st...
import sys import time from entrypoint2 import entrypoint import pyscreenshot from pyscreenshot.plugins.gnome_dbus import GnomeDBusWrapper from pyscreenshot.plugins.gnome_screenshot import GnomeScreenshotWrapper from pyscreenshot.plugins.kwin_dbus import KwinDBusWrapper from pys
creenshot.util import run_mod_
as_subproc def run(force_backend, n, childprocess, bbox=None): sys.stdout.write("%-20s\t" % force_backend) sys.stdout.flush() # before any crash if force_backend == "default": force_backend = None try: start = time.time() for _ in range(n): pyscreenshot.grab( ...
""" models ~~~~~~ Module containing all of o
ur models that are typically accessed in a CRUD like manner. """ from ..models.base import Model as BaseModel from ..models.default_schema import Model as DefaultSchemaModel from ..models.login import Model as LoginMode
l MODELS = [ BaseModel, DefaultSchemaModel, LoginModel, ]
from mpf.tests.MpfGameTestCase import MpfGameTestCase class TestPlayerVars(MpfGameTestCase): def get_config_file(self): return 'player_vars.yaml' def get_machine_path(self): return 'tests/machine_files/player_vars/' def test_initial_values(self): self.fill_troughs() self...
self.assertEventCalledWith('player_some_var', value=1, prev_value=10, change=-9, player_num=1,
bar='foo')
Proxies all messages to a real smtpd which does final # delivery. One known problem with this class is that it doesn't handle # SMTP errors from the backend server at all. This should be fixed # (contributions are welcome!). # # MailmanProxy - An experimental hack to work with GNU Mailman # <www.list.org>. ...
= [] if self.__state == self.COMMAND: if not line: self.push('500 Error: bad syntax') return method = None i = line.find(' ') if i < 0: command = line.upper() arg = None
else: command = line[:i].upper() arg = line[i+1:].strip() method = getattr(self, 'smtp_' + command, None) if not method: self.push('502 Error: command "%s" not implemented' % command) return method(arg) ...
ad, precompile) def __del__(self): """Close index handle.""" if hasattr(self, '_index_handle'): self._index_handle.close() def __len__(self): """Returns number of rows in table.""" return self.index.size def __copy__(self): """Returns a copy of an IndexTable object.""" clone = Ind...
"" # Parse each template index onl
y once across all instances. # Without this, the regexes are parsed at every call to CliTable(). _lock = threading.Lock() INDEX = {} # pylint: disable=C6409 def synchronised(func): """Synchronisation decorator.""" # pylint: disable=E0213 def Wrapper(main_obj, *args, **kwargs): main_obj._lo...
from coc_war_planner.api.permissions import CreateNotAllowed from coc_war_planner.api.permissions import IsChiefOrReadOnly from coc_war_planner.api.permissions import IsUserOrReadOnly from coc_war_planner.api.permissions import IsOwnerOrReadOnly from coc_war_planner.api.permissions import IsNotPartOfClanOrCreateNotAllo...
class ClanViewSet(viewsets.ModelViewSet): queryset = Clan.objects.all() serializer_class = ClanSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsChiefOrReadOnly, IsNotPartOfClanOrCreateNotAllowed) filter_backends = (filters.OrderingFilter, filters.Search...
',) ordering = 'name' # default ordering search_fields = ('name', 'pin',) def perform_create(self, serializer): instance = serializer.save(chief=self.request.user.member) self.request.user.member.clan = instance self.request.user.member.save() def get_serializer_class(self): ...
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2013 Agile Business Group sagl # (<http://www.agilebg.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public ...
'/'), the standard sequence is used.""", 'author': "Agile Business Group,Odoo Community Association (OCA)", 'website': 'http://www.agilebg.com', 'license': 'AGPL-3', "depends": ['pu
rchase'], "data": [ 'purchase_view.xml', ], "demo": [], "active": False, "installable": False }
D_LIBRARY_PATH' if not IS_DARWIN else 'DYLD_LIBRARY_PATH': ['lib', os.path.join('lib', 'x86_64-linux-gnu')], 'PATH': 'bin', 'PKG_CONFIG_PATH': [os.path.join('lib', 'pkgconfig'), os.path.join('lib', 'x86_64-linux-gnu', 'pkgconfig')], 'PYTHONPATH': 'lib/python2.7/dist-packages', } def rollback_env_variables...
riables(environ, env_var_subfolders, workspaces): ''' Generate shell code to prepend environment variables for the all workspaces. ''' lines
= [] lines.append(comment('prepend folders of workspaces to environment variables')) paths = [path for path in workspaces.split(os.pathsep) if path] prefix = _prefix_env_variable(environ, 'CMAKE_PREFIX_PATH', paths, '') lines.append(prepend(environ, 'CMAKE_PREFIX_PATH', prefix)) for key in sorted...
#!/usr/bin/python """ Small web application to retrieve genes from the tomato genome annotation involved to a specified pathways. """ import flask from flaskext.wtf import Form, TextField import ConfigParser import datetime import json import os import rdflib import urllib CONFIG = ConfigParser.ConfigParser() CON...
associated with the specified pathway. """ query = ''' PREFIX gene:<http://pbr.wur.nl/GENE#> PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#> PREFIX uniprot:<http://purl.uniprot.org/core/> SELECT DISTINCT ?gene ?desc FROM <%(itag)s> FROM <%(uniprot)s> WHERE{ ?geneo...
:annotation ?annot . ?annot rdfs:seeAlso ?url . ?annot rdfs:comment "%(search)s" . } ORDER BY ASC(?gene) ''' % {'search': pathway, 'uniprot': GRAPHS['uniprot'], 'itag': GRAPHS['itag']} data_js = sparql_query(query, SERVER) if not data_js: return genes = {} for ...
# Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the f...
N ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from blinkpy.common.host_mock import MockHost class MockBlinkTool(MockHos
t): def __init__(self, *args, **kwargs): MockHost.__init__(self, *args, **kwargs) def path(self): return 'echo'
""" URLs for the Enrollment API """ from django.conf import settings from django.conf.urls import url from .views import ( CourseEnrollmentsApiListView, EnrollmentCourseDetailView, EnrollmentListView, EnrollmentUserRolesView, EnrollmentView, UnenrollmentView ) urlpatterns = [ url(r'^enr...
EnrollmentView.as_view(), name='courseenrollment'), url(r'^enrollment$', EnrollmentListView.as_view(), name='courseenrollments'),
url(r'^enrollments/?$', CourseEnrollmentsApiListView.as_view(), name='courseenrollmentsapilist'), url(r'^course/{course_key}$'.format(course_key=settings.COURSE_ID_PATTERN), EnrollmentCourseDetailView.as_view(), name='courseenrollmentdetails'), url(r'^unenroll/$', UnenrollmentView.as_view(), name='un...
def getitem(v,d): "Returns the value of entry d in v" assert d in v.D return v.f[d] if d in v.f else 0 def setitem(v,d,val): "Set the element of v with label d to be val" assert d in v.D v.f[d] = val def equal(u,v): "Returns true iff u is equal to v" assert u.D == v.D union = set(u...
# "Returns a vector which is the difference of a and b." # return a+(-b) def __sub__(self, other): "Returns a vector which is the difference of a and b." return self+(-other) __eq__ = equal
__str__ = toStr def __repr__(self): return "Vec(" + str(self.D) + "," + str(self.f) + ")" def copy(self): "Don't make a new copy of the domain D" return Vec(self.D, self.f.copy())
# # Copyright 2014 Quantopian, 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 wr...
) def test_arg_superset(self): def f(a, b, c): pass with self.assertRaises(TooManyArguments): verify_callable_argspec(f, [Argument('a'), Argument('b')]) def test_no_default(self): """ Tests when an argument expects a default and it is not present....
pass with self.assertRaises(MismatchedArguments): verify_callable_argspec(f, [Argument('a', 1)]) def test_default(self): """ Tests when an argument expects a default and it is present. """ def f(a=1): pass verify_callable_argspec(f, ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for the analysis mediator.""" from __future__ import unicode_literals import unittest from dfvfs.lib import definitions as dfvfs_definitions from dfvfs.path import factory as path_spec_factory from plaso.analysis import mediator from plaso.containers import se...
ed_display_name) # TODO: add test for GetUsernameForPath. # TODO: add test for ProduceAnalysisReport. # TODO: add test for ProduceEventTag. def testSignalAbort(self): """Tests the SignalAbort function.""" session = sessions.Session() storage_writer = fake_writer.FakeStorageWriter(session) know...
knowledge_base) analysis_mediator.SignalAbort() if __name__ == '__main__': unittest.main()
""" This module describes the unlogged state of the default game. The setting STATE_UNLOGGED should be set to the python path of the state instance in this module. """ from evennia.commands.cmdset import CmdSet from evennia.commands.default import un
loggedin class UnloggedinCmdSet(CmdSet): """ Sets up the unlogged cmdset. """ key = "DefaultUnloggedin" priority = 0 def at_cmdset_creation(self): "Populate the cmdset" self.add(unloggedin.CmdUnconnectedConnect()) self.add(unloggedin.CmdUnconnectedCreate()) sel...
)) self.add(unloggedin.CmdUnconnectedEncoding()) self.add(unloggedin.CmdUnconnectedScreenreader())
#!/usr/bin/env python3 #This extracts data from xml plists # #########################COPYRIGHT INFORMATION############################ #Copyright (C) 2013 dougkoster@hotmail.com # #This program is free software: you can redistribute it and/or modify # #it under the terms of the GNU General Public License as...
ort_file.write("(K
odiak)") return key
# -*- coding: utf-8 -*- from typing import Text from zerver.lib.test_classes import WebhookTestCase class HelloSignHookTests(WebhookTestCase): STREAM_NAME = 'hellosign' URL_TEMPLATE = "/api/v1/external/hellosign?stream={stream}&api_key={api_key}"
FIXTURE_DIR_NAME = 'hellosign' def test_signatures_message(self): # type: () -> None expected_subject = "NDA with Acme Co." expected_message = ("The NDA with Acme Co. is awaiting the signature of " "Jack and was just signed by Jill.") self.send_and_t...
"application/x-www-form-urlencoded") def get_body(self, fixture_name): # type: (Text) -> Text return self.fixture_data("hellosign", fixture_name, file_type="json")
return result def __len__(self): """Return number of image pages in file.""" return len(self.pages) def __getitem__(self, key): """Return specified page.""" return self.pages[key] def __iter__(self): """Return iterator over pages.""" return iter(s...
2. image_depth Z (sgi) 3. image_length Y 4. image_width X 5. contig samples_per_pixel """ def __init__(self, parent): """Initialize instance from file.""" self.parent = parent self.index = len(parent.pages) self.shape = self._shape = () self.dtype = sel...
self._process_tags() def _fromfile(self): """Read TIFF IFD structure and its tags from file. File cursor must be at storage position of IFD offset and is left at offset to next IFD. Raises StopIteration if offset (first bytes read) is 0. """ fh = self.parent....
self.sync_all() def run_test(self): peer_node, rbf_node = self.nodes rbf_node_address = rbf_node.getnewaddress() # fund rbf node with 10 coins of 0.001 btc (100,000 satoshis) print("Mining blocks...") peer_node.generate(110) self.sync_all() for i in ...
l("0.001")) segwit_out = rbf_node.validateaddress(rbf_node.getnewaddress()) rbf_node.addwitnessaddress(segwit_out["address"]) segwitid = send_to_witness( version=0, node=rbf_node, utxo=segwit_in, pubkey=segwit_out["pubkey"], encode_p2sh=False, amount=Decimal("...
EQUENCE_NUMBER }], {dest_address: Decimal("0.0005"), get_change_address(rbf_node): Decimal("0.0003")}) rbfsigned = rbf_node.signrawtransaction(rbfraw) rbfid = rbf_node.sendrawtransaction(rbfsigned["hex"]) assert rbfid in rbf_node.getrawmempool() bumped_tx = rbf_node.bumpfee(rbfid) asse...
fro
m __future__ import unicode_literals from django.apps import AppConfig class DirtyDri
veConfig(AppConfig): name = 'DirtyDrive'
ormatter that produces man-style documentation. @note: This module is under development. It generates incomplete documentation pages, and is not yet incorperated into epydoc's command-line interface. """ __docformat__ = 'epytext en' ################################################## ## Imports ######################...
') str += self._funclist(doc.staticmethods(), doc, 'STATIC METHODS') str += self._funclist(doc.classmethods(), doc, 'CLASS METHODS') return str def _routinepage(self, uid
, doc): str = self._name(uid) str += self._descr(uid, doc) return str def _varpage(self, uid, doc): str = self._name(uid) str += self._descr(uid, doc) return str #//////////////////////////////////////////////////////////// # Functions #/////////////////...
Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the ...
al[aio.Channel]): A ``Channel`` instance through which to make calls. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials f...
ult SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_cha...
#!/usr/bin/env python from pylab import * t,x,y,u,v,ax,ay = loadtxt('trajectory.dat',unpack=True) r = sqrt(x**2+y**2) k = u**2+v**2 s = '.' if t.size < 100 else '' figure('Trajectory',figsize=(5,4)) subplot(111,aspect=1) plot(x,y,'b%s-'%s,lw=1) xl,xh = (x.min(),x.max()) xb = 0.1*(xh-xl) xlim(xl-xb,xh+xb) yl,yh = (...
#~ figure('Acceleration',figsize=(5,4)
) plot(t,ax,'r%s-'%s,label=r'$\vec{a}\cdot\hat{e}_x$') plot(t,ay,'b%s-'%s,label=r'$\vec{a}\cdot\hat{e}_y$') yl,yh = ylim() yb = 0.1*(yh-yl) ylim(yl-yb,yh+5*yb) xlabel(r'Time $t$ [s]') ylabel(r'Acceleration $\vec{a}\cdot\hat{e}_n$ [m/s$^2$]') legend(loc='best',fancybox=True,ncol=2) #~ tight_layout() tight_layout() sho...
#!/usr/bin/env python3 import os import sys import json import boto3 import platform import traceback import subprocess from datetime import datetime config = {} with open(os.path.expanduser('~/.ddns.conf')) as conf: config.update(json.load(conf)) ZONE_ID = config['zone_id'] ROOT = config['root'] HOST = config.ge...
if current_ip != r53_ip: print(f'{datetime.utcnow(
).isoformat()}+UTC Mismatch alert, {r53_ip} does not match {current_ip}') change_recordset(current_ip) else: print(f'{datetime.utcnow().isoformat()}+UTC All good - IP is updated in R53') if __name__ == '__main__': main()
[230,"Water Gun","Water",5,500,5,10,10], [231,"Splash","Water",0,1730,20,11.560693641618498,0
], [232,"Water Gun B
lastoise","Water",10,1000,6,6,10], [233,"Mud Slap","Ground",15,1400,12,8.571428571428571,10.714285714285715], [234,"Zen Headbutt","Psychic",12,1100,10,9.09090909090909,10.909090909090908], [235,"Confusion","Psychic",20,1600,15,9.375,12.5], [236,"Poison Sting","Poison",5,600,7,11.666666666666668,8.333333...
# # # # # # MOVE THE NEWLY DOWNLOADED TAS / PR CMIP5 data from work desktop to /Shared # # # # # def move_new_dir( fn, output_dir ): dirname, basename = os.pa
th.split( fn ) elems = basename.split('.')[0].split( '_' )
variable, cmor_table, model, scenario, experiment, years = elems new_dir = os.path.join( output_dir, model, scenario, variable ) try: if not os.path.exists( new_dir ): os.makedirs( new_dir ) except: pass return shutil.copy( fn, new_dir ) if __name__ == '__main__': import os, glob, shutil path = '/srv/sy...
from datetime import timedelta import numpy as np import pytest import pandas as pd from pandas import ( Float64Index, Index, Int64Index, NaT, Timedelta, TimedeltaIndex, timedelta_range) import pandas.util.testing as tm class TestTimedeltaIndex(object): def test_astype_object(self): idx = timede...
, True])) tm.assert_index_equal(result, expected) re
sult = obj._data.astype(bool) expected = np.array([True, True]) tm.assert_numpy_array_equal(result, expected)
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import add_days, cint, cstr, flt, getdate, nowdate, rounded from frappe.model.naming import make_autoname from frappe ...
and docstatus != 2 and employee = %s and name != %s""", (self.month, self.fiscal_year, self.employee, self.name)) if ret_exist: self.employee = '' frappe.throw(_("Salary Slip of employee {0} already created for this month").format(self.employee)) def validate(self): from frappe.utils import money_in_...
without_pay) if not self.net_pay: self.calculate_net_pay() company_currency = get_company_currency(self.company) self.total_in_words = money_in_words(self.rounded_total, company_currency) set_employee_name(self) def calculate_earning_total(self): self.gross_pay = flt(self.arrear_amount) + flt(self.lea...
from django.conf import settings from django.conf.urls import patterns, url from django.contrib.auth.views import l
ogin, logout import views urlpatterns = patterns( 'gauth', url(r'^login/$', login, {'template_name': 'login.html'}, name='login'), url(r'^login/$', logout, {'template_name': 'logout.html'}, name='logout'), url(r'^oauth2_begin/$', views.oauth2_begin, name='oauth2_begin'), url(r'^' + settings.OAUTH...
ete, name='oauth2_complete'), )
# # Copyright (c) 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 # # Unles...
return self._enforce(context, res_type_wc, scope, target, is_registered_policy=is_registered_policy) except self.exc: raise self.exc(action=res_type) return result def enforce_stack(self, stack, scope=None, targe
t=None, is_registered_policy=False): for res in stack.resources.values(): self.enforce(stack.context, res.type(), scope=scope, target=target, is_registered_policy=is_registered_policy)
ssage, UnregisterFrameworkMessage, ResourceRequestMessage, ReviveOffersMessage, LaunchTasksMessage, KillTaskMessage, StatusUpdate, StatusUpdateAcknowledgementMessage, FrameworkToExecutorMessage, ReconcileTasksMessage ) from .process import UPID, Process, async logger = logging.getLogger(__name__) class ...
sconnected) self.sched.rere
gistered(self, master_info) def onDisconnected(self): self.connected = False logger.warning("disconnected from master") self.delay(5, lambda:self.register(self.master)) def onResourceOffersMessage(self, offers, pids): for offer, pid in zip(offers, pids): self.savedO...
# -*- coding: utf-8 -*- # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os...
option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is
the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'pyrotrfiddoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The f...
# Copyright 2016: Mirantis Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
from oss_lib import config from ceagle.api import client from ceagle.api_fake_data import fake_regions CONF = config.CONF bp = flask.Blueprint("regions", __name__) @bp.route("", defaults={"detailed": False}) @bp.route("/detailed", defaults={"detailed": True}) @fake_regions.get_regions def get_regions(detailed): ...
keys(): if service_name == "infra": continue # TODO(boris-42): This should not be checked here. service_client = client.get_client(service_name) resp, code = service_client.get("/api/v1/regions") if code != 200: # FIXME ADD LOGS HERE continue ...
"""Support for BMW car locks with BMW ConnectedDrive.""" import logging from homeassistant.components.bmw_connected_drive import DOMAIN as BMW_DOMAIN from homeassistant.components.lock import LockDevice from homeassistant.const import STATE_LOCKED, STATE_UNLOCKED DEPENDENCIES = ['bmw_connected_drive'] _LOGGER = logg...
ere because it takes some time before the # update callback res
ponse self._state = STATE_UNLOCKED self.schedule_update_ha_state() self._vehicle.remote_services.trigger_remote_door_unlock() def update(self): """Update state of the lock.""" from bimmer_connected.state import LockState _LOGGER.debug("%s: updating data for %s", sel...
egetter, data, current_time, print_search_info=True, print_body=True): """Function called, each time the download of a web page finish. Will parse and print the results of this page.""" print_results(req, lang, pagegetter, data, current_time, print_search_info, print_body) finished_list = a...
co_collection_external_searches = {} dico_collection_seealso = {} query = "SELECT collection_externalcollection.id_collection,
collection_externalcollection.type, externalcollection.name FROM collection_externalcollection, externalcollection WHERE collection_externalcollection.id_externalcollection = externalcollection.id;" try: results = run_sql(query) except (OperationalError, ProgrammingError): results = None if ...
from openerp import tools from openerp.osv import osv, fields from openerp.tools.translate import _ import openerp.addons.decimal_precision as dp class product_category(osv.osv): _inherit='product.category' _columns = { 'sale_price' : field
s.float('Sale Price',digits_compute=dp.get_precision('Product Price')), 'shape_id':fields.many2one('product.shape',string="Shape"), 'weight_from':fields.float('Weight From',digits_compute=dp.get_precision('Stock W
eight')), 'weight_to':fields.float('Weight To',digits_compute=dp.get_precision('Stock Weight')), 'color_id':fields.many2one('product.color',string='Color'), 'clarity_id':fields.many2one('product.clarity',string='Clarity', ondelete='restrict'), 'shape_l...
#!/usr/bin/python3 import gpxpy import datetime import time import os import gpxpy.gpx import sqlite3 import pl import re DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ' filebase = os.environ["XDG_DATA_HOME"]+"/"+os.environ["APP_ID"].split('_')[0] def create_gpx(): # Creating a new file: # -------------------- gpx = g...
(label): os.makedirs(filebase, exist_ok=True) conn = sqlite3.connect('%s/activitie
s.db' % filebase) cursor = conn.cursor() cursor.execute("UPDATE settings SET units=? WHERE 1", (label,)) conn.commit() conn.close() def onetime_db_fix(): os.makedirs(filebase, exist_ok=True) filename = "%s/%s" % (filebase,".dbfixed") if not os.path.exists(filename): print("Fixing db...
# Copyright 2021 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Mozaik Website Event Track", "summary": """ This module allows to see the event menu configuration even without activated debug mode""", "version": "14.0.1.0.0", "license": "AGPL-3",...
": "https://github.com/OCA/mozaik", "depends": [ # Odoo "website_event_track", ], "da
ta": [ "views/event_event.xml", ], }
, vk_mean = self.sample_v_given_h(hk_samp,v_bias) hk_samp, hk_mean = self.sample_h_given_v(vk_samp,h_bias) if noisy == 0: # hk_mean --> v_mean v_mean = self.mean_field_v_given_h(hk_mean,v_bias) return v_mean elif noisy == 1: # hk_samp --> v_mean v_me...
f x.ndim == 1: axis = 0 if axis == 0: x_lab = x[-Nl:] x_vis = x[:-Nl] elif axis == 1: x_lab = x[:,-Nl:] x_vis = x[:,:-Nl] return x_vis, x_lab def join_vis_lab(self,x_vis,x_lab,axis=1): ''' join visible unit data t...
el unit data ''' if x_vis.ndim == 1: axis = 0 x = gp.concatenate((x_vis,x_lab),axis=axis) return x def mean_field_v_given_h(self,h,v_bias): '''compute mean-field reconstruction of P(vt|ht,v<t)''' x = v_bias + gp.dot(h, self.W.T) x_vis, x_lab = s...
#!/usr/bin/python # coding: UTF-8 # Driver for testing pydPiper display # Uses the curses system to emulate a display # Written by: Ron Ritchey import time, curses import lcd_display_driver class lcd_curses(lcd_display_driver.lcd_display_driver): def __init__(s
elf, rows=2, cols=16 ): self.FONTS_SUPPORTED = False self.rows = rows self.cols = cols self.stdscr = curses.initscr() self.curx = 0 self.cury = 0 # Set up parent class. Note. This must occur after display has been # initialized as the parent class may attempt to load custom fonts super(lcd_curse...
h() self.curx = 0 self.cury = 0 def setCursor(self, row, col): self.curx = col self.cury = row def loadcustomchars(self, char, fontdata): # Load custom characters RuntimeError('Command loadcustomchars not supported') def cleanup(self): curses.endwin() def message(self, text, row=0, col=0): '''...
# -*- coding: utf-8 -*- # # English Language RTD & Sphinx config file # # Uses ../conf_common.py for most
non-language-specific settings. # Importing conf_common adds all the non-language-specific # parts to this conf module try: from conf_common import * # noqa: F403,F401 except ImportError: import os import sys sys.path.insert(0, os.path.abspath('..')) from conf_common import * # noqa: F403,F401 ...
技(上海)股份有限公司'.format(current_year) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. language = 'zh_CN'
#!/usr/bin/env python3 # -*- coding:UTF-8 -*- #Copyright (c) 1986 Nick Wong. #Copyright (c) 2016-2026 TP-NEW Corp. # License: TP-NEW (www.tp-new.com) __author__ = "Nick Wong" """ 用asyncio提供的@asyncio.coroutine可以把一个generator标记为coroutine类型,然后在coroutine内部用yield from调用另一个coroutine实现异步操作 从Python 3.5开始引入了新的语法async和await,可以...
orld! 1') r = await asyncio.sleep(2) print('Hello again! 1') #获取EventLoop: loop = asyncio.get_event_loop() #执行coroutine loop.run_until_complete(hello())
loop.run_until_complete(hello1()) loop.close()
#!/usr/bin/env python # -*- coding: utf-8 -*- # Pasos para transformar proy a geod/proy/GK y exportar a DXF from geod_proy import * from toDXF import * # # 1) Configurar Proyecciones usadas # # 1.1) Proyección Mercator Transversal cualquiera. lat_orig = gms2gyf(-33,52) merid_c = gms2gyf(-61,14) pserapio = config_p...
"geod". # proy -> proy.geod proy2geod('coord/proy', pserapio) # proy.geod -> proy.geod.proy geod2proy('coord/proy.geod', pserapio) # proy.geod.proy -> proy.geod.proy.geod proy
2geod('coord/proy.geod.proy', pserapio) # # 3) Transformar entre geodésicas y proyectadas (GK-Faja5) # # 3.1) El proceso es geod -> gk5 -> geod -> gk5. Si se comparan los archivos de # salida, deberían ser iguales entre ambas "gk5" y ambas "geod". # proy.geod -> proy.geod.gk5 geod2proy('coord/proy.geod', gk_fa...
import os import sys import codecs from fnmatch import fnmatchcase from distutils.util import convert_path from setuptools import setup, find_packages def read(fname): return codecs.open(os.path.join(os.path.dirname(__file__), fname)).read() # Provided as an attribute, so you can append to these instead # of repl...
t') PACKAGE = "l
ike_button" VERSION = __import__(PACKAGE).__version__ setup( name='django-like-button', version=VERSION, description='Django App for adding a Facebook like button', maintainer='John Costa', maintainer_email='john.costa@gmil.com', url='https://github.com/johncosta/django-like-button', classi...
from datetime import datetime import os import pytz class PrintingLogObserver(object): def __init__(self, fp): self.fp = fp def __call__(self, event): if event.get('log_format', None): message = event['log_format'].format(**event) else: message = event.get('me...
'time': datetime.fromtimestamp(event['lo
g_time'], pytz.utc).time().replace(microsecond=0).isoformat(), 'pid': pid, 'source': event.get('cb_namespace', event['log_namespace']).split('.')[-1], 'message': message, 'ws': max(0, 35 - len(pid)) } self.fp.write('{time} [{source:<{ws}} {pid}] {message...
#!/usr/bin/env python # # HPFeeds.py # # This program 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 Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; w...
data(self.opts['host'], int(self.opts['port'])) if data is None: return self.publish_data(data, 'thug.events', pubdata) self.sockfd.close() def log_event(self, basedir): if log.ThugOpts.local: return m = None for module in self.formats: ...
if m: break if m is None: return data = m(basedir) self.__log_event(data) def log_file(self, pubdata, url = None, params = None): if log.ThugOpts.local: return self.sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ...
#This is a function containing an algorithmic model of the Scribner log rule, # board-foot log volume tables. It outputs the Scribner log volume for an # input log length and top diameter. # # Annotation: [v]=logvolume(L,TD) # v = Scribner log volume # L = log length # ...
]) / 10.0) elif L < 41: v = 10 * round((L * volume_table_2[TD + 12]) / 10.0) else: v = 0 else: if TD == 5: v = 10 * round((L
* volume_table_1[0]) / 10.0) else: v = 10 * round((L * volume_table_1[TD - 11]) / 10.0) return v def debug_logvolume(): print v = logvolume_2(input("length: "),input("topdia: ")) print "volume is:", v
__author__ = 'Cjsheaf' import csv from threading import Lock class ResultsWriter: """ This class is designed to take out-of-order result data from multiple threads and write them to an organized csv-format file. All data is written to disk at the very end via the "write_results" method, since th...
for c in e.compounds: writer.writerow('', '', c.name, c.rseq, c.mseq,
c.rmsd_refine, c.e_conf, c.e_place, c.e_score1, c.e_score2, c.e_refine) class Entry: def __init__(self, name): self.name = name self.rmsd = None self.compounds = [] def add_compound(self, compound_name, compound): self.compounds[compound_name] ...
total = 0 n = 0 stop = 0
nextMark = input('Type in a mark: ') while stop == 0: nextMark = eval(nextMark) total = total+nextMark n = n +
1 nextMark = input('Hit enter to stop, or type in a mark: ') if nextMark == "": stop = 1 print("You entered", n, 'marks. The average is:',total/n)
#!/usr/bin/env python import subprocess as sp from runtest import TestBase XDIR='xxx' YDIR='yyy' class TestCase(TestBase): def __init__(self): TestBase.__init__(self, 'diff', """ # # uftrace diff # [0] base: xx
x (from uftrace record -d yyy -F main tests/t-diff 1 ) # [1] diff: yyy (from uftrace record -d xxx -F main tests/t-diff 0 ) # Total time (diff) Self time (diff) Calls (diff) Function ===================
================ =================================== ================================ ================================================ 1.075 us 1.048 us -0.027 us 1.075 us 1.048 us -0.027 us 1 1 +0 atoi 158.971 us 0.118 us -158.853 us 1.437 us 0.118 u...
""" Initializer Initialize application data. Created by Lahiru Pathirage @ Mooniak<lpsandaruwan@gmail.com> on 19/12/2016 """ from session import Base from session import mysql_con_string from sqlalchemy import create_engine from utility import DBManager
def initialize(): engine = create_engine( mysql_con_string ) Base.metadata.create_all(engine, checkfirst=Tr
ue) DBManager().update_font_cache()
#!/usr/bin/env python # coding=utf-8 import commands import sys from docopt import docopt #from handler import LogFileClient from sdutil.log_util import getLogger from sdutil.date_util import * reload(sys) sys.setdefaultencoding('utf-8') from elasticsearch import Elasticsearch from pdb import * import requests import ...
ime,'_s1:',_s1,',_s2:',_s2,',len:',len(all_response['hits']['hits']) print '-s1--',time.strftime('
%Y-%m-%d %H:%M:%S',time.localtime(_s1/1000)) print '-s2--',time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(_s2/1000)) print time_count time.sleep(2) else: all_response = do_search(host,index,query_str,startTimeStamp,endTimeStamp,scroll,_source,time_step) return ...
from __future__ import with_statement from alembic import context from sqlalchemy import engine_from_config, pool from logging.config import fileConfig from ocfnet.database import Model from ocfnet.media.models import * from ocfnet.user.models import * try: from config import DATABASE_URL except: from configd...
odel # target_metadata = mymodel.Base.metadata target_metadata = Model.metadata # other values from the config, defined by the needs of env.py, # can be acquired: # my_important_option = config.get_main_option("my_important_option") # ... etc. def run_migrations_offline(): """Run mi
grations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output. ...
from sys import s
tdin, stdout n = int(stdin.read
()) if n == 1: res = "14" elif n == 2: res = "155" else: res = "1575" + ("0" * (n - 3)) stdout.write(res + "\n")
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, Chatham Financial <oss@chathamfinancial.com> # # 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...
se for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. DOCUM
ENTATION = ''' --- module: rabbitmq_user short_description: Adds or removes users to RabbitMQ description: - Add or remove users to RabbitMQ and assign permissions version_added: "1.1" author: Chris Hoffman options: user: description: - Name of user to add required: true default: null aliases:...
""" Test plugin for Artifactor """ import time from artifactor import ArtifactorBasePlugin class Test(ArtifactorBasePlugin): def plugin_initialize(self): self.register_plugin_hook("start_test", self.start_test) self.register_plugin_hook("finish_test",
self.finish_test) def start_test(self, test_name, test_location, artifact_path): filename = artifact_path + "-" + self.ident + ".log" with open(filename, "a+") as f:
f.write(test_name + "\n") f.write(str(time.time()) + "\n") for i in range(2): time.sleep(2) print("houh") def finish_test(self, test_name, artifact_path): print("finished")
SL private_key = rsa.generate_private_key( public_exponent=65537, key_size=key_size, backend=default_backend() ) elif key_algo.lower() == 'ec': if not key_size or key_size == 256: key_curve = ec.SECP256R1 elif key_size == 384: ...
/rfc8037#appendix-A.2 return "EdDSA", {"kty": "OKP", "crv": "Ed25519",
"x": bytes_to_base64url(key.public_key().public_bytes(encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw) )} elif "cryptography.hazmat.pri...
#!/usr/bin/env python # Copyright 2014 Hewlett-Packard Development Company, L.P. # # 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 # # Unles...
pidfile = os.path.join(self.test_root, "daemon.pid") flagfile = os.path.join(self.test_root, "daemon.flag") open(flagfile, 'w').close() if not os.fork(): self._cleanups = [] daemon_test(pidfile, flagfile) for x in iterate_timeout(30, "daemon to start"): ...
if not os.path.exists(pidfile): break
# vim: set encoding=utf-8 # Copyright (c) 2016 Intel Corporation  # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You 
may obtain a copy of the License at # #       http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree
d to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # class PythonFrame(object): """frame b...
# -*- coding: utf-8 -*- from __future__ import absolute_import, u
nicode_literals, print_function VERSION = (1, 0, 8, 'final') __version__ = VERSION def get_version(): version = '{}.{}'.format(VERSION[0], VERSION[1]) if VERSION[2]: version
= '{}.{}'.format(version, VERSION[2]) if VERSION[3:] == ('alpha', 0): version = '{} pre-alpha'.format(version) else: if VERSION[3] != 'final': version = '{} {}'.format(version, VERSION[3]) return version
from flask import Fl
ask app = Flask(__name_
_) import views
from django.db import models class SpectralTemplate(models.Model): name = models.CharField(max_length=10) path = models.CharField(max_length=100) def __str__(self): return
self.name class PhotometricFilter(models.Model): name
= models.CharField(max_length=10) path = models.CharField(max_length=100) cwl = models.FloatField() width = models.FloatField() lambda_b = models.FloatField() lambda_e = models.FloatField() mvega = models.FloatField() fvega = models.FloatField() def __str__(self): return self.na...
game_type = 'input_output' parameter_lis
t = [['$x1','string'], ['$y0','string']] tuple_list = [ ['KnR_1-10_',[None,None]] ] global_code_template = '''\ d #include &lt;stdio.h> x #include <stdio.h> dx #define MAXLINE 1000 /* maximum input line length */ dx dx int max; /* maximum length seen so far */ dx char line[MAXLINE]; /* current ...
void); dx dx /* my_getline: specialized version */ dx int my_getline(void) dx { dx int c, i; dx extern char line[]; dx dx for (i = 0; i < MAXLINE - 1 dx && (c=getchar()) != EOF && c != '\\n'; ++i) dx line[i] = c; dx if (c == '\\n') { dx line[i] = c; dx ++i; dx } dx line[i] = '\\0'; dx return i; dx } dx...
import json import pytest from yelp_beans.logic.secret import get_secret def test_get_secret_file(tmpdir, database): with tmpdir.as_cwd(): expected = 'password' with open(tmpdir.join('client_secrets.json').strpath, 'w') as secrets: secret = {'secret': expected} secrets.wri...
ecret('secret') assert expected == actual def test_get_secret_file_no_exist(tmpdir, database): with tmpdir.as_cwd(): with pytest.ra
ises(IOError): assert get_secret('secret')
# Copyright (c) 2013-2014 Lingpeng Kong # All Rights Reserved. # # This file is part of TweeboParser 1.0. # # TweeboParser 1.0 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 version 3 of the Lic...
ine = line.strip() if line == "": sys.stdout.write("\n") continue cvlist = line.split("\t") if sys.argv[3] == "N": brown = brown_dict.get(cvlist[1].lower().strip(), 'OOV')
else: brown = brown_dict.get(cvlist[1].strip(), 'OOV') b4 = brown[:4] if len(brown) >= 4 else brown b6 = brown[:6] if len(brown) >= 6 else brown cvlist.append(b4) cvlist.append(b6) cvlist.append(brown) tline = "" for ele in cvlist: ...
# -*- coding: utf-8 -*- from __f
uture__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('postcode_api', '0010_auto_20150601_1513'), ] operations = [ migrations.AlterIndexTogether( name='address', index_together=set([('pos...
prn')]), ), ]
import sys import os.path import logging import ply.yacc from rightarrow.annotations import * from rightarrow.lexer import Lexer logger = logging.getLogger(__name__) class Parser(object): tokens = Lexer.tokens def __init__(self, debug=False, lexer_class=None): self.debug = debug self.lexer_...
warg(self, p):
"arg_ty : KWARG ty" p[0] = { 'kwarg_type' : p[2] } # Special types that never require parenthesis def p_bare_arg_ty(self, p): """ bare_arg_ty : identifier_ty | dict_ty | list_ty | object_ty | any_ty ...