prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
shipProperties :param tags: the ke
y-value pairs used to add additional metadata to the job information. (Only for use internally with Scope job type.) :type tags: dict[str, str] :ivar error_message: the error message details for the job, if the job failed. :vartype error_message: list[~azure.mgmt.datalake.analytics.job.models...
def neighbors(node, all_nodes): dirs = [[0, 1], [1, 0], [-1, 0], [0, -1]] ddirs = [[1, 1], [1, -1], [-1, 1], [-1, -1]] result = set() # cdef bool x for dir in dirs: nx, ny = node[0] + dir[0], node[1] + dir[1] try: all_nodes[nx][ny] except IndexError: ...
.node == c.node:
closed = True if not closed: c.count = count count += 1 c.score = get_score(c, current.node, goal, heightmap) open_list.append(c) open_list = sorted( open_list, key=lambda x: x.count, ...
import demistomock as demisto from CommonServerPython import BaseClient import BitSightForSecurityPerformanceManagement as bitsight from datetime import datetime def test_get_companies_guid_command(mocker): # Positive Scenario client = bitsight.Client(base_url='https://test.com') res = {"my_company": {"g...
2021-02-01T00:00:00Z', 'rawJSON': '{"severity
": "severe", "first_seen": "2021-02-01", "temporary_id": "temp1"}'}]
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from .aws import Action as BaseAction from .aws import BaseARN service_name = "Amazon Mechanical Turk" prefix = "mechanicalturk" class Action(BaseAction): def __init__(self, action: str = None) -> ...
hWorker = Action("AssociateQualificationWithWorker") BlockWorker = Action("BlockWorker") ChangeHITTypeOfHIT = Action("ChangeHITTypeOfHIT") CreateAdditionalAssignmentsForHIT = Action("CreateAdditionalAssignmentsForHIT") CreateHIT = Action("CreateHIT") CreateHITType = Action("CreateHITType") CreateHITWithHITType = Action...
ype") CreateQualificationType = Action("CreateQualificationType") CreateWorkerBlock = Action("CreateWorkerBlock") DeleteHIT = Action("DeleteHIT") DeleteQualificationType = Action("DeleteQualificationType") DeleteWorkerBlock = Action("DeleteWorkerBlock") DisableHIT = Action("DisableHIT") DisassociateQualificationFromWor...
# Copyright 2015 Cisco Systems, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
rds_compatibility as bc from networking_cisco.plugins.cisco.db.device_manager import ( # noqa hd_models) from networking_cisco.plugins.cisco.db.l3 import ( # noqa ha_db) from networking_cisco.plugins.cisco.db.l3 import ( # noqa l3_models) from n
etworking_cisco.plugins.ml2.drivers.cisco.n1kv import ( # noqa n1kv_models) from networking_cisco.plugins.ml2.drivers.cisco.nexus import ( # noqa nexus_models_v2) from networking_cisco.plugins.ml2.drivers.cisco.ucsm import ( # noqa ucsm_model) def get_metadata(): return bc.model_base.BASEV2.metadat...
subject_id = node._id attribute_type_node = None if attr_key in attr_type_dict: attribute_type_node = attr_type_dict[attr_key] else: ...
tend(gsystem_type_node.type_of) relation_type_no
de = None if rel_key in rel_type_dict: relation_type_node = rel_type_dict[rel_key] else: relation_type_node = node_collection.one({ ...
from flask import Flask from flask import make_response from flask import request from flask import render_template from flask import redirect from flask import url_for import logging from logging.handlers import RotatingFileHandler app = Flask(__name__) @app.route('/') def index(): app.logger.info('index') ...
info('login') if request.method == 'POST': if validate_credentials(request.form['username'], request.
form['password']): resp = make_response(redirect(url_for('index'))) resp.set_cookie('username', request.form['username']) return resp else: return render_template('login.html', error='Invalid username or password') else: return render_template('login....
class EmptyResult(object): ''' Null Object pattern to pr
event Null reference errors when there is no result ''' def __init__(self): self.status = 0 self.body = '' self.msg = '' self.reason = '' def __nonzero__(s
elf): return False class HapiError(ValueError): """Any problems get thrown as HapiError exceptions with the relevant info inside""" as_str_template = u''' ---- request ---- {method} {host}{url}, [timeout={timeout}] ---- body ---- {body} ---- headers ---- {headers} ---- result ---- {result_status} ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from bs4 import BeautifulSoup as bs from sasila.system_normal.spider.spider_core import SpiderCore from sasila.system_normal.pipeline.console_pipeline import ConsolePipeline from sasila.system_normal.processor.ba
se_processor import BaseProcessor from sasila.system_nor
mal.downloader.http.spider_request import Request if sys.version_info < (3, 0): reload(sys) sys.setdefaultencoding('utf-8') class FirstProcessor(BaseProcessor): spider_id = 'test' spider_name = 'test' allowed_domains = ['mzitu.com'] start_requests = [Request(url="http://www.mzitu.com/")] ...
= [x * 1.0 for x in members] + [0.0, 0.0, 1.0] return tuple.__new__(Affi
ne, mat3x3) else: raise TypeError(
"Expected 6 number args, got %s" % len(members)) @classmethod def identity(cls): """Return the identity transform. :rtype: Affine """ return identity @classmethod def translation(cls, offset): """Create a translation transform from an offset vector. ...
''' # print type(self) if type(i)==int: return self.table[i] elif type(i)==str: #assume that they are searching by column, i.e. #table['col_name'] #this allows access by column and then row ind=self.attributes.index(i) col=[] for row_no in range(0, len(self.table)-1): col...
ers_tuple=(), tuple_values_list=[], commit=True, print_query=False): if tuple_values_list==[]: print("\n\tSQLiteDefaults: insert_table_sqlite() ERROR: tuple_value_list cannot be empty") return query="" if parameters_tuple==(): query="INSERT INTO %s VALUES " %(tablename); else: query="INSERT INTO %s ...
ALUES" %(tablename, parameters_tuple); #else: #print("\n\tSQLiteDefaults: insert_table_sqlite() ERROR: parameters_tuple must be a tuple") query=query+"(?" + (",?"*(len(parameters_tuple)-1)) + ")" #source: https://docs.python.org/2/library/sqlite3.html if print_query: print query conn.executemany(qu...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root
for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if t
he code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class BusinessIdentity(Model): """The integration account partner's business identity. :param qualifier: The business identity qualifier e.g. as2identity, ZZ, ZZ...
# -*- coding: utf-8 -*- from peewee import * import urllib import tempfile import os from contextlib import contextmanager from sshtunnel import SSHTunnelForwarder import traceback db = MySQLDatabase( "cod", host="127.0.0.1", user="cod_reader", port=3308, connect_timeout=10000 ) # Get # ssh wout@axil1.ua.ac.be...
s.select() .where(
cls.mineral == name or cls.commonname == name or cls.chemname == name ) .order_by(cls.year.desc()) ) @contextmanager def codtunnel(): server = SSHTunnelForwarder( ssh_address_or_host=("axil1.ua.ac.be", 22), ssh_username="wout", ssh_pkey="/us...
from tests.base import TestBase from pascal.program import Program class TestVariables(TestBase): def test_pass_valid_var(self): file_name = "tests/mock_pas/all_var.pas" pascal_program = Program(file_name) pascal_program.run() self.assertEqual(len(pascal_program.symbol_table), 7) ...
program.symbol_address, 23) def test_pass_assign(self): file_name = "tests/mock_pas/variables.pas" pascal_pr
ogram = Program(file_name) pascal_program.run()
import _plotly_utils.basevalidators cla
ss ShowlegendValidator(_plotly_utils.basevalidators.BooleanValidator): def __init__(self, plotly_name="showlegend", parent_name="cone", **kwargs):
super(ShowlegendValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "style"), **kwargs )
. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. # source_enc...
cuments. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor dir...
False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # If true, `todo` and `todoList`...
# Copyright (c) 2013 Hesky Fisher # See LICENSE.txt for details. from orthography import add_suffix import unittest class OrthographyTestCase(unittest.TestCase): def test_add_suffix(self): cases = ( ('artistic', 'ly', 'artistically'), ('cosmetic', 'ly', 'cosmetically'), ...
rator'), ('emerge', 'ent', 'emergent'), ('equip', 'ed', 'equipped'), ('defer', 'ed', 'deferred'), ('defer', 'er', 'deferrer'), ('defer', 'ing', 'deferring'),
('pigment', 'ed', 'pigmented'), ('refer', 'ed', 'referred'), ('fix', 'ed', 'fixed'), ('alter', 'ed', 'altered'), ('interpret', 'ing', 'interpreting'), ('wonder', 'ing', 'wondering'), ('target', 'ing', 'targeting'), ('limit',...
params size: %.2fM' % (sum(para.numel() for para in model.parameters())/1000000.0)) # define criterion and optimizer criterion = torch.nn.MSELoss(size_average=True).cuda() optimizer = torch.optim.RMSprop(model.parameters(), lr = args.lr, momen...
win = plt.imshow(gt_batch_img) plt.subplot(122)
pred_win = plt.imshow(pred_batch_img) else: gt_win.set_data(gt_batch_img) pred_win.set_data(pred_batch_img) plt.pause(.05) plt.draw() # measure accuracy and record loss losses.update(loss.data[0], inputs.size(0)) ac...
#!/usr/bin/env python from ConfigParser import ConfigParser from ordereddict import OrderedDict import sys def make_parser(): parser = ConfigParser(dict_type=OrderedDict) parser.optionxform = str return parser def transform(sectionName): sectionName = sectionName.replace(",Dialog=", ", Dialog=") ...
iewer"): return "Type=Viewer, " + sectionName.split(", ")[0] else: parts = sectionName.split(",") parts.reverse() if len(parts) == 1: parts.insert(0, "Type=View") return ", ".join(parts) else: return sectionName if __name__...
rser.sections(): newSection = transform(section) newParser.add_section(newSection) for option, value in parser.items(section): newParser.set(newSection, option, value) newParser.write(open(fileName + ".tmp", "w"))
# -*- coding: utf-8 -*- """ "Sandbox" module for exploring API useful for digital labbooks. Examples -------- >>> from chempy.units import to_unitless, default_units as u >>> s1 = Solution(0.1*u.dm3, {'CH3OH': 0.1 * u.molar}) >>> s2 = Solution(0.3*u.dm3, {'CH3OH': 0.4 * u.molar, 'Na+': 2e-3*u.molar, 'Cl-': 2e-3*u.mola...
ey not in self._store: self._store[key] = self.factory(key) return self.
_store[key] class Solution(object): def __init__(self, volume, concentrations, substances=None, solvent=None): if not is_unitless(volume / u.dm3): raise ValueError("volume need to have a unit (e.g. dm3)") self.volume = volume self.concentrations = QuantityDict(u.molar, concentr...
from django import forms from django.contrib.auth.models import User from django.forms.models import ModelFo
rm from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit from .models import UserProfile class UserForm(ModelForm):
password = forms.CharField(widget=forms.PasswordInput()) #email = forms.EmailField(max_length=100, required=False) class Meta: model = User #fields = ('username', 'email', 'password') ## I really don't need your email and you're safer not sharing it with me fields = ('username...
# This file
is part of Rubber and thus covered by the GPL # (c) Sebastian Reichel, 2012 """ Dependency analysis for package 'ltxtable' in Rubber. """ def setup (document, context): global doc doc = document doc.hook_macro('LTXtable', 'aa', hook_ltxtable) def hook_ltxtable (loc, width, file): # If the file name looks like it...
ource(file)
# Copyright (c) 2006-2012 Mitch Garnaat http://garnaat.org/ # # Permission is hereby granted, free of charge, to any
person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom ...
ssion notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL ...
#!/usr/bin/python # -*- coding: utf-8 -*- ### # Copyright (2016-2017) Hewlett Packard Enterprise Development LP # # 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/licen...
ents: - "python >= 2.7.9" - "hpeOneView >= 3.0" author: "Abilio Parada (@abiliogp)" options: name: description: - Name of SAS Logical JBOD Attachment.
required: false notes: - This resource is only available on HPE Synergy extends_documentation_fragment: - oneview - oneview.factsparams ''' EXAMPLES = ''' - name: Gather facts about all SAS Logical JBOD Attachment oneview_sas_logical_jbod_attachment_facts: config: "{{ config_path }}" - debug: v...
lass:`Pool`, :class:`Prefix`) or a list of instances. The :func:`search` and :func:`smart_search` functions also embeds the lists in dicts which contain search meta data. The easiest way to get data out of NIPAP is to use the :func:`get`-method, given that you know the ID of the object you want to fetc...
classes which maps to data in NIPAP (:py:class:VRF, :py:class:Pool, :py:class:Prefix) extends this class. """ _logger = None """ Logging instance for this object. """ id = None """ Intern
al database ID of object. """ def __eq__(self, other): """ Perform test for equality. """ # Only possible if we have ID numbers set if self.id is None or other.id is None: return False return self.id == other.id def __init__(self, id=None): "...
# -*- coding: utf-8 -*- """ 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...
where set. # i don't know the JSON-HTTP specs in detail, but the previous author # accessed json_response['js']['error'] as well as js_answer['error']. # see the two lines commented out with "# ~?". if 'error' in json_response['js']: if json_response['js']['error'] == 'downl...
nse['js']['params']['next_download']) # ~? self.retry(wait_time=js_answer['params']['next_download']) elif 'Wrong file password' in json_response['js']['error']: return None elif 'You entered a wrong CAPTCHA code' in json_response['js']['error']: r...
rate=baudINDI, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_TWO, bytesize=serial.EIGHTBITS ) def open_connection(self): """ Open serial connection to INDI""" self.indi.close() self.indi.open() indi_open = self.indi.isOpen() ...
se = set rate of lamp (pulses/second) """ if lamp_pulse != '':
self.indi.write(('LAMP '+ str(lamp_set) + ' ' + str(lamp_pulse) + '\r').encode()) else: self.indi.write(('LAMP '+ str(lamp_set) + '\r').encode()) def get_lamp(self): """ Returns the lamp Variable Rate trigger setting """ self.indi.write('LAMP VAR?\r'.encode()) return...
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at
http://mozilla.org/MPL/2.0/. from marionette_driver.by import By from marionette_harness import MarionetteTestCase class TestPosition(MarionetteTestCase): def test_should_get_element_position_back(self): test_url = self.marionette.absolute_url('rectangles.html') self.marionette.nav
igate(test_url) r2 = self.marionette.find_element(By.ID, "r2") location = r2.rect self.assertEqual(11, location['x']) self.assertEqual(10, location['y'])
import unittest2 from zounds.util import simple_in_memory_settings from .preprocess import MeanStdNormalization, PreprocessingPipeline import featureflow as ff import numpy as np class MeanStdTests(unittest2.TestCase): def _forward_backward(self, shape):
@simple_in_memory_settings class Model(ff.BaseModel): meanstd = ff.PickleFeature( MeanStdNormalization, store=False) pipeline = ff.PickleFeature( PreprocessingPipeline, needs=(meanstd,), ...
#!/usr/bin/env python #-*-coding:utf-8-*- from evaluator import Evaluator from loader import Loader import matplotlib.pyplot as plt from confidence_weighted import Confi
denceWeighted def graph_plot(plt_obj, show=False): plt_obj.ylim(0, 1) plt_obj.xlabel("Number of trials") plt_obj.ylabel("Accuracy") plt_obj.legend(["CW", "CW1", "CW2"], loc="lower right") if show is True: plt_obj.show() else: plt_obj.figure() if __name__ == '__main__': # ...
enceWeighted(123, 0.30)) cw.append(ConfidenceWeighted(123, 0.50)) # training phase loader = Loader('a1a', 123, 30956, 1605) y_vec, feats_vec = loader.load_train() for i in range(len(cw)): evaluator = Evaluator(cw[i], y_vec, feats_vec) evaluator.update() plt.plot(evaluator.ac...
#!/usr/bin/env python # coding: utf-8 import os import csv from schedule_entry import EntryStatus from machine import MachineStatus def dump_stat(path, data, headers): with open(path, 'w') as out: csv_out = csv.writer(out) csv_out.writerow(headers) for row in data: csv_out.wri...
== 2: jt = parts[0] else: jt = '_'.join(parts[:2]) d[jt] = [ (d[jt][0] if jt in d.keys() else 0) +1, (d[jt][1] if jt in d.keys() else 0) +(e.log['JOB_TERMINATED'] - e.log['EXECUTE']).total_seconds(), ...
t][3] if jt in d.keys() else 0) +(e.log['JOB_TERMINATED'] - e.log['SUBMIT']).total_seconds(), ] for jt in d.keys(): self.durations.append((jt, d[jt][1]*1.0 / d[jt][0], d[jt][2]*1.0 / d[jt][0], d[jt][3]*1.0 / d[jt][0], d[jt][0])) def dump(self): home = os.pat...
# coding=utf-8 # Licensed Materials - Property of IBM # Copyright IBM Corp. 2019 # Separated test code with Python 3.6 syntax. import typing import decimal from streamsx.spl.types import int64 class NTS(typing.NamedTuple): x: int msg: str class NamedTupleBytesSchema(typing.NamedTuple): idx: str msg...
ap<string, tuple<int64 int1,
map<rstring, tuple<int64 x_coord, int64 y_coord>> map1>> map2> # This schema contains map attributes at different nesting levels with different attribute names and different Value types class TupleWithMapToTupleWithMap(typing.NamedTuple): int2: int map2: typing.Mapping[str,TupleWithMapToTupleAttr1] #tuple<int6...
# Copyright 2010 Michael Murr # # This file is part of LibForensics. # # LibForensics is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later ver...
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 LibForensics. If not, see <http://www.gnu.org/licenses/>. """Windows shell link files""" ...
raDataBlock, ConsoleProps, ConsoleFEProps, DarwinProps, ExpandableStringsDataBlock, EnvironmentProps, IconEnvironmentProps, KnownFolderProps, PropertyStoreProps, ShimProps, SpecialFolderProps, DomainRelativeObjId, TrackerProps, VistaAndAboveIDListProps, TerminalBlock, ExtraDataBlockFactory, StringDa...
# -*- encoding: utf-8 -*- ############################################################################### # # # Copyright (C) 2015 Trustcode - www.trustcode.com.br # # ...
ur 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 # # MERCHA...
See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gn...
# -*- coding: utf-8 -* import uuid import random import string from test import DjangoTestCase class Account(object): def __init__(self, email=None, password=None): self.email = email self.password = password @staticmethod def create_email(): return u"some.one+%s@example.com" % u...
"password_confirmation"] = password_confirmation response = self.http_post(u"/signup", data) return Account(email=email, password=password), response def login(self, email=None, password=None): data = {} if email is not None: data[u"email"] = email if passwo...
data = {} if email is not None: data[u"email"] = email if password is not None: data[u"password"] = password return self.http_post(u"/logout", data)
# Copyright (c) 2008, 2012 testtools developers. See LICENSE for details. from testtools import TestCase from testtools.matchers import Equals, MatchesException, Raises from testtools.content_type import ( ContentType, JSON, UTF8_TEXT, ) class TestContentType(TestCase): def test___init___None_er...
elf.assertEqual({}, content_type.parameters) def test___init___with_parame
ters(self): content_type = ContentType("foo", "bar", {"quux": "thing"}) self.assertEqual({"quux": "thing"}, content_type.parameters) def test___eq__(self): content_type1 = ContentType("foo", "bar", {"quux": "thing"}) content_type2 = ContentType("foo", "bar", {"quux": "thing"}) ...
# Licensed under a 3-clause BSD style license - see LICENSE.rst import contextlib import imp import os import sys import inspect # Python 3.3's importlib caches filesystem reads for faster imports in the # general case. But sometimes it's necessary to manually invalidate those # caches so that the import system can ...
hidden files and directories. This function does not have the parameter `topdown` from `os.walk`: the directories must always be recursed top-down when using this function. See also -------- os.walk : For a description of the parameters """ for root, dirs, files in os.walk(
top, topdown=True, onerror=onerror, followlinks=followlinks): # These lists must be updated in-place so os.walk will skip # hidden directories dirs[:] = [d for d in dirs if not is_path_hidden(d)] files[:] = [f for f in files if not is_path_hidden(f)] yield root...
""" Django settings for dfiid project. 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/ """ import os BA
SE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) from django.core.exceptions import ImproperlyConfigured def get_env(setting): """ Get the environment setting or return exception """ try: return os.environ[setting] except KeyError: error_msg = 'Set the %s env variable' % setting raise Imp...
#Evaluate semantic space against MEN dataset import sys import utils from scipy import stats import numpy as np from math import sqrt #Note: this is scipy's spearman, without tie adjustment def spearman(x,y): return stats.spearmanr(x, y)[0] def readMEN(annotation
_file): pairs=[] humans=[] f=open(annotation_file,'r') for l in f: l=l.rstrip('\n') items=l.split() pairs.append((items[0],items[1])) humans.ap
pend(float(items[2])) f.close() return pairs, humans def compute_men_spearman(dm_dict, annotation_file): pairs, humans=readMEN(annotation_file) system_actual=[] human_actual=[] count=0 for i in range(len(pairs)): human=humans[i] a,b=pairs[i] if a in dm_dict and b in dm_...
t Gdk import cPickle import xapian import json import tempfile import shutil from sugar3.graphics.radiotoolbutton import RadioToolButton from sugar3.graphics.palette import Palette from sugar3.graphics import style from sugar3 import env from sugar3 import profile from jarabe.journal import model from jarabe.journal....
b(self, button, strerror, severity): self.emit('volume-error', strerror, severity) def _button_toggled_cb(self, button): if button.props.active: self.emit('volume-changed', button.mount_point) def _ge
t_button_for_mount(self, mount): mount_point = mount.get_root().get_path() for button in self.get_children(): if button.mount_point == mount_point: return button logging.error('Couldnt find button with mount_point %r', mount_point) return None def _remove...
rpreter raise SyntaxError('encoding problem: utf-8') encoding += '-sig' return encoding first = read_or_stop() if first.startswith(BOM_UTF8): bom_found = True first = first[3:] default = 'utf-8-sig' if not first: return default, [] en...
elif initial == '#': assert not token.endswith("\n") yield (COMMENT, token, spos, epos, line) elif token in triple_quoted:
endprog = endprogs[token] endmatch = endprog.match(line, pos) if endmatch: # all on one line pos = endmatch.end(0) token = line[start:pos] yield (STRING, token, spos, (lnum, pos),...
# -*- coding: utf-8 -*- fro
m __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('hack_plot',
'0005_auto_20150505_1940'), ] operations = [ migrations.AddField( model_name='sshhackip', name='located', field=models.BooleanField(default=False), preserve_default=True, ), ]
from trackers.fitbit
_tracker import Fitb
itTracker __author__ = 'doughyde' # FitBit connection f = FitbitTracker() f.authenticate() f.get_devices()
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
overning permissions and # limitations under the License. import os from st2common.content.loader import ContentPackLoader from st2common.exceptions.content import ParseException from st2common.bootstrap.aliasesregistrar import AliasesRegistrar from st2common.models.utils.action_alias_utils import extract_parameters_...
estCase' ] class BaseActionAliasTestCase(BasePackResourceTestCase): """ Base class for testing action aliases. """ action_alias_name = None action_alias_db = None def setUp(self): super(BaseActionAliasTestCase, self).setUp() if not self.action_alias_name: raise V...
from sft.runner.Trainer import T
rainer import sft.config.exp if __name__ == "__main__": Trainer().run(sft.config.exp)
import time import sqlite3 from base_model import BaseModel from datetime import datetime from contextlib import contextmanager class SSIDTrafficHistory(BaseModel): def __init__(self, dbfile, table_name, time_limit): super(SSIDTrafficHistory, self).__init__(dbfile, table_name) self.time_limit = time_limit de...
imestamp))) result = c.fetchone() if result == None: result = (self.truncate_time(timestamp), adapter, ssid, 0, 0) return { 'timestamp': self.truncate_time(timestamp), 'adapter': adapter, 'ssid': ssid, 'rx': result[3], 'tx': result[4] } def query_all(self, start_time=None, end_time=None, ...
me: start_time = self.truncate_time(end_time) with self.db_cursor(commit=False) as c: query = ''' SELECT timestamp, adapter, ssid, sum(rx), sum(tx) FROM {} WHERE timestamp >= ? AND timestamp <= ? GROUP BY adapter, ssid ORDER BY adapter, ssid; '''.format(self.table_name) c.execute(que...
''' Created on 28/set/2014 @author: Vincenzo Pirrone <pirrone.v@gmail.com> ''' import serial, time class Connector: def readline(self): pass def writeline(self, line): pass def close(self): pass class FakeSerial(Connector): def __init__(self, port): p...
return 'TIME:%d' % int(time.time()) def writeline(
self, line): print 'FAKE SERIAL: ' + line def close(self): print 'closing fake serial' class Serial(Connector, serial.Serial): def __init__(self, port=None, baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.S...
# Generated by Django 1.11.15 on 2018-08-08 18:28 import django.db.models.deletion import django_extensions.db.fields import stdimage.models from course_discovery.apps.course_metadata.utils import UploadToFieldNamePath from django.db import migrations, models class Migration(migrations.Migration): dependencies...
blank=True, help_text='Please provide an image file for the lead capture banner.', null=True, upload_to=UploadToFieldNamePath('uuid', path='media/degree_marketing/lead_capture_im
ages/')), ), ]
import os.path from subprocess import call class InstallerTools(object): @staticmethod def update_environment
(file_path,environment_path): upda
te_file = open(file_path, 'r') original_lines = update_file.readlines() original_lines[0] = environment_path+'\n' update_file.close() update_file = open(file_path, 'w') for lines in original_lines: update_file.write(lines) update_file.close() @staticmethod def fix_migrate(base_directory): print "\n...
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
eded by Bioconductor proteomics packages.""" homepage = "https://bioconductor.org/packages/ProtGenerics/" url = "https://git.bioconductor.org/packages/ProtGenerics" list_url = homepage version('1.8.0', git='https://git.bioconductor.org/packages/ProtGenerics', commit='b2b3bb0938e
20f58fca905f6870de7dbc9dfd7a3') depends_on('r@3.4.0:3.4.9', when='@1.8.0')
# Input: # 2
# 5 # 1 2 3 4 5 # 6 # 2 4 6 7 5 1 # # Output: # 3 # 7 def findMid(head): if head == None: return -1 fast, slow = head, head while fast.next != None and fast.next.next != None: fast = fast.next.next slow = slow.next if fast.next != None: return slow.next ret
urn slow
from tests.util.base import event def test_invite_generation(event, default_account): from inbox.events.ical import generate_icalendar_invite event.sequence_number = 1 event.participants = [{'email': 'helena@nylas.com'}, {'email': 'myles@nylas.com'}] cal = generate_icalendar...
an attachment. count = 0 for mimepart in msg.walk(with_self=msg.content_type.is_singlepart()): format_type = mimepart.content_type.format_type subtype = mimepart.content_type.subtype
if (format_type, subtype) in [('text', 'plain'), ('text', 'html'), ('text', 'calendar; method=request'), ('application', 'ics')]: count += 1 assert count == 3
# 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
ed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either ex
press or implied. See the # License for the specific language governing permissions and limitations # under the License. from openstack.network import network_service from openstack import resource2 as resource class ServiceProfile(resource.Resource): resource_key = 'service_profile' resources_key = 'service...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2014 The Plaso Project Authors. # Please see the AUTHORS file for details on individual 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 L...
Formatter): """Formatter for ASL Securityd file.""" DATA_TYPE = 'mac:asl:securityd:line' FORMAT_STRING_PIECES = [ u'Sender: {sender}', u'({sender_pid})', u'Level: {level}', u'Facility: {facility}', u'Text: {message}'] FORMAT_STRING_SHORT_PIECES = [u'Text: {message}'] SOURCE_L...
= 'Mac ASL Securityd Log' SOURCE_SHORT = 'LOG'
# -*- coding: utf-8 -*- # Copyright (c) 2021, Frappe Te
chnologies and contributors # License: MIT. See LICENSE # import frappe from frappe.model.document import Document cl
ass UserDocumentType(Document): pass
from protorpc import messages from protorpc import message_types from protorpc import remote from google.appengine.api import taskqueue import json import endpoints import urllib2 import logging, os import settings import inspect from seqid import SeqidIssuer, seqid2str from endpointshelper import EndpointsHelper fr...
message' field The info field in the response contains some debug information """ response = TestResponse(message=request.message, status='OK') response.info = "USER: %s" % endpoints.get_current_user() try: EndpointsHelper.authenticat...
g (op='test') except Exception, err: response.status=str(err) return response #app = endpoints.api_server([hub_api]) #app = endpoints.api_server([GeoFeedApi])
have a backport of ``surrogateescape`` for Python2, be sure to register the error handler prior to importing this module. The last error handler is: :surrogate_then_replace: Will use ``surrogateescape`` if it is a valid handler. If encoding with ``surrogateescape``...
simplerepr: The default. This takes the ``str`` of the object and then returns the
text version of that string. :empty: Return an empty text string :passthru: Return the object passed in :strict: Raise a :exc:`TypeError` :returns: Typically this returns a text string. If a nonstring object is passed in this may be a different type depending on the strategy ...
# -*- coding: utf-8 -*- # Aualé oware graphic user interface. # Copyright (C) 2014-2020 Joan Sala Soler <contact@joansala.com> # # 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...
from game import Oware from uci import Strength from .constants import COEFFICIENTS class OpeningBook(object): """Opening book implementation""" __MARGIN = 42 def __init__(self, p
ath): self._scores = [] self._header = dict() self._min_score = self.__MARGIN self._load_opening_book(path) def set_strength(self, strength): """Sets the playing strength of the book""" margin = self.__MARGIN factor = 1 - strength.strength_factor sel...
d server state as the first component of the output. If there is no need for server state, the input/output state should be modeled as an empty tuple. In addition to updating state, `next` additionally takes client-side data as input, and can produce results on server side in addition to state intended to be passed to...
`accumulate` is the TensorFlow computation that updates the state of an update accumulator (initialized with `zero` above) with a single client's update. Its type signature is `(<A,U> -> A)`. Typically, a
single acumulator would be used to combine the updates from multiple clients, but this does not have to be the case (it's up to the target deployment platform to choose how to use this logic in a particular deployment scenario). * `merge` is the TensorFlow computation that merges two accumulators holding the r...
ergy - (-2.855160426155)) < 1.e-5 def test_load_wfn_low_h2o(): fn_wfn = context.get_fn('test/h2o_sto3g.wfn') title, numbers, coordinates, centers, type_assignment, exponents, \ mo_count, occ_num, mo_energy, coefficients, energy = load_wfn_low(fn_wfn) assert title == 'H2O Optimization' assert n...
ients[-1, -1] == -0.33277355E-15 assert abs(energy - (-74.965901217080)) < 1.e-6 def test_get_permutation_orbital(): assert (get_permutation_orbital(np.array([1, 1, 1])) == [0, 1, 2]).all() assert (get_permutation_orbital(np.array([1, 1, 2, 3, 4])) == [0, 1, 2, 3, 4]).all() assert (get_permutation_orb...
tion_orbital(np.array([2, 2, 3, 3, 4, 4])) == [0, 2, 4, 1, 3, 5]).all() assign = np.array([1, 1, 2, 2, 3, 3, 4, 4, 1]) expect = [0, 1, 2, 4, 6, 3, 5, 7, 8] assert (get_permutation_orbital(assign) == expect).all() assign = np.array([1, 5, 6, 7, 8, 9, 10, 1]) expect = [0, 1, 2, 3, 4, 5, 6, 7] asse...
# -*- coding: utf-8 -*- # # clopath_synapse_spike_pairing.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 ...
o the dictionary. nrn_params = {'V_m': -70.6,
'E_L': -70.6, 'C_m': 281.0, 'theta_minus': -70.6, 'theta_plus': -45.3, 'A_LTD': 14.0e-5, 'A_LTP': 8.0e-5, 'tau_u_bar_minus': 10.0, 'tau_u_bar_plus': 7.0, 'delay_u_bars': 4.0, 'a': 4.0, ...
# This code is so you can run the samples without installing the package import sys import os sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) # import cocos from cocos.director import director from cocos.sprite import Sprite import pyglet import random class TestLayer(cocos.layer.Layer): def _...
self.change_y, 1 ) def change_x(self, dt): self.sprite.x = random.random()*director.get_window_size()[0] def change_y(self, dt): self.sprite.y = random.random()*director.get_window_size()[1] if __name__ == "__main__": director.init() test_layer = TestLayer () ...
st_layer) director.run (main_scene)
import tornado.web import json from tornado_cors import CorsMixin from common import ParameterFormat, EnumEncoder class DefaultRequestHandler(CorsMixin, tornado.web.RequestHandler): CORS_ORIGIN = '*' def initialize(self): self.default_format = self.get_argument("format", "json", True) self.s...
stuff("conf") for category in output_data: self.write("# {}\n".format(category["description"])) for parameter in category["parameters"]: config_value = parameter.get("config_value", "NI") value_format = parameter.get("format", ParameterFormat.NONE) ...
config_value = "'{}'".format(config_value) parameter_comment = parameter.get("comment", "NONE") if parameter_comment != "NONE": self.write_comment("conf", parameter_comment) self.write("{} = {}\n".format(parameter["name"], config_value)) ...
(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.formLayout.setItem(5, QtGui.QFormLayout.LabelRole, spacerItem1) spacerItem2 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.formLayout.setItem(8, QtGui.QFormLayout.LabelRole, spacerI...
jectName("gridLayout_2") spacerItem8 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.gridLayout_2.addItem(spacerItem8, 1, 2, 1, 1) self.pushButton_24 = QtGui.QPushButton(self.gridLayoutWidget_2) self.pushButton_24.setObjectName("pushButton_24"...
idLayoutWidget_2) self.pushButton_25.setObjectName("pushButton_25") self.gridLayout_2.addWidget(self.pushButton_25, 1, 3, 1, 1) spacerItem9 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.gridLayout_2.addItem(spacerItem9, 1, 4, 1, 1) ...
# ---------------------------------------------------------------------------------------------------------------------- # Introdução a Programação de Computadores - IPC # Universidade do Estado do Amazonas - UEA # Prof. Jucimar Jr # Edson de Lima Barros 1715310043 # Tiago Ferreira Aranha
1715310047 # Vitor Simôes Azevedo 1715310025 # Roberta de Oliveira da Cruz 0825070169 # Uriel Brito Barros 151512
0558 # # 16. Faça um procedimento que recebe, por parâmetro, # 2 vetores de 10 elementos inteiros e que calcule e retorne, # também por parâmetro, o vetor intersecção dos dois primeiros. from lista08.ipc import vetor vetor1 = vetor.cria_vetor(10) vetor2 = vetor.cria_vetor(10) vetor_interseccao = vetor.vetor_interse...
import mcpi.minecraft as minecraft import mcpi.block as Block import serial import time # The location where redstone torch needs to spawn. a0 = (-112, 0, 62) # <- YOU MUST SET THIS VALUE (x,y,z) """ Helper method: get_pin(pin) Returns whether the minecraft pin is turned on or off (based on redstone torch type) B...
# write the result to the LED1 on Espruino if int(cur_val): # turn LED on ser.write("digitalWrite(LED1, 1)\n") else: # turn LED off ser.write("digitalWrite(LED1, 0)\n")
old_val = cur_val time.sleep(.5) # small sleep except KeyboardInterrupt: print("stopped") ser.close()
#!/usr/bin/env python # # Copyright 2013 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...
) if not config.Paths().sdk_root: # Don't do update checks if there is no install root. properties.VALUES.component_manager.disable_update_check.Set(True) def UpdateCheck(command_path, **unused_kwargs): try: update_manager.UpdateManager.PerformUpdateCheck(command_path=co
mmand_path) # pylint:disable=broad-except, We never want this to escape, ever. Only # messages printed should reach the user. except Exception: log.debug('Failed to perform update check.', exc_info=True) def CreateCLI(surfaces): """Generates the gcloud CLI from 'surface' folder with extra surfaces. Arg...
DEBUG = False USERNAME = 'hikaru' CHANNEL = 'random' VOCAB = { 'RANDOM': ['random', ':troll:', ':trollface:'], 'PASS': ['pass', 'skip'], 'RESIGN': ['resign', 'give up'], 'VOTE': ['vote', 'move', 'play'], 'VOTES': ['votes', 'moves', 'voted', 'chance'], 'CAPTURES': ['captures'], 'SHOW': ['s...
'Ok.', 'Resignation cancelled.', ], 'UNKNOWN': [ "I don't know.", 'What do you mean?', "That doesn't make any sense.", "I'm just a bot.", ], } # How often to play moves. See `man crontab` for format information. if DEBUG: CRON = '*/2 * * * *' #
Every two minutes. else: CRON = '0 9-18 * * 1-5' # Hourly between 9:00 and 18:00 on weekdays.
# Copyright 2018 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/licen
ses/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. # ============================================================================== """Test Transformer model.""" from __future__ import absolute_import from __future__ import division from __future__ import pr...
from . import mne # noqa from .m
ne.spect
ral import TFRmorlet # noqa
# Copyright (C) 2010-2017 GRNET S.A. # # 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 i...
b import transaction HELP_MSG = """Query Ganeti backends and update the status of backend in DB. This command updates: * the list of the enabled disk-templates * the available resources (disk, memory, CPUs) """ class Command(SynnefoCommand): help = HELP_MSG @transaction.atomic def handle(self,...
templates(backend) backend_mod.update_backend_resources(backend) self.stdout.write("Successfully updated backend '%s'\n" % backend)
"""Defines all search scopes used in this project.""" from os import path ROOT_PATH = path.abspath('/') class TreeSearchScope: """Encapsulation of a search scope to search up the tree.""" def __init__(self, from_folder=ROOT_PATH, to_folder=ROOT_PATH): """Initialize ...
if path.isdir(f)] self._iter = iter(self._folders) def __bool__(self): """Check if the search scope is not empty.""" return len(self._folders) > 0 def __iter__(self): """Make this an iterator.""" self._iter = iter(self._folders) return self._iter def __nex...
return 'SearchScope: folders: {}'.format(self._folders)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_stack ---------------------------------- Tests for `python_algorithms.stack` module. """ import unittest from python_algorithms.basic.stack import Stack class TestStack(unittest.TestCase): def setUp(self): self.empty_stack = Stack() self....
r curr in self.stack:
iter_seq.append(curr) iter_seq.reverse() self.assertEqual(iter_seq, self.seq) def test_str_empty_stack(self): self.assertEqual(str(self.empty_stack), "") def test_str_stack(self): self.assertEqual(str(self.stack), " ".join([str(x) for x in self.seq])) def tearDown(self)...
checks") for item in result: assert item in qs assert result.count() == result.distinct().count() if check_type == "checks": for item in result: assert any( qc in item.qualitycheck_set.values_list("name", flat=True) for qc in check...
__project=Project.objects.first())] for _qs in test_qs: _test_units_contribution_filter(_qs, user, unit_filter) @pytest.mark.django_db def test_units_state_filter(units_state_searches): unit_filter = units_state_searches qs = Unit.objects.all() if not hasattr(UnitStateFilter, "filter_%s" % uni...
er(qs).filter(unit_filter) return test_qs = [ qs, qs.none(), qs.filter( store__translation_project__project=Project.objects.first())] for _qs in test_qs: _test_units_state_filter(_qs, unit_filter) @pytest.mark.django_db def test_units_checks_filter(units_che...
#!/usr/bin/python # # Copyright 2018-2021 Polyaxon, 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 ...
sert DummyFeature.parse_key() == (None, "FOO") de
f test_parse_key_with_namespace(self): DummyFeature.key = "FEATURES:FOO:BAR" assert DummyFeature.parse_key() == ("FOO", "BAR")
import sqlalchemy as sa from sqlalchemy_utils.functions.sort_query import make_order_by_deterministic from tests import assert_contains, TestCase class TestMakeOrderByDeterministic(TestCase): def create_models(self): class User(self.Base): __tablename__ = 'user' id = sa.Column(sa....
ASC', query) def test_string_order_by(self): query = self.session.query(self.U
ser).order_by('name') query = make_order_by_deterministic(query) assert_contains('ORDER BY name, "user".id ASC', query) def test_annotated_label(self): query = self.session.query(self.User).order_by(self.User.article_count) query = make_order_by_deterministic(query) assert_c...
from gooddataclient.dataset import Dataset from gooddataclient.columns import ConnectionPoint, Label, Reference class Employee(Dataset): employee = ConnectionPoint(title='Employee', folder='Employee') firstname = Label(title='First Name', reference='employee', folder='Employee') lastname = Label(ti...
r>Employee</folder> </column> </columns> </schema> ''' data_csv = '''"employee","firstname","lastname","department" "e1","Sheri","Nowmer","d1" "e2","Derrick","Whelply",
"d1" "e6","Roberta","Damstra","d2" "e7","Rebecca","Kanagaki","d3" "e8","Kim","Brunner","d11" "e9","Brenda","Blumberg","d11" "e10","Darren","Stanz","d5" "e11","Jonathan","Murraiin","d11" "e12","Jewel","Creek","d11" "e13","Peggy","Medina","d11" "e14","Bryan","Rutledge","d11" "e15","Walter","Cavestany","d11" "e...
# Copyright 2019 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...
ions=16) columns = [price, keywords_embedded, ...] feature_layer = tf.keras.layers.DenseFeatures(columns) features = tf.io.parse_example( ..., features=tf.feature_column.make_pa
rse_example_spec(columns)) dense_tensor = feature_layer(features) for units in [128, 64, 32]: dense_tensor = tf.keras.layers.Dense(units, activation='relu')(dense_tensor) prediction = tf.keras.layers.Dense(1)(dense_tensor) ``` """ def __init__(self, feature_columns, traina...
o insert concentration is given -> returns mass of insert needed Example Usage: .. code-block:: python from autoprotocol_utilities import ligation_insert_ng from autoprotocol.unit import Unit plasmid_size = 3000 plasmid_mass = Unit(100, 'ng') insert_size = 48 ...
mass concentration of insert ds: bool, optional True for dsDNA, False for ssDNA molar_ratio : int, float, string, optional Ligation molar ratio of insert : vector. Common ratios are 1:3, 1:1, and 3:1. 1:1 by default Returns ------- insert_amount: Unit Volume of inser...
"" conc_dimension = ["[substance] / [length] ** 3", '[mass] / [length] ** 3'] # Check input types if not isinstance(plasmid_size, int): raise ValueError("Plasmid_size: must be an integer") if isinstance(plasmid_mass, str): plasmid_mass = Unit.fromstring(plasmid_mass) if not isins...
""" Revision ID: 0356_add_webautn_auth_type Revises: 0355_add_webauthn_table Create Date: 2021-05-13 12:42:45.190269 """ from alembic import op
revision = '0356_add_webautn_auth_type' down_revision = '0355_add_webauthn_table' def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.execute("INSERT INTO auth_type VALUES ('webauthn_auth')") op.drop_constraint('ck_users_mobile_or_email_auth', 'users', type_=None, schema=Non...
in ('email_auth', 'webauthn_auth') or mobile_number is not null) NOT VALID """) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.execute("UPDATE users SET auth_type = 'sms_auth' WHERE auth_type = 'webauthn_auth'") op.execute(...
import fileinput import argparse from astexport import __version__, __prog_name__ from astexport.parse import parse from astexport.export import export_json def create_parser(): parser = argparse.ArgumentParser( prog=__prog_name__, description="Python source code in, JSON AST out. (v{})".format( ...
help="print indented JSON" ) parser.add_argument( "-v", "--version", action="store_true", help="print version and exit" ) return parser def main(): """Read source from stdin, parse and export the AST as JSON""" parser = create_parser() args = parser.parse_a...
input(args.input)) tree = parse(source) json = export_json(tree, args.pretty) print(json)
from copy import deepcopy from distutils.spawn import find_executable class Settings(object): _upload_limit = 0 def __init__(self, settings=None): if settings: self._upload_limit = settings.up_kbytes_sec @property def upload_limit(self): """ Returns the value as required ...
Couldn't find 'trickle' program") def wrap_call(self, call_cmd): """ "wraps" the call_cmd so it can be execut
ed by subprocess.call (and related flavors) as "args" argument :param call_cmd: original args like argument (string or sequence) :return: a sequence with the original command "executed" under trickle """ if isinstance(call_cmd, basestring): # FIXME python 3 unsafe call_cm...
#!/usr/bin/env python """ simple example script for running notebooks and reporting exceptions. Usage: `checkipnb.py foo.ipynb [bar.ipynb [...]]` Each cell is submitted to the kernel, and checked for error
s. """ import os import glob from runipy.notebook_runner import NotebookRunner from pyfolio.utils import pyfolio_root from pyfolio.ipycompat import read as read_notebook def test_nbs(): path = os.path.join(pyfolio_root(), 'examples', '*.ipynb') for ipynb in glob.glob(path): with open(ipynb) as f: ...
_notebook(skip_exceptions=False)
ertEqual(value, context.exception.value) def test_value_unmatched_by_all_match_statements(self): value = unittest.mock.Mock() value.__len__ = unittest.mock.Mock(return_value=2) with self.assertRaises(rail.UnmatchedValueError) as context: match = rail.match_length( ...
arg2=val2) ) def test_docstring_preserved(self): @rail.partial def func1(arg1, arg2): """Docstring for func"""
return arg1, arg2 self.assertEqual('Docstring for func', func1.__doc__) func2 = func1(unittest.mock.Mock()) self.assertEqual('Docstring for func', func2.__doc__) class TestCompose(unittest.TestCase): def test_compose_with_no_funcs(self): func = rail.compose() value = uni...
ad = 1. # th
is statement will be i
gnored at the codegen x = ad is None
import json from django.utils import unittest from django.test.client import RequestFactory from formalizr.tests.views import SimpleFormView, SimpleCreateView, SimpleUpdateView from formalizr.tests.models import SimpleModel class AjaxFormViewTest(unittest.TestCase): view_class = SimpleFormView VALUE = 1 ...
t.VALUE, "_return": "result"} request = self.factory.post('/', data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') response = self.view_class.as_view()(request) self.assertEqual(200, response.status_code) self.assertEqual('application/json', response['content-type'].split(';')[0]) re...
tus"]) return resp class AjaxCreateViewTest(AjaxFormViewTest): view_class = SimpleCreateView def testRequest(self): self.assertEqual(SimpleModel.objects.filter(value=AjaxFormViewTest.VALUE).count(), 0) super(AjaxCreateViewTest, self).testRequest() self.assertEqual(SimpleMode...
#!/usr/bin/python # -*- coding: utf-8 -*- ''' Created on 2016. 10. 11. @author: "comfact" ''' import yaml from ansible.module_utils.basic import * from acidi
py import deployACI DOCUMENTATION = ''' --- module: acibuilder version_added: historical short_description: acidipy ansible module. description: - This is Acidipy Ansible Module named AciBuilder options: {} author: hyjang@cisco.com ''' EXAMPLES = ''' # Test 'webservers' status ansible webservers -m ...
c = dict( Controller=dict(required=True), Option=dict(required=True), Tenant=dict(required=True) ), supports_check_mode = True ) ctrl = yaml.load(module.params['Controller']) opts = yaml.load(module.params['Option']) tnts = yaml.load(mod...
lLayout_5.addLayout(self.horizontalLayout_21) self.horizontalLayout_22 = QtGui.QHBoxLayout() self.horizontalLayout_22.setObjectName(_fromUtf8("horizontalLayout_22")) self.itemLabelTextBrowser_21 = QtGui.QTextBrowser(self.scrollAreaWidgetContents) sizePolicy = QtGui.QSizePolicy(QtGui.QSiz...
= QtGui.QTextBrowser(self.scrollAreaWidgetContents) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.itemLabelTextBrowser_24.sizePolicy().hasHeightForWid...
self.itemLabelTextBrowser_24.setMaximumSize(QtCore.QSize(1234, 31)) self.itemLabelTextBrowser_24.setObjectName(_fromUtf8("itemLabelTextBrowser_24")) self.horizontalLayout_25.addWidget(self.itemLabelTextBrowser_24) self.SendButton_24 = QtGui.QPushButton(self.scrollAreaWidgetContents) ...
# coding=utf-8 # Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from contextlib impo...
es of a project which relies on a subproject which relies on its own internal library, a failure occurs without the --subproject-roots option """ with harness(): pants_args = ['dependencies', SUBPROJ_SPEC] self.assert_failure(self
.run_pants(pants_args)) @ensure_engine def test_subproject_with_flag(self): """ Assert that when getting the dependencies of a project which relies on a subproject which relies on its own internal library, all things go well when that subproject is declared as a subproject """ with harness(...
#!/usr/bin/env python ################################################## # Parallel MLMC: Config class # # # # Jun Nie # # Last modification: 19-09-2017 # ##############################
#################### import sys, os import numpy as np class Config: """ config class wchich is used for fvm solver, mlmc & parallelization TODO: adding read config parameters from file. """ def __init__(self, config_file): # === fvm solver parameters self.
DIM = 2 self.ORDER = 1 self.case = 'vayu_burgers' # 'vayu_ls89', 'su2_ls89' self.mesh_ncoarsest = 8+1 self.mesh_nfinest = 128+1 self.mesh_filename = '/home/jun/vayu/TestMatrix/Burgers.Test/mesh/' + \ 'cartesian_tube_0009x0009x2.BlockMesh' ...
######################################################################## # amara/xslt/expressions/avt.py """ Implementation of XSLT attribute value templates """ from amara.xpath import datatypes from amara.xpath.expressions import expression from amara.xslt import XsltError from amara.xslt.expressions import _avt _p...
mat % tuple(arg.evaluate_as_string(context) for arg in self._args) return datatypes.string(result) evaluate = evaluate_as_string def __str__(self): return
'{' + self._format % tuple(self._args) + '}'
#!/usr/bin/env python from distutils.core i
mport setup from pip.req import parse_requirements install_reqs = parse_requirements("requirements.txt", session=False) reqs = [str(ir.req) for ir in install_reqs] setup(name='pgoapi', version='1.0', url='https://github.com/tejado/pgoapi', packages=['p
goapi'], install_requires=reqs)
from oracleplsqlsource import OraclePLSQLSourc
e class OracleJavaSource(OraclePLSQLSource): def __init__(self, name, source): self.name = name
#debug_message("debug: generating java source ") OraclePLSQLSource.__init__(self,source)
from cupy import elementwise _id = 'out0 = in0' # TODO(okuta): Implement convolve _clip = elementwise.create_ufunc( 'cupy_clip', ('???->?', 'bbb->b', 'BBB->B', 'hhh->h', 'HHH->H', 'iii->i', 'III->I', 'lll->l', 'LLL->L', 'qqq->q', 'QQQ->Q', 'eee->e', 'fff->f', 'ddd->d'), 'out0 = min(in2, max(in1, i...
.. seealso:: :func:`numpy.clip` ''' return _clip(a, a_min, a_max, out=out) sqrt = elementwise.create_ufunc( 'cupy_sqrt', # I think this order is a bug of NumPy,
though we select this "buggy" # behavior for compatibility with NumPy. ('f->f', 'd->d', 'e->e'), 'out0 = sqrt(in0)', doc='''Elementwise positive square-root function. .. note:: This ufunc outputs float32 arrays for float16 arrays input by default as well as NumPy 1.9. If you want to o...
"""
Configuration values. """ # Command paths (you can change these to e.g. absolute paths in calling code) CMD_FLAC = "flac" CMD_FFMPEG = "ffmpeg" CMD_IM_MONTAGE = "montag
e" CMD_IM_MOGRIFY = "mogrify" CMD_IM_CONVERT = "convert"
# python3 class HeapBuilder: def __init__(self): self._swaps = [] self._data = [] def ReadData(self): n = int(input()) self._data = [int(s) for s in input().split()] assert n == len(self._data) def WriteResponse(self): print(len(self._swaps)) for swap in self._swaps: print(swa...
following naive implementation just sorts # the given sequence using selection sort algorithm # and saves the resulting sequence of swaps. # This turns the given array into a he
ap, # but in the worst case gives a quadratic number of swaps. # # TODO: replace by a more efficient implementation for i in range(len(self._data)): for j in range(i + 1, len(self._data)): if self._data[i] > self._data[j]: self._swaps.append((i, j)) self._data[i], self...
2015-04-01 csv|xml # cities.csv obtained from "Gestió agrupada impost 1.5%" class MunicipalTaxesInvoicingReport: def __init__(self, cursor, start_date, end_date, tax, aggregated): self.cursor = cursor self.start_date = start_date self.end_date = end_date self.tax = tax self....
er = record[3] invoicing_by_name.setdefault(name, {'total_provider_amount': 0, 'total_client_amount': 0, 'quarters': []}) invoicing_by_name[name]['total_provider_amount'] += record[4] invoicing_by_name[name]['total_client_amount'] += record[5] invoicing_by_name[name]['qua...
ount': record[4], 'client_amount': record[5] }) invoicing_by_date.setdefault(year, {}) invoicing_by_date[year].setdefault(quarter, {'total_provider_amount': 0, 'total_client_amount': 0}) invoicing_by_date[year][quarter]['total_provider_amount'] += record[...
import android import android.activity from os import unlink from jnius import autoclass, cast from plyer_lach.facades import Camera from plyer_lach.platforms.android import activity Intent = autoclass('android.content.Intent') PythonActivity = autoclass('org.renpy.android.PythonActivity') MediaStore = autoclass('andr...
i = Uri.parse('file://' + filename) parcelable = cast('android.os.Parcelable', uri) intent.putExtra(MediaStore.EXTRA_OUTPUT, parcelable) # 0 = low quality, suitable for MMS messages, # 1 = high quality intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1) activity.startActi...
sult(self, requestCode, resultCode, intent): if requestCode != 0x123: return android.activity.unbind(on_activity_result=self._on_activity_result) if self.on_complete(self.filename): self._unlink(self.filename) def _unlink(self, fn): try: unlink(fn...
#!/usr/bin/env python from __future__
import absolute_import from __future__ import division from
__future__ import print_function from __future__ import unicode_literals 'fbcode_builder steps to build Facebook Thrift' import specs.fbthrift as fbthrift def fbcode_builder_spec(builder): return { 'depends_on': [fbthrift], } config = { 'github_project': 'facebook/fbthrift', 'fbcode_builde...
from setuptools import setup import pybvc setup( name='pybvc', version=pybvc.__version__, description='A python library for programming your network via the Brocade Vyatta Controller (BVC)', long_description=open('README.rst').read(), author='Elbrys Networks', author_email='jeb@elbrys.com', ...
'sdn nfv bvc brocade vyatta controller network vrouter', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: System Administrators', 'Topic :: System :: Networking', 'License :: OSI A
pproved :: BSD License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ] )