prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
from django.apps import AppConfig from django.conf impor
t settin
gs from neomodel import config config.AUTO_INSTALL_LABELS = False class NeomodelConfig(AppConfig): name = 'django_neomodel' verbose_name = 'Django neomodel' def read_settings(self): config.DATABASE_URL = getattr(settings, 'NEOMODEL_NEO4J_BOLT_URL', config.DATABASE_URL) config.FORCE_TIME...
#!/usr/bin/env python # -*- coding: UTF-8 -*- from bs4 import BeautifulSoup from urllib.request import urlopen def getSoupAQHI(): html = urlopen("http://www.aqhi.gov.hk/en/aqhi/past-24-hours-aqhi45fd.html?stationid=80") soup = BeautifulSoup(html, "lxml") return soup def getLatestAQHI(dataTable): aqhiTable = data...
e def getLatestAQICN(source): aqi = source.split("Air Pollution.")[1] aqi = aqi.split("title")[1]
aqi = aqi.split("</div>")[0] aqi = aqi.split(">")[1] aqits = source.split("Updated on ")[1].strip() aqits = aqits.split("<")[0] aqhiData = {} aqhiData['index'] = aqi aqhiData['dateTime'] = aqits return aqhiData def getPollutionData(): soupAQHI = getSoupAQHI() dataTableAQHI = soupAQHI.find('table', {'...
# Copy
right (C) 2011-2015 Patrick Totzke <patricktotzke@gmail.com> # Thi
s file is released under the GNU GPL, version 3 or a later revision. # For further details see the COPYING file from __future__ import absolute_import import re import abc class AddressbookError(Exception): pass class AddressBook(object): """can look up email addresses and realnames for contacts. .. n...
e platform observations.""" config = { "binary_sensor": { "platform": "bayesian", "name": "Test_Binary", "observations": [ { "platform": "numeric_state", "entity_id": "sensor.test_moni...
ert [] == state.attributes.get("observations") assert 0.2 == state.attributes.get("probability") assert state.state == "off" self.hass.states.set("sensor.test_monitored", 6) self.hass.block_till_done() self.hass.states.set("sensor.test_monitored", 4) self.hass.block_til...
nsor.test_monitored", 6) self.hass.states.set("sensor.test_monitored1", 6) self.hass.block_till_done() state = self.hass.states.get("binary_sensor.test_binary") assert state.attributes.get("observations")[0]["prob_given_true"] == 0.6 assert state.attributes.get("observations")[1...
self.opman2.start() collection = self.mongos_conn["test"]["mcsharded"] for i in range(1000): collection.insert_one({"i": i + 500}) # Assert current state of the mongoverse self.assertEqual(self.shard1_conn["test"]["mcsharded"].find().count(), 500) self.assertEqual(se...
self.assertEqual(len(do
cs), 1000) self.assertEqual(sorted(d["i"] for d in docs), list(range(500, 1500))) self.shard1_conn.admin.command( "configureFailPoint", "rsSyncApplyStop", mode="off" ) # cleanup mover.join() def test_rollback(self): """Test the rollback method in a sharde...
# This file is part of ZUKS-Controller. # # ZUKS-Controller is free software: you can redistribute it
and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ZUKS-Controller is distributed in the hope that it will be useful, # but WITH
OUT 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 ZUKS-Controller. If not, see <http://www.gnu.org/licenses/>. """ WSGI ...
# Copyright 2016 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from psycopg2._psycopg import IntegrityError from odoo.exceptions import UserError, ValidationError from odoo.tests import common from odoo.tools import mute_logger class TestPartnerIdentification...
out required category with self.assertRaises(IntegrityError): partner_1.write({"id_numbers": [(0, 0, {"name": "1234"})]}) def test_update_partner_with_category(self): partner_1 = self.env.ref("base.res_partner_1") partner_id_category = self.env["res.partner.id_category"].create(...
{"name": "1234", "category_id": partner_id_category.id}) ] } ) self.assertEqual(len(partner_1.id_numbers), 1) self.assertEqual(partner_1.id_numbers.name, "1234") # delete partner_1.write({"id_numbers": [(5, 0, 0)]}) self.assertEqual(len(partne...
from math import floor, log10 def round_(x, n): """Round a float, x, to n significant figures. Caution should be applied when performing this operation. Significant figures are an implication of precision; arbitrarily truncating floats mid-calculation is probably not Good Practice in almost all cases. Rounding...
s a decimal string representation of a float to a specified number of significant figures. >>> create_string(9.80665, 3) '9.81' >>> create_string(0.0120076, 3) '0.0120' >>> create_string(100000, 5) '100000' Note the last representation is, without context, ambiguous. This is a good reason to
use scientific notation, but it's not always appropriate. Note ---- Performing this operation as a set of string operations arguably makes more sense than a mathematical operation conceptually. It's the presentation of the number that is being changed here, not the number itself (which is in turn only approxim...
# Copyright 2021 Ecosoft Co.,
Ltd. (http://ecosoft.co.th) # License LGPL-3.0
or later (https://www.gnu.org/licenses/lgpl.html). from . import models
"""Utilities for extracting macros and preprocessor definitions from C files. Depends on Clang's python bindings. Note that cursors have children, which are also cursors. They are not iterators, they are nodes in a tree. Everything here uses iterators. The general strategy is to have multiple passes over the same cu...
list of Macro objects;
the second is a list of strings that name macros we couldn't handle.""" handled_macros = [] currently_known_macros = dict() failed_macros = [] possible_macro_cursors = extract_macro_cursors(c) #begin the general awfulness. for i in possible_macro_cursors: desired_tokens = list(i.get_tokens())[:-1] #the last on...
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from nipype.testing import assert_equal from nipype.interfaces.freesurfer.preprocess import ApplyVolTransform def test_ApplyVolTransform_inputs(): input_map = dict(args=dict(argstr='%s', ), environ=dict(nohash=True, usedefault=True, ), fs_ta...
'--inv', ), invert_morph=dict(argstr='--inv-morph', requires=['m3z_file'], ), m3z_file=dict(argstr='--m3z %s', ), no_ded_m3z_path=dict(argstr='--noDefM3zPath', requires=['m3z_file'], ), no_resample=dict(argstr='--no-resample', ), reg_file=dict(ar
gstr='--reg %s', mandatory=True, xor=('reg_file', 'fsl_reg_file', 'xfm_reg_file', 'reg_header', 'subject'), ), reg_header=dict(argstr='--regheader', mandatory=True, xor=('reg_file', 'fsl_reg_file', 'xfm_reg_file', 'reg_header', 'subject'), ), source_file=dict(argstr='--mov %s', copyf...
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2011 credativ Ltd (<http://www.credativ.co.uk>). # All Rights Reserved # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Ge...
as # published by the Free
Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero ...
#pragma
error #pragma repy global
foo foo = 2
import re LINE_RE = re.compile(r'\s*namer.add\("(.*)", 0x(.*)\);.*') with open('/tmp/colors.txt') as f: data = {} for line in f: matches = LINE_RE.match(line) if matches: color, number = matches.gr
oups() if len(number) < 8: number = 'ff%s' % number data[color] = number else: print 'ERROR: don\'t understand:', line inverse = {} dupes = {} for color, number in sorted(data.iteritems()): if number in inverse: dupes.setdefault(number, []).append(co
lor) else: inverse[number] = color print ' namer.add("%s", 0x%s);' % (color, number) if dupes: print dupes for number, colors in dupes.iteritems(): print '%s -> %s (originally %s)' % (number, colors, inverse[number])
, COALESCE(l_out.p_r, 0) AS 'out_packets_received' , COALESCE(l_out.sum_duration * 1.0 / l_out.total_out, 0) AS 'out_duration' , COALESCE(l_in.unique_in_ip, 0) AS 'unique_in_ip' , COALESCE(l_in.unique_in_conn, 0) AS 'unique_in_conn' , COALESCE...
query = """
SELECT src, dst, port, links, protocols , sum_bytes , (sum_bytes / links) AS 'avg_byte
#!/usr/bin/env python """ This file transfer example demonstrates a couple of things: 1) Transferring files using Axolotl to encrypt each block of the transfer with a different ephemeral key. 2) Using a context manager with Axolotl. The utility will prompt you for the location of the Axolotl key database and th...
file_name = plaintext[2:2+filenamelength] with open(file_name, 'wb') as f: f.write(plaintext[2+filenamelength:]) # send confirmation reply
= a.encrypt('Got It!') client.send(reply) print file_name + ' received'
struction_context = InstructionContext() class InstructionFormat(object): """ Every instruction opcode has a corresponding instruction format which determines the number of operands and their kinds. Instruction formats are identified structurally, i.e., the format of an instruction is derived from ...
setattr(self, attr, f) return f raise AttributeError( '
{} is neither a {} member or a ' .format(attr, self.name) + 'normal InstructionFormat attribute') @staticmethod def lookup(ins, outs): # type: (Sequence[Operand], Sequence[Operand]) -> InstructionFormat """ Find an existing instruction format that matches...
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'tjtest', # Or path to database file if using sqlite3. # The following settings are not used with sqlite3: 'USER': ...
alse # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts ALLOWED_HOSTS = ['tjugovich.webfactional.com'] # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/var/www/example.com/media/" MEDIA_ROOT = '' #
Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/var/www/example.com/static/" STATIC_ROOT = '/home/tjugovich/webapps/test_static'
""".. Ignore pydocstyle D400. =============== Signal Handlers =============== """ from asgiref.sync import async_to_sync from django.conf import settings from django.db import transaction from django.db.models.signals import post_delete, post_save from django.dispatch import receiver from resolwe.flow.managers impo...
if ( instance.status == Data.STATUS_DONE or instance.status == Data.STATUS_ERROR or created ): # Run manager at the end of the potential transaction. Otherwise # tasks are send to workers before transaction ends and therefore # workers
cannot access objects created inside transaction. transaction.on_commit(lambda: commit_signal(instance.id)) # NOTE: m2m_changed signal cannot be used because of a bug: # https://code.djangoproject.com/ticket/17688 @receiver(post_delete, sender=RelationPartition) def delete_relation(sender, instance, **kwargs...
# coding: utf-8 # # Copyright 2012 NAMD-EMAP-FGV # # This file is part of PyPLN. You can get more information at: http://pypln.org/. # # PyPLN is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by #
the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # PyPLN is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public Lic
ense for more details. # # You should have received a copy of the GNU General Public License # along with PyPLN. If not, see <http://www.gnu.org/licenses/>. from mongodict import MongoDict from nltk import word_tokenize, sent_tokenize from pypln.backend.celery_task import PyPLNTask class Tokenizer(PyPLNTask): ...
FTP_SERVER = "stage.mozilla.org" FTP_USER = "ffxbld" FTP_SSH_KEY = "~/.ssh/ffxbld_dsa" FTP_UPLOAD_BASE_DIR = "/pub/mozilla.org/mobile/candidates/%(version)s-candidates/build%(buildnum)d" DOWNLOAD_BASE_URL = "http://%s%s" % (FTP_SERVER, FTP_UPLOAD_BASE_DIR) APK_BASE_NAME = "fennec-%(version)s.%(locale)s.android-arm.apk"...
lease.py", "default_actions": ["clobber", "pull", "download", "repack", "upload-unsigned-bits"], # signing (optional) "keystore": KEYSTORE, "key_alias": KEY_ALIAS, "exes": { "jarsigner": "/tools/jdk-1.6.0_17/bin/jarsigner", "zipalign": "/tools/android-sdk-r8/tools/zipalign", },...
""" Implements compartmental model of a passive cable. See Neuronal Dynamics `Chapter 3 Section 2 <http://neuronaldynamics.epfl.ch/online/Ch3.S2.html>`_ """ # This file is part of the exercise code repository accompanying # the book: Neuronal Dynamics (see http://neuronaldynamics.epfl.ch) # located at http://github.c...
ts for spatial indexing: myVoltageStateMonitor[mySpatialNeuron.morphology[0.123*b2.um]].v """ assert isinstance(input_current, b2.TimedArray), "input_current is not of type TimedArray" assert input_current.values.shape[1] == len(current_injection_location),\ "number of injection_locations do...
t at a specific position on dendrite EL = e_leak RT = r_transversal eqs = """ Iext = current(t, location_index): amp (point current) location_index : integer (constant) Im = (EL-v)/RT : amp/meter**2 """ cable_model = b2.SpatialNeuron(morphology=cable_morphology, model=eqs, Cm=capacitance...
import numpy as np import bisect import pygame import scipy.signal from albow.widget import Widget, overridable_property from albow.theme import ThemeProperty class SignalRendererWidget(Widget): def __init__(self, signal_list, dev, buf, rect, **kwds): """ Initialize the renderer with the s...
ltiplier * frame.height / (200.0 / 0.51) draw_pts_y
= zero_ax_y - (sig - zero_lev) * pixel_per_lsb draw_pts_y[draw_pts_y < frame.top] = frame.top draw_pts_y[draw_pts_y > frame.bottom] = frame.bottom draw_pts_x = np.linspace(0, frame.width, len(sig)) + frame.left pygame.draw.lines(surf, color, False, zip(draw_pts_x, draw_pts_y)) ...
# Copyright 2019 TWO SIGMA OPEN SOURCE, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
, __version__ from .handlers import load_jupyter_server_extension from .commands import parse def _jupyter_nbextension_paths(): return [{ 'section': 'notebook', 'src': 'static', 'dest': 'beakerx_tabledisplay', 'require': 'beakerx_tabledisplay/index' } ] def _jupyt
er_server_extension_paths(): return [dict(module="beakerx_tabledisplay")] def run(): try: parse() except KeyboardInterrupt: return 130 return 0
""" Exceptions: mccabehalsted: there are triple curly brackets ({{{) in jm1 that jekyll doesn't like spe: is in "other" directory in terapromise reuse: double curly brackets in reuse dump: links end like "/ABACUS2013" without closing slash """ relativePath = "defect/ck/" import os, re, datetime from types import Non...
eName, fileContents) fileContents = doDeletions(fileContents) fileContents = changeHeaders(fileContents) fileContents = reformatLinks(fileContents) fileContents = changeURLs(fileContents, relativePath) fileContents = removeExtr
aneousLinks(fileContents) fileContents = reformatTables(fileContents) fileContents = escapeCurlyBrackets(fileContents) writeObj = file(newFilePath, "w") writeObj.write(header + fileContents) writeObj.close()
from apetools.baseclass import BaseClass from apetools.tools import copyfiles from apetools.log_setter import LOGNAME from apetools.proletarians import teardown class TearDownBuilder(BaseClass): """ A basic tear-down builder that just copies log and config files. """ def __init__(self, configfilename...
if self._logcopier is None: self._logcopier = copyfiles.CopyFiles((LOGNAME,),
self.storage, self.subdir) return self._logcopier @property def teardown(self): """ :return: A teardown object for the test-operator to run to cleanup """ if self._teardown is None: self._t...
# This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Re
search (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # Indico is distributed in the hope that it will be useful,...
ense for more details. # # You should have received a copy of the GNU General Public License # along with Indico; if not, see <http://www.gnu.org/licenses/>. """ Just for backwards-compatibility """ from indico.util.contextManager import *
import unittest from libs.funcs import * class TestFuncs(unittest.TestCase): def test_buildPaths(self): recPaths, repPaths, rouPaths, corePaths = buildPaths() findTxt = lambda x, y: x.find(y) > -1 assert findTxt(recPaths["Task"][0], "base") assert findTxt(recPaths["Department"][0...
Man", "InvoiceDate", "CustCode", "Currency", "ShiftDate", "OriginNr", "SerNr", "attachFlag")]) assert all(
[d in recd for d in ("CompoundItemCosts", "Payments", "Items", "Taxes", "Installs")]) recf, recd = getRecordInheritance("AccessGroup") assert all([f2 in recf for f2 in ("PurchaseItemsAccessType", "InitialModule", "Closed", "internalId")]) assert all([d in recd for d in ("PurchaseItems", "Custom...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' ponysay - Ponysay, cowsay reimplementation for ponies Copyright (C) 2012, 2013, 2014 Erkin Batu Altunbaş et al. 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 Softw...
param n:list<str> See the info manual @param nne:list<str> See the info manual @param ne:list<str> See the info manual @param nee:str See the info manual @param e:str
See the info manual @param see:str See the info manual @param se:list<str> See the info manual @param sse:list<str> See the info manual @param s:list<str> See the info manual @param ssw:list<str> See the info manual @param sw:list<str> S...
") oa01 = Column( String(10), comment="2001 Census Output Area (OA). (There are " "about 222,000, so ~300 population?)") casward = Column( String(6), comment="Census Area Statistics (CAS) ward [PROBABLY FK to " "cas_ward_2003.cas_ward_code]") p...
comment="2001 Census urban/rural indicator [numeric in " "England/Wales/Scotland; letters in N. Ireland]") oac01 = Column( String(3), comment="2001 Census Output Area classification (OAC)" "[POSSIBLY FK to output_area_classification_2011." "su...
11 = Column( String(CODE_LEN), comment="2011 Census Output Area (OA) [England, Wales, Scotland;" " ~100-625 population] / Small Area (SA) [N. Ireland]") lsoa11 = Column( String(CODE_LEN), comment="2011 Census Lower Layer Super Output Area (LSOA) [England & " ...
fro
m .visitor import Visitor from .metavisitor import MetaVisitor from .experiments import ExperimentsVisitor from .usedby import UsedByVisitor from .testedscenarios import TestedScenariosVisitor from .invalidentities import InvalidEntitiesVisitor # from presenter.gesurvey i
mport GESurveyPresenter
opA = DummyOperator(task_id='A') opB = DummyOperator(task_id='B') opC = DummyOperator(task_id='C') opD = DummyOperator(task_id='D') opE = DummyOperator(task_id='E') opF = DummyOperator(task_id='F') opA.set_downstream(opB) opB.set_downs...
+00:00") self.assertEqual(next_local.isoformat(), "2018-10-28T02:00:00+01:00") prev = dag.previous_schedule(utc) prev_local = local_tz.convert(prev) self.assertEqual(prev_local.isoformat(), "2018-10-28T02:50:00+02:00") prev = dag.previous_schedule(_next) prev_local = l...
self.assertEqual(prev, utc) def test_following_previous_schedule_daily_dag_CEST_to_CET(self): """ Make sure DST transitions are properly observed """ local_tz = pendulum.timezone('Europe/Zurich') start = local_tz.convert(datetime.datetime(2018, 10, 27, 3), ...
# -*- coding: utf-8 -*- import os import time from StringIO import StringIO from PIL import Image from django.conf import settings from easy_thumbnails.base import Thumbnail from easy_thumbnails.main import DjangoThumbnail, get_thumbnail_setting from easy_thumbnails.processors import dynamic_import, get_valid_options...
ail((160, 120), thumb, expected_filename=expected) def t
estAlternateExtension(self): basename = RELATIVE_PIC_NAME.replace('.', '_') # Control JPG thumb = DjangoThumbnail(relative_source=RELATIVE_PIC_NAME, requested_size=(240, 120)) expected = os.path.join(settings.MEDIA_ROOT, basename) expected += '_240...
.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['catalog.ProductImage']"}), 'product': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['catalog.Product']"}), 'time': ('django.db.models.f...
ookCustomUser']"}) }, u'catalog.makey': { 'Meta': {'object_name': 'Makey'}, 'added_time': ('django.db.models.fields.DateTimeField', [], {}), 'collaborators': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'collaborators'", '...
related_name': "'makeycomments'", 'null': 'True', 'symmetrical': 'False', 'to': u"orm['catalog.Comment']"}), 'description': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'disabled': ('django.db.models.fields.BooleanField', [], {'default': 'Fal...
from functions impo
rt * from utils imp
ort *
#!/usr/bin/env python """A
llows functions from coot_utils to be imported""" # Copyright 2011, 2012 Kevin Keating # # Licensed under the Educational Community 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.osedu.org/licenses/ECL-...
S 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. #"import coot_utils" results in an error, so this module is required to retrieve #functions that are defined in coot_utils impo...
""" @brief test log(time=0s) """ import os import unittest from pyquick
helper.loghelper import fLOG
from pyquickhelper.filehelper import explore_folder_iterfile from pyquickhelper.ipythonhelper import upgrade_notebook, remove_execution_number class TestConvertNotebooks(unittest.TestCase): """Converts notebooks from v3 to v4. Should not be needed anymore.""" def test_convert_notebooks(self): fLOG( ...
weblate.org/> # # 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 the License, or # (at your option) any later version. # # This program is distributed in the hope that it will...
f setUp(self): super(LockingCommandTest, self).setUp() self.create_subproject() def test_locking(self): subproject = SubProject.objects.all()[0] self.assertFalse( SubProject.objects.filter(locked=True).exists() ) call_command( 'lock_translatio...
, '{0}/{1}'.format( subproject.project.slug, subproject.slug, ) ) self.assertTrue( SubProject.objects.filter(locked=True).exists() ) call_command( 'unlock_translati
#/**************************************************************************** # Copyright 2015, Colorado School of Mines and others. # 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 # # htt...
= getLightnessFromLab(Lab) icm2 = getNewColorModel(Lab) return plot(L,icm2) def plot(L,icm): pp = PlotPanel(2,1) pv = pp.addPixels(0,0,f) pv.setColorModel(icm) pv.setOrientation(PixelsView.Orientation.X1DOWN_X2RIGHT) pv.setInterpolation(PixelsView.Interpolation.LINEAR) pov = pp.addPoints(1,0,L) pov.s...
L*)") pp.setVLimits(1,0,100) return pp def getNewColorModel(Lab): col = zeros(len(x),Color) for i in range(len(x)): j = 3*i rgb = ColorMap.cieLabToRgb(Lab[j+0],Lab[j+1],Lab[j+2]) col[i] = Color(rgb[0],rgb[1],rgb[2]); cm = ColorMap(0,1,col) return cm.getColorModel() def getRgbAndLab(): cm =...
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is mozilla.org code. # # The Initial Developer o
f the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # This library is free software; you can redistribute it and/or # modify it unde...
brary is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # Lic...
import numpy as np from stcad.source_dev.chip import Base_Chip from stcad.source_dev.objects import Drum imp
ort gdsCAD as cad chipsize = 50 chip = Base_Chip('drum', chipsize, chipsize,label=False) inductor = Drum(base_layer = 1, sacrificial_layer = 2 , top_layer = 3, outer_radius = 9, head_radius = 7, electrode_radius = 6, cable_width = 0.5, sacrificial_tail_width = 3, sacrificial_tai...
dge = 0.5, name = '') chip.add_component(inductor, (0,0)) chip.save_to_gds(show=False, save=True,loc='')
fro
m django.contrib import admin from django import forms from . import models from nnmarkdown.form import MarkdownWidget from nnscr.admin import site class PageAdminForm(forms.ModelForm): class Meta: model = models.Page exclude = ("slug",) widgets = { "text": MarkdownWidget ...
models.Page, PageAdmin)
class Garden(object):
"""An object implementing a Kindergarten Garden.""" def __init__(self, cup_string, students=None): self.garden_rows = cup_string.split('\n') if students: self.class_list = sorted(students) else: self.class_list
= [ "Alice", "Bob", "Charlie", "David", "Eve", "Fred", "Ginny", "Harriet", "Ileana", "Joseph", "Kincaid", "Larry" ] self.plants_dict = { "R": "Radishes", "C": "Clover", "G": "Grass", "V": "Violets" ...
# -*- coding: utf-8 -*- from nani.admin import TranslatableModelAdminMixin from nani.forms import translatable_inlineformset_factory from nani.forms import TranslatableModelForm, TranslatableModelFormMetaclass from nani.test_utils.context_managers import LanguageOverride from nani.test_utils.testcase import NaniTestCas...
field="test", translated_field="translated test") rf = RequestFactory() self.request = rf.post('/url/') def test_create_fields_inline(self): with LanguageOverride("en"): # Fixtures (should eventually be shared with other tests) translate_mixin = Translatable...
formset = translatable_inlineformset_factory(translate_mixin._language(self.request), Normal, Related)(#self.request.POST, instance=self.object) self.assertTrue(formset...
# coding=utf-8 # Copyright 2022 RigL Authors. # # 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...
., expect nothing to fall outside 3 stddev. self.assertTrue((image >= -3.).all() and (image <= 3.).all()) with self.subTest(name='LabelShape'): self.assertLen(label, self._batch_size) with self.subTest(name='LabelType'): self.assertTrue(np.issubdtype(label.dtype, np.int)) with self.subT...
def test_test_image_dims_content(self): """Tests dimensions and contents of train data.""" iterator = self._dataset.get_test() sample = next(iterator) image, label = sample['image'], sample['label'] with self.subTest(name='DataShape'): self.assertTupleEqual(image.shape, (self._batch_size_t...
# -*- coding: utf-8 -*- """ sphinx.util.parallel ~~~~~~~~~~~~~~~~~~~~ Parallel building utilities. :copyright: Copyright 2007-2015 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ import os import traceback try: import multiprocessing import threading except I...
self.result_queue = queue.Queue() self._nprocessed = 0 # maps tasks to result functions self._result_funcs = {} # allow only "nproc" worker processes at once self._semaphore = threading.Semaphore(self.nproc) def _process(self, pipe, func, arg): try: ...
pipe.send((False, ret)) except BaseException as err: pipe.send((True, (err, traceback.format_exc()))) def _process_thread(self, tid, func, arg): precv, psend = multiprocessing.Pipe(False) proc = multiprocessing.Process(target=self._process, ...
#!/usr/bin/python # script find clusters of small RNA reads in the genome # version 3 - 24-12-2013 evolution to multiprocessing # Usage clustering.py <bowtie input> <output> <bowtie index> <clustering_distance> <minimum read number per cluster to be outputed> <collapse option> <extention value> <average_cluster_size> #...
n the cluster was forward reads shift = max(Instance.readDict[cluster[-1]]) downstream_coord = cluster[-1] + shift -1 else: downstream_coord = cluster[-1] readcount = Instance.readcount(upstream_coord=upstream_coord, downstream_coord=downstream_coord) mea
n_size, median_size, stdv_size = Instance.statsizes(upstream_coord=upstream_coord, downstream_coord=downstream_coord) if readcount >= minimum_reads and median_size >= min_median_size: location = [Instance.gene.split()[0], upstream_coord, downstream_coord] if output_format == "intervals": return ...
from ConfigParser import SafeConfigParser, NoSectionError import json import logging import os import sys import deimos.argv import deimos.docker from deimos.logger import log import deimos.logger from deimos._struct import _Struct def load_configuration(f=None, interactive=sys.stdout.isatty()): error = None ...
append=coercearray(append), ignore=coercebool(ignore)) def override(self, options=[]): a = options if (len(options) > 0 and not self.ignore) else self.default return a + self.append class Containers(_Struct): def __init__(self, im...
_Struct.__init__(self, image=image, options=options) def override(self, image=None, options=[]): return self.image.override(image), self.options.override(options) class URIs(_Struct): def __init__(self, unpack=True): _Struct.__init__(self, unpack=coercebool(unpack)) class Log(_Struct)...
#!/usr/bin/python ''' Title: Hangman Description: A Simple Hangman Game Author: Usman Sher (@usmansher) Disclaimer: Its Just A Small Guessing Game made By Me (Beginning Of Coding). ''' # Imports import pygame, sys from pygame.locals import * from random import choice # Color Variables RED = (255, 0, 0) GREEN = (0,...
me.draw.rect(screen, BLUE, (450, 350, 100, 10)) pygame.draw.rect(screen, BLUE, (495, 250, 10, 100)) pygame.draw.rect(screen, BLUE, (450, 250, 50, 10)) pygame.draw.rect(screen, BLUE, (450, 250, 10, 25)) # Body Parts def drawMan(screen, bodyPart): if bodyPart ==
'head': pygame.draw.circle(screen, RED, (455, 285), 10) if bodyPart == 'body': pygame.draw.rect(screen, RED, (453, 285, 4, 50)) if bodyPart == 'lArm': pygame.draw.line(screen, RED, (455, 310), (445, 295), 3) if bodyPart == 'rArm': pygame.draw.line(screen, RED, (455, 310), (4...
# YouTube Video: https://www.youtube.com/watch?v=wlnx-7cm4Gg from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import twitter_credentials # # # # TWITTER STREAMER # # # # class TwitterStreamer(): """ Class for streaming and processing live tweets. """ ...
with open(self.fetched_tweets_filename, 'a') as tf: tf.write(data) return True except Bas
eException as e: print("Error on_data %s" % str(e)) return True def on_error(self, status): print(status) if __name__ == '__main__': # Authenticate using config.py and connect to Twitter Streaming API. hash_tag_list = ["donal trump", "hillary clinton", "barack ob...
#!/usr/bin/python import sys sys.path.append('/usr/share/mandriva/') from mcc2.backends
.services.service impor
t Services if __name__ == '__main__': Services.main()
from flask import Flask, request, redirect, render_template, session, flash from mysqlconnection import MySQLConnector import re app = Flask(__name__) mysql = MySQLConnector(app, 'emailval') app.secret_key = 'secret' EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$') @app.route('/') def validat...
te('/emails') # def show(email_id): # query = "SELECT * FROM email WHERE id = :specific_id" # data = {'specific_id': email_id} # emails = mysql.query_db(query, data) # return render_template('email.html', email = email) @a
pp.route('/delete/<id>') def delete(id): query = "DELETE FROM email WHERE id = :id" data = {'id': id} mysql.query_db(query, data) flash("The email address ID {} has been deleted".format(id)) query = "SELECT * FROM email" email = mysql.query_db(query) return render_template('email.html', email = email) app...
me of the MUMmer program that produced the output - query: path to the query sequence file - subject: path to the subject sequence file """ def __init__(self, name, handle=None): self.name = name self._metadata = None self._comparisons = [] if handle is not None: ...
s == other._comparisons ) def __len__(self): return len(self._comparisons) def __str__(self): """Return the object in .delta format output""" outstr = os.linesep.join( [str(self._metadata)] + [str(_) for _ in self._compar
isons] ) return outstr class DeltaMetadata(object): """Represents the metadata header for a MUMmer .delta file""" def __init__(self): self.reference = None self.query = None self.program = None def __eq__(self, other): if not isinstance(other, DeltaMetadat...
from rest_framework import routers from . import views class SecretsRootView(routers.APIRootView): """ Secrets API root view """ def get_view_name(self): return 'Secrets' router = rout
ers.DefaultRouter() r
outer.APIRootView = SecretsRootView # Field choices router.register(r'_choices', views.SecretsFieldChoicesViewSet, basename='field-choice') # Secrets router.register(r'secret-roles', views.SecretRoleViewSet) router.register(r'secrets', views.SecretViewSet) # Miscellaneous router.register(r'get-session-key', views.Ge...
import requests import hashlib import os import json USERNAME = 'christine' API_KEY = 'd0e4164c2bd99f1f888477fc25cf8c5c104a5cd1' #Read in t
he path with user input (or navigate to the directory in the GUI)
#path = '/home/wildcat/Lockheed/laikaboss/malware/' os.chdir("/home/wildcat/Lockheed/laikaboss") print("Hint: /home/wildcat/Lockheed/laikaboss/malware/") path = raw_input("Enter the path of your file: ") for f in os.listdir(path): os.system("sudo python laika.py {} | jq '.scan_result[]' > /home/wildcat/Lockheed/cr...
#!/usr/bin/env python # coding: utf-8 import sys import time from twisted.internet import defer, reactor from twisted.python import log import txmongo def getConnection(): print "getting connection..." return txmongo.MongoConnectionPool() def getDatabase(conn, dbName): print "getting database..." ...
nn, dbName) def getCollection(db, collName): print "getting collection..." return getattr(db, collName) def insertData(coll): print "inserting data..." # insert some data, building a deferred list so that we can later check
# the succes or failure of each deferred result deferreds = [] for x in xrange(10000): d = coll.insert({"something":x*time.time()}, safe=True) deferreds.append(d) return defer.DeferredList(deferreds) def processResults(results): print "processing results..." failures = 0 succ...
elect the option in the next line option_pars['l_linear'] = True # Alfven speed constant along the axis of the flux tube if option_pars['l_const']: option_pars['l_B0_quadz'] = True model_pars['chrom_scale'] *= 5e1 model_pars['p0'] *= 1.5e1 physical_constants['gravity'] *= 1. model_pars['radial_scale...
mode
l']+'/') filename = datadir + model_pars['model'] + option_pars['suffix'] if not os.path.exists(datadir): os.makedirs(datadir) sourcefile = datadir + model_pars['model'] + '_sources' + option_pars['suffix'] aux3D = datadir + model_pars['model'] + '_3Daux' + option_pars['suffix'] aux1D = datadir + model_pars['model'...
#!/usr/bin/env python # # Limitations: # - doesn't work if another node is using a persistent connection # - all names MUST be fully qualified, else rosservice will fail # # TODO: # - watch out for new services and tap them when they come online # - stop broadcasting a service when the original host dies? # # http://do...
DO: will fail with complex, embedded objects params = {p: getattr(req, p) for p in req.__slots__} # send the request and wait for a response success = False try: ret = proxy(req) success = True response = {p: getattr(ret, p) for p in ret.__slots__} ...
service call finally: time_end = timer() time_duration = time_end - time_start log = { 'service': service_name, 'server': server, 'client': client, 'time_start': time_start, 'time_end': time_end,...
sult["OK"]: return result failed.update(result["Value"]["Failed"]) successful = result["Value"]["Successful"] return S_OK({"Successful": successful, "Failed": failed}) def _getFileRelatives(self, lfns, depths, relation, connection=False): connection = self._getConnection...
nection) if not result["OK"]: return result if result["Value"]["Failed"]: failed.update(result["Value"]["Failed"]) for lfn in result["Value"]["Failed"]: lfns.pop(lfn)
if not lfns: return S_OK({"Successful": successful, "Failed": failed}) inputIDDict = {} for lfn in result["Value"]["Successful"]: inputIDDict[result["Value"]["Successful"][lfn]["FileID"]] = lfn inputIDs = list(inputIDDict) if relation == "ancestor": ...
#!/usr/bin/env python """ This activity will calculate the average of ratios between CPU request and Memory request by each event type. These fields are optional and could be null. """ # It will connect to DataStoreClient from sciwonc.dataflow.DataStoreClient import DataStoreClient import ConfigDB_Average_0 # connect...
aList: sum_ratio = 0 total_valid_tasks = 0 total_tasks = 0 event_type = i[config.COLUMN] while True: doc = i['data'].next() if doc is None: break;
total_tasks += 1 if(doc['ratio cpu memory']): sum_ratio = sum_ratio + float(doc['ratio cpu memory']) total_valid_tasks += 1 newline = {} newline['event type'] = event_type newline['sum ratio cpu memory'] = sum_ratio newline['total val...
# -*- coding: utf-8 -*- from setuptools import setup, find_packages import django_cassandra_engine as meta DESCRIPTION = 'Django Cassandra Engine - the Cassandra backend for Django' try: with open('README.rst', 'rb') as f: LONG_DESCRIPTION = f.read().decode('utf-8') except IOError: with open('READM...
cassandra-engine', version='.'.join(map(str, meta.__version__)
), author=meta.__author__, author_email=meta.__contact__, url=meta.__homepage__, keywords='django cassandra engine backend driver wrapper database nonrel ' 'cqlengine', download_url='https://github.com/r4fek/django-cassandra-engine/tarball/master', license='2-clause BSD', descri...
__author__ = 'Nataly' from model.project import Project import string import random def random_string(prefix, maxlen): symbols = string
.ascii_letters return prefix + "".join([random.choice(symbols) for i in range(random.randrange(maxlen))]) def test_add_project(app): project = Project(random_string("name_", 10), random_string("description_", 10)) old_list = app.soap.get_project_list() if project in old_list: app.project.delet...
t_project_list() app.project.add_project(project) new_list = app.soap.get_project_list() old_list.append(project) assert sorted(old_list, key=Project.id_or_max) == sorted(new_list, key=Project.id_or_max)
#!/usr/bin/env python3 # Copyright
(c) 2020 The Bitcoin Core developers # Distributed under the MIT software
license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test fee filters during and after IBD.""" from decimal import Decimal from test_framework.messages import COIN from test_framework.test_framework import BitcoinTestFramework MAX_FEE_FILTER = Decimal(9170997) / COI...
import os Basketball
PlayerDatabase = 'Basket
ballPlayerDatabase.p' Root_URL = 'https://' + os.getenv('basketball_root_url')
# Copyright 2015, Ansible, Inc. # Luke Sneeringer <lsneeringer@ansible.com> # # 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 r
equired by applicable law or agreed to in writing, software # distributed under the License is distrib
uted 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. import click class Command(click.Command): """A Command subclass that adds support for the concept that invoc...
onth) senc_page_retry_times = self.max_retry while True: senc_page_retry_times -= 1 key, level, call_log_history, wrong_flag = self.deal_call_log('1', kwargs['tel'], query_month) if level == -1: month_missing += 1 ...
break elif level != 0: now_time = time.time() if senc_p
age_retry_times >0: continue elif now_time<end_time: time.sleep(rand_time) else: missing_list.append(query_month) if wrong_flag == 'website': website...
"""Simple script to delete all forms with "PLACEHOLDER" as their transcription and translation value. """ import sys import json from old_client import OLDClient url = 'URL' username = 'USERNAME' password = 'PASSWORD' c = OLDClient(url) logged_in = c.login(username, password) if not logged_in: sys.exit('Could not...
tion', '=', 'PLACEHOLDER'], ['Form', 'translations', 'transcription', '=', 'PLACEHOLDER'] ]] } } empty_forms = c.search('forms', search) print 'Deleting %d forms.' % len(empty_forms) deleted_count = 0 for form in empty_forms: delete_path = 'forms/%d' % form['id'] resp = c.delete...
.' % deleted_count
from .curry_spec import
CurrySpec, ArgValues from .arg_values_fulfill_curry_spec import arg_values_fulfill_curry_spec from .make_func_curry_spec import make_func_curry_spec from .remove_args_from_curry_spec import remove_args_from_c
urry_spec
import re from measures.periodicValues.PeriodicValues import PeriodicValues from measures.generic.GenericMeasure import GenericMeasure as GenericMeasure import measures.generic.Units as Units class Overhead(GenericMeasure): def __init__(self, period, simulationTime): GenericMeasure.__init__(self...
self.__neighbors += 1 return for measure in self.__measures: measure.parseLine(line) def getValues(self): return PeriodicValues(0, self.getPeriod(), self.getSimulationTime()) def getTotalValue(self): total = 0 for measure ...
al / float(self.__neighbors) / self.getSimulationTime()
# Copyright (C) 2018 Philipp Hörist <philipp AT hoerist.com> # # This file is part of nbxmpp. # # 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 the License, or (at your opt...
{ 'publish': 'PubSub', 'request_items': 'PubSub', } def __init__(self, client): BaseModule.__init__(self, client) self._client = clie
nt self.handlers = [ StanzaHandler(name='message', callback=self._process_pubsub_bookmarks, ns=Namespace.PUBSUB_EVENT, priority=16), ] def _process_pubsub_bookmarks(self, _client, stanza, properties): ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import eventlet eventlet.monkey_patch() import re import sys import errno import logging from settings import LOG_NAME class BaseAuthConfig(object): """ read auth config and store it. Try be a singletone """ def __init__(self): ...
e -- the path to config file """ auth_conf_errors = { 'OS_TENANT_NAME': 'Missing tenant name.', 'OS_USERNAME': 'Missing username.', 'OS_PASSWORD': 'Missing password.', 'OS_AUTH_URL': 'Missing API url.', } rv = {} stripchars = " \'\"...
try: with open(cfg_file) as f: for line in f: rg = re.match(r'\s*export\s+(\w+)\s*=\s*(.*)', line) if rg: rv[rg.group(1).strip(stripchars)] = \ rg.group(2).strip(stripchars) except IOErr...
ve self.is_active = self.is_time_valid(now) # If we got a change, log it! if self.is_active != was_active: _from = 0 _to = 0 # If it's the start, get a special value for was if was_active is None: _from = -1 if was_acti...
if dr_mins != []: local_min = min(dr_mins) # Take the minimum valid as lower for next search #local_min_valid = 0 #if val_valids != []: # local_min_valid = min(val_valids) #if local_min_valid != 0: ...
local_min = min(dr_mins) #print "UPDATE After dr: found invalid local min:", time.asctime(time.localtime(local_min)), "is valid", self.is_time_valid(local_min) #print self.get_name(), 'Invalid: local min', local_min #time.asctime(time.localtime(local_min)) # We do not loop unle...
from dialtone.blue
prints.message.views import bp as message # n
oqa
tures[ self._structures.keys()[ int(items[6])]].get_value( di, surn=items[8], param=items[10]))) else: res.append((path, self._devices[ ...
'time_zone': 'Europe/Paris', 'smoke_co_alarms': ['kpv19WDjBwPi-fbhzZ5CpbuE3_EunExt'], 'postal_code': '13005', 'thermostats': ['o4WARbb6TBa0Z81uC9faoLuE3_EunExt',
'o4WARbb6TBZmNT32aMeJ8ruE3_EunExt'], 'country_code': 'FR', 'structure_id': 'fwo7ooZml1BE5o_zUEVOOAmD6p4_KKcf5h-hy' + 'F9S9gGD8gz61GVajg', 'wheres': { 'UDex0umsLcPn9ADdpOYzBnI...
import traceback from flask import (
Blueprint, current_app, jsonify, render_template, ) bp = Blueprint('patilloid', __name__) @bp.route('/', methods=('GET',)) def index(): try: current_app.logger.info("Let's show them Patilloid!") return render_template('patilloid.html') except Exception as err: current_app....
rent_app.logger.error(traceback.format_exc()) return ( jsonify({"error": "Sorry, something bad happened with your request."}), 400, )
#!/usr/bin/env python ''' Using Arista's pyeapi, create a script that allows you to add a VLAN (both the VLAN ID and the VLAN name). Your script should first check that the VLAN ID is available and only add the VLAN if it doesn't already exist. Use VLAN IDs between 100 and 999. You should be able to call the script ...
pi_conn = pyeapi.connect_to("pynet-sw2") # Argument parsing parser = argparse.ArgumentParser( description="Idempotent addition/removal of VLAN to Arista switch" ) parser.add_argument("vlan_id", help="VLAN number to create or remove", action="store", type=int) parser.add_argument( "-...
type=str ) parser.add_argument("--remove", help="Remove the given VLAN ID", action="store_true") cli_args = parser.parse_args() vlan_id = cli_args.vlan_id remove = cli_args.remove vlan_name = cli_args.vlan_name # Check if VLAN already exists check_vlan = check_vlan_exists(eapi...
#!/usr/bin/env python # -*-
coding: utf-8 -*- """ In this problem set you work with cities infobox data, audit it, come up with a cleaning idea and then clean it up. Since in the previous quiz you made a decision on which value to keep for the "areaLand" field, you now know what has to be done. Finish the function fix_area(). It will receive a...
n fix_area. You can use extra functions if you like, but changes to process_file will not be taken into account. The rest of the code is just an example on how this function can be used. """ import codecs import csv import json import pprint CITIES = 'cities.csv' def fix_area(area): # YOUR CODE HERE if area...
umn_name] = Content((self._Nmax - self._Nmin + 1, self._len_testing_set)) self._columns_not_implemented[column_name] = None # will be set to a bool self._rows_not_implemented[column_name] = { n: None for n in range(self._Nmax - self._Nmin + 1)} # will be set to a bool if group_name...
en(columns) == 0: continue # Storage for print table_index = list() # of strings table_header = dict() # from string to string table_content = dict() # from string to Content array column_size = dict() # from string to int # Fir...
max + 1)) column_size["N"] = max([max([len(str(x)) for x in table_content["N"]]), len("N")]) # Then fill in with postprocessed data for column in columns: for operation in self._columns_operations[column]: # Set header if operat...
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2019, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
selector = self.params.get('selector') replicas = self.params.get('replicas') if selector: definition['spec']['selector'] = selector
if replicas is not None: definition['spec']['replicas'] = replicas # Execute the CURD of VM: template = definition['spec']['template'] dummy, definition = self.construct_vm_definition(KIND, definition, template) result_crud = self.execute_crud(KIND, definition) ...
# -*- coding: utf-8 -*- # Generated
by Django 1.11.2 on 2017-08-27 23:09 from __future__ import unicode_li
terals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("studies", "0024_merge_20170823_1352"), ("studies", "0029_auto_20170825_1505"), ] operations = []
#!/usr/bin/python import usb.core import usb.util import serial import socket from escpos import * from constants import * from exceptions import * from time import sleep class Usb(Escpos): """ Define USB printer """ def __init__(self, idVendor, idProduct, interface=0, in_ep=0x82, out_ep=0x01): """ ...
self.device = None return True except usb.core.USBError as e: i += 1 if i > 10: return False sleep(0.1) def _raw(self, msg): """ Print any command sent in raw format """ if len(msg) !=...
ce): self.device.write(self.out_ep, self.errorText, self.interface) raise TicketNotPrinted() def __extract_status(self): maxiterate = 0 rep = None while rep == None: maxiterate += 1 if maxiterate > 10000: raise NoStatusErro...
#!/usr/bin/env python # a script to delete the contents of an s3 buckets # import the sys and boto3 modules import sys import boto3 # create an s3 resource s3 = boto3.resource('s3') # iterate over the script arguments as bucket names for bucket_name in sys.argv[1:]: # use the bucket name to create a bucket obje...
nts and print the response or error
for key in bucket.objects.all(): try: response = key.delete() print response except Exception as error: print error
#!/usr/bin
/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Symplicity.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv
)
#!/usr/bin/env python # # Wrapper scr
ipt for Java Conda packages that ensures that the java runtime # is invoked with the right options. Adapted from the bash script (http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in/246128#246128). # # # Program Parameters # import os import sys import subprocess from os import...
r-serviceable code below this line !!! def real_dirname(path): """Return the symlink-resolved, canonicalized directory-portion of path.""" return os.path.dirname(os.path.realpath(path)) def java_executable(): """Return the executable name of the Java interpreter.""" java_home = getenv('JAVA_HOME') ...
#!/usr/bin/env python import os import sys import argparse import pat3dem.star as p3s def main(): progname = os.path.basename(sys.argv[0]) usage = progname + """ [options] <a star file> Write two star files after screening by an item and a cutoff in the star file. Write one star file after screening by a file con...
toff != '00': # Name the output files screened1 = '{}_screened_{}-gt-{}.star'.format(basename, args.screen, args.cutoff) screened2 = '{}_screened_{}-le-{}.star'.format(basename, args.screen, args.cutoff) write_screen1 = open(screened1, 'w') write_screen1.write(''.join(header)) write_screen2 = open(scr...
write_screen1.write(line) else: write_screen2.write(line) write_screen1.write(' \n') write_screen1.close() write_screen2.write(' \n') write_screen2.close() print 'The screened star files have been written in {} and {}!'.format(screened1, screened2) elif args.sfile != '0': with open(...
#*** #********************************************************************* #************************************************************************* #*** #*** GizmoDaemon Config Script #*** LIRCMceUSB2 MythTV config #*** #***************************************** #***************************************** ...
rn False elif Event.Button == "Star": return False elif Event.Button == "Zero": return False elif Event.Button == "Hash": return False elif Event.Button
== "Clear": Gizmod.Keyboards[0].createEvent(GizmoEventType.EV_KEY, GizmoKey.KEY_C) return True elif Event.Button == "Enter": Gizmod.Keyboards[0].createEvent(GizmoEventType.EV_KEY, GizmoKey.KEY_I) return True else: # unmatched event, keep processing return False def onEvent(se...
""" Test DarwinLog "source include debug-level" functionality provided by the StructuredDataDarwinLog plugin. These tests are currently only supported when running against Darwin targets. """ import lldb import platform import re from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lld...
ilename. self.exe_name = self.getBuildArtifact("a.out") self.d = {'OBJC_SOURCES': self.source, 'EXE': self.exe_name}
# Locate breakpoint. self.line = line_number(self.source, '// break here') def tearDown(self): # Shut down the process if it's still running. if self.child: self.runCmd('process kill') self.expect_prompt() self.runCmd('quit') # Let parent cl...
# Copyright (c) 2015 The Phtevencoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' Dummy Socks5 server for testing. ''' from __future__ import print_function, division, unicode_literals import socket, threadin...
recvall(self.conn, ulen))
plen = recvall(self.conn, 1)[0] password = str(recvall(self.conn, plen)) # Send authentication response self.conn.sendall(bytearray([0x01, 0x00])) # Read connect request (ver,cmd,rsv,atyp) = recvall(self.conn, 4) if ver != 0x05:...
#!/usr/bin/env python # encoding: utf-8 # Copyright 2010 California Institute o
f Technology. ALL RIGHTS # RESERVED. U.S. Government Sponsorship acknowledged. from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler class DropHandler(
BaseHTTPRequestHandler): def dropRequest(self): self.send_response(200) self.send_header('Content-length', '0') self.send_header('Connection', 'close') self.end_headers() do_GET = do_POST = do_HEAD = do_PURGE = do_OPTIONS = do_PUT = do_DELETE = do_TRACE = do_CONNECT = dropRequest...
import sys class DualModulusPrescaler: def __init__(self,p): self.m_p = p return def set_prescaler(self): return # may be internal def set_a(self,a): self.m_a = a return # may be internal def set_n(self,n): self.m_n = n return def ...
t_ref_divider(self): return self.m_r def get_division_ratio(self): v = (self.m_p * self.m_n) + self.m_a return v class Osc: def __init__(self, ref_freq, prescaler): self.m_ref = ref_freq self.m_prescaler = prescaler return def get_fre
q(self): # print self.m_prescaler.get_division_ratio() return (self.m_ref/self.m_prescaler.get_ref_divider()) * self.m_prescaler.get_division_ratio() def calc_a(self): return def calc_n(self): return def get_counter_params(self,freq): x = freq * self.m_prescaler.get...
if self.source != otherpo.source or self.getcontext() != otherpo.getcontext(): self.markfuzzy() else: self.markfuzzy(otherpo.isfuzzy()) elif not otherpo.istranslated(): if self.source != otherpo.source: self.markfuzzy() e...
(self._msgstrlen() == 0) and len(self._msgctxt) == 0: return True return False def hastypecomment(sel
f, typecomment): """Check whether the given type comment is present""" # check for word boundaries properly by using a regular expression... return sum(map(lambda tcline: len(re.findall("\\b%s\\b" % typecomment, tcline)), self.typecomments)) != 0 def hasmarkedcomment(self, commentmarker): ...
import pytest import eagerpy as ep import foolbox as fbn def test_plot(dummy: ep.Tensor) -> None: # j
ust tests that the calls don't throw any errors images = ep.zeros(dummy, (10, 3, 32, 32)) fbn.plot.images(images) fbn.plot.images(images, n=3) fbn.plot.images(images, n=3, data_format="channels_first") fbn.plot.images(images, nrows=4) fbn.plot.images(images, ncols=3) fbn.plot.images(images, ...
, 32, 1)) fbn.plot.images(images) with pytest.raises(ValueError): images = ep.zeros(dummy, (10, 3, 3, 3)) fbn.plot.images(images) with pytest.raises(ValueError): images = ep.zeros(dummy, (10, 1, 1, 1)) fbn.plot.images(images) with pytest.raises(ValueError): images...
# class generated by DeVIDE::createDeVIDEModuleFromVTKObject from module_kits.vtk_kit.mixins import SimpleVTKClassModuleBase import vtk cla
ss vtkFieldDataToAttributeDataFilter(SimpleVTKClassModuleBase): def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkFieldDataToAttributeDataFilter(), 'Processing.', ('vtkDataSet',), ('vtkDataSet',), replaceDoc=Tr...
s=None)
import codecs from ConfigParser import ConfigParser import os import subprocess import sys import six import twiggy from twiggy import log from twiggy.levels import name2level from xdg import BaseDirectory def asbool(some_value): """ Cast config values to boolean. """ return six.text_type(some_value).lower()...
racle[13:] p = subprocess.Popen( command, shell=True, stdout=subprocess.PIPE, #stderr=subprocess.STDOUT ) password = p.stdout.read()[:-1] if password is None: die("MISSING PASSWORD: oracle='%s', interactive=%s for service=%s" % ...
os.path.dirname(__file__), 'docs/configuration.rst' ) with open(fname, 'r') as f: readme = f.read() example = readme.split('.. example')[1][4:] return example error_template = """ ************************************************* * There was a problem with your bugwarriorrc *...
27,2015 @author: Yongxiang Qiu, Kay Kasemir ''' try: import xml.etree.cElementTree as ET except: import xml.etree.ElementTree as ET from datetime import datetime def getTimeSeries(data, name, convert='plain'): '''Get values aligned by different types of time. :param name: channel name :param co...
t += key + ' : \n'
prettyOut += '{\n' prettyOut += " 'id' : " + str(self.__logData[key]['id']) + ' ,\n' prettyOut += " 'time' : " + str(self.__logData[key]['time']) + ' ,\n' prettyOut += " 'value' : " + str(self.__lo
# -*- coding: utf-8 -*- u""" Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U. This file is part of Toolium. 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/lic...
CONDITION
S OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from nose.tools import assert_equal from android.pageobjects.menu import MenuPageObject from android.pageobjects.tabs import TabsPageObject from android.test_cases import An...
# -*- coding: utf-8 -*- # Copyright (c) 2015, Michael Droettboom 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, t...
p is a multiple of this parameter. Common values
are 1, 2, or 4. Returns ------- target : Bitmap The bitmap, converted to 8bpp. """ Bitmap_num_grays = """ The number of gray levels used in the bitmap. This field is only used with `PIXEL_MODE.GRAY`. """ Bitmap_pitch = """ The number of bytes taken by one bitmap row. Includes padding. The pitch is positive wh...
azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.OperationStatus] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatus"] ...
sponse) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'billingAccountId': self._serialize.url("billing_account_id", billing_account_id, 'str'), } if polling is True:
polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( ...
#!/usr/bin/env python # # Build QT5 webengine # import os import sys import xsysroot if __name__ == '__main__': # You want to be careful to enable a debug build. libQtWebengine.so takes 817MB :-) debug_build=False build_mode='release' if not debug_build else 'debug' # We need a xsysroot profile wit...
b/arm-linux-gnueabihf/pkgconfig'.format(picute.query('sysroot')) print '>>> cmdline_prefix: ', cmdline_prefix qmake_
command='{}/usr/local/qt5/bin/qmake ' \ 'WEBENGINE_CONFIG+=use_proprietary_codecs CONFIG+={}'.format(picute.query('sysroot'), build_mode) print '>>> Qmake command:', qmake_command rc=os.system('{} ; cd {} ; {}'.format(cmdline_prefix, webengine_path, qmake_command)) if rc: print '>>> Qmake fa...
#-*- coding: utf-8 -*- import struct import pytest from proteusisc.controllerManager import getDriverInstanceForDevice from proteusisc.jtagScanChain import JTAGScanChain from proteusisc.test_utils import FakeUSBDev, FakeDevHandle,\ MockPhysicalJTAGDevice, FakeXPCU1Handle from proteusisc.bittypes import bitarray, N...
200E(chain) chain._hasinit = True chain._devices = [d0, d1, d2] chain.jtag_enable() d0.run_instruction("CFG_IN", data=bitarray('11010001')) d1.run_instruction("BYPASS", data=NoCareBitarray(1)) a, _ = d2.run_instruction("CFG_IN", read=True, bitcount=8) chain.flush() assert a() == bitar...
000010010011') def get_XC3S1200E(chain): return chain.initialize_device_from_id(chain, XC3S1200E_ID) def test_black_hole_register_constraints_bad_order_complimentary_prims(): #Tests if a Blask Hole Read, a Black Hole Write, and a nocare #write are combined in a way that satisfies all requests. The #ex...