prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
from kolibri.core.tasks.job import Job from kolibri.core.tasks.job import State from kolibri.core.tasks.storage import Storage DEFAULT_QUEUE = "ICEQUBE_DEFAULT_QUEUE" class Queue(object): def __init__(self, queue=DEFAULT_QUEUE, connection=None): if connection is None: raise ValueError("Connec...
return self.storage.count_all_jobs(self.name) @property def job_ids(self):
return [job.job_id for job in self.storage.get_all_jobs(self.name)] @property def jobs(self): """ Return all the jobs scheduled, queued, running, failed or completed. Returns: A list of all jobs. """ return self.storage.get_all_jobs(self.name) def enqueue(se...
__author__ = 'PaleNeutron' import os from urllib.parse import urlparse, unquote import sys from PyQt5 import QtWidgets, QtCore, QtGui class MyMainWindo
w(QtWidgets.QMainWindow): file_loaded = QtCore.pyqtSignal(str) image_loaded = QtCore.pyqtSignal(QtGui.QImage) def __init__(self): super(MyMainWindow, self).__init__() self.windowList = [] self.text_path = '' self.epub_path = '' self.win_file_mime = "applicat...
ent_browser() def create_content_browser(self): self.content_browser = QtWidgets.QTextBrowser() self.content_browser.setFontPointSize(12) self.content_browser.setGeometry(QtCore.QRect(300, 150, 600, 400)) self.windowList.append(self.content_browser) def dragEnterEvent(s...
#!/usr/bin/python # (c) 2012, Stephen Fromm <sfromm@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your optio...
2012. name = selinux.selinux_boolean_sub(name) if not has_boolean_value(module, name): module.fail_json(msg="SELinux boolean %s does not exist." % name) cur_value = get_boolean_value(module, name) if cur_value == state: result['state']
= cur_value result['changed'] = False module.exit_json(**result) if module.check_mode: module.exit_json(changed=True) if persistent: r = semanage_boolean_value(module, name, state) else: r = set_boolean_value(module, name, state) result['changed'] = r if not...
-like list. Calling it returns the head of the stack. """ def __call__(self): """ Return the current default application. """ return self[-1] def push(self, value=None): """ Add a new :class:`Bottle` instance to the stack """ if not isinstance(value, Bottle): value ...
assignment (most of itertools). """ def __init__(self, iterator, close=None): self.iterato
r = iterator self.close_callbacks = makelist(close) def __iter__(self): return iter(self.iterator) def close(self): for func in self.close_callbacks: func() class ResourceManager(object): """ This class manages a list of search paths and helps to find and open ...
import numpy as np def zero_mean_normalize_image_data(data, axis=(0, 1, 2)): return np.divide(data - data.mean(axis=axis), data.std(axis=axis)) def foreground_zero_mean_normalize_image_data(data, channel_dim=4, background_value=0, tolerance=1e-5): data = np.copy(data) if data.ndim == channel_dim or data...
ta: 3D
numpy array. :param windows: :param floor: defaults to 0. :param ceiling: defaults to 1. :return: Array with data windows listed in the final dimension """ data = np.squeeze(data) normalized_data = np.ones(data.shape + (len(windows),)) * floor for i, (l, w) in enumerate(windows): ...
cified here is # # used to dimension the transport stream STD (2.4.2 in ITU-T Rec. xxx | # # ISO/IEC 13818-1), or the program stream STD (2.4.5 in ITU-T Rec. xxx | # # ISO/IEC 13818-1). # # # # If the bitstream is not a constant rate bitstream the vbv_delay # # field shall have the val...
16) * (1 << 16)) + low4Bytes) / 90000 @staticmethod def ReadSCRMpeg1(buffer): """ read SCR (timestamp) for MPEG1 at the buffer beginning (5 Bytes) """ if len(buffer) < 5: return None highbit = (byte2int(buffer) >> 3) & 0x01 low4Bytes = ((int(byte2in...
ffer)) >> 1) & 0x03) << 30 low4Bytes |= indexbytes(buffer, 1) << 22 low4Bytes |= (indexbytes(buffer, 2) >> 1) << 15 low4Bytes |= indexbytes(buffer, 3) << 7 low4Bytes |= indexbytes(buffer, 4) >> 1 return (int(highbit) * (1 << 16) * (1 << 16) + low4Bytes) / 90000 @staticmetho...
# Configuration settings for Enso. Eventually this will take # localization into account too (or we can make a separate module for # such strings). # The keys to start, exit, and cancel the quasimode. # Their values are strings referring to the names of constants defined # in the os-specific input module in use. QUAS...
sh message shown when Enso first loads. OPENING_MSG_XML = "<p>Welcome to <command>Enso</command>!</p>" + \ "<caption>Copyright &#169; 2008 Humanized, Inc.</caption>" # Message XML displayed when the mouse hovers over a mini message. MINI_MSG_HELP_XML = "<p>The <command>hide mini messages</command>" \ " and <co...
\ " these mini-messages.</p>" ABOUT_BOX_XML = u"<p><command>Enso</command> Community Edition</p>" \ "<caption> </caption>" \ "<p>Copyright &#169; 2008 <command>Humanized, Inc.</command></p>" \ "<p>Copyright &#169; 2008-2009 <command>Enso Community</command></p>" \ "<p>Version 1.0</p>" # List of ...
th.log10(config["DEFAULT"]["1200000"]["CPE"] / _CyclesPerElement_) absorption_range_1200000 = config["DEFAULT"]["1200000"]["RANGE"] + ((config["DEFAULT"]["1200000"]["ABSORPTION_SCALE"] - absorption) * config["DEFAULT"]["1200000"]["RANGE"]) if _SystemFrequency_ > config["DEFAULT"]["1200000"]["FREQ"]: ...
on_range_1200000 + config["DEFAULT"]["1200000"]["BIN"] * dB_1200000) else: wpRange_1200000 = 0.0 else: btRange_1200000 = 0.0 wpRange_1200000 = 0.0 # 600khz btRange_600000 = 0.0 wpRange_600000 = 0.0 refBin_600000 = 0.0 xmtW_600000 = 0.0 rScale_600000 = ma...
config["DEFAULT"]["600000"]["DIAM"] / waveLength) dB_600000 = 0.0; if config["DEFAULT"]["600000"]["BIN"] == 0 or _CyclesPerElement_ == 0: dB_600000 = 0.0; else: dB_600000 = 10.0 * math.log10(_CWPBS_ / config["DEFAULT"]["600000"]["BIN"]) + dI - dI_600000 - 10.0 * math.log10(config["DEFAULT"]...
from toee import * from utilities import * from Co8 import * from py00439script_daemon import npc_set, npc_get from combat_standard_routines import * def san_dialog( attachee, triggerer ): if (npc_get(attachee, 1) == 0): triggerer.begin_dialog( attachee, 1 ) elif (npc_get(attachee, 1) == 1): triggerer.begin_dia...
eate_item_in_inventory( aaa, pc ) elif pc.stat_level_get(stat_level_warmage) > 0: if pc.stat_level_get(stat_race) in [race_gnome, race_halfling]: for aaa in [6013 ,6045 ,6046 ,6059, 4071 , 4115 ,50
07 ,5007, 8014]: # mace (4071) instead of spear create_item_in_inventory( aaa, pc ) else: for aaa in [6013 ,6045 ,6046 ,6059, 4117 , 4115 ,5007 ,5007, 8014]: create_item_in_inventory( aaa, pc ) elif pc.stat_level_get(stat_level_beguiler) > 0: for aaa in [6042 ,6045 ,6046 ,4049 ,4060 ,6233 ,...
in=-inf, ymax=inf): xs, ys = [], [] for xi, yi in zip(x, y): if xmin<=xi<=xmax and ymin<=yi<=ymax: xs.append(xi) ys.append(yi) return array(xs), array(ys) class optimbox(object): """optimbox is a class used for fitting curves and linked with the fmin decorator. a...
.countiter%10==0: print print '{step:>6}{residual:>11}{x}'.format(step='ste
p', x='{:>11}'*len(variables), residual='residual').format(*variables) print '-'*(6+11+11*len(variables)) indx = objectives.index(min(objectives)) x = tfinv(solutions[indx], bounds) isbest = '' if objectives[indx] == best_objective: isbest...
from __future__ import print_function from sqlalchemy import create_engine from sqlalchemy.pool import NullPool import sqlalchemy import sys # This value must be incremented after schema changes on replicated tables! SCHEMA_VERSION = 1 engine = None def init_db_engine(connect_str): global engine engine = cre...
_transaction(sql_file_path): with open(sql_file_path) as sql: connection = engine.connect() connection.connection.set_isolation_level(0) lines = sql.read().splitlines() try: for line in lines: # TODO: Not a great way of removing comments. The alternati
ve is to catch # the exception sqlalchemy.exc.ProgrammingError "can't execute an empty query" if line and not line.startswith("--"): connection.execute(line) except sqlalchemy.exc.ProgrammingError as e: print("Error: {}".format(e)) retu...
import random import musictheory import fileza
rt import math from pydub import AudioSegment from pydub.playback import play class Part: def __init__(self, typ=None, intensity=0, size=0, gen=0, cho=0): self._type = typ #"n1", "n2", "bg", "ch", "ge" if inte
nsity<0 or gen<0 or cho<0 or size<0 or intensity>1 or size>1 or gen>1 or cho>1: raise ValueError ("Invalid Values for Structure Part") self._intensity = intensity # [0-1] self._size = size # [0-1] self._genover = gen # [0-1] overlay of general type lines self._chover = cho # ...
# -*- coding: utf-8 -*- import sqlite3 from flask import g, c
urrent_app def connect_db(): db = sqlite3.connect(current_app.config['DATABASE_URI']) db.row_factory = sqlite3.Row return db # http://flask.pocoo.org/docs/0.10/appcontext/ def get_db(): """Opens a new database connection if there is none yet for the current application context. """ db = ...
database = connect_db() return db
import threading import time class Status: lock = None statusno =0 def __init__(self): self.lock = threading.Lock() def update(self, add): self.lock.acquire() self.statusno = self.statusno + add self.lock.release() def get(self): self.loc...
time.sleep (1) #print i status.update(1) def show_status(status): while threading.active_count() > 2: time.sleep(1) print status.get() status = Status() slaves = [] for i in range(5): t = threading.Thread(target=md5calc, args=(status, [1,2,...
args=(status,)) m.start() m.join() for t in slaves: t.join()
import os.path import platform from nose2.compat import unittest from nose2.tests._common import FunctionalTestCase class TestCoverage(FunctionalTestCase): @unittest.skipIf( platform.python_version_tuple()[:2] == ('3', '2'), 'coverage package does not support python 3.2') def test_run(self): ...
'-v', '--with-coverage', '--coverage=lib/' ) STATS = '\s+8\s+5\s+38%' expected = os.path.join('lib', 'mod1(.py)?') expected = expected.replace('\\', r'\\') expected = expected + STATS stdout, stderr = proc.communicate() self.assertTest...
derr='TOTAL\s+' + STATS)
__author__ = 'Alex Breshears' __license__ = ''' Copyright (C) 2012 Alex Breshears Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (t
he "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyrig...
S IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR...
# Copyright (C) 2013 - 2016 - Oscar Campos <oscar.campos@member.fsf.org> # This program is Free Software see LICENSE file for details import logging import traceback from collections import defaultdict from ..anagonda.context import guru from commands.base import Command class PackageSymbols(Command): """Run g...
details['name'] = desc['desc'] details['kind'] = details['type'] aggregated_data[filename].append(details) for elem in details.get('methods', []): filename = elem['pos'].split(':')[0] elem['type'] = elem['name'] elem['kind']...
details['pos'] = details['objpos'] details['name'] = details['type'] details['kind'] = details['type'] aggregated_data[filename].append(details) for filename, elems in aggregated_data.items(): symbols += sorted(elems, key=lambda x: x['pos']) ret...
import time import numpy as np import keras import tensorflow as tf import keras.backend as K from keras import optimizers from keras.models import load_model from keras.callbacks import Callback from functions import calculate_top_k_new_only """ PeriodicValidation - Keras callback - checks val_loss periodically i...
f.val_data[1], self.batch_size, (not self.val_data[0][1].shape[2] == self.val_data[1].shape[1])) print("testing MAP@K for NEW products: ", y_top_k_new_only) if h[0] < self.min_val_loss: if self.fil
epath: self.model.save(self.filepath, overwrite=True) print("val_loss improved from "+str(self.min_val_loss)+" to "+str(h[0])+", saving model to "+self.filepath) else: print("val_loss improved from "+str(self.min_val_loss)+" to "+str(h[0])) ...
# -*- coding: u
tf8 -*- from .task import TaskID from .core import Handler from .queue import EventQueue __all__ = [ 'TaskID', 'Handler', 'EventQueue'
, ]
from .PBXResolver import * from .PBX_Constants import * class PBX_Base(object): def __init__(self, lookup_func, dictionary, project, identifier): # default 'name' property of a PBX object is the type self.name = self.__class__.__name__; # this is the identifier for this object ...
# set of any referenced identifiers on this object self.referencedIdentifiers = set(); def __attrs(self): return (self.identifier); def __repr__(self): return
'(%s : %s : %s)' % (type(self), self.name, self.identifier); def __eq__(self, other): return isinstance(other, type(self)) and self.identifier == other.identifier; def __hash__(self): return hash(self.__attrs()); def resolve(self, type, item_list): return filter(lambda...
########################################################################## # # Copyright (c) 2014, John Haddon. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of so...
RACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # #############################################
############################# import IECore import Gaffer import GafferScene import GafferSceneTest class PrimitiveVariablesTest( GafferSceneTest.SceneTestCase ) : def test( self ) : s = GafferScene.Sphere() p = GafferScene.PrimitiveVariables() p["in"].setInput( s["out"] ) self.assertScenesEqual( s["out"...
import logging logger = logging.getLogger(__name__) def get(isdsAppliance, check_mode=False, force=False): """ Retrieve available updates """ return isdsAppliance.invoke_get("Retrieving available updates", "/updates/available.json") def discover(isdsAppliance, ch...
" Parse the file name to see if it is already uploaded - use version and release date from pkg file name Also check to see if the firmware level is already uploaded Note: Lot depends on the name of the file. :param isdsAppliance:
:param file: :return: """ import os.path # If there is an exception then simply return False # Sample filename - 8.0.1.9-ISS-ISDS_20181207-0045.pkg logger.debug("Checking provided file is ready to upload: {0}".format(file)) try: # Extract file name from path f = os.path....
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import re import task_classes from task_classes import QsubAnalysisTask class DemoQsubAnalysisTask(QsubAnalysisTask): """ Demo task that will submit a single qsub job for the analysis """ def __init__(self, analysis, taskname = 'DemoQs...
_handlers) def main(self, analysis): """ Main function for performing the analysis task on the entire analysis Put your code for performing the analysis task on the entire analysis here Paramet
ers ---------- analysis: SnsWESAnalysisOutput the `sns` pipeline output object to run the task on. If ``None`` is passed, ``self.analysis`` is retrieved instead. Returns ------- qsub.Job a single qsub job object """ self.logger.debug('Put...
#!/usr/bin/python # -*- coding: utf-8 -*- #------------------------------------------------------------------------------# # Security - Linux Authentication Tester with /etc/shadow # # ============================================================================ # # Not
e: To be used for test purpose only # # Developer: Chavaillaz Johan
# # Filename: LinuxAuthenticationTesterShadow.py # # Version: 1.0 # # # # Licensed to the Apache Software Foundation (ASF) under one ...
lient_mock = action_mocks.ActionMock( searching.Find, searching.Grep, ) session_id = flow_test_lib.TestFlowHelper( registry.RegistryFinder.__name__, client_mock, client_id=client_id, keys_paths=keys_paths, conditions=conditions, creator=self.test_...
tetime.FromSecondsSinceEpoch(1)) client_id = self.SetupClient(0) session_id = self.RunFlow(client_id, [self.runkey], [ registry.RegistryFinderCondition(
condition_type=registry.RegistryFinderCondition.Type .MODIFICATION_TIME, modification_time=modification_time) ]) self.assertFalse(flow_test_lib.GetFlowResults(client_id, session_id)) def testFindsKeysIfModificationTimeConditionMatches(self): modification_time = rdf_file_finde...
from bitmovin.resources.models import AbstractModel from bitmovin.resources import AbstractNameDescriptionResource from bitmovin.errors import InvalidTypeError from bitmovin.utils import Serializable from .encoding_output import EncodingOutput class Sprite(AbstractNameDescriptionResource, AbstractModel, Serializable)...
Name = vtt_name if outputs is not None and not isinstance(outputs, list): raise InvalidTypeError('outputs must be a list') self.outputs = outputs
@classmethod def parse_from_json_object(cls, json_object): id_ = json_object['id'] custom_data = json_object.get('customData') width = json_object.get('width') height = json_object.get('height') distance = json_object.get('distance') sprite_name = json_object.get(...
ry_user(user.fullname)['results']), 1) assert_equal(len(query_user(merged_user.fullname)['results']), 0) def test_employment(self): user = factories.UserFactory(fullname='Helga Finn') user.save() institution = 'Finn\'s Fine Filers' docs = query_user(institution)['results'] ...
ery(value)['results'] assert_equal(len(docs), 0) with run_celery_tasks(): self.registration.create_o
r_update_node_wiki(name=key, content=value, auth=self.consolidate_auth) # Query and ensure unique string shows up docs = query(value)['results'] assert_equal(len(docs), 1) # Query and ensure registration does show up docs = query('category:registration AND ' + self.t...
#!/usr/bin/env jython import sys #sys.path.append("/usr/share/java/itextpdf-5.4.1.jar") sys.path.append("itextpdf-5.4.1.jar") #sys.path.append("/usr/share/java/itext-2.0.7.jar") #sys.path.append("/usr/share/java/xercesImpl.jar") #sys.path.append("/usr/share/java/xml-apis.jar") from java.io import FileOutputStream fro...
t0=time.time() pdf=pdf1 t1=time.time() #print "finished in %.2fs"%(t1-t0) return pdf serv=SimpleXMLRPCServer(("localhost",9999)) serv.re
gister_function(pdf_fill,"pdf_fill") serv.register_function(pdf_merge,"pdf_merge") print "waiting for requests..." serv.serve_forever()
from __future__ import print_function import math, nltk from termcolor import colored from analyze import generate_stopwords, sanitize from vector import Vector class NaiveBayesClassifier(): def __init__(self): """ Creates: """ self.c = {"+" : Vector(), "-" : Vector()} ...
p += math.log(.1 - values[word]) # print "%s : %f" % (word, math.log(.1 - values[word])) #print p return p ''' for feature in s
elf.features: #print "c[%s] = %s" % (feature, c[feature]) if feature in sanitized_tweet: p += math.log(1 - c[feature]) # add feature's score per the sentiment else: p += math.log(1 - c[feature]) return p ''' def classify(self, ...
# -*- codin
g: utf-8 -*- # © 2015 Eficent Business and IT Consulting Services S.L. - # Jordi Ballester Alomar # License AGPL-3.0 or later (https://www.gnu.org/licens
es/agpl.html). from . import models
''' compile_test.py - check pyximport functionality with pysam ========================================================== test script for checking if compilation against pysam and tabix works. ''' # clean up previous compilation import os import unittest import pysam from TestUtils import make_data_files, BAM_DATADIR...
Equal(nread, 3270) class GTFTest(unittest.TestCase): input_filename = os.path.join(TABIX_DATADIR, "example.gtf.gz") def testCount(self): nread = _compile_test.testCountGTF( py
sam.Tabixfile(self.input_filename)) self.assertEqual(nread, 237) if __name__ == "__main__": unittest.main()
""" Title: Ch3LpfPlotResponse - Chapter 3: Plot filter response Author: Ricardo Alejos Date: 2016-09-20 Description: Plots the micro-strip filter response against the specifications Version: 1.0.0 Comments: - """ # Import Python's built-in
modules import csv as _csv import logging as _logging import os as _os import sys as _sys import time as _time import math as _math # Add project root directory to sys.path so other modules can be imported _projectRoot = _os.path.abspath(__file__ + "\\..\\..\\..") if _projectRoot not in _sys.path: _sys.path.inser...
kg.Helpers.MatlabFunctions as _mf def _initLogger(): global logger logger = _logging.getLogger(_strThisFileName) logger.setLevel(_logging.DEBUG) map(logger.removeHandler, logger.handlers[:]) ch = _logging.StreamHandler(_sys.stdout) ch.setLevel(_logging.INFO) fh = _logging.FileHandler(_strTh...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2018 Jonathan Peirce # Distributed under the terms of the GNU General Public License (GPL). # Support for fake joystick/gamepad during devlopment # if no 'real' joystick/gamepad is available use keyboard emulation # 'ctrl' + ...
eys] mouseButtons = self.mouse.getPressed() self.state[:len(mouseButtons)] = [a or b != 0 for (a,b) in zip(self.state, mouseButtons)] return(self.state) def getX(self): (x, y) = self.mouse.getPos() return x def ge
tY(self): (x, y) = self.mouse.getPos() return y
# -*- coding: L
atin-1 -*- # Copyright (c) 2015, The MITRE Corporation. All rights reserved. # See License.txt for complete terms. # file object -> CybOX File Object mappings file_object_mappings = {'file_format': 'file_format', 'type': 'type',
'file_name': 'file_name', 'file_path': 'file_path', 'size': 'size_in_bytes', 'magic_number': 'magic_number', 'file_extension': 'file_extension', 'entropy': 'peak_entropy'}
, sideB = self.sqGetPointLists() toDeleteList = [] p = 2 for
k in range((sideA+2), (sideB-1)): if p%2 == 0: toDeleteList.append(self.baseCurve+".cv["+str(k)+"]") toDeleteList.append(self.baseCurve+".cv["+str(k+len(pointListA)-1)+"]") p = p+1 q = 2 m = sideA-2 if
m >= 0: while m >= 0: if not m == sideA and not m == sideB: if q%2 == 0: toDeleteList.append(self.baseCurve+".cv["+str(m)+"]") m = m-1 q = q+1 cmds.delete(toDeleteLis...
logging.getLogger(__name__), energieopwek_nl=True): if target_datetime is None: target_datetime = arrow.utcnow() else: target_datetime = arrow.get(target_datetime) r = session or requests.session() consumptions = ENTSOE.fetch_consumption(zone_key=zone_key, ...
value we look up the corresponding ENTSOE # valu
es and copy the nuclear, gas, coal, biomass and unknown production. productions = [] for p in productions_eopwek: entsoe_value = next((pe for pe in productions_ENTSOE if pe["datetime"] == p["datetime"]), None) if entsoe_value: p["production"]["nuc...
import argparse import glob import matplotlib.pyplot as plt import numpy as np import os import pandas as pd import pickle from sklearn.preprocessing import StandardScaler, normalize import sys import common FACT = 'pmi' # nmf/pmi_wl/pmi_wp/pmi_wlp DIM = 200 DATASET = 'MSDmm' WINDOW = 1 NSAMPLES = 'all' #all MAX_N_S...
ription='Trains the model', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argum
ent('-d', '--dataset', dest="dataset", type=str, help='Dataset name', default=DATASET) parser.add_argument('-f', '--fact', dest="fact", ...
import sys p
rint("Hello, World!")
from cantilever_divingboard import * # We need to scale the parameters before applying the optimization algorithm # Normally there are about 20 orders of magnitude between the dimensions and # the doping concentration, so this is a critical step
# Run the script freq_min = 1e3 freq_max = 1e5 omega_min = 100e3 initial_guess = (50e-6, 1e-6, 1e-6, 30e-6, 1e-6, 1e-6, 500e-9, 5., 1e15) constraints = ((30e-6, 100e-6), (500e-9, 20e-6), (1e-6, 10e-6), (2e-6, 100e-6), (500e-9, 5e-6), (500e-9, 20e-6), (30e-9, 10e-6), ...
x) c.print_performance()
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
# Delete delete_entry = BashOperator(task_id="delete_entry", bash_command="echo delete_entry") create_entry_gcs >> delete_entry delete_entry_group = BashOperator(task_id="delete_entry_group",
bash_command="echo delete_entry_group") create_entry_group >> delete_entry_group delete_tag = BashOperator(task_id="delete_tag", bash_command="echo delete_tag") create_tag >> delete_tag delete_tag_template_field = BashOperator( task_id="delete_tag_template_field", bash_command="echo delete_tag...
def pytest_addoption(parser): parser.ad
doption( '--integration', action='store_true', help='run integration tests', ) def pytest_ignore_collect(path, config): if not config.getoption('integration') and 'int
egration' in str(path): return True
def read_logfile_by_line(logfile): """generator function that yields the log file content line by line""" with open(logfile, 'r') as f: for line in f: yield line yield None def parse_commands(log_content): """ parse cwl commands from the line-by-line generator of log file cont...
if in_command: command.append(line.stri
p('\\').rstrip(' ')) if not line.endswith('\\'): in_command = False command_list.append(command) command = [] line = next(log_content) return(command_list)
import copy import json import logging import threading import uuid from flask import Flask, abort, jsonify, request import kubernetes app = Flask(__name__) app.secret_key = "mega secret key" JOB_DB = {} def get_config(experiment): with open('config_template.json', 'r') as config: return json.load(config...
d, [(k8s_volume, '/data')], env_vars, request.json['experiment']) if job_obj: job = copy.deepcopy(request.json) job['job-id'] = job_id job['status'] = 'started'
job['restart_count'] = 0 job['max_restart_count'] = 3 job['obj'] = job_obj job['deleted'] = False JOB_DB[job_id] = job return jsonify({'job-id': job_id}), 201 else: return jsonify({'job': 'Could not be allocated'}), 500 @app.route('/api/v1.0/jobs/<job_id>', m...
# encoding: utf-8 # This file is part of Guacamole. # # Copyright 2012-2015 Canonical Ltd. # Written by: # Zygmunt Krynicki <zygmunt.krynicki@canonical.com> # # Guacamole is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License version 3, # as published by ...
"""Common initialization method.""" self.bowl = Bowl([CommandTreeBuilder(_cmd())]) self.bowl.eat() def test_build_command_tree(self): """check if a co
rrect command tree is built.""" cmd_obj = self.bowl.context.cmd_tree[1] sub_obj = self.bowl.context.cmd_tree[2][0][1] self.assertIsInstance(cmd_obj, _cmd) self.assertIsInstance(sub_obj, _sub) self.assertEqual( self.bowl.context.cmd_tree, (None, cmd_obj, ((...
# This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Research (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 (a...
rib_id' in kwargs: kwargs['contribution_id'] = kwargs.p
op('contrib_id') if 'subcontrib_id' in kwargs: kwargs['subcontribution_id'] = kwargs.pop('subcontrib_id') # extension is just to make the links prettier kwargs.pop('ext', None) # session id is only used for actual sessions, not for stuff inside them if 'contribution_id' in kwargs: kw...
import
sys [_, ms, _, ns] = list(sys.stdin) ms = set(int(m) for m in ms.split(' ')) ns = set(int(n) for n in ns.split(' ')) print(sep='\n', *sorted(ms.difference(ns).uni
on(ns.difference(ms))))
import os from whylog.log_reader.exceptions impor
t EmptyFile, OffsetBiggerThanFileSize class ReadUtils(object): STANDARD_BUFFER_SIZE = 512 @classmethod def size_of_
opened_file(cls, fh): prev_position = fh.tell() fh.seek(0, os.SEEK_END) size = fh.tell() fh.seek(prev_position) return size @classmethod def _read_content(cls, fd, position, buf_size): fd.seek(position) return fd.read(buf_size) @classmethod def _...
#!python # -*- coding: utf-8 -*- from os import path import shutil def install(): fi
lename = 'ilmaruuvi.service' install_path = path.join('/etc/systemd/system', filename) here = path.abspath(path.dirname(__file__)) with open(path.join(here, filename), 'r') as f: service = f.read() service = service.format(working_dir=here, exec_start=shuti
l.which('ilmaruuvi')) with open(install_path, 'w') as f: f.write(service)
all PTX special objects. """ from __future__ import print_function, absolute_import, division import operator import numpy import llvmlite.llvmpy.core as lc from numba import types, ir, typing, macro from .cudadrv import nvvm class Stub(object): '''A stub object to represent special objects which is meaningless ...
Return the absolute position of the current thread in the entire grid of blocks. *ndim* should correspond to the number of dimensions declared when instantiating the kernel. If *ndim* is 1, a single
integer is returned. If *ndim* is 2 or 3, a tuple of the given number of integers is returned. Computation of the first integer is as follows:: cuda.threadIdx.x + cuda.blockIdx.x * cuda.blockDim.x and is similar for the other two indices, but using the ``y`` and ``z`` attributes. """...
""" sampyl.samplers.NUTS ~~~~~~~~~~~~~~~~~~~~ This module implements No-U-Turn Sampler (NUTS). :copyright: (c) 2015 by Mat Leonard. :license: MIT, see LICENSE for more details. """ from __future__ import division import collections from ..core import np from .base import Sampler from .hamiltonian import energy, ...
the paper: http://www.stat.columbia.edu/~gelman/research/published/nuts.pdf :param logp: log P(X) function for sampling distribution :param start: Dictionary of starting state for the sampler. Sho
uld have one element for each argument of logp. :param grad_logp: (optional) Function or list of functions that calculate grad log P(theta). Pass functions here if you don't want to use autograd for the gradients. If logp has multiple parameters, grad_logp must ...
#!/usr/bin/env python # This work was created by participants in the DataONE project, and is # jointly copyrighted by participating institutions in DataONE. For # more information on DataONE, see our web site at http://dataone.org. # # Copyright 2009-2017 DataONE # # Licensed under the Apache License, Version 2.0 (t...
. """MIME-Type Parser. This module provides basic functions for handling mime-types. It can handle matching mime-types against a list of media-ranges. See section 14.1 of the HTTP specification [RFC 2616] for a complete explanation. http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1 Contents:
- parse_mime_type(): Parses a mime-type into its component parts. - parse_media_range(): Media-ranges are mime-types with wild-cards and a 'q' quality parameter. - quality(): Determines the quality ('q') of a mime-type when compared against a list of media-ranges. - quality_parsed():...
# Copyright (c) 2015 SUSE Linux GmbH. All rights reserved. # # This file is part of kiwi. # # kiwi 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 la...
m str filename: base filename in target """ xen = self.get_xen_hypervisor() if xen: if not file_name: file_name = 'hypervisor-' + xen.name target_file = ''.join( [target_dir, '/', file_name] ) Command.run(['cp', xen....
up(self): """ The kernel image name is different per arch and distribution This method returns a list of possible kernel image names in order to search and find one of them :return: list of kernel image names :rtype: list """ kernel_names = [] ke...
import medic from maya import OpenMaya class FaceAssigned(medic.PyTester): def __init__(self): super(FaceAssigned, self).__init__() def Name(self): return "FaceAssigned" def Description(self): return "Face assigned mesh(s)" def Match(self, node): return node.object()...
arr = OpenMaya.MPlugArray() if not gelm.connectedTo(arr, False, True): continue for n in range(arr.length()): if arr[n].node().hasFn(OpenMaya.MFn.kShadingEngine): return True return False def test(self, node...
ups"): return medic.PyReport(node) if FaceAssigned.__TestObjGrp(node, "instObjGroups", "objectGroups"): return medic.PyReport(node) return None def Create(): return FaceAssigned()
image = clutter.Texture() if image_src: self.image.set_from_file(image_src) self.image.set_parent(self) self.set_font_name('16') self.set_font_color('#000000ff') self.set_inner_color('#aaaaaaff') self.set_border_color('#888888ff') def set_ima...
d tempor incididunt.') b.set_size(*b.get_preferred_size()[2:]) box0.add(b) # Butt
on larger than natural size b = ClassicButton('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt.') b.set_size(630, 50) box0.add(b) # Intermediate flowbox to force line wrapping box1 = FlowBox() box1.set_size(640, 50) box0.add(box1) # Bu...
import logging from . import generic from .elfreloc import ELFReloc l = logging.getLogger(name=__name__) # http://refspecs.linuxfoundation.org/ELF/ppc64/PPC-elf64abi-1.9.pdf arch = 'PPC64' class R_PPC64_JMP_SLOT(ELFReloc): def relocate(self): if self.owner.is_ppc64_abiv1: # R_PPC64_JMP_SLOT ...
return False self.owner.memory.pack_word(self.relative_addr, self.value, size=2) return True class R_PPC64_TOC16_HA(ELFReloc): """ Relocation Type: 50 Calculation:
#ha(S + A - .TOC.) Field: half16 """ @property def value(self): A = self.addend S = self.resolvedby.rebased_addr if self.owner.ppc64_initial_rtoc is None: l.warning(".TOC. value not found") return ((((S + A) >> 16) + (1 if ((S + A) & 0x8000) else 0)) & 0x...
def flatten(x): """ Takes an N times nested list of lis
t like [[a,b],[c, [d, e]],[f]] and returns a single list [a,b,c,d,e,f] """ result = [] for el in x: if hasattr(el, "__iter__") and not isinstance(el, str): result.extend(flatten(el)) else: result.append(el) retur
n result
ene table detailed_out.write("\t".join(["Chromosome","Gene_name","Is_hgnc","Ensembl_gene_id","Ensembl_transcript_id","Biotype", "Transcript_status","CCDS_id","HGNC_id","CDS_length","Protein_length", "Transcript_start","Transcript_end","strand","Synonyms", ...
string = gene_string.replace(",None","") #Nonetype object has no attribute split if string is not None: genes = set(string.split(",")) if len(genes) > 1: # We would like to represent each member of the gene list as a key and the remainder as synonyms each time ...
set([each]) synonym = genes.difference(keygene) gene_name = ','.join(keygene) other_names = ','.join(synonym) hgnc_flag = "1" if gene_name in list_hgnc else "0" # only when the gene is a HGNC name, it would have an hgnc ...
# -*- coding: u
tf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0014_generalsetting_titulo'), ] operations = [ migrations.AlterField( model_name='imagen', name='img', ...
.ImageField(upload_to=b'imgenEvento', verbose_name=b'Ruta'), ), ]
#!/usr
/bin/env python3 # -*- coding : utf-8 -*- def mymodules2(): print("test module2!") mymodules2(
)
if self.tkconsole.getvar("<<toggle-jit-stack-viewer>>"): self.remote_stack_viewer() elif how == "ERROR": errmsg = "PyShell.ModifiedInterpreter: Subprocess ERROR:\n" print(errmsg, what, file=sys.__stderr__) print(errmsg, what, file=cons...
es complete exec source" filename = self.stuffsource(source) self.execfile(filename, source) def execfile(self, filename, source=None): "Execute an existing file" if source is None: with tokenize.open(filename) as fp: source = fp.read() try: ...
tkerr = self.tkconsole.stderr print('*** Error in script or command!\n', file=tkerr) print('Traceback (most recent call last):', file=tkerr) InteractiveInterpreter.showsyntaxerror(self, filename) self.tkconsole.showprompt() else: self.runcode(code) ...
event time to emit sleep(3) self.assertFalse(PostgresConnector.is_server_master.called) PostgresConnector.is_server_master = old_func class ClientComponentTestCase(TestCase): def test_add_listener_throws_on_non_component(self): client = Client(MagicMock(), MagicMock()) se...
once_with() class ClientShutdownTestCase(TestCase): def test_shutdown(self): client = Client(MagicMock()) client.log = MagicMock() client._stop_components = MagicMock() c
lient._stop_observer = MagicMock() client._should_run = True client._shutdown() client._stop_components.assert_called_once_with() client._stop_observer.assert_called_once_with() self.assertFalse(client._should_run) def test_stop_terminates(self): client = Client(Mag...
# -*- coding: utf-8 -*- from __future__ import absolute_import import random class BackoffTimer(object): def __init__(self, ratio=1, max_interval=None, min_interval=None): self.c = 0 self.ratio = ratio self.max_interval = max_interval self.min_interval = min_interval def is_r...
self def get_interval(self): k = pow(2, self.c) - 1 interval = random.random() * k * self.ratio if self.max_interval is not None: interval = min(interval, self.max_interval) i
f self.min_interval is not None: interval = max(interval, self.min_interval) return interval
# -*- coding: utf-8 -*- from __future__ import absolute_import import os import sys from pip.basecommand import Command from pip.index import PackageFinder from pip.log import logger from pip.exceptions import CommandError, PreviousBuildDirError from pip.req import InstallRequirement, RequirementSet, parse_requirement...
options=options, session=session): if req.editable:
logger.notify("ignoring %s" % req.url) continue requirement_set.add_requirement(req) #fail if no requirements if not requirement_set.has_requirements: opts = {'name': self.name} msg = ('You must give at least one requirement ' ...
# -*- coding: utf-8 -*- import os import lxml.etree import io from . import pipeline_item import core.docvert_exception class GeneratePostConversionEditorFiles(pipeline_item.pipeline_stage): def stage(self, pipeline_value): return pi
peline_value
import random from plugin import Plugin class Flatter(Plugin): def help_text(self, bot): return bot.translate("flatter_help") def on_msg(self, bot, user_nick, host, channel, message): if message.lower().startswith(b
ot.translate("flatter_cmd")): if len(message.split()) >= 2: if bot.getlanguage() == "de": bot.send_message(channel, message.split()[1] + ", " + random.choice(list(open('lists/flattery.txt'))), user_nick) elif bot.getlanguage() == "en": # Source http://www.pickuplinesgalore.com/c...
user_nick)
import scipy as sp import numpy as np import matplotlib.pyplot as plt import matplotlib import sys import matplotlib.lines as lines import h5py from matplotlib.font_manager import FontProperties import matplotlib.ticker as ticker from scipy.fftpack import fft axial_label_font = FontProperties() axial_label_font.se...
5+10/scale_meter, 0.5+10/scale_meter], color='k', linewidth=0.5) # # plt.gca().add_line(l1); # # plt.gca().add_line(l2); # # plt.gca().add
_line(l3); # PGA_depth = sp.zeros(len(depth)); # for x in xrange(0,len(node_ID)): # current_node = node_ID[x]; # current_depth = depth[x]; # Time, current_displacement_component, current_acceleration_component = node_response_extraction_sequential(current_node, file_name, num_DOF); # plot_curre...
# -*- python -*- # Copyright (C) 2009-2017 Free Software Foundation, Inc. # 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 versio...
et from libdir to the prefix. dotdots = ('..' + os.sep) * len (libdir.split (os.sep)) objfile = gdb.current_objfile ().filename dir_ = os.path.join (os.path.dirname (objfile), dotdots, pythondir)
if not dir_ in sys.path: sys.path.insert(0, dir_) # Call a function as a plain import would not execute body of the included file # on repeated reloads of this object file. from libstdcxx.v6 import register_libstdcxx_printers register_libstdcxx_printers(gdb.current_objfile())
survey = Survey(name=name) survey.set_beam(model='airy', n_sidelobes=1) if name in ('chime-frb', 'wsrt-apertif', 'parkes-htru'): survey.set_beam(model=name) surveys.append(survey) return surveys def set_up_dirs(self, run=np.nan): """Create subdir...
.df.run == run) mask &= (self.so.df.alpha == al
pha) mask &= (self.so.df.si == si) mask &= (self.so.df.li == li) mask &= (self.so.df.survey == survey.name) uuid = self.so.df[mask].uuid.iloc[0] surv_pop.name = f'mc/run_{run}/{uuid}' ...
class Solution(object): def imageSmoother(self, M): """ :type M: List[L
ist[int]] :rtype: List[List[int]] """ row, col = len(M), len(M[0]) ans = [[0]*col f
or i in xrange(row)] for i in xrange(row): for j in xrange(col): cnt = 0 val = 0 for p in xrange(-1, 2): for q in xrange(-1, 2): if ((i+p)<0) or ((i+p)>=row) or ((j+q)<0) or ((j+q)>=col): ...
"""Help to make choice""" # PYTHON STUFFS ####################################################### import random import shlex from nemubot import context from nemubot.exception import IMException from nemubot.hooks import hook from nemubot.module.more import Response # MODULE INTERFACE ############################...
ception("indicate some terms to pick!") return Response(random.choice(msg.args), channel=msg.channel, nick=msg.frm) @hook.command("choicecmd") def cmd_choicecmd(msg): if not len(msg.args): raise IMException("indicate some command to pick!") choice = shlex....
n [x for x in context.subtreat(context.subparse(msg, choice))] @hook.command("choiceres") def cmd_choiceres(msg): if not len(msg.args): raise IMException("indicate some command to pick a message from!") rl = [x for x in context.subtreat(context.subparse(msg, " ".join(msg.args)))] if len(rl) <= 0:...
from datetime import datetime import uuid class Torrent(object): def __init__(self): self.tracker = None self.url = None self.title = None self.magnet = None self.seeders = None self.leechers = None self.size = None self.date = None self.detai...
@property def html_friendly_title(self): return self.title.replace('.', '.&#8203;').replace('[', '&#8203;[').replace(']', ']&#8203;') def __unicode__(self): return "%s Size: %s Seeders: %s Age: %s %s" % (self.title.ljust(60)[0:60], str(self.human_size).ljust(12), ...
str(self.seeders).ljust(6), self.human_age, self.tracker) def __str__(self): return self.__unicode__()
from . import services def prep_rules(rules): prepped = [] for rule in rules: if rule['enabled']: prepped.append(prep_rule(rule)) return prepped def prep_rule(raw_rule): rule = dict(raw_rule) if rule['service'] != 'custom': proto, port = services.decode_service(rul...
raise ValueError("Unknown service: {service}".format( service=rule['service'] ))
rule['proto'] = proto rule['port'] = port if not rule['comment']: rule['comment'] = "{service} service ({proto}:{port})".format( service=rule['service'], proto=proto, port=port ) return rule
self._operator_map = operator_map def get_options(self): return self._operator_map.get_options() def handle_BoolOp(self, op): return {self.handle(op.op): list(map(self.handle, op.values))} def handle_And(self, op): '''and''' return '$and' def handle_Or(self, ...
col_offset=node.col_offset, options=self.get_options()) return handler(node)
def handle_exists(self, node): return {'$exists': self.parse_arg(node, 0, BoolField())} def handle_type(self, node): return {'$type': self.parse_arg(node, 0, IntField())} class StringFunc(Func): def handle_regex(self, node): result = {'$regex': self.parse_arg(node, 0, StringField())} ...
from __future__ import unicode_literals from . import exceptions DEFAULT_HOST = 'http://api.acoustid.org/' FORMATS = ('json', 'jsonp', 'xml') META = ( 'recordings', 'recordingids', 'releases', 'releaseids', 'releasegroups', 'releasegroupids', 't
racks', 'compress',
'usermeta', 'sources' ) ERRORS = { 1: exceptions.UnknownFormat, 2: exceptions.MissingParameter, 3: exceptions.InvalidFingerprint, 4: exceptions.InvalidClientKey, 5: exceptions.InternalError, 6: exceptions.InvalidUserApiKey, 7: exceptions.InvalidUUID, 8: exceptions.InvalidDuration, ...
import sys import time from naoqi import ALProxy IP = "nao.local" PORT = 9559 if (len(sys.argv) < 2): print "Usage: 'python RecordAudio.py nume'" sys.exit(1) fileName = "/home/nao/" + sys.argv[1] + ".wav" aur = ALProxy("ALAudioRecorder", IP, PORT) channels = [0,0,1,0] aur.startMicrophonesRecording(fileName...
"wav", 160000, channels) c=raw_input("Sfarsit?") aur.stopMicrophonesRecording() c=raw_input("play?") aup = ALProxy("ALAudioPlayer", IP, PORT) #Launchs the playing of a file aup.playFile(fileName,0.5,-1.0) c=raw_input("gata?") #Launchs the playing of a file #aup.playFile("/usr/share/naoqi/wav/random.wav") #Launchs the...
ng of a file on the left speaker to a volume of 50% #aup.playFile("/usr/share/naoqi/wav/random.wav",0.5,-1.0)
import os, sys, shutil import zipfile from zipfile import ZipFile from urllib import urlretrieve from subprocess import Popen, PIPE from distutils.cmd import Command def zip_directory(dir, zip_file): zip = ZipFile(zip_file, 'w', compression=zipfile.ZIP_DEFLATED) root_len = len(os.path.abspath(dir)) ...
print "*Compiling C Extensions inplace for portable distribution" cext_cmd = [sys.executable, #path to python.exe 'setup.py', 'build_ext', #make setup.py create a sr
c distribution '--inplace'] #do it inplace #this time it runs teh setup.py inside the source distribution #thats has been generated inside the build dir (to generate ext #for teh target, instead of the source were building from) Popen(cext_cmd...
# Copyright 2014 Alcatel-Lucent USA 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 l...
limi
tations # under the License. ''' Nuage specific exceptions ''' from neutron.common import exceptions as n_exc class OperationNotSupported(n_exc.InvalidConfigurationOption): message = _("Nuage Plugin does not support this operation: %(msg)s") class NuageBadRequest(n_exc.BadRequest): message = _("Bad req...
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-10-26 14:20 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel
( name='Occupancy', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('room_name', models.CharField(max_length=255)), ('occupancy', models.IntegerField()), ('timest
amp', models.DateField()), ], ), ]
from djan
go import template from django.conf import settings from django.template.defaultfilters import stringfilter import os register = template.Library() @register.filter(name='basename') @stringfilter def basename(value): return os.path.basename(value) @register.filter(name='replace_macros') @stringfilter def repl...
r_dict['first_name'].strip()) \ .replace("#LASTNAME#", user_dict['last_name'].strip()) @register.filter(name='state_label_css') def state_label_css(subm): green_label = "badge label label-success" red_label = "badge label label-important" grey_label = "badge label label-info" # We expe...
""" This script is a starting point for new Blocks users already familiar with Machine Learning and Theano. We demonstrate how to use blocks to train a generic set of parameters (theano shared variables) that influence some arbitrary cost function (theano symbolic variable), so you can start using blocks features (...
with your Theano code today. To run an experiment, we simply construct a main_loop.MainLoop and call its run() method. It suffices to pass the MainLoop a blocks.model.Model (which needs the cost), a blocks.algorithms.TrainingAlgorithm (which needs the cost and parameters), and a fuel.streams.DataStream* As it is...
You can interrupt training training anytime with Ctrl+C, or termination conditions can be added via extensions. *The DataStream object is part of the partner library Fuel (https://github.com/mila-udem/fuel). """ import numpy np = numpy import theano import theano.tensor as T # (Here we make a toy dataset of two...
if men.point == 2: screen.blit(lab_help_red, (342, 380)) else: screen.blit(lab_help, (342, 380)) if men.point == 3: screen.blit(lab_credits_red, (359, 430)) else: screen.blit(lab_credits, (359, 430)) pygame...
r detect = cDetect() # Main game loop while True: scorelabel = stdfont.render("Hits: " + str(score), True, (255, 255, 255)) healthlabel = stdfont.render("Health: " + str(playerobj.health), True, (255, 255, 255)) ...
ergy), True, (225, 225, 255)) collidelabel = stdfont_bold.render("Collision Detected!", True, (225, 0, 0)) clock.tick(FPS) timer += 1 if flash < 11: flash += 1 # ----------------------...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import datetime # Datetime ############################ dt = datetime.datetime.now() print(dt) dt = datetime.datetime(year=2018, month=8, day=30, hour=13, minute=30) print(dt) print(dt.isoformat()) # Date ################################ d = datetime.date.today() pr...
ate() print(d) d = datetime.date(year=2018, month=8, day=30) print(d) print(d.isoformat()) # Time #######################
######### t = datetime.datetime.now().time() print(t) t = datetime.time(hour=1, minute=30) print(t) print(t.isoformat())
"""AWS plugin for integration tests.""" from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os from ..util import ( ApplicationError, display, ConfigParser, ) from . import ( CloudProvider, CloudEnvironment, CloudEnvironmentConfig, ) from ..core_ci ...
def get_environment_config(self): """ :rtype: CloudEnvironmentConfig ""
" parser = ConfigParser() parser.read(self.config_path) ansible_vars = dict( resource_prefix=self.resource_prefix, ) ansible_vars.update(dict(parser.items('default'))) display.sensitive.add(ansible_vars.get('aws_secret_key')) display.sensitive.add(a...
from Sire.IO import * from Sire.MM import * from Sire.System import * from Sire.Mol import * from Sire.Maths import * from Sire.FF import * from Sire.Move import * from Sire.Units import * from Sire.Vol import * from Sire.Qt import * import os coul_cutoff = 20 * angstrom lj_cutoff = 10 * angstrom amber = Amber() (...
idff.setLJCutoff(lj_cutoff) gridff.setCoulombCutoff(coul_cutoff) gridff.setShiftElectrostatics(True) #gridff.setUseAtomisticCutoff(True) #gridff.setUseReactionField(True) cljgridff = CLJGrid() cljgridff.setCLJFunction( CLJShiftFunction(coul_cutoff,lj_cutoff) ) cljgridff.setFixedAtoms( CLJAtoms(waters.molecules()) ) cl...
0.5 * angstrom, 2 * angstrom ) print("Grid box equals %s" % cljgridff.grid()) cljboxes = CLJBoxes(cljatoms) (cnrg, ljnrg) = cljgridff.calculate(cljboxes) print("CLJGridFF: %s %s %s" % (cnrg+ljnrg, cnrg, ljnrg)) cljgridff.setUseGrid(False) (cnrg, ljnrg) = cljgridff.calculate(cljboxes) print("CLJGridFF: %s %s %s" %...
._get_size(size) return stats def list_luns_for_host(self, host): tree = self._request("/show/host-maps", host) return [int(prop.text) for prop in tree.xpath( "//PROPERTY[@name='lun']")] def _get_first_available_lun_for_host(self, host): luns = self.list_luns_fo...
portals[iscsi_ips[index]] = status return portals def get_chap_record(self, initiator_name): tree = self._request("/show/chap-records") for prop in tree.xpath("//PROPERTY[@name='initiator-name' and "
"text()='%s']" % initiator_name): chap_secret = prop.getparent().findtext("PROPERTY[@name='initiator" "-secret']") return chap_secret def create_chap_record(self, initiator_name, chap_secret): self._req...
moyal = tfd.Moyal(loc=0., scale=scale, validate_args=True) self.assertIs(scale, moyal.scale) self.evaluate(moyal.mean()) with tf.control_dependencies([scale.assign([-.01])]): with self.assertRaisesOpError('Argument `scale` must be positive.'): self.evaluate(moyal.mean()) def testMoyalLogPdf...
ution_regimes class MoyalTestStaticShape(test_util.TestCase, _MoyalTest): dtype = np.float32 use_static_shape = True @test_util.test_all_tf_execution_regimes class MoyalTestDynamicShape(test_util.TestCase, _Mo
yalTest): dtype = np.float32 use_static_shape = False @test_util.test_all_tf_execution_regimes class MoyalTestFloat64StaticShape(test_util.TestCase, _MoyalTest): dtype = np.float64 use_static_shape = True @test_util.test_all_tf_execution_regimes class MoyalTestFloat64DynamicShape(test_util.TestCase, _MoyalT...
""" UnitTests for the SimpleHTTPServer """ import mock import unittest class TestHTTPServerHandler(unittest.TestCase): """ """ def setUp(self): self.handler = m
ock.Mock() def test_do_GET(self): pass def test_do_POST(self): pass def tearDown(self): self.handler() if __name__ == "__main__": unittest.ma
in()
#a=[int(x) for x in in
put().split()] #print (a) x=5 y=10 b=[int(y) for y in input().split()] #a=[int
(x) for x in input().split()] dir(_builtins_)
a = "python" print(a*2) try: print(a[-10]) except IndexError as e: print("인덱스 범위를 초과 했습니다.") pr
int(e) print(a[0:4]) print(a[1:-2]) # -10은 hi뒤로 10칸 print("%-10sjane." % "hi") b = "Python is best choice." print(b.find("b")) print(b.find("B")) try: print(b.index("B")) except ValueError as e: print(e) c = "hi"
print(c.upper()) a = " hi" print("kk",a.lstrip()) a = " hi " print(a.strip())
# 3rd party imports from reportlab.platypus import Image, Paragraph, PageBreak, Table, Spacer from reportlab.lib.units import cm from reportlab.lib.pagesizes import A4 # Django imports from django.conf import settings # Project imports from .arabic_reshaper import reshape from .pdf_canvas import NumberedCanvas, getAr...
= STRINGS['female'] if (gender == FEMALE) else STRINGS['male'] cover_string = STRINGS['center_book_cover'] if center_book else STRINGS['center_list_cover'] header_string = STRINGS['center_book_header'] if center_book else STRINGS['center_list_header'] # cover page center_name = reshape(center.name) ...
me_arabic) params = (STRINGS['subconstituency_name'], center.subconstituency.id, subconstituency_name) subconstituency = template % params center_info = { 'gender': '%s: %s' % (STRINGS['gender'], mf_string), 'number': '%s: %d' % (STRINGS['center_number'], center.center_id), 'name': ...
from .analysis import * from
.toolbox import * from . import ut
ils
"""Utilities for extracting common archive formats""" import zipfile import tarfile import os import shutil import posixpath import contextlib from distutils.errors import DistutilsError if "__PEX_UNVENDORED__" in __import__("os").environ: from pkg_resources import ensure_directory # vendor:skip else: from pex.t...
o any chowning! tarobj.chown = lambda *args: None for member in tarobj: name = member.name # don't extract absolute paths or ones with .. in them if not name.startswith('/') and '..' not in name.split('/'): prelim_dst = os.path.join(extract_dir, *name....
) # resolve any links and to extract the link targets as normal # files while member is not None and (member.islnk() or member.issym()): linkpath = member.linkname if member.issym(): base = posixpath.dirname...
# coding: utf-8 # These tests are taken from astropy, as with the astrodynamics.constant.Constant # class. It retains the original license (see licenses/ASTROPY_LICENSE.txt) from __future__ import absolute_import, division, print_function import copy import astropy.units as u from astropy.units import Quantity impor...
parser to run. assert not isinstance(val.unit, u.UnrecognizedUnit) def test_copy(): copied = copy.deepcopy(J2) assert copied == J2 copied = copy.copy(J2) assert copied == J2 def test_view(): """Check that Constant and Quantity views can be taken.""" x = J2 x2 = x.view(Consta...
lank assert x2.uncertainty assert x2.name == x.name assert x2.reference == x.reference assert x2.unit == x.unit q1 = x.view(Quantity) assert q1 == x assert q1.value == x.value assert type(q1) is Quantity assert not hasattr(q1, 'reference') q2 = Quantity(x) assert q2 == x ...
# coding: utf-8 # # Query `apiso:ServiceType` # In[43]: from owslib.csw import CatalogueServiceWeb from owslib import fes import numpy as np # The GetCaps request for these services looks like this: # http://catalog.data.gov/csw-all/csw?SERVICE=CSW&VERSION=2.0.2&REQUEST=GetCapabilities # In[56]: endpoint =...
records.keys()): print csw.records[rec].title # Now let's print out the references (service endpoints) to see what types of services are available # In[48]: choice=np.random.choice(list(csw.records.keys())) print(csw.records[choice].title) csw.records[choice].references # In[49]: csw.records[choice].xml #...
AWST" and "experimental" and that have an "opendap" service available. # # We should get the same number of records, as all COAWST records have OPeNDAP service endpoints. If we get no records, something is wrong with the CSW server. # In[50]: val = 'OPeNDAP' filter3 = fes.PropertyIsLike(propertyname='apiso:Servic...
from __future__ import unicode_literals import json from django.utils import six from kgb import SpyAgency from reviewboard.hostingsvcs.github import GitHub from reviewboard.hostingsvcs.models import HostingServiceAccount from reviewboard.hostingsvcs.repository import RemoteRepository from reviewboard.hostingsvcs.ut...
get_remote_repository_list_url(account) # # HTTP GET tests # def setup_basic_get_test(self, user, with_local_site, local_site_name, populate_items): account = HostingServiceAccount.objects.create( service_name='github', username='bob', ...
local_site_name), data=json.dumps({ 'authorization': { 'token': '123', }, })) service = account.service remote_repositories = [ RemoteRepository(service, repository_id='123', ...
-attributes, too-many-public-methods # pylint: disable=abstract-method class SonosDevice(MediaPlayerDevice): """Representation of a Sonos device.""" # pylint: disable=too-many-arguments def __init__(self, hass, player): """Initialize the Sonos device.""" from soco.snapshot import Snapshot ...
ate( reversed(duration.split(':'))))
media_image_url = trackinfo.get('album_art', None) media_artist = trackinfo.get('artist', None) media_album_name = trackinfo.get('album', None) media_title = trackinfo.get('title', None) if media_image_url in ('', 'NOT_IMPLEMENTED', None): ...
#!/usr/bin/python # -*- coding: utf-8 -*- # thumbor imaging service # https://github.com/thumbor/thumbor/wiki # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2011 globo.com thumbor@googlegroups.com from shutil import which from unittest.mock import patch from urllib...
clude("Vary") expect(response.headers["Vary"]).to_include("Accept")
expect(response.body).to_be_webp() @patch("thumbor.handlers.Context") @gen_test async def test_can_auto_convert_unsafe_jpeg_from_result_storage( self, context_mock ): context_mock.return_value = self.context self.context.request = self.get_request(accepts_webp=True) r...
#!/usr/bin/env python import os import sys import string import random def id_generator(size=6, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) kernels = { 'aes-aes' : 'gf_alog,gf_log,gf_mulinv,rj_sbox,rj_xtime,aes_subBytes,aes_addRoundKey,aes_addRoundKey...
directory, bench, source): if not 'TRACER_HOME' in os.environ: raise Exception('Set TRACER_HOME directory as an environment variable') if not 'MACH_HOME' in os.environ: raise Exception('Set MACH_HOME directory as an environment variable') #id = id_generator() os.chdir(directory) obj = source + '.ll...
]=kernels[bench] test = os.getenv('MACH_HOME')+'/common/harness.c' test_obj = source + '_test.llvm' source_file = source + '.c' #for key in os.environ.keys(): # print "%30s %s" % (key,os.environ[key]) print directory print '======================================================================' com...
import Linked_List import sys import random def split_list(lst, a, b): if lst.length % 2 == 1: first_length = (lst.length / 2) + 1 else: first_length = lst.length / 2 list_iterator = lst.head count = 0 while count < first_length: a.append(list_iterator.data) list_i...
t "\nSplitted List B:" b.print_list() # Performance # ------------ # # * Speed # The algorithm traverses the original list once and constructs # both the list. The list construction operation (append) can be implemented with # O(1) complexity. In a nutshell, the time complexity of this algorithm is # O(N). # # Ideal t...
s algorithm? # O(1). It's all about changing the pointers. However, the limiting factor is # traversing the list, which is a linear operation. # # * Memory # 2N. Where N is the memory required to store the original list.
'ABCDEFGHIJKLMNOPQRSTUVWXYZ' r'[\]^_`' 'abcdefghijklmnopqrstuvwxyz' '{|}~') upper: str = (''' !"#$%&'()*+,-./''' '0123456789' ':;<=>?@' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' r'[\]^_`' 'ABCDEFGHIJKLMNOPQRSTUVW...
ld_italic: FormatText = _createAsciiTo( 'to_serif_bold_italic', serifBoldItalic) to_sanserif: FormatText = _createAsciiTo('to_sanserif', sanSerif) to_sanseri
f_bold: FormatText = _createAsciiTo('to_sanserif_bold', sanSerifBold) to_sanserif_italic: FormatText = _createAsciiTo( 'to_sanserif_italic', sanSerifItalic) to_sanserif_bold_italic: FormatText = _createAsciiTo( 'to_sanserif_bold_italic', sanSerifBoldItalic) to_script: FormatText = _createAsciiTo('to_script', sc...