prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
"""Const
ant definitions for testing purposes.""" from bddbot.config import TEST_COMMAND BANK_PATH_1 = "banks/first.bank" BANK_PATH_2 = "banks/second.bank" FEATURE_PATH_1 = BANK_PATH_1
.replace("bank", "feature") FEATURE_PATH_2 = BANK_PATH_2.replace("bank", "feature") (HOST, PORT) = ("bank_server", 0xBDD) CLIENT = "client" DEFAULT_TEST_COMMANDS = [TEST_COMMAND, ]
ield(max_length=100) reverse_one_to_one = PrimaryKeyRelatedField(queryset=RelationalModel.objects.all()) """) self.assertEqual(unicode_repr(TestSerializer()), expected) def test_pk_reverse_many_to_many(self): class TestSerializer(serializers.ModelSerializer): cla...
) for idx in range(3) ] data = { 'foreign_key': new_foreign_key.pk, 'one_to_one': new_one_to_one.pk, 'many_to_many': [item.pk for item in new_many_to_many], } # Serializer should validate okay. serializer = TestSerializer(data=data) ...
tes should be set. instance = serializer.save() assert instance.foreign_key.pk == new_foreign_key.pk assert instance.one_to_one.pk == new_one_to_one.pk assert [ item.pk for item in instance.many_to_many.all() ] == [ item.pk for item in new_many_to_many ...
# Copyright (C) 2020 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
rement at 4lx resolution. Typically 16ms. """ buffer = bytearray(0) with self.i2c_device as i2c: i2c.write(buffer) def set_oncehres2mode(self): """ Start measurement at 0.5lx resolution. Typically 120ms. Pow
er Down after measurement. """ buffer = bytearray(0) with self.i2c_device as i2c: i2c.write(buffer) def set_oncehresmode(self): """ Start measurement at 1lx resolution. Typically 120ms. Power Down after measurement. """ buffer = bytearra...
from django.conf import settings from django.conf.urls import url from django.conf.urls.static import static from vod import user_views from vod.alias_id_views import AliasIdListView, AliasIdCreateView, AliasIdUpdateView, AliasIdRetireView from vod.datatype_views import DataTypeListView, DataTypeCreateView, DataTypeUp...
er/create/$', login_required(UserCreateView.as_view()), name='user-create'), url(r'^user/update/(?P<id>\d+)/$', login_required(UserUpdateView.
as_view()), name='user-update'), url(r'^user/delete/(?P<id>\d+)/$', login_required(UserRetireView.as_view()), name='user-retire'), url(r'^institution/list/$', login_required(InstitutionListView.as_view()), name='institution-list'), url(r'^institution/create/$', login_required(InstitutionCreateView.as_view(...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Cloudbase Solutions Srl # 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.ap...
text, name) image_metadata = {"is_public": False, "disk_format": "vhd", "container_format": "bare",
"properties": {}} with self._pathutils.open(image_vhd_path, 'rb') as f: glance_image_service.update(context, image_id, image_metadata, f) def snapshot(self, context, instance, name, update_task_state): """Create snapshot from a running VM instance.""" instance_name = inst...
import Queue import atexit import logging import threading import traceback class WorkerPool(object): """ Pool of worker threads; grows as necessary. """ _lock = threading.Lock() _pool = None # Singleton. def __init__(self): self._idle = [] # Queues of idle workers. self._workers =...
self._idle.append(queue) def _servi
ce_loop(self, request_q, one_shot): """ Get (callable, args, kwargs) from request_q and queue result. """ while True: callable, args, kwargs, reply_q = request_q.get() if callable is None: request_q.task_done() return # Shutdown. exc ...
#!/usr/bin/env python #Copyright (c) <2015>, <Jaakko Leppakangas> #All rights reserved. # #Redistribution and use in source and binary forms, with or without #modification, are permitted provided that the following conditions are met: # #1. Redistributions of source code must retain the above copyright notice, this #...
ONTRACT, STRICT LIABILITY, OR TORT #(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS #SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# #The views and conclusions contained in the software and documentation are those #of the authors and should not be interpreted as representing official policies, #either expressed or implied, of the FreeBSD Project. ''' Created on Dec 16, 2014 @author: Jaakko Leppakangas ''' import sys from PyQt4 import QtGui fro...
rns: [HEIGHT, WIDTH, 3] points in the world's coordinate frame. """ shape = depth.shape.as_list() height, width = shape[0], shape[1] xx, yy = tf.meshgrid(tf.lin_space(0., width-1., width), tf.lin_space(0., height-1., height)) p_pixel_homogeneous = tf.concat([tf.stack([xx, yy], axis=...
mages. output_height: (int) the height dimension of the output perspective images. output_width: (int) the width dimension of the output perspective images. Returns: Tensorflow Dataset. """ def load_text(file_path, n_lines=200): """Load text data from a file.""" return tf.data.Dataset.from_t...
sor_slices( tf.data.experimental.get_single_element( tf.data.TextLineDataset(file_path).batch(n_lines))) def load_single_image(filename): """Load a single image given the filename.""" image = tf.image.decode_jpeg(tf.read_file(filename), 3) image = tf.image.convert_image_dtype(image, t...
# Copyright (c) 2014 Rackspace US, 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 req...
elp='Passphrase for encrypting Amphora Certificates and ' 'Private Keys. Must be 32, base64(url) compatible, ' 'characters long. Defaults to env[TLS_PASS_AMPS_DEFAULT] ' 'or insecure-key-do-not-use-this-key', regex=r'^[A-Za-z0-9\-_=]{32}$', ...
e signing digest. Defaults' ' to env[OS_OCTAVIA_CA_SIGNING_DIGEST] or "sha256".'), cfg.IntOpt('cert_validity_time', default=30 * 24 * 60 * 60, help="The validity time for the Amphora Certificates " "(in seconds)."), ] certmgr_opts = [ cfg.St...
tandard deviation :math:`\\sigma`: .. math:: Z(x(t))= \\frac{x(t)-\\mu}{\\sigma} If an AnalogSignalArray containing multiple signals is provided, the z-transform is always calculated for each signal individually. If a list of AnalogSignalArray objects is supplied, the mean and standard d...
] [-0.29277002] [ 0.29277002]
[ 0.87831007] [ 1.46385011]] dimensionless >>> print zscore(b) [[-1.46385011 -1.46385011] [-0.87831007 -0.87831007] [-0.29277002 -0.29277002] [ 0.29277002 0.29277002] [ 0.87831007 0.87831007] [ 1.46385011 1.46385011]] dimensionless >>> print zscore([b,c]) # doctest: +...
import requests from PIL import Image, ImageEnhance, ImageChops, ImageFilter from io import BytesIO, StringIO import time import sys, os import codecs url = 'http://d1222391-23d7-46de-abef-73cbb63c1862.levels.pathwar.net' imgurl = url + '/captcha.php' headers = { 'Host' : 'd1222391-23d7-46de-abef-73cbb63c1862.levels....
img = Image.open(file) # img = prepare(img) img = img.resi
ze((img.size[0]*4, img.size[1]*4), Image.BILINEAR) img.show() # bounds = separate(img) bounds = vertical_cut(img) _train(img, bounds) i = i + 1
#
!/usr/bin/env python3 # Copyright (c) 2008-9 Qtrac Ltd. All rights reserved. # This program or module is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Fr
ee Software Foundation, either version 2 of the License, or # version 3 of the License, or (at your option) any later version. It is # provided for educational purposes and is distributed in the hope that # it will be useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FO...
# -*-coding:Utf-8 -* # Copyright (c) 2012 LE GOFF Vincent # 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 # l...
du masque.""" str_coordonnees = liste_vers_chaine(commande).lstrip() str_coordonnees = str_coordonnees.split(" ")[0] if not str_coordonnees: raise ErreurValidation( "Précisez des coordonnées.", False) if not RE_COORDS.
search(str_coordonnees): raise ErreurValidation( "Ceci ne sont pas des coordonnées valides.", False) self.a_interpreter = str_coordonnees commande[:] = commande[len(str_coordonnees):] masques.append(self) return True def valider(self, personn...
import json from mflow_nodes.processors.base import BaseProcessor from mflow_nodes.stream_node import get_processor_function, get_receiver_function from mflow_nodes.node_manager import NodeManager def setup_file_writing_receiver(connect_address, output_filename): """ Setup a node that writis the message head...
connection_address=connect_address), receiver_function=get_receiver_function(connection_address=connect_address), processor_instance=process
or) return receiver
t_active_optimized(self): self._check_self() path = "%s/alua_support_active_optimized" % self.path return int(fread(path)) def _set_alua_support_active_optimized(self, enabled): self._check_self() path = "%s/alua_support_active_optimized" % self.path try: ...
support_standby(self): self._check_self() path = "%s/alua_support_standby" % self.path return int(fread(path)) def _set_alua_support_s
tandby(self, enabled): self._check_self() path = "%s/alua_support_standby" % self.path try: fwrite(path, str(int(enabled))) except IOError as e: raise RTSLibError("Cannot set alua_support_standby: %s" % e) def _get_alua_support_transitioning(self): se...
from django.core.management.base import BaseCommand, CommandError from django.core.cache import cache class Command(BaseCommand): help = 'Clears the cache' def handle(self, *args, **optio
ns): print("Clearing cache!") cach
e.clear()
ain", "wet_grass", "winter", "sprinkler"], ["slippery_road", "rain", "winter", "wet_grass", "sprinkler"], ["slippery_road", "rain", "winter", "sprinkler", "wet_grass"], ["slippery_road", "rain", "sprinkler", "wet_grass", "winter"], ...
edCliques = ["slippery_roadrain", "wet_grasssprinklerrain", "wet_grassrainsprink
ler", "sprinklerwinterrain", "sprinklerrainwinter", "wintersprinklerrain", "winterrainsprinkler", "rainsprinklerwinter", "rainwintersprinkler"] self.assertEqual(len(ft.tree), 3) for n in ft.tree.nodes(): # was nodes_iter in...
#--------------------------------- #Joseph Boyd - joseph.boyd@epfl.ch #--------------------------------- from bs4 import BeautifulSoup from urllib2 import urlopen import csv BASE_URL = 'http://www.tutiempo.net' PAGE_1 = '/en/Climate/India/IN.html' PAGE_2 = '/en/Climate/India/IN_2.html' headings = ['Location', 'Year',...
climate_table = soup.find('table', 'TablaClima') if climate_table is None: continue climate_rows = climate_table.findAll('tr') for row in climate_rows[1:-2]: dat...
n data: a = ','.join(datum.findAll(text=True)) print_line.append(a.encode('utf8')) csv_writer.writerow(print_line) num_rows += 1 if num_rows == MAX_ROWS: csvfile.cl...
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
# Create a 2 x 2 linear operator. matrix = [[1., 2.], [3., 4.]] operator = LinearOperatorFullMatrix(matrix) operator.to_dense() ==> [[1., 2.] [3., 4.]] operator.shape ==> [2, 2] operator.log_abs_determinant() ==> scalar T
ensor x = ... Shape [2, 4] Tensor operator.matmul(x) ==> Shape [2, 4] Tensor # Create a [2, 3] batch of 4 x 4 linear operators. matrix = tf.random_normal(shape=[2, 3, 4, 4]) operator = LinearOperatorFullMatrix(matrix) ``` #### Shape compatibility This operator acts on [batch] matrix with compatibl...
- endrec = reclen # # Then, info on whether we're done with data block: # [reclen, key, endrec] # - reclen = 1 32-bit integer that specifies number of bytes in # key (either 4 or 8) # - key = 4 or 8 byte integer specifying number of words in next # record; if 0, done with ...
i') if reclen == 4: self._bit64 = False self._intstr = self._endian + 'i4' self._intstru = self._en
dian + '%di' self._ibytes = 4 self._Str = self._Str4 else: self._bit64 = True self._intstr = self._endian + 'i8' self._intstru = self._endian + '%dq' self._ibytes = 8 self._Str = struct.Struct(self._endian + 'q') # print...
import time t0 = time.time() import os import numpy as n import sys import glob import cPickle import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as p from scipy.interpolate import interp1d L_box = 1000./0.6777 tracer_names = n.array(['S8_ELG', 'S8_BG1', 'S8_BG2', 'S5_GAL', 'S8_QSO', 'S6_AGN', 'S5_B...
)) tracer_files.sort() # tracer loop #path_2_tracer_file = tracer_files[0] for path_2_tracer_file in tracer_files: print path_2_tracer_file spl_bn = os.path.basename(path_2_tracer_file)[:-5].split('_') tracer_name = spl_bn[-2]+'_'+spl_bn[-1] ids = fits.open(path_2_tracer_file)[1].data['lin
e_number'] x_i = positions['x'][ids]/0.6777 - x_observer + x_shift y_i = positions['y'][ids]/0.6777 - y_observer + y_shift z_i = positions['z'][ids]/0.6777 - z_observer + z_shift shell = (x_i*x_i + y_i*y_i + z_i*z_i < r_max**2.) & (x_i*x_i + y_i*y_i + z_i*z_i > r_min**2.) slice = (shell) & (z_i>sl...
t namespace resources. The values are lists of objects. Setting an existing value appends the object to the value. Setting a value with a list sets/replaces the value. """ __slots__ = ('_store',) def __init__(self, *args: Any, **kwargs: Any): self._store: Dict[str, List[Any]] = {} s...
_qname(self, qname: str) -> str: """ Converts an exten
ded QName to the prefixed format. Only registered namespaces are mapped. :param qname: a QName in extended format or a local name. :return: a QName in prefixed format or a local name. """ try: if qname[0] != '{' or not self._namespaces: return qname ...
import pygame from pygame import event class Player: def __init__(self, p_id): self.points = None self.p_id = p_id def
turn(self, nr): return pygame.even
t.get()
""" homeassistant.components.ifttt ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This component enable you to trigger Maker IFTTT recipes. Check https://ifttt.com/maker for details. Configuration: To use Maker IFTTT you will need to add something like the following to your config/configuration.yaml. ifttt: key: xxxxx-x-xxxxxxxxxx...
if not validate_config(config, {DOMAIN: ['key']}, _LOGGER): return False
key = config[DOMAIN]['key'] def trigger_service(call): """ Handle ifttt trigger service calls. """ event = call.data.get(ATTR_EVENT) value1 = call.data.get(ATTR_VALUE1) value2 = call.data.get(ATTR_VALUE2) value3 = call.data.get(ATTR_VALUE3) if event is None: ...
"""Train ILSVRC2017 Data using homemade scripts.""" import cv2 import os import math import tensorflow as tf from multiprocessing import Process, Queue import os import sys FILE_DIR = os.path.dirname(__file__) sys.path.append(FILE_DIR + '/../') import config as cfg from img_dataset.ilsvrc2017_cls_multithread import ...
lection(tf.GraphKeys.UPDATE_OPS) with
tf.control_dependencies(update_ops): # train_op = tf.train.AdamOptimizer(0.0005).minimize(loss) train_op = tf.train.MomentumOptimizer(0.001, 0.9).minimize(loss) correct_pred = tf.equal(tf.cast(tf.argmax(logits, 1), tf.int32), label_data) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) tf.summary...
__all__ = [] from common import * import common __all__ += common.__all__ from levinson_lpc import * import levinson_lpc __all
__ += levins
on_lpc.__all__
import os import os.path def pytest_configure(config): test_db = os.environ.ge
t('DB', 'sqlite') os.environ['DJANGO_SETTINGS_MODULE'] = 'pytest_django_casperjs.tests.settings' # noqa from django.conf import settings if test_db == 'postgresql': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'postgres',...
'].update({ 'ENGINE': 'django.db.backends.mysql', 'USER': 'root', 'NAME': 'pytest_django_casperjs_test', }) elif test_db == 'sqlite': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', ...
#!/usr/bin/env python # encoding: utf-8 from ImageFusion import ImageFusion from PIL import Image import numpy as np import pylab as plt import pywt class FusionDWB(ImageFusion): """ Image Fusion based wavelet """ def __init__(self, imageNames = None, zt=2, ap=2, mp=0): self._imageNames = imageNames...
usion, 'db1') return self._fusionImage def plot(self): plt.
figure(0) plt.gray() plt.subplot(131) plt.imshow(self._images[0]) plt.subplot(132) plt.imshow(self._images[1]) plt.subplot(133) plt.imshow(self._fusionImage) plt.show() if __name__ == '__main__': IMAGEPATH = "../../images/multifocus/" imLists = [...
xact." self.assertEqual(1/4.0, fpu.down(lambda: 1.0 / 4.0)) self.assertEqual(1/4.0, fpu.up(lambda: 1.0 / 4.0)) self.assertEqual(-1/4.0, fpu.up(lambda: 1.0 / -4.0)) self.assertEqual(-1/4.0, fpu.down(lambda: 1.0 / -4.0)) def test_fifth(self): "Nearest rounding of 1/5 is upward...
) + 3], interval[4503599627370496 * 4.0, 4503599627370497 * 4.0]) self.assertEqual(interval[-2 ** (52 + 2) - 1], interval[-4503599627370497 * 4.0, -4503599627370496 * 4.0]) self.assertEqual(interval[-2 ** (52 + 2) - 2], interval[-4503599627370497 * 4.0, -4503599627370496 * 4.0]) self.assertEqual...
99627370496 * 4.0]) def test_unary(self): self.assertEqual(interval[1, 2], +interval[1, 2]) self.assertEqual(interval[-2, -1], -interval[1, 2]) def test_sum(self): self.assertEqual(interval[-fpu.infinity, +fpu.infinity], interval[-fpu.infinity] + interval[fpu.infinity]) self.as...
""" Cisco_IOS_XR_clns_isis_datatypes This module contains a collection of generally useful derived YANG data types. Copyright (c) 2013\-2016 by Cisco Systems, Inc. All rights reserved. """ import re import collections from enum import Enum from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedB...
ta_table['IsisInternalLevelEnum'] class IsisSubAddressFamilyEnum(Enum): """ IsisSubAddressFamilyEnum Isis sub address family .. data:: unicast = 0 Unicast .. data:: multicast = 1 Multicast """ unicast = 0 multicast = 1 @staticmethod def _meta_info(): ...
yEnum']
"""TcEx Notification Module""" # standard library import json import logging from typing import TYPE_CHECKING # first-party from tcex.exit.error_codes import handle_error if TYPE_CHECKING: # third-party from requests import Session # get tcex logger logger = logging.getLogger('tcex') class Notifications: ...
self._recipients = None self._priority = priority self._is_organization = True def send(self, message): """Send our message Args: message (str): The message to be sent. Returns: requests.models.Response: The response
from the request. """ body = { 'notificationType': self._notification_type, 'priority': self._priority, 'isOrganization': self._is_organization, 'message': message, } if self._recipients: body['recipients'] = self._recipients ...
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # # MDAnalysis --- https://www.mdanalysis.org # Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors # (see the file AUTHORS for the full list of names) # # Released under t...
If you don't have trajectories at hand you can play with the ones that come with MDAnalysis for testing (see below under `Examples`_):: >>> u = MDAnalysis.Universe(PSF, DCD) Select the C-alpha atoms and store them as a group of atoms:: >
>> ca = u.select_atoms('name CA') >>> len(ca) 214 Calculate the centre of mass of the CA and of all atoms:: >>> ca.center_of_mass() array([ 0.06873595, -0.04605918, -0.24643682]) >>> u.atoms.center_of_mass() array([-0.01094035, 0.05727601, -0.12885778]) Calculate the CA end-to-end distance (in angstroem...
import sys import wx
import wx.dataview as dv #import os; print('PID:'+str(os.getpid())); raw_input("Press enter...") #---------------------------------------------------------------------- class MyCustomRenderer(dv.DataViewCustomRenderer): def __init__(self, log, *args, **kw): dv.DataViewCustomRenderer.__init__(self, *args...
= value return True def GetValue(self): #self.log.write('MyCustomRenderer.GetValue\n') return self.value def GetSize(self): # Return the size needed to display the value. The renderer # has a helper function we can use for measuring text that is # aware of any ...
from sgfs import SGFS from sgactions.utils import notify, progress, alert def run_create(**kwargs): _run(False, **kwargs) def run_preview(**kwargs): _run(True, **kwargs) def _run(dry_run, entity_type, selected_ids, **kwargs): title='Preview Folders' if dry_run else 'Creating Folders' verb = 'p...
else 'Creating') + ' folders for %s %ss; please wait...' % (len(selected_ids), entity_type)) sgfs = SGFS() entities = sgfs.session.merge([dict(type=entity_type, id=id_) for id_ in selected_ids]) heirarchy = sgfs.session.fetch_heirarchy(entities) sgfs.session
.fetch_core(heirarchy) command_log = sgfs.create_structure(entities, dry_run=dry_run) if command_log: details = '\n'.join(command_log) if dry_run: alert(title='Folder Preview', message=details) else: notify( message='Created folders for %...
rt, unicode_literals import environ ROOT_DIR = environ.Path(__file__) - 3 # (/a/b/myfile.py - 3 = /) APPS_DIR = ROOT_DIR.path('nhweb') env = environ.Env() # APP CONFIGURATION # ------------------------------------------------------------------------------ DJANGO_APPS = ( # Default Django apps: 'django.cont...
'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.templat...
our stuff: custom template context processors go here ], }, }, ] # See: http://django-crispy-forms.readthedocs.org/en/latest/install.html#template-packs CRISPY_TEMPLATE_PACK = 'bootstrap3' # STATIC FILE CONFIGURATION # ---------------------------------------------------------------------------...
# Copyright 2017 SAS Project Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
'total distance is ', profile[0]*profile[1] loss = pytm.point_to_point(profile, h1, h2, dielectric_constant, soil_conductivity, refract
ivity, f, radio_climate, polarization, confidence, reliability) print 'ITM P2P is ', loss return loss # Adjusted propagation loss according to the adjust...
"""Scenario Outline tests.""" import textwrap from pytest_bdd.utils import collect_dumped_objects from tests.utils import assert_outcomes STEPS = """\ from pytest_bdd import parsers, given, when, then from pytest_bdd.utils import dump_obj @given(parsers.parse("there are {start:d} cucumbers"), target_fixture="cucumb...
| bork \\ | | bork \\\| | """ ), ) testdir.makepyfile( textwrap.dedent( """\ from pytest_bdd import scenario, given, parsers from pytest_bdd.utils import dump_obj @scena
rio("outline.feature", "Outline with escaped pipe character") def test_outline_with_escaped_pipe_character(request): pass @given(parsers.parse("I print the {string}")) def i_print_the_string(string): dump_obj(string) """ ) ) ...
# # calculator.py : A calculator module for the deskbar applet. # # Copyright (C) 2008 by Johannes Buchner # Copyright (C) 2007 by Michael Hofmann # Copyright (C) 2006 by Callum McKenzie # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License...
" : math.ceil, "cos" : math.cos, "cosh" : math.
cosh, "degrees" : math.degrees, "exp" : math.exp, "floor" : math.floor, "hex" : lenient_hex, "int" : int, "log" : math.log, "pow" : math.pow, "lo...
Field')(auto_now=True, blank=True)), ('order', self.gf('django.db.models.fields.IntegerField')()), ('card', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['matches.Card'])), ('event_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['matches.EventType']...
ype': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Me...
'django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', ...
"""Identity matrix in sparse format Returns an identity matrix with shape (n,n) using a given sparse format and dtype. Parameters ---------- n : integer Shape of the identity matrix. dtype : Data type of the matrix format : string Sparse format of the result, e....
Examples -------- >>> from scipy.sparse import coo_matrix, bmat >>> A = coo_matrix([[1,2],[3,4]]) >>> B = coo_matrix([[5],[6]]) >>> C = coo_matrix([[7]]) >>> bmat( [[A,B],[None,C]] ).todense() matrix([[1, 2, 5],
[3, 4, 6], [0, 0, 7]]) >>> bmat( [[A,None],[None,C]] ).todense() matrix([[1, 2, 0], [3, 4, 0], [0, 0, 7]]) """ blocks = np.asarray(blocks, dtype='object') if np.rank(blocks) != 2: raise ValueError('blocks must have rank 2') M,N = block...
# -*- coding: iso-8859-15
-*- """ A wxValidator that matches APDU in hexadecimal such as: A4 A0 00 00 02 A4A0000002 __author__ = "http://www.gemalto.com" Copyright 2001-2010 gemalto Author: Jean-Daniel Aussel, mailto:jean-daniel.aussel@gemalto.com This file is part of pyscard. pyscard is free software; you can redistribute it and/o...
eneral Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. pyscard is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. S...
# 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...
xceptions from oslo_config import cfg from oslo_utils import netutils from ironic
_inspector.common import lldp_parsers from ironic_inspector.common import lldp_tlvs as tlv from ironic_inspector.plugins import base from ironic_inspector import utils LOG = utils.getProcessingLogger(__name__) CONF = cfg.CONF PORT_ID_ITEM_NAME = "port_id" SWITCH_ID_ITEM_NAME = "switch_id" LLDP_PROC_DATA_MAPPING =\ ...
aWeights.append(100) # else: # aWeights.append(0) # # envelopeop.Weights.Array = aWeights return curve # ======================================================== ## Create a NurbsCurve with a single subcurve. # @param parent X3DObject - Parent object. # @param name ...
0Y, point0Z, 1, point1X, point1Y, point1Z, 1, ...]. # @param close Boolean - True to close the curve. # @param degree Integer - 1 for linear curve, 3 for Cubic. # @param t SITransformation - Global transform. # @param color List of Double - The RGB color of the Null (ie. [1,0,0] for red). # @return NurbCurve - The newl...
curve = parent.AddNurbsCurve(points, None, close, degree, c.siNonUniformParameterization, c.siSINurbs, name) uti.setColor(curve, color) curve.Kinematics.Global.Transform = t return curve # ======================================================== ## Create a NurbsCurve with multiple subcurve. # @param...
## Copyright (c) 2012 Szymon Zmilczak ## ## ## This file is part of Odtwarzacz. ## ## Odtwarzacz is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ##...
) self.Bind(wx.EVT_MENU, self.onExit, menuExit) self.Bind(wx.EVT_CLOSE, self.onExit)
#startPath = "D:\\Gas n' Metal" sizer2 = wx.BoxSizer(wx.VERTICAL) sizer = wx.BoxSizer(wx.HORIZONTAL) sizer3 = wx.BoxSizer(wx.VERTICAL) self.te = wx.StaticText(self, -1, u"Biblioteka:", (0, 0)) f = self.te.GetFont() f.SetPixelSize((10,25)) self.te.Se...
# Lint as: python3 """Unit tests for dmiparse.""" import os import dmiparse from google3.pyglib import resources from google3.testing.pybase import googletest TEST_PATH = 'google3/third_party/py/dmiparse/test_data' class DmiParserTest(googletest.TestCase): def setUp(self): super(DmiParserTest, self).setUp(...
rd_record.props['MAC Address'].items) self.assertIn('Contained Object Handles', base_board_record.props) self.assertEqual('5', base_board_record.props['Contained Object Handles'].val) self.assertEqual(['0x009A', '0x009B', '0x009C', '0x009D', '0x009E'],
base_board_record.props['Contained Object Handles'].items) self.assertIn('Characteristics', base_board_record.props) self.assertEqual('', base_board_record.props['Characteristics'].val) self.assertEqual([ 'PCI is supported', 'BIOS is upgradeable', 'ACPI is supported', 'UE...
# -*- coding:utf-8 -*- from mako import runtime, filters, cache UNDEFINED = runtime.UNDEFINED __M_dict_builtin = dict __M_locals_builtin = locals _magic_number = 10 _modified_time = 1440369075.543512 _enable_loop = True _template_filename = u'themes/monospace/templates/index.tmpl' _template_uri = u'index.tmpl' _source_...
finally: context.caller_stack._pop_frame() def render_content(context,**pageargs): __M_caller = context.caller_stack._push_frame() try: date_format = context.get('date_format', UNDEFINED) helper = _mako_get_namespace(context, 'help
er') messages = context.get('messages', UNDEFINED) posts = context.get('posts', UNDEFINED) _link = context.get('_link', UNDEFINED) def content(): return render_content(context) comments = _mako_get_namespace(context, 'comments') index_teasers = context.get('in...
#!/usr/bin/env python from api.camara.orgaos import * from api.camara.deputados import * from core.models import * import django django.setup() ## Orgaos Webservice orgaos = OrgaosCamara() orgaos.importar_tipos_orgaos() org
aos.importar_orgaos() orgaos.importar_cargos() ## Deputados Webservice deputados = DeputadosCamara() deputados.importar_partidos() deputados.importar_deputad
os() #deputados.importar_detalhes_deputados() # Google Images download #for parlamentar in Parlamentar.objects.all(): # parlamentar.download_photos() # Wikipedia data #for parlamentar in Parlamentar.objects.all(): # parlamentar.get_wikipedia_data()
ValuesEnum(_messages.Enum): """Apply a predefined set of access controls to this bucket. Values: authenticatedRead: Project team owners get OWNER access, and allAuthenticatedUsers get READER access. private: Project team owners get OWNER access. projectPrivate: Project team members ge...
allUsers get WRITER access. """ authenticatedRead = 0 private = 1 projectPrivate = 2 publicRead = 3 publicReadWrite
= 4 class PredefinedDefaultObjectAclValueValuesEnum(_messages.Enum): """Apply a predefined set of default object access controls to this bucket. Values: authenticatedRead: Object owner gets OWNER access, and allAuthenticatedUsers get READER access. bucketOwnerFullControl: Object own...
from django.conf import settings from rest_framework import serializers from rest_framework.decorators import api_view from rest_framework.response import Response from kitsune.products.models import Product from kitsune.questions.models import Question, QuestionMappingType from kitsune.questions.api import QuestionS...
roduct'], data['max_questions']), 'documents': _document_suggestions( searcher, data['q'], data['locale'], data['product'], data['max_documents']), }) def _question_suggestions(searcher, text, locale, product, max_results): if max_results <= 0: return [] search_filter = es_uti...
model='questions_question', question_is_archived=False, question_is_locked=False, question_is_solved=True) if product: search_filter &= es_utils.F(product=product) if locale: search_filter &= es_utils.F(question_locale=locale) questions = [] searcher = _query...
from csacompendium.csa_practice.models import PracticeLevel from csacompendium.utils.pagination import APILimitOffsetPagination from csacompendium.utils.permissions import IsOwnerOrReadOnly from csacompendium.utils.viewsutils import DetailViewUpdateDelete, CreateAPIViewHook from rest_framework.filters import DjangoFilt...
set = PracticeLevel.objects.all() s
erializer_class = practice_level_serializer['PracticeLevelListSerializer'] filter_backends = (DjangoFilterBackend,) filter_class = PracticeLevelListFilter pagination_class = APILimitOffsetPagination class PracticeLevelDetailAPIView(DetailViewUpdateDelete): """ Updates a reco...
from scipy.cluster.hierarchy imp
ort dendrogram import matplotlib.pyplot as plt def augmented_dendrogram(*args, **kwargs): ddata = dendrogram(*args, **kwargs) if not kwargs.get('no_plot', False): for i, d in zip(ddata['icoord'], ddata['dcoord']): x = 0.5 * sum(i[1:3]) y = d[1] #plt.plot(x, y, 'ro'...
a='top', ha='center') return ddata
__author__ = 'dako' class SessionHelper: def __init__(self, app): self.app = app def login(self, username, password): wd = self.app.wd self.app.open_home_page() wd.find_element_by_name("user").click() wd.find_element_by_name("user").clear() wd.find_element_by_...
lf, username): wd = self.app.wd return self.get_logged_user() == username def get_logged_user(self): wd = self.app.wd return
wd.find_element_by_xpath("//div/div[1]/form/b").text[1:-1] def ensure_logout(self): wd = self.app.wd if self.is_logged_in(): self.logout() def ensure_login(self, username, password): wd = self.app.wd if self.is_logged_in(): if self.is_logged_in_as(usernam...
in self.snapshots] return min([s.snapshot for s in self.snapshots]) @first_snapshot.expression def first_snapshot(cls): return select([func.min(PortalSnapshot.snapshot)])\ .where(PortalSnapshot.portalid == cls.id).label("first_snapshot") @hybrid_property def last_snapshot(s...
elf.intersected) if self.intersected >0 else 0 @hybrid_property def adddelratio(self): return (self.added-self.deleted)\ /(1.0* (self.added+self.deleted))if ((self.added+self.deleted)) >0 else 0 @hybrid_property
def addRatio(self): return (self.added) \ / (1.0 * self.intersected)if self.intersected >0 else 0 @hybrid_property def delRatio(self): return (self.deleted) \ / (1.0 * self.intersected)if self.intersected >0 else 0 @hybrid_property def updatedRatio(se...
############################################################################## # Copyright (c) 2013-2018, 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...
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-
1307 USA ############################################################################## from spack import * class Stc(AutotoolsPackage): """STC: The Swift-Turbine Compiler""" homepage = 'http://swift-lang.org/Swift-T' url = 'http://swift-lang.github.io/swift-t-downloads/stc-0.7.3.tar.gz' versi...
est(one_instr_line) def test_04_no_pop_blocks(self): self.run_test(no_pop_blocks) def test_05_no_pop_tops(self): self.run_test(no_pop_tops) def test_06_call(self): self.run_test(call) def test_07_raise(self): self.run_test(test_raise) def test_08_settrace_and_return(...
exception raised in response to the given event is handled OK.""" self.raiseOnEvent = event try: for i in xrange(sys.getrecursionlimit() + 1): sys.settrace(self.trace) try: self.f() except ValueError: ...
ecursion counter not reset") # Test the handling of exceptions raised by each kind of trace event. def test_call(self): self.run_test_for_event('call') def test_line(self): self.run_test_for_event('line') def test_return(self): self.run_test_for_event('return') def test_exce...
ime(now_time.year, now_time.month, now_time.day, 12, 0) evening = datetime.datetime(now_time.year, now_time.month, now_time.day, 18, 0) morning_off_by_minutes = datetime.datetime(now_time.year, now_time.month, now_time.day, 9, 5) morning_exact = datetime.datetime(now_time.year, now_time.month, n...
est_scaler.add_to_history(TOO_HIGH) self.test_scaler.add_to_history(TOO_HIGH) self.test_scaler.add_to_history(TOO_HIGH) self.test_scaler.add_to_history(TOO_HIGH) self.test_scaler.do_autoscale() assert_equals(self.test_scaler.num_dynos, 2) assert_equals(self.test_scaler.re...
s, []) def test_a_mixed_stack_of_low_high_scales_to_the_min_needed_for_the_condition(self): assert_equals(self.test_scaler.num_dynos, 1) self.test_scaler.add_to_history(TOO_LOW) self.test_scaler.add_to_history(TOO_LOW) self.test_scaler.add_to_history(TOO_LOW) self.test_scale...
import trafaret as t from server.core.passwords import generate_password, check_password from server.core.forms import TrafaretForm, TrafaretError class RegistrationForm(TrafaretForm): fields = t.Dict({ t.Key('email'): t.Email(), t.Key('password'): t.String(max_length=255), t.Key('confirm...
_length=255), }) async def extra_validation(self): errors = {} user = await self.db.users.find_one({'
email': self.data['email']}) if not user: errors['email'] = 'User not found' else: if not check_password(self.data['password'], user.password): errors['password'] = 'Password is not correct' self.user = user if errors: raise Trafare...
= 1 if len(arg.split('=')) == 2: dry_run = int(arg.split('=')[1]) elif arg.startswith('--memory-estimate-depth'): memory_estimate_depth = -1 if len(arg.split('=')) == 2: memory_estimate_depth = int(arg.split('=')[1]) elif arg.startswith('--domain-decomposition='):...
sl_lrtddft.append(sl_args[sl_args_index]) elif arg.startswith('--buffer_size='): # Buffer size for MatrixOperator in MB buffer_size = int(arg.split('=')[1]) elif arg.startswith('--gpaw='): extra_parameters = eval('dict(%s)' % arg[7:]) elif arg == '--gpaw': extra_parameters = ...
d command line argument: del sys.argv[i] if debug: np.seterr(over='raise', divide='raise', invalid='raise', under='ignore') oldempty = np.empty def empty(*args, **kwargs): a = oldempty(*args, **kwargs) try: a.fill(np.nan) except ValueError: a.fill(-1000...
# # Copyright (c) 2008--2015 Red Hat, Inc. # # This software is licensed to you under the GNU General Public License, # version 2 (GPLv2). There is NO WARRANTY for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. You should have received a c...
along with this software; if not, see # http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. # # Red Hat trademarks are not licensed under GPLv2. No permission is # granted to use or replicate Red Hat trademarks that are incorporated # in this software or its documentation. # # Sends notification to search-server tha...
ort log_error class SearchNotify: def __init__(self, host="127.0.0.1", port="2828"): self.addr = "http://%s:%s" % (host, port) def notify(self, indexName="server"): try: client = xmlrpclib.ServerProxy(self.addr) result = client.admin.updateIndex(indexName) exc...
ing FRAME_SPEED = 50 elif len(sys.argv) == 3 and sys.argv[1] == 'record': ACTION='record' FILENAME = sys.argv[2] # Stored data processing FRAME_SPEED = 50 else: usage() def parse_get_frame_resp(line): _,vals_raw = line.split(':') vals = list(map(int, vals_raw.split(','))) frame_nr = v...
gin)), 20), (((freq_mhz + 7.5) - MHz(scan_range_begin)), 20), (((freq_mhz + 10) - MHz(scan_range_begin)), 0), ), linestyle='solid', linewidth=0, color='grey', alpha=0.4) ax.add_patch(pac) plt.grid(linewidth=2,linestyle='solid',color='black') plt.tight_layout() bbox = fig.get_window_e...
nitial data and history of amount of pixels of the screen, since it is # important that all lines are draw on the screen. bbox = fig.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) width, height = bbox.width*fig.dpi, bbox.height*fig.dpi matrix = np.empty([int(height),bin_size]) * np.nan pcm = ax.pcolor...
# coding: utf-8 from __future__ import unicode_literals # created by: Han Feng (https://github.com/hanx11) import collections import hashlib import logging import requests from wxpy.api.messages import Message from wxpy.ext.talk_bot_utils import get_context_user_id, next_topic from wxpy.utils.misc import get_text_wi...
utf-8") signature = hashlib.sha1(signature).hexdigest() ret = collections.namedtuple("signature_return", "signature nonce") ret.signature = signature ret.nonce = nonce return ret def _make_http_header_xauth(self): """ 生成请求认证 """ sign = self...
"X-Auth": "app_key=\"{0}\",nonce=\"{1}\",signature=\"{2}\"".format( self.key, sign.nonce, sign.signature) } return ret def do_reply(self, msg): """ 回复消息,并返回答复文本 :param msg: Message 对象 :return: 答复文本 """ ret = self.reply_text(msg) ...
n result_vars] def fitness(y, t): y = np.asarray(y).flatten() t = np.asarray(t).flatten() diff = np.asarray([0.0 if np.isnan(t_tmp) else y_tmp - t_tmp for y_tmp, t_tmp in zip(y, t)]).flatten() t[np.isnan(t)] = 1.0 t[t == 0] = 1.0 weights = 1 / np.abs(t) return weights @ np.abs(diff) if _...
= 1e-2 dts = 1e-1 compute_dir = f"{os.getcwd()}/stn_gpe_str_opt
" # perform genetic optimization ga = CustomGOA(fitness_measure=fitness, gs_config={ 'circuit_template': f"{os.getcwd()}/config/stn_gpe/stn_gpe_str", 'permute_grid': True, 'param_map': param_map, 'sim...
# coding=utf-8 class _Webhooks: def __init__(self, client=None): self.client = client def create_webhook(self, params=None, **options): """Establish a webhook :param Object params: Parameters for the request :param **options - opt_fields {list[str]}: Defines fields...
tions. - opt_pretty {bool}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. ...
bhooks/{webhook_gid}".replace("{webhook_gid}", webhook_gid) return self.client.delete(path, params, **options) def get_webhook(self, webhook_gid, params=None, **options): """Get a webhook :param str webhook_gid: (required) Globally unique identifier for the webhook. :param Object pa...
"""Test safe_exec.py""" from cStringIO import StringIO import os.path import textwrap import unittest import zipfile from nose.plugins.skip import SkipTest from codejail import safe_exec class SafeExecTests(unittest.TestCase): """The tests for `safe_exec`, to be mixed into specific test classes.""" # Safe...
ise SkipTest def safe_exec(self, *args, *
*kwargs): safe_exec.not_safe_exec(*args, **kwargs)
''' Created on Dec 3, 2014 @author: gearsad ''' import sys from roverpylot import rover from bot_update_t import bot_update_t from bot_control_command_t import bot_control_command_t import lcm # Try to start OpenCV for video try: import cv except: cv = None class LCMRover(rover.Rover): ''' A rover ...
e = battery self.__lcm.publish("ARNerve_Bot_Update_" + self.__botname, camUpdate.encode()) #except: # print "Exception", sys.exc_info()[0] # pass def Update(self): '''
Update the LCM ''' self.__lcm.handle() def Disconnect(self): self.lc.unsubscribe(self.__controlSubscription) def UpdateBotControlHandler(self, channel, data): ''' Get the updated bot parameters and send them to the bot. ''' controlPara...
# -*- coding: utf-8 -*- # # This file is part of Invenio-Previewer-ISPY # Copyright (C) 2014 CERN # # Invenio-Previewer-ISPY is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, o...
ense for more details. # # You should have received a copy of the GNU General Public License # along with Invenio-Previewer-ISPY; if not, write to the Free Software Foundation, # Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307,
USA. """Invenio-Previewer-ISPY testsuite."""
he Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distr...
is expected to have a low number of values that
are relatively stable over time, as opposed to version, which can be changed whenever new code is deployed. :type version: str :param version: Represents the source code version that the developer provided, which could represent a version label or a...
#!/usr/bin/env python3 import urllib import codecs from bs4 import BeautifulSoup from sys import argv import
re,time class Translate: def start(self): self._get_html_sourse() self._get_content("enc") self._remove_tag() self.print_result() def _get_html_sourse(self): word=argv[1] if len(argv)>1 else '' url="http://dict.
baidu.com/s?wd=%s&tn=dict" % word self.htmlsourse=urllib.unicode(urllib.urlopen(url).read(),"gb2312","ignore").encode("utf-8","ignore") def _get_content(self,div_id): soup=BeautifulSoup("".join(self.htmlsourse), "lxml") self.data=str(soup.find("div",{"id":div_id})) def _remove_tag(sel...
cription=u'The default domain', id=CONF.identity.default_domain_id, name=u'Default') self.domains['domain_default'] = create_domain(self.default_domain) def test_config_upload(self): # The values below are the same as in the domain_configs_multi_ldap # directory of t...
ck_print.assert_has_calls( [mock.call(_('The --all option cannot be used with ' 'the --domain-name option'))]) class CliDomainConfigInvalidDomainTestCase(CliDomainConf
igAllTestCase): def config(self, config_files): self.invalid_domain_name = uuid.uuid4().hex CONF(args=['domain_config_upload', '--domain-name', self.invalid_domain_name], project='keystone', default_config_files=config_files) def test_config_upload(self): ...
import tornado import tornado.gen from req import Service from re
q import ApiRequestHandler
class Index(ApiRequestHandler): @tornado.gen.coroutine def get(self): self.render()
s # GLOBALS # define -v and -d as false (-d defaults to encrypt mode) verbose_opt = False decrypt_opt = False key_phrase = '' # clear text key phrase key_hashed = '' # hashed key phrase clear_text = '' # starting message input pigpen_message = '' # message after pigpen stage encrypted_message = '' # the encryp...
1]: 1 of 3 dictionaries is derived from the sum of the
pre-hashed key ASCII values (mod 3)") print("[ENCRYPTION - Phase 1]: The clear text is converted into pigpen cipher text using the selected dictionary:") print("[ENCRYPTION - Phase 1]: \"" + pigpen_message + "\"\n") return # reverses the pigpen process. takes a pigpen string and converts it back to clear text #...
TE INDEX start_date_idx ON programs(start_date)') c.execute('CREATE INDEX end_date_idx ON programs(end_date)') self.conn.commit() c.close() except sqlite3.OperationalError, ex: pass def updateChannels(self, rebuild=False): c = self.conn.cursor() if rebuild == False:...
country = row['country'] category =row['category'] if get_long_description and description_long is None: #description_long = self.getShowInfo(row["showID"],'description') info = self.getShowLongDescription(row['showID']) print 'ProgINFO ' + str(type(info))...
info.get('description','') year = info.get('year',' ') country = info.get('country','') category = info.get('category','') programList.append({ 'channel': row['channel'], 'showID' : row['showID'], 'title' : row['title'],...
###############################################################################
#### # # Copyright (c) 2017-2019 MuK IT GmbH. # # This file is part of MuK Documents Access # (see https://mukit.at). # # This program 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, ...
without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See 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, see <http://www.gnu.org/licenses/>. # ###...
class RepositoryCache: def __init__(self): self.data_dict = {} def add_data(self, keys, data): self.data_dict[keys, data] def clear(self):
self.data_dict = {} d
ef is_data_cached(self, keys): result = self.data_dict.has_key(keys) return result def get_data(self, keys): result = self.data_dict[keys] return result Cache = RepositoryCache()
"""Testing for overlap intervals """ import unittest from genda.transcripts.exon_utils import calcOverlap, collideIntervals, \ collapseIntervals class TestOverlapFunctions(unittest.TestCase): def setUp(self): # Simple Overlap self.simple = [(1,10), (6,15)] # One interval enclosed ...
self.partial = [(150,300), (160,300), (170,330)] # No overlap self.no = [(150,300), (10,30)] # Equal self.equal = [(1,15), (1,5)] #Complex interval list self.full = [(7,20), (1,5), (8,11), (18,50), (100,150)] def test_bpOverlap(self): # Make sure overlap...
assertEqual(calcOverlap(self.partial),400) def test_collideIntervals(self): self.assertEqual(collideIntervals(self.simple[0], self.simple[1]), [(1,15)]) self.assertEqual(collideIntervals(self.enclosed[0], self.enclosed[1]), [(100,200)]) self.assertEqual(colli...
import lcm from lilylcm import 03Citrus def my_handler(channel, data): msg = 03Citrus.decode(data) pr
int("Received message on channel /"%s/"" % channel) print(" value = %s" % str(msg.value)) print("") lc = lcm.LCM() subscription = lc.subscribe("03Citrus", my_handler) try: while True:
lc.handle() except KeyboardInterrupt: pass lc.unsubscribe(subscription)
#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- encoding: utf-8 -*- # # This file is part of my scripts project # # Copyright (c) 2013 Marco Antonio Islas Cruz # # This script 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 So...
","--prefix", dest="prefix",a
ction="store", type="string", help="mailbox prefix") options, args = parser.parse_args() if not options.newemail: options.newemail = options.email OLDHOST= options.oldhost.split(":")[0] OLDPORT= int(options.oldhost.split(":")[1]) NEWHOST=options.newhost.split(":")[0] NEWPORT=int(options.newhost.sp...
# License AGPL-3.0 or later (http://www.gnu.org/li
censes
/agpl.html). from . import test_purchase_delivery
#!/usr/bin/env python # -*- coding: utf-8 -*- """Register models to admin view.""" # System imports from django
.contrib import admin from django.contrib.admin.models import LogEntry # Project imports from draalcore.models.admin_log import LogEntr
yAdmin admin.site.register(LogEntry, LogEntryAdmin)
""" Django settings for paralelnipolis project. Generated by 'django-admin startproject' using Django 1.8.3. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Bui...
essors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'paralelnipolis.wsgi.applic
ation' if os.environ.get('PRODUCTION'): DEBUG = False SECRET_KEY = os.environ.get('SECRET_KEY') # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = {} DATABASES['default'] = dj_database_url.config() # email settings EMAIL_HOST = 'smtp.mandrillapp.co...
# -*- coding: UTF-8 -*- from django.db.models.signals import post_save from django.core.mail import send_mail from django.template.loader import render_to_string from django.dispatch import receiver from matricula.models import Enroll from .models import Bill from django.utils.translation import ugettext_lazy as _ from...
r_to_string('invoice.html', { 'student': instance.student, 'enroll': smart_text(instance.group), 'date': instance.enroll_date.strftime("%Y-%m-%d %H:%M"), 'group': instanc...
amount=instance.group.cost, student=instance.student, currency=instance.group.currency, ) instance.save() def paypal_bill_paid(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLE...
# rename
this file to private_config.py # dropbox api credentials DROPBOX_APP_ID='' DROPBOX_API_SECRET='' # django app sercret for salting and hashing cookies SECRET_K
EY = '' # automatic admin configuration AUTO_ADMINS = ( ('admin_username','admin_password','admin_password@yoursite.com'), )
icy = attrs.get('printer-op-policy', "") or "default" self.op_policy_supported = attrs.get( 'printer-op-policy-supported', ["default"]) self.default_allow = True self.except_users = [] if attrs.has_key('requesting-user-name-allowed'): self.except_users = attrs['r...
requested_attributes=r) except TypeError:
# requested_attributes requires pycups 1.9.50 jobs = self.connection.getJobs (which_jobs='completed') except cups.IPPError: return ret for id, attrs in jobs.iteritems(): try: uri = attrs['job-printer-uri'] uri = uri[uri.rindex ...
"""Helper module for parsing AWS ini config files.""" import os try: import configparser except ImportError: import ConfigParser as configparser AWS_CLI_CREDENTIALS_PATH = "~/.aws/credentials" AWS_CLI_CONFIG_PATH = "~/.aws/config" DEFAULT_PROFILE_NAME = os.getenv("AWS_DEFAULT_PROFILE", "default") class N...
None: return key, secret raise NoConfigFoundException("AWS credentials not found.") config = _get_config_parser(path=AWS_CLI_CREDENTIALS_PATH) key = config.get(profile, "aws_access_key_id") secret = config.get(profile, "aws_secret_access_key") return key, secret def get_creden...
ey, secret = get_credentials(profile) return {"aws_access_key_id": key, "aws_secret_access_key": secret} def get_profile_names(): """Get available profile names. :rtype: list :returns: list of profile names (strings) """ try: return _get_config_parser(path=AWS_CLI_CREDEN...
# -*- encoding:utf-8 -*- from __future__ import unicode_literals MESSAGES = { "%d min remaining to read": "%d минути до прочитане", "(active)": "(активно)", "Also available in:": "Достъпно също на:", "Archive": "Архив", "Authors": "Автори", "Categories": "Категории", "Comments": "Коментари"...
{month} {day}, {year}": "Публикации от {day} {month} {year}", "Posts for {month} {year}": "Публикации за {month} {year}", "Previous post": "Предишна публикация", "Previous": "",
"Publication date": "Дата на публикуване", "RSS feed": "RSS поток", "Read in English": "Прочетете на български", "Read more": "Чети нататък", "Skip to main content": "Прескочи до основното съдържание", "Source": "Изходен код", "Subcategories:": "Подкатегории:", "Tags and Categories": "Таго...
acts['system'] == 'OpenBSD': self.facts['pkg_mgr'] = 'openbsd_pkg' else: self.facts['pkg_mgr'] = 'unknown' for pkg in Facts.PKG_MGRS: if os.path.isfile(pkg['path']): self.facts['pkg_mgr'] = pkg['name'] def get_service_mgr_facts(self): ...
']['policyvers'] = selinux.security_policyvers() except (AttributeError,OSError): self.facts['selinux']['policyvers'] = 'unknown' try:
(rc, configmode) = selinux.selinux_getenforcemode() if rc == 0: self.facts['selinux']['config_mode'] = Facts.SELINUX_MODE_DICT.get(configmode, 'unknown') else: self.facts['selinux']['config_mode'] = 'unknown' except (AttributeErr...
from django import template fr
om go.base.utils import get_router_view_definition register = template.Library() @register.simple_tag def router_screen(router, view_name='show'): view_def = get_router_view_definition(router.router_type, router) return view_def.get_view_url(view_name, router_k
ey=router.key)
#!/usr/bin/env python import camera import resize import ftpupload import time # wait 10s to not inte
rfer with the timelaps script time.sleep(10) print("taking a picture") imagePath = camera.capture() print("captured %s" %
imagePath) smallImagePath = resize.resizeImg(imagePath) print("resized image") print("uploading....") ftpupload.uploadFile(smallImagePath) print("upload completed")
"""audio driver subsystem""" from os.path import exists from os import environ from subprocess import check_call from functools import partial from .drive import Driver import click DRIVE_QUEUE = 'a.drive' CTL_PATH = '{}/.config/pianobar/ctl'.format(environ['HOME']) COMMANDS = {'p', 'n', '^', '(', ')'} def callback...
.option('--queue', default=DRIVE_QUEUE) def main(ctl_path:str, queue:str) -> "IO ()": """daemon for a.drive queue consumption""" if not exists(ctl_path): with open('/dev/
null', 'w') as null: check_call(['pianoctl'], stdout=null) with open(ctl_path, 'w') as ctl: Driver(callback=partial(callback, ctl), queue=queue).drive()
from myhdl import * from UK101AddressDecode import UK101AddressDecode def bench(): AL = Signal(intbv(0)[16:]) MonitorRom = Signal(bool(0)) ACIA = Signal(bool(0)) KeyBoardPort = Signal(bool(0)) VideoMem = Signal(bool(0)) BasicRom = Signal(bool(0)) Ram = Signal(bool(0)) dut = UK101Addr...
KeyBoardPort, VideoMem, BasicRom, Ram) @instance def stimulus(): for i in range(0, 2**16): AL.next = i yield delay(10) raise StopSimulation()
return dut, stimulus sim = Simulation(traceSignals(bench)) sim.run()
from django.db import models from
django.utils.html import format_html from sorl.thumbnail import get_thumbnail from sorl.thumbnail.field
s import ImageField from sno.models import Sno class SnoGalleries(models.Model): class Meta: verbose_name = 'Фотография в галереи СНО' verbose_name_plural = 'Фотографии в галереи СНО' name = models.CharField('Название фото', max_length=255, blank=True, null=True) photo = ImageField(verbos...
#!/usr/bin/python # -*- coding: utf-8 -*- """ Ansible module to configure .deb packages. (c) 2014, Brian Coca <briancoca+ansible@gmail.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 Softwa...
true default: null aliases: ['pkg'] question: description: - A debconf configuration setting required: false default: null aliases: ['setting', 'selection'] vtype: description: - The type of the value supplied. - C(seen
) was added in 2.2. required: false default: null choices: [string, password, boolean, select, multiselect, note, error, title, text, seen] value: description: - Value to set the configuration to required: false default: null aliases: ['answer'] unseen: description: - Do...
# -*- coding: utf-8 -*- from tespy.networks import network from tespy.components import sink, source, solar_collector from tespy.connections import connection import numpy as np from matplotlib import pyplot as plt import pandas as pd from mpl_toolkits.mplot3d import Axes3D # %% network fluid_list = ['H2O'] nw = net...
at this point coll.set_attr(pr=0.99, Q=8e3) # %% connection parameters b_c.set_attr(p=5, T=35, fluid={'H2O': 1}) c_f.set_attr(p0=2, T=120) # %% solving # going through several parametrisation
possibilities print('###############') print('simulation 1') mode = 'design' nw.solve(mode=mode) nw.print_results() # set absorption instead of outlet temperature coll.set_attr(E=9e2, eta_opt=0.9, lkf_lin=1, lkf_quad=0.005, A=10, Tamb=10) c_f.set_attr(T=np.nan) print('###############') print('simulation 2') nw.solve...
users/?q= API""" rsp = self.api_get(get_user_list_url(), {'q': 'gru'}, expected_mimetype=user_list_mimetype) self.assertEqual(rsp['stat'], 'ok') self.assertEqual(len(rsp['users']), 1) # grumpy def test_query_users_auth_backend(self): """Testing the GET us...
lf.client.login(username='admin', password='admin') rsp = self.api_post( get_user_list_url(), { 'username': 'username',
'password': 'password', 'email': 'email@example.com', }, expected_mimetype=user_item_mimetype) self.assertIn('stat', rsp) self.assertEqual(rsp['stat'], 'ok') self.compare_item(rsp['user'], User.objects.get(username='username')) @webapi_te...
import logging import colander from grano.core import db, celery from grano.model import Entity from grano.logic import properties as properties_logic from grano.logic.references import ProjectRef, AccountRef from grano.logic.references import SchemaRef, EntityRef from grano.plugins import notify_plugins log = loggi...
) schema_validator.add(colander.SchemaNode(SchemaRef(project), name='schema')) sane.update(schema_validator.deserialize(data
)) sane['properties'] = properties_logic.validate('entity', entity, project, sane.get('schema'), data.get('properties', [])) return sane @celery.task def _entity_changed(entity_id, operation): """ Notify...
}, 'MAPBOX_Streets': { 'URL': 'https://api.mapbox.com/styles/v1/mapbox/streets-v11/tiles/256/{zoom}/{lon}/{lat}@2x?', 'TECHNOLOGY': 'mapbox', 'ATTRIBUTION': {'source': 'MapBox', 'attribution': None}, 'PARAMS': { # 'userid':'', # 'layerid': '', ...
]) }, 'USDA_WFS': { 'URL': 'https://sdmdataaccess.sc.egov.usda.gov/Spatial/SDMWGS84GEOGRAPHIC.wfs', 'WFS_VERSION': '1.1.0', 'DATA_LAYER': 'mapunitpolyextended', 'ID_FIELD': 'musym', 'ATTRIBUTION': ''.join([ # RDH 2020-10-20: I am not sure this is the correct a...
ulture. ", "U.S. General Soil Map (STATSGO2). ", "Available online at https://sdmdataaccess.sc.egov.usda.gov. ", "Accessed %s" % TODAY_DATE, ]) }, 'MAPBOX': { 'URL': 'https://api.mapbox.com/styles/v1/{userid}/{layerid}/tiles/256/{zoom}/{lon}/{lat}@2x?', ...
# Copyright 2015 Google Inc. All Rights Reserved. # #
Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or
agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """'functions call' command.""" from goo...
from django_webtest import WebTest from candidates.views.people import MERGE_FORM_ID, SUGGESTION_FORM_ID import people.tests.factories from candidates.tests import factories from candidates.tests.auth import TestUserMixin from candidates.tests.uk_examples import UK2015ExamplesMixin
from people.models import Person from uk_results.models import CandidateResult, ResultSet class TestUKResultsPreserved(TestUserMixin, UK2015ExamplesMixin, WebTest): def setUp(self): super().setUp() self.primary_person = people.tests.factories.PersonFactory.cr
eate( id="3885", name="Harriet Harman" ) self.secondary_person = people.tests.factories.PersonFactory.create( id="10000", name="Harriet Ruth Harman" ) def test_uk_results_for_secondary_preserved(self): self.assertTrue(Person.objects.filter(pk=10000).exists())...
#!/usr/bin/env python # # File Name : rouge.py # # Description
: Computes ROUGE-L metric as described by Lin and Hovey (2004) # # Creation Date : 2015-01-07 06:03 # Author : Ramakrishna Vedantam <vrama91@vt.edu> import numpy as np import pdb def my_lcs(string, sub): """ Calculates longest common subsequence for a pair of tokenized strings :param string : list of st
r : tokens from a string split using whitespace :param sub : list of str : shorter string, also split using whitespace :returns: length (list of int): length of the longest common subsequence between the two strings Note: my_lcs only gives length of the longest common subsequence, not the actual LCS ""...
# Copyright 2014 Huawei Technologies Co. Ltd # # 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 ...
) )) return installers def add_os_installers_internal(session, exception_
when_existing=True): configs = util.load_configs(setting.OS_INSTALLER_DIR) return _add_installers( session, models.OSInstaller, configs, exception_when_existing=exception_when_existing ) def add_package_installers_internal(session, exception_when_existing=True): configs = util.load_con...