prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
from cargo.base import CargoBase, lowercase, make_id_dict class Image(CargoBase): """Python wrapper class encapsulating the metadata for a Docker Image""" def __init__(self, *args, **kw): super(Image, self).__init__(*args, **kw) @property def config(self, *args , **kw): image = make_id_dict(self._do...
): return self.config.get('image') @property def size(self): return self.config.get('size') @property def vsize(self): return self.config.get('virtualsize') @proper
ty def image_id(self): return self.config.get('id') @property def repository(self): return self.config.get('repository') @property def tag(self): return self.config.get('tag') def __repr__(self): if self.repository: return '<Image [%s:%s]>' % (self.repository, self.image_id[:12]) ...
""" Constructs a planner that is good for being kinda like a car-boat thing! """ from __future__ import division import numpy as np import numpy.linalg as npl from params import * import lqrrt ################################################# DYNAMICS magic_rudder = 6000 def dynamics(x, u, dt): """ Returns...
3:5]) ang = np.arctan2(vw[1], vw[0]) c = np.cos(x[2]) s = np.sin(x[2]) cg = np.cos(ang) sg = np.sin(ang) u[2] = magic_rudder*np.arctan2(sg*c - cg*s, cg*c + sg*s) # Actuator saturation u = B.dot(np.clip(invB.dot(u), -thrust_max, thrust_max)) # M*vdot + D*v = u and pdot = R*v x...
t = np.concatenate((R.dot(x[3:]), invM*(u - D*x[3:]))) # First-order integrate xnext = x + xdot*dt # Impose not driving backwards if xnext[3] < 0: xnext[3] = abs(x[3]) # # Impose not turning in place # xnext[5] = np.clip(np.abs(xnext[3]/velmax_pos[0]), 0, 1) * xnext[5] return xne...
ects in ", t2-t, "secs. ", (t2-t)/n, " per connect") print_() def cursors(n): c = getConnection() c.connect() print_( "Cursor: ") t = time.time() for i in range(0,n): cu = c.cursor() cu.close() t2 = time.time() c.Close() print_( n, " cursors in ", t2-t, "secs. "...
0, dataTable = "data1", operators={"pool_type": "="}, start=1, max=123) pool.Query(sql, values) t2 = time.time() pool.Close() print_( n, " queries in ", t2-t, "secs. ", (t2-t)/n, " per statement") print_() def sqlquery6(n): pool = getPool()...
print_( n, " queries in ", t2-t, "secs. ", (t2-t)/n, " per statement") print_() def createentries(n): pool = getPool() print_( "Create entries (nodb): ") t = time.time() for i in range(0,n): e=pool._GetPoolEntry(i, version=None, datatbl="data1", preload="skip", virtual=True) t2 = time...
" for e in top.childNodes: if e.nodeType == element.Node.ELEMENT_NODE: for styleref in ( (CHARTNS,u'style-name'), (DRAWNS,u'style-name'), (DRAWNS,u'text-style-name'), (PRESENTATIONNS,u'sty...
"" Section 3.1.1
: The application MUST NOT export the original identifier belonging to the application that created the document. """ for m in self.meta.childNodes[:]: if m.qname == (METANS, u'generator'): self.meta.removeChild(m) self.meta.addElement(meta.Generator(text=...
import json from DIRAC.Core.Base.Client import Client from DIRAC import S_OK, S_ERROR from DIRAC.DataManagementSystem.private.FTS3Utilities import FTS3JSONDecoder class FTS3Client(Client): """ Client code to the FTS3 service """ def __init__(self, url=None, **kwargs): """ Constructor function. """ ...
ftsStatus and error :param fileStatusDict : { fileID : { status , error, ftsGUID } } :param ftsGUID: if specified, only update the files having a matchign ftsGUID """ return self._getRPC(**kwargs).updateFileStatus(fileStatusDict, ftsGUID) def updateJobStatus(self, jobStatusDict, **kwargs): ...
param jobStatusDict : { jobID : { status , error } } """ return self._getRPC(**kwargs).updateJobStatus(jobStatusDict) def getNonFinishedOperations(self, limit=20, operationAssignmentTag="Assigned", **kwargs): """ Get all the FTS3Operations that have files in New or Failed state (reminder: Failed...
_nabucasa.google_report_state import ErrorResponse from homeassistant.components.google_assistant.const import DOMAIN as GOOGLE_DOMAIN from homeassistant.components.google_assistant.helpers import AbstractConfig from homeassistant.const import ( CLOUD_NEVER_EXPOSED_ENTITIES, ENTITY_CATEGORY_CONFIG, ENTITY_...
return len(self._store.agent_user_ids) > 0 def get_agent_user_id(self, context): """Get agent user ID making request.""" return self.agent_user_id def should_2fa(self, state): """If an entity should be checked for 2FA.""" entity_configs = self._prefs.google_entity_configs ...
y_id, {}) return not entity_config.get(PREF_DISABLE_2FA, DEFAULT_DISABLE_2FA) async def async_report_state(self, message, agent_user_id: str): """Send a state report to Google.""" try: await self._cloud.google_report_state.async_send_message(message) except ErrorResponse...
import pathlib import urllib.error import urllib.request import logging import bs4 import parmap import pandas as pd from betel import utils from betel import info_files_helpers from betel import betel_errors class PlayAppPageScraper: """A class for scraping the icons and categories from Google Play Store app...
_info_data_frame(app_id, category) info_files_helpers.add_to_data(self._info_file, app_info) def store_apps_info(self, app_ids: [str]) -> None: """Adds the specified apps to the data set by retrieving all the info needed and appending them to the list of apps (kept in _info_file). ...
url: str) -> bs4.BeautifulSoup: try: page = urllib.request.urlopen(url) soup = bs4.BeautifulSoup(page, 'html.parser') return soup except (urllib.error.HTTPError, urllib.error.URLError) as exception: raise betel_errors.AccessError("Can not open URL.", exception) def _build_app_i...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from
django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('protocoltool', '0023_auto_20161208_1723'), ] operations
= [ migrations.RenameField( model_name='basicdataset', old_name='checked', new_name='hidden', ), ]
# -*- coding: utf-8 -*- from odoo import mo
dels, fields, api from ./eqpt_equipment import EQPT_TYPES class Paddler(models.Model): _name = 'eqpt.paddler' _description = "Paddler Cycle Equipment" _description = "Cycle paddler equipment" eqpt_type = fields.Selection(selection=EQPT_TYPES, string="") eqpt_id = fields.Reference(selection='_get_e...
dels', string="Equipment") cycle_id = fields.Many2one(comodel_name='pac.cycle', string="Cycle") member_id = fields.Many2one(comodel_name='adm.asso.member', string="Member")
#!/homes/janeway/zhuww/bin/py import numpy import pyfits from pylab import * #from Pgplot import * #from ppgplot import * #import ppgplot from numpy import * class Cursor: badtimestart=[] badtimeend=[] lines = [] def __init__(self, ax): self.ax = ax #self.lx = ax.axhline(color='k') #...
estart[j] >= badtimeend[j]: print "invalid bad time interval: abandon." else: print len(start),len(s
top) for i in range(len(start)): if start[i] < badtimestart[j]: if stop[i] <= badtimestart[j]: continue else: if stop[i] <= badtimeend[j]: stop[i]=badtimestart[j] else: ...
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting model 'Participant' db.delete_table(u'pa_participant') # Removing M2M table for field us...
nKey', [], {'to': u"orm['pa.ReportingPeriod']"}) }, u'pa.profession': { 'Meta': {'object_name': 'Profession'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '60'}) },...
'Meta': {'object_name': 'ReportingPeriod'}, 'end_date': ('django.db.models.fields.DateTimeField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '120'}), 'slots_per_hou...
import re thisDict = { "path": "thisDict", "2": "2", "3": "3", "5": "5", "7": "7", "2 x 2": "{2} x {2}", "3 x 2": "{3} x {2}", "4": "{2 x 2}", "6": "{3 x 2}", "8": "{2 x 2} x {2}", "16": "{2 x 2} x {2 x 2}", "96": "{16} x {6}", "thisModel.Root": "thisModel.Root: {96}...
Root": "{anotherModel.Root}" } directory = [thisDict, thatDict, anotherDict] #When there are more than one identical key throughout dictionaries
: prioritizes current dict for now -> Later how? #Limitation: We only go through dictionaries in the order given in directory; the first key we find will be used, always #Had to add "path" field to all dictionaries to keep track of pathname -> had no way to print out the name of dictionary without using globals() = bad...
from packetbeat import BaseTest """ Tests for HTTP messages with gaps (packet loss) in them. """ class Test(BaseTest): def test_gap_in_large_file(self): """ Should recover well from losing a packet in a large file download. """ self.render_config_template( htt...
assert len(o["notes"]) == 1 assert o["notes"][0] == "Packet loss while capturing
the response"
# -*- coding: utf-8 -*- import sys def __if_number_get_string(number): converted_str =
number if i
sinstance(number, (int, float)): converted_str = str(number) return converted_str def get_string(strOrUnicode, encoding='utf-8'): strOrUnicode = __if_number_get_string(strOrUnicode) return strOrUnicode
"""Multiply two LTI objects (serial connection).""" # Convert the second argument to a transfer function. if isinstance(other, (int, float, complex, np.number)): return FRD(self.fresp * other, self.omega, smooth=(self.ifunc is not None)) else: ot...
esp : complex ndarray The frequency response of the system. If the system is SISO and squeeze is not True, the shape of the array matches the shape of omega. If the system is not SISO or squeeze is False, the first two dimensions of the array are indices for the output ...
ngle-dimensional axes are removed. """ omega_array = np.array(omega, ndmin=1) # array-like version of omega # Make sure that we are operating on a simple list if len(omega_array.shape) > 1: raise ValueError("input list must be 1D") # Make sure that frequencies are...
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Xmessage(AutotoolsPackage, XorgPackage): """xmessage displays a message or query in a wind...
7375997435d5ff4f2d50353acca') depends_on('libxaw') depend
s_on('libxt') depends_on('pkgconfig', type='build') depends_on('util-macros', type='build')
import sys
tem # Create the computer system and power it up. sys = system.System() sys.power_on()
squared Hilbert-Schmidt norm of the difference between the auto-correlation operators, in the RKHS induced by 'frame_kern', of the two time series Notes ----- Truncated version. """ assert tau <= min(T1 / 2.0, T2 / 2.0), "Too big tau" # define the truncated matrices ...
T2 - tau, T1:T1 + T2 - tau] K12 = K[:T1 - tau, T1:T1 + T2 - tau] # define the truncated matrices of the shifted series K12tau = K[tau:T1, T1 + tau:] # compute the different terms N1 = regul * np.eye(T1 - tau) - solve( (T1 - tau) * np.eye(T1 - tau) + 1.0 / regul * K1, K1, sym_pos=True) N...
2 - tau) + 1.0 / regul * K2, K2, sym_pos=True) KK12 = np.dot(np.dot(N1.T, K12), np.dot(N2, K12tau.T)) # compute the trace hsdp = 1.0 / ((regul ** 4) * (T1 - tau) * (T2 - tau)) * KK12.trace() return hsdp def hsdotprod_autocor_cyclic(K, T1, T2, tau=1, regul=1e-3): """ Compute the Hilbert-Schmidt inn...
self.transition_phase("begin") self.task(partial(setattr, self, "phase", "ready"), 3) def update(self, time_delta): """ Update the combat state. State machine is checked. General operation: * determine what phase to execute * if new phase, then run transition into new on...
eate a new list for items, possibly running/swap #sort items by speed of monster applied to #remove items from action_queue and insert them into their new location precedent = [] for action in self._action_queue: if action.technique.effect == 'heal': ...
precedent.append(action) #sort items by fastest target precedent.sort(key=attrgetter("target.speed")) for action in precedent: self._action_queue.remove(action) self._action_queue.insert(0,action) elif phase == "post action phase"...
############################################################################## # 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...
and/or modify # it under the terms of the GNU Lesser General Public
License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesse...
from locu
st import HttpLocust, TaskSet, task class UserBehavior(TaskSet): def on_start(self): """ on_start is called when a Locust start before any task is scheduled """ self.login() def login(self): # do a login here # self.client.post("/login", {"username":"ellen_key", "password":"edu...
app/category/featured/") class WebsiteUser(HttpLocust): task_set = UserBehavior min_wait=5000 max_wait=9000
from __future__ import absolute_import import redisext.backend.abc import rm.rmredis class Client(redisext.backend.abc.IClient): def __init__(self, database=None, ro
le=None): self._redis = rm.rmredis.RmRedis.get_instance(database, role) class Connection(redisext.backend.ab
c.IConnection): CLIENT = Client
mystring="40
523116" mystring=mystring
+" test" print(mystring)
import pyotherside from firebase import firebase firebase = firebase.FirebaseApplication('https://hacker-news.firebaseio.com', None) responses = [] getItemsCount = 0 eventCount = 0 itemIDs = [] def getCommentsForItem(itemID): itemID = int(itemID) itemID = str(itemID) item = firebase.get('/v0/item/'+ite...
# print(item) # print(item['kids']) for commentID in item['kids']: # print("inside loop. kid:", commentID) commentID = str(commentID) comment = firebase.get_async('/v0/item/'+commentID, None, callback=cbNewComment) def getItems(items, startID=None, count=None): if ite
ms is None and startID is None and count is None: return currentlyDownloading(True) global getItemsCount global itemIDs items = str(items) if count is None: getItemsCount = 30 else: getItemsCount = count if startID is None: itemIDs = firebase.get('/v0/'+it...
cts use the oxidation state and coordination environment to provide further properties. Attributes: Species.symbol: Elemental symbol used to retrieve data Species.name: Full name of element Species.oxidation: Oxidation state of species (signed integer) Species....
e oxidation state and coordination. self.shannon_radius = None; if radii_source=="shannon": shannon_data = data_
loader.lookup_element_shannon_radius_data(symbol); elif radii_source == "extended": shannon_data = data_loader.lookup_element_shannon_radius_data_extendedML(symbol) else: print("Data source not recognised. Please select 'shannon' or 'extended'. ") if s...
#!/usr/bin/env python import sys from os.path import normpath, join, dirname, abspath machine_file = normpath(join(dirname(abspath(__file__)), '../files/machine-images.csv')) def read_machine_file(): amis = {} with open(machine_file) as fp: for l in fp: type...
region] = ami write_machine_file(amis) def main(argv): if len(argv) == 3: print(get_ami(argv[1], argv[2])) elif len(argv) == 4: set_ami(argv[1], argv[2], argv[3]) else: print(""" Usage: Get AMI ami.py <typ
e> <region> Save AMI ami.py <type> <region> <ami> """) sys.exit(1) if __name__ == "__main__": main(sys.argv)
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( compat_str, float_or_none, int_or_none, smuggle_url, str_or_none, try_get, ) class STVPlayerIE(InfoExtractor): IE_NAME = 'stv:player' _VALID_URL = r'https?://play...
props = (self._parse_json(self._search_regex( r'<script[^>]+id="__NEXT_DATA__"[^>]*>({.+?})</script>', webpage, 'next data', default='{}'), video_id, fatal=False) or {}).get('props') or {} player_api_cache = try_get( props, lambda x: x['initialReduxState']['playe...
import random from django.test import TestCase from .models import TechType, Tech, Component # shared data across the tests types = [ { "name": "framework", "description": "to do web stuff" }, { "name": "database", "description": "to store stuff" }, { "nam...
the 2nd go = Tech(**techs[2]) # Is the 3rd django = Tech(**techs[0]) # Is the 1st sharestack = Tech(**techs[-1]) # Is the last postgres = Tech(**techs[3]) # Is the 4th # Save before adding m2m fields programming_lang.save() app.save() framework.save(...
save() # add types python.types.add(programming_lang) go.types.add(programming_lang) django.types.add(framework) sharestack.types.add(app) postgres.types.add(database) # Check types are ok in both sides for programmign languages python2 = Tech.objects.ge...
""" .. _ex-morph-surface: ============================= Morph surface source estimate ============================= This example demonstrates how to morph an individual subject's :class:`mne.SourceEstimate` to a common reference space. We achieve this using :class:`mne.SourceMorph`. Pre-computed data will be morphed ...
epicting the successful morph will be created for the spherical and inflated surface representation of ``'
fsaverage'``, overlaid with the morphed surface source estimate. References ---------- .. [1] Greve D. N., Van der Haegen L., Cai Q., Stufflebeam S., Sabuncu M. R., Fischl B., Brysbaert M. A Surface-based Analysis of Language Lateralization and Cortical Asymmetry. Journal of Cognitive Neuroscience...
# Copyright(c) 2009, Gentoo Foundation # # Licensed under the GNU General Public License, v2 # # $Header: $ """Checks timestamps and MD5 sums for files owned by a given installed package""" from __future__ import print_function __docformat__ = 'epytext' # ======= # Imports # ======= import os import sys from funct...
parse_module_options(module_opts) if not queries: print_help() sys.exit(2) first_run = True for query in (Query(x, QUERY_OPTS['is_regex']) for x in queries): if not first_run: print() matches = query.smart_find(**QUERY_OPTS) if not matches: raise errors.GentoolkitNoMatches(query, in_installed=T...
s'] ) check = VerifyContents(printer_fn=printer) check(matches) first_run = False # vim: set ts=4 sw=4 tw=79:
# Test the module type from test.test_support import verify, vereq, verbose, TestFailed from types import ModuleType as module # An uninitialized module has no __dict__ or __name__, and __doc__ is None foo = module.__new__(module) verify(foo.__dict__ is None) try: s = foo.__name__ except AttributeError: pass ...
on should not replace the __dict__ foo.bar = 42 d = foo.__dict__ foo.__init__("foo", "foodoc") vereq(foo.__name__, "foo") vereq(foo.__doc__, "foodoc") vereq(foo.bar, 42) vereq(foo.__dict__, {"__name__": "foo", "__package__": None, "__doc__": "foodoc", "bar": 42}) verify(foo.__dict__ is d)
if verbose: print "All OK"
_backend(domain), } context.update(_url_context()) if toggles.USE_FORMPLAYER_FRONTEND.enabled(domain): return render(request, "cloudcare/formplayer_home.html", context) else: return render(request, "cloudcare/cloudcare_home.html", context) class FormplayerMain(V...
self, request, *args, **kwargs): return super(FormplayerMain, self).dispatch(request, *args, **kwargs) def fetch_app(self, domain, app_id): username = self.request.couch_user.username if (toggles.CLOUDCARE_LATEST_BUILD.enabled(domain) or toggles.CLOUDCARE_LATEST_BUILD.enable...
_released_app_doc(domain, app_id) def get(self, request, domain): app_access = ApplicationAccess.get_by_domain(domain) app_ids = get_app_ids_in_domain(domain) apps = map( lambda app_id: self.fetch_app(domain, app_id), app_ids, ) apps = filter(None, a...
# -*- encoding: utf-8 -*- from abjad.tools.durationtools import Duration from abjad.tools.rhythmtreetools import RhythmTreeContainer, RhythmTreeLeaf def test_rhythmtreetools_RhythmTreeNode_duration_01(): tree = RhythmTreeContainer(preprolated_duration=1, children=[ RhythmTreeLeaf(preprolated_duration=1),...
eaf(preprolated_duration=2) ]) assert tree.duration == Duration(1) assert tree[0].duration == Duration(1, 5) assert tree[1].duration == Duration(2, 5) assert tree[1][0].duration == Duration(6, 25) assert tree[1][1].duration == Duration(4, 25) assert tree[2].duration == Duration(2, 5) t...
= Duration(1, 3) assert tree[1].duration == Duration(2, 3) assert tree[1][0].duration == Duration(2, 7) assert tree[1][1].duration == Duration(4, 21) assert tree[1][2].duration == Duration(4, 21) tree.preprolated_duration = 19 assert tree.duration == Duration(19) assert tree[0].duration ==...
import datetime from dateutil.relativedelta import relativedelta from decimal import Decimal import factory from factory.fuzzy import FuzzyDate, FuzzyInteger import random from django.contrib.auth import models as auth from django.contrib.auth.hashers import make_password from timepiece.contracts import models as con...
els as entries from timepiece import utils class User(factory.DjangoModelFactory): FACTORY_FOR = auth.User # FIXME: Some tests depend on first_name/last_name being unique. first_name = factory.Sequence(lambda n: 'Sam{0}'.format(n)) last_name = factory.Sequence(lambda
n: 'Blue{0}'.format(n)) username = factory.Sequence(lambda n: 'user{0}'.format(n)) email = factory.Sequence(lambda n: 'user{0}@example.com'.format(n)) password = factory.LazyAttribute(lambda n: make_password('password')) @factory.post_generation def permissions(self, create, extracted, **kwargs): ...
""" Base test case for the course API views. """ from django.core.urlresolvers import reverse from rest_framework.test import APITestCase from lms.djangoapps.courseware.tests.factories import StaffFactory from student.tests.factories import UserFactory from xmodule.modulestore.tests.django_utils import TEST_DATA_SPL...
ItemFactory.create( parent_location=unit3.location, category="video", ) def get_url(self, course_id): """ Helper function to create the url """ return reverse( self.view_name, kwargs={ 'course_id': course_id ...
path.basename(file)[0:-len(".ig")] + "\", \n") cf.write("};\n") cf.write("\n") cf.write("Output = \"" + ExportBuildDirectory + "/" + RbankBboxBuildDirectory + "/temp.bbox\";\n") cf.write("\n") cf.close() subprocess.call([ BuildIgBoxes ]) os.remove("build_ig_boxes.cfg") printLog(log, "") printLog(log, ">>> Build...
hborsTool, ToolSuff
ix) elif ExecTimeout == "": toolLogFail(log, ExecTimeoutTool, ToolSuffix) else: zonefiles = findFiles(log, ExportBuildDirectory + "/" + ZoneWeldBuildDirectory, "", ".zonew") for zonefile in zonefiles: zone = os.path.basename(zonefile)[0:-len(".zonew")] lr1 = ExportBuildDirectory + "/" + RbankSmoothBuildDirectory...
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.8.2 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re ...
list of Roles :return: The items of this V1alpha1RoleList. :rtype: list[V1alpha1Role] """ return self._items @items.setter def items(self, items): """ Sets the items of this V1alpha1RoleList. Items is a list of Roles :param items: The items of t...
raise ValueError("Invalid value for `items`, must not be `None`") self._items = items @property def kind(self): """ Gets the kind of this V1alpha1RoleList. Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpo...
# -*- co
ding: utf-8 -*- """ priority: HTTP/2 priority implementation for Python """ from .priority import ( # noqa Stream, PriorityTree, DeadlockError, PriorityLoop, PriorityError, Dupl
icateStreamError, MissingStreamError, TooManyStreamsError, BadWeightError, PseudoStreamError, ) __version__ = "2.0.0"
# Copyright (c) 2014-2017. Mount Sinai School of Medicine # # 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 applicabl...
express or implied. # See the License for the specific language governing permissions and # limitations under th
e License. from __future__ import print_function, division, absolute_import from .base_commandline_predictor import BaseCommandlinePredictor from .parsing import parse_netmhccons_stdout class NetMHCcons(BaseCommandlinePredictor): def __init__( self, alleles, program_name="netM...
uname = ParseFunction('uname -a > {OUT}') for group in ('disc', 'ccl', 'gh'): batch_options = 'requirements = MachineGroup == "{0}"'.format(group) uname(outputs='uname.{0}'.format(group), environment={'BATCH_OPTIONS': batch_options}) #for group in ('disc', 'ccl', 'gh'): # with
Options(batch='requirements = MachineGroup == "{0}"'.format(group))
: # uname(outputs='uname.{0}'.format(group))
# # Copyright 2019 The FATE 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 appli...
th.join(data_base, "examples/data/breast_hetero_guest.csv"), table_name=dense_data["name"], # table name namespace=dense_data["namespace"], # namespace head=1, partition=partition, ...
_sid=True) pipeline_upload.add_upload_data(file=os.path.join(data_base, "examples/data/tag_value_1000_140.csv"), table_name=tag_data["name"], namespace=tag_data["namespace"], head=0, partition=partition, ...
import _plo
tly_utils.basevalidators class ColorValidator(_plotly_utils.basevalidators.ColorValidator): def __init__( self, plotly_name="color", parent_name="surface.hoverlabel.font", **kwargs ): super(ColorValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name...
), edit_type=kwargs.pop("edit_type", "none"), **kwargs )
k.dataframe as dd except ImportError: dd = None # Python3 compatibility import types if sys.version_info.major == 3: basestring = str unicode = str generator_types = (zip, range, types.GeneratorType) else: basestring = basestring unicode = unicode from itertools import izip generator_ty...
, doc=""" Whether the first letter should be converted to upperca
se. Note, this will only be applied to ASCII characters in order to make sure paths aren't confused with method names.""") eliminations = param.List(['extended', 'accent', 'small', 'letter', 'sign', 'digit', 'latin', 'greek', 'arabic-indic', 'with', 'dollar'], doc=""" ...
# -*- coding: utf-8 -*- # # UnitX documentation build configuration file, created by # sphinx-quickstart on Thu Mar 17 05:31:20 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All...
as "system message" paragraphs in the built documents. #keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False #html_theme = 'default' #Good! #html_theme = 'sphinx_rtd_theme' #Good! #html_theme = 'agogo' #Good! #html_theme = 'nature' #Pretty Good! ...
bar': True} # Short title used e.g. for <title> HTML tags. html_short_title = '%s Documentation' % release # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%b %d, %Y' # Path to find HTML templates. templates_path = ['tools/templ...
# -*- coding: utf-8 -*- from al
lauth.socialaccount.tests import create_oauth_tests from allauth.tests import MockedResponse from allauth.socialaccount.providers import registry from .provider import FlickrProvider class FlickrTests(create_oauth_tests(registry.by_id(FlickrProvider.id))): def get_mocked_response(self): # return ...
}} """), # noqa MockedResponse(200, r""" {"person": {"username": {"_content": "pennersr"}, "photosurl": {"_content": "http://www.flickr.com/photos/12345678@N00/"}, "nsid": "12345678@N00", "path_alias": null, "photos": {"count": {"_content": 0}, "firstdatetaken": {"_content": null}, "views": {"_content": "2...
ns.KeyError # becomes: # kombu.exceptions.KeyError # # Your best choice is to upgrade to Python 2.6, # as while the pure pickle version has worse performance, # it is the only safe option for older Python versions. pickle = pypickle else: pickle = cpickle or pypickle bytes_type =...
e: content_encoding = 'binary' return content_type, content_encoding, payload def register_json(): """Register a encoder/decoder for JSON serialization.""" from anyjson import s
erialize as json_serialize from anyjson import deserialize as json_deserialize registry.register('json', json_serialize, json_deserialize, content_type='application/json', content_encodi
# -*- coding: utf
-8 -*- """ BlueButtonDev.appmgmt FILE: utils Created: 12/2/15 8:09 PM """ __author__ = 'Mark Scrimshire:@ekivemark' from django.contrib import messages from .models import DEVELOPER_ROLE_CHOICES from django.conf import settings def Choice_D
isplay(role): """ Receive a string of the current role Lookup in DEVELOPER_ROLE_CHOICES Return the String :param role: :return: """ result = dict(DEVELOPER_ROLE_CHOICES).get(role) if role == "None": return else: return result class MessageMixin(object): """...
''' Created on J
un 15, 2014 @author: geraldine ''' import socket import fcntl import struct def get_ip_address(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl(s.fileno(),0x8915,struct.pack('256s', ifname[:15]))[
20:24])
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from app.openapi_server.models.base_model_ import Model from openapi_server import util class GithubRepositorypermissions(Model): """NOTE: This class is auto gene...
itorypermissions. # noqa: E501 :type admin: bool :param push: The push of this GithubRepositorypermissions. # noqa: E501 :type push: bool :param pull: The pull of this GithubRepositorypermissions. # noqa: E501 :type pull: bool :param _class: The _class of this GithubRe...
:type _class: str """ self.swagger_types = { 'admin': bool, 'push': bool, 'pull': bool, '_class': str } self.attribute_map = { 'admin': 'admin', 'push': 'push', 'pull': 'pull', '_class': '_cl...
# -*- codi
ng: utf-8 -*- class CrazyBoxError(Exception): """ The base class for custom exceptions raised by crazybox. """ pass class DockerError(Exception): """ An error occurred with the underlying
docker system. """ pass
r_create_if_message_sid_no_exception(self): message_1 = message_recipe.make(sid='test') message_2, created = Message.get_or_create(message_sid='test') self.assertFalse(created) self.assertEqual(message_1, message_2) self.assertEqual(1, Message.objects.all().count()) def test...
rt_not_called() @patch('django_twilio_sms.models.unsubscribe_signal') def test_check_for_subscription_message_if_body_in_unsubscribe( self, unsubscribe_signal): from_phone_number = phone_number_recipe.make(unsubscribed=False) message = message_recipe.make( body='STOP', ...
) message.check_for_subscription_message() self.assertTrue(message.from_phone_number.unsubscribed) unsubscribe_signal.send_robust.assert_called_once_with( sender=Message, message=message, unsubscribed=True ) def test_check_for_subscription_message_if_body_in_sub...
#-*- coding: utf-8 -*- import numpy as np from sklearn.cluster import AgglomerativeClustering as sk_AgglomerativeClustering from sklearn.externals.joblib import Memory from .clustering
import Clustering class AgglomerativeClustering(Clustering): """docstring for AgglomerativeClustering.""" def __init__(self, data, n_cluster
s = 2, affinity = 'euclidean', memory = Memory(cachedir = None), connectivity = None, compute_full_tree = 'auto', linkage = 'ward', pooling_func = np.mean): super(AgglomerativeClustering, self).__init__() self.data = data self.n_clusters = n_clu...
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-09-15 15:10 from __future__ import unicode_literals from django.db import migrations, models i
mport django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('silo', '0028_auto_20170913_0206'), ] operations = [ migrations.AlterField( model_name='silo', name='workflowlevel1', field=models.ForeignKey(blank=True, null=True...
r', name='workflowlevel1', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='silo.WorkflowLevel1'), ), migrations.AlterField( model_name='workflowlevel2', name='activity_id', field=models.IntegerFie...
from os import path rosalind_id = path.basename(__
file__).split('.').pop(0) dataset = "../datasets/rosalind_{}.txt".format(rosalind_id) data = open(dataset, 'r').read().s
plitlines()
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from django import forms from django.utils.translation import ugettext_lazy ...
ion information in a serializable form """ cleaned_data = super(CategoryLinksConfigForm, self).clean() categories = cleaned_data.get("categories", []) cleaned_data["categories"] = [category.pk for category in categories if hasattr(category, "pk")] return cleaned_data class Cate...
template_name = "shuup/xtheme/plugins/category_links.jinja" editor_form_class = CategoryLinksConfigForm fields = [ ("title", TranslatableField(label=_("Title"), required=False, initial="")), ("show_all_categories", forms.BooleanField( label=_("Show all categories"), re...
import json import os import re from django import http from django.conf import settings from django.db.transaction import non_atomic_requests from django.http import HttpResponse, HttpResponseBadRequest from django.shortcuts import render from django.utils.encoding import iri_to_uri from django.views.decorators.cache...
ext/plain") @non_atomic_requests def contribute(request): path = os.path.join(settings.ROOT, 'contribute.json') return HttpResponse(open(path, 'rb'), content_type='application/json') @non_atomic_requests def handler403(request): if request.path_info.startswith('/api/'): # Pass over to
handler403 view in api if api was targeted. return api.views.handler403(request) else: return render(request, 'amo/403.html', status=403) @non_atomic_requests def handler404(request): if request.path_info.startswith('/api/'): # Pass over to handler404 view in api if api was targeted. ...
, and Jinja templates don't know their filename, the only thing needed by :class:`AppyBuildMethod <lino.mixins.printable.AppyBuildMethod>`. One possibility might be to write a special Jinja Template class... Die Reihenfolge in :setting:`INSTALLED_APPS` sollte sein: zuerst `django.contrib.*`, dann ``lino``,...
parent) #~ add_config_dir(app_mod) LOCAL_CONFIG_DIR = None #~ if settings.SITE.project_dir != settings.SITE.source_dir: if settings.SITE.is_local_project_dir: p = join(settings.SITE.project_dir,SUBDIR_NAME) if isdir(p): LOCAL_CONFIG_DIR = ConfigDir(p,True) config_dirs.append(...
everse() config_dirs = tuple(config_dirs) #~ logger.debug('config_dirs:\n%s', '\n'.join([repr(cd) for cd in config_dirs])) #~ for app_name in settings.INSTALLED_APPS: #~ app = import_module(app_name) #~ fn = getattr(app,'__file__',None) #~ if fn is not None: #~ pth = join(dirname(fn),'con...
import unittest
from literoticapi.author import * class testStory(unittest.TestCase): def setUp(self): self.author = Author(868670)
def testGetSeriesAndNonSeries(self): assert len(self.author.get_stories()) >= 132 if __name__ == "__main__": unittest.main()
# Copyright (c) 2008 Simplistix Ltd # See license.txt for license details. from mock import Mock from testfixtures import wrap,compare from unittest import TestCase,TestSuite,makeSuite class TestWrap(TestCase): def test_wrapping(self): m = Mock() @wrap(m.before,m.after) def test_functio...
compare(m.method_calls,[]) compare(test_function(),'something') compare(m.method_calls,[ ('before1', (), {}), ('before2', (), {}), ('test_function', (1,2), {}), ('after2', (), {}), ('after1', (), {}), ]) def test_mul
tiple_wrappers_only_want_first_return(self): m = Mock() m.before1.return_value=1 @wrap(m.before2,m.after2) @wrap(m.before1,m.after1) def test_function(r1): m.test_function(r1) return 'something' compare(m.method_calls,[]) compare...
OperandLookupTable = b''.join([ b'\x81\xbd\x81\xbd\x41\x7d\x00\x00\x81\xbd\x81\xbd\x41\x7d\x00\
x00' b'\x81\xbd\x81\xbd\x41\x7d\x00\x00\x81\xbd\x81\xbd\x41\x7d\x00\x00' b'\x81\xbd\x81\xbd\x41\x7d\x00\x00\x81\xbd\x81\xbd\x41\x7d\x00\x00' b'\x81\xbd\x81\xbd\x41\x7d\x00\x00\x81\xbd\x81\xbd\x41\x7d\x00\x00' b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' b'\x00\x00\x0
0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' b'\x00\x00\xbf\x82\x00\x00\x00\x00\x7d\xfd\x41\xc1\x00\x00\x00\x00' b'\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41' b'\xc1\xfd\xc1\xc1\x81\xbd\x81\xbd\x81\xbd\x81\xbd\x82\x88\x82\xbd' b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x7...
# -*- coding: UTF-8 -*- import requests from bs4 import BeautifulSoup, UnicodeDammit import time import os import re import log import tools class Get(object): # timeout, retry_interval -> seconds def __init__(self, url='', timeout=5, retry=5, retry_interval=2, proxies={}, headers={}, download_file=None, sav...
TENT_TYPE_REVERSE[i.strip()] except Exception as e: pass except Exception as e:
self.log.error('cannot get suffix, url[%s], headers [%s]' % (url, str(r.headers))) # ๅฐ่ฏ•่Žทๅ–Content-Disposition๏ผŒๅนถไปฅ่ฏฅ้กนไธญ็š„ๆ–‡ไปถๅๅŠๅŽ็ผ€ไผ˜ๅ…ˆ try: content_disposition = r.headers['Content-Disposition'] fntmp = re.findall(r'filename=[\"\'](.*?)[\"\']', content_disposition)[0] po...
from __future__ import absolute_import, division, unicode_literals from django.utils.translation import ugettext_lazy as _ from django.utils.safestring import mark_safe from debug_toolbar.panels import Panel from debug_toolbar import settings as dt_settings import cProfile from pstats import Stats from colorsys impor...
e(func_list, root, dt_settings.CONFIG['PROFILER_MAX_DEPTH'], root.stats[3] /
8) self.record_stats({'func_list': func_list})
""" For types associated with installation schemes. For a general overview of available schemes and their context, see https://docs.python.org/3/install/index.html#alternate-installation. """ SCHEME_KEYS = ['platlib', 'purelib', 'headers', 'scripts', 'data'] class Scheme: """A Scheme holds paths which are used...
__slots__ = SCHEME_KEYS def __init__( self, platlib, # type: str purelib, # type: str headers, # type: str scripts, # type: str data, # type: str ): self.platlib = pl
atlib self.purelib = purelib self.headers = headers self.scripts = scripts self.data = data
# David Tsui 2.9.2016 # Human Languages and Technologies # Dr. Rebecca Hwa from Ngrams import * #TRAIN train_file = open("tokenized_train
.txt","r") train_str = train_file.read(); tri = Trigram(1) print "Begin training vocabulary----------------------" tri.trainVocabulary(train_str) #tri.printVocabulary() #Takes in questions for development dev_file = open("Holmes.lm_format.questions.txt") output_file = open("holmes_output.txt","w+") print "Begin c
alculating perplexity----------------------" for i, line in enumerate(dev_file): #Clean text by removing all quotations line = line[:-1] exclude = set(string.punctuation) s = ''.join(ch for ch in line if ch not in exclude) s = s.lower() #Lambda factors lu = .3 lb = .3 lt = .4 print "Question %d complete" %(i)...
# -*- coding: UTF-8 -*- # Copyright 2009-2019 Rumma & Ko Ltd # License: GNU Affero General Public License v3 (see file COPYING for details) from django.conf import settings from django.utils.encoding import force_str from django.db import models from django.utils.translation import gettext_lazy as _ from django.apps...
database_connected.send(sender) #~ dd.database_connected.send(sender,**kw) from django.test.signals import setting_changed from lino.core.signals import testcase_setup setting_changed.connect(my_handler) testcase_setup.connect(my_handler) dd.connection_created.connect(my_handler) models.signals.post_migrate.connec...
nfigs(dd.Table): model = 'system.SiteConfig' required_roles = dd.login_required(SiteStaff) # default_action = actions.ShowDetail() #~ has_navigator = False hide_navigator = True allow_delete = False # hide_top_toolbar = True #~ can_delete = perms.never detail_layout = dd.DetailLayou...
# # Author: Martin Sandve Alnes # Date: 2008-10-03 # from ufl import (Coefficient, Tes
tFunction, TrialFunction, VectorElement, dot, dx, grad, triangle) element = VectorElement("Lagrange", triangle
, 1) u = TrialFunction(element) v = TestFunction(element) w = Coefficient(element) a = dot(dot(w, grad(u)), v) * dx
from __future__ import unicode_literals import logging import os import tornado.ioloop import tornado.web from .webhandler.DownloadHandler import DownloadHandler from .webhandler.OverviewHandler import OverviewHandler from .webhandler.GradingPreviewMailsHandler import GradingPreviewMailsHandler from .webhandler.Grad...
Handler import TaskDeleteHandler from .webhandler.TaskEditHandler import TaskEditHandler from .webhandler.UpdateDatabaseHandler import UpdateDatabaseHandler from .webhandler.contact import ( ContactCraftHandler, ContactSendHandler, ContactAllCraftHandler, ContactAllSendHandler, ) from .webhandler.merge ...
tem' def __init__(self, config, handlers): super(KorrekturApp, self).__init__(handlers) for handler in handlers: handler[1].config = config self.config = config @property def users(self): return self.config('korrektoren') def web_main(config): try: ...
#!/usr/local/bin/python3.5 """ Author: Maximilian Golub Simulate the chain parsing and replying to a http request to test the ESP8266 """ import serial import socket import re import traceback import sys import subprocess import time PORT = '/dev/cu.usbserial-FTZ29WSV' #OSX #PORT = 'COM3' # If on windows BAUD = 1152...
parse(data, serial_socket) pound_count = 0 data = '' else: if start: data += decode_data except UnicodeDecodeError: pass def parse(data, serial_...
Looks for the Host header, trys to get the host+port with regex. :param data: :param serial_socket: :return: """ try: host_match = re.search('Host: (\S+)\\r\\n', data) if host_match: host = host_match.group(1) #print(host) try: hos...
from django.core.management.base import BaseCommand from webserver.codemanagement
.models import TeamClient import os import re import tempfile import subprocess class Command(BaseCommand): help = 'Attempts to update all repositories by pulling from bases' def handle(self, *args, **options): # A list of tuples: (message, repo_directory, s
tderr) errors = [] # A list of tuples: (team name, git-show output) successes = [] for client in TeamClient.objects.all(): directory = tempfile.mkdtemp(prefix='GRETA_UPDATE') repo_name = os.path.basename(client.repository.name) repo_name = repo_name....
from office365.
sharepoint.base_entity_collection import BaseEntityCollection from office365.sharepoint.files.checkedOutFile import CheckedOutFile class CheckedOutFileCollection(BaseEntityCollection): def __init__(self, context, resource_path=None): super(CheckedOu
tFileCollection, self).__init__(context, CheckedOutFile, resource_path)
import csv from meerkat_abacus.config import config def data_types(param_config=config): with open(param_config.config_directory + param_config.country_config["types_file"], "r", encoding='utf-8', errors="replace") as f: DATA_TYPES_DICT = [_dict for _dict in csv.DictReader(f)]...
rm_name, param_config=config): return [data_type for data_type in data_types(param_config=param_config) if form_name == data_type['form']] DATA_TYPES_DICT = da
ta_types()
import logging from time import strftime def closed(): logging.info('Headlights process stopped') de
f criterr(errortext): logging.critical('A fatal error occured :: ' + errortext) exit() def err(errortext): logging.error('A
n error occured :: ' + errortext) def warn(errortext): logging.warning(errortext) def inf(errortext): logging.info(errortext) def debug(errortext): logging.debug(errortext)
""" File: <Sin2_plus_cos2> Copyright (c) 2016 <Lauren Graziani> License: MIT <debugging a program> """ """ # a from math import sin, cos #need to import pi from math x = pi/4 1_val = math.sin^2(x) + math.cos^2(x) #can't start a variable with a number, powers are written by ** print 1_VAL """ # a debugged from m...
after 2, get rid of m/s s = v0.t + 0,5.a.t**2 #v0.t should be v0*2, change comma to period and periods to * print s """ # b debugged v0 = 3 t = 1 a = 2 ** 2 s = v
0*t + 0.5*a*t**2 print s #c """ a = 3,3 b = 5,3 a2 = a**2 b2 = b**2 eq1_sum = a2 + 2ab + b2 eq2_sum = a2 - (2ab + b2 eq1_pow = (a+b)**2 eq2_pow = (a-b)**2 print 'First equation: %g = %g', % (eq1_sum, eq1_pow) print 'Second equation: %h = %h', % (eq2_pow, eq2_pow) # c debugged (cofused???) a = 3,3 b=5,3 a2 = a**2 b2 =...
class A(object): def __init__(self, bar): self._x = 1 ; self._bar = bar def __getX(self): return self._x def __setX(self, x): self._x = x def __delX(self): pass x1 = property(__getX, __setX, __delX, "doc of x1") x2 = property(__setX) # should return x3 = property(__getX, __getX) # shou...
(self, x): self._x = x @foo.deleter # ignored in 2.5 def foo(self): pass @property def boo(self): return self._x @boo.setter def boo1(self, x): # ignored in 2.5 self._x = x @boo.deleter def boo2(self): # ignored in 2,5 pass @property def moo(self): # should return pas...
# unknown qoo is reported in ref inspection def qoo(self, v): self._x = v @property def bar(self): return None class Ghostbusters(object): def __call__(self): return "Who do you call?" gb = Ghostbusters() class B(object): x = property(gb) # pass y = property(Ghostbusters()) # pass z = pro...
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-09-25 12:24 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('venue', '0005_auto_20170916_0701'), ] operations = [ migrations.CreateModel...
e='EventCalander', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(default='Default Event', max_length=200)), ('calander_id', models.TextField()), ('active', ...
mat = np.reshape(col_inv_var.repeat(no), (nx_cutout,no) ) b_mat = phi * col_inv_var_mat c_mat = np.dot(phi.T,phi*col_inv_var_mat) pixel_weights = np.dot(b_mat,np.linalg.inv(c_mat)) extracted_flux[i,j,:] = np.dot(col_data,pixel_weights) extr...
lor approximation for #the matrix inverse. #(Bolton and Schlegel 2009, equation 10) #D = diag(C) #A = D^{-1/2} (C-D) D^{-1/2}, so C = D^{1/2}(I + A)D^{1/2} #Then if Q = (I - 1/2 A + 3/8 A^2) D^{-1/2} #... then C^{-1} = QQ, approximately. ...
#data independence is returned. extracted_sig = np.sqrt(extracted_var) a_diag_p1 = extracted_covar/extracted_sig[:,:-1,:]/extracted_sig[:,1:,:] # a_diag_m1 = extracted_covar/extracted_var[:,1:,:] Q_diag = np.ones( (nm,ny,no) ) Q_diag[:,:-1,:] += 3/8....
class IPParseError(Exc
eption): pass class ZoneNotFoundError(Exception): pass class InvalidInputError(Exception): p
ass
# -*- coding: utf-8 -*- # code for console Encoding difference. Dont' mind on it import sys import imp imp.reload(sys) try: sys.setdefaultencoding('UTF8') except Exception as E: pass import testValue from popbill import CashbillService, PopbillException cashbillService = CashbillService(testValue.LinkID, te...
.UseStaticIP = testValue.UseStaticIP cashbillService.UseLocalTimeYN = testValue.UseLocalTimeYN ''' ์—ฐ๋™ํšŒ์›์˜ ํ˜„๊ธˆ์˜์ˆ˜์ฆ API ์„œ๋น„์Šค ๊ณผ๊ธˆ์ •๋ณด๋ฅผ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค. - https://docs.popbill.com/cashbill/python/api#GetChargeInfo ''' try:
print("=" * 15 + " ๊ณผ๊ธˆ์ •๋ณด ํ™•์ธ " + "=" * 15) # ํŒ๋นŒํšŒ์› ์‚ฌ์—…์ž๋ฒˆํ˜ธ CorpNum = testValue.testCorpNum # ํŒ๋นŒํšŒ์› ์•„์ด๋”” UserID = testValue.testUserID response = cashbillService.getChargeInfo(CorpNum, UserID) print(" unitCost (๋ฐœํ–‰๋‹จ๊ฐ€) : %s" % response.unitCost) print(" chargeMethod (๊ณผ๊ธˆ์œ ํ˜•) : %s" % response.charge...
# fmt: off """ This file holds code for a Distributed Pytorch + Tune page in the docs. FIXME: We switched our code formatter from YAPF to Black. Check if we can enable code formatting on this module and update the paragraph below. See issue #21318. It ignores yapf because yapf doesn't allow comments right after code ...
help="Enables GPU training") parser.add_argument( "--lr-reduce-on-plateau", action="store_true", default=False, help="If enabled, use a ReduceLROnPlateau scheduler. If not set, " "no scheduler is used." ) args, _ = parser.parse_known_args() if args.
smoke_test: ray.init(num_cpus=3) elif args.server_address: ray.init(f"ray://{args.server_address}") else: ray.init(address=args.address) CustomTrainingOperator = get_custom_training_operator( args.lr_reduce_on_plateau) if not args.lr_reduce_on_plateau: tune_examp...
"""Test MLPerf logging. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import sys import pytest from tensorflow_models.mlperf.models.rough.mlp_log import mlp_log class TestMLPerfLog(object): """Test mlperf log.""" def test_format(...
if __name__ == '__main__': sys.exit(pytest.
main())
# Copyright ยฉ 2020, Joseph Berry, Rico Tabor (opendrop.dev@gmail.com) # OpenDrop is released under the GNU GPL License. You are free to # modify and distribute the code, but always under the same license # (i.e. you cannot make commercial derivatives). # # If you use this software in your research, please cite the foll...
y, OpenDrop: Open-source software for pendant drop # tensiometry & contact angle measurements, submitted to the Journal of # Open Source Software # # These citations help us not onl
y to understand who is using and # developing OpenDrop, and for what purpose, but also to justify # continued development of this code and other open source resources. # # OpenDrop is distributed WITHOUT ANY WARRANTY; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR # PURPOSE. See the...
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-06-13 03:20 from __future__ import unicode_literals import django.contrib.postgres.fields.ranges from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('climate_data',...
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True))
, ('updated', models.DateTimeField(auto_now=True)), ('time_range', django.contrib.postgres.fields.ranges.DateTimeRangeField()), ('comment', models.TextField()), ('sensor', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='clima...
#coding:utf-8 bind = 'unix:/var/run/gunicorn.sock' workers = 4 # you should change thi
s user = 'root' # maybe you like error loglevel = 'debug' errorlog = '-' logfile = '/var/log/gunicorn/debug.log' timeout = 300 secure_scheme_headers = { 'X-SCHEME': 'https', } x_forwarded_for_header = 'X-FORWARDED-FOR
'
"""Entities: things that exist in the world.""" from .gfx import GraphicsGroup from .util import ir class Entity (objec
t): """A thing that exists in the world. Entity() Currently, an entity is just a container of graphics. """ def __init__ (self): #: The :class:`World <engine.game.World>` this entity is in. This is #: set by the world when the entity is added or removed. self.world = None #:...
csGroup>` #: containing the entity's graphics, with ``x=0``, ``y=0``. self.graphics = GraphicsGroup() def added (self): """Called whenever the entity is added to a world. This is called after :attr:`world` has been changed to the new world. """ pass def update (self): ...
# -*- encoding:utf8 -*- from model.parser import Parser from model.googledrive import GoogleDrive from plugins.base.responsebase import IResponseBase class Drive(IResponseBase): def hear_regex(self, **kwargs): lists = Parser().get_keyword_list(expand=True) print("Lists : %r" % lists) ret...
ent_id': Parser().get_do
cument_id(kwargs.get('text')), 'export_type': 'text/plain' } return GoogleDrive().retrieve_content(**drive_kwargs)
import pyaf.Bench.TS_datasets as tsds import tests.arti
ficial.process_artificial_dataset as art art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "MovingMedian", cycle_length = 0, transform = "Logit", sigma = 0.0, exog
_count = 100, ar_order = 0);
from __future__ import absolute_import import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ers_backend.settings') from django.conf import settings app = Celery('dataset_manager', backend="redis://localhost") # Usin...
_task(self): print(
'Request: {0!r}'.format(self.request))
# -*- coding: utf-8 -*- """ MIT License Copyright (c) 2017 - 2018 FrostLuma 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, c...
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 ACTIO
N OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from mousey import commands from mousey.utils import haste, Timer class Context(commands.Context): """ Provides context while executing commands and utility methods. ...
from django import template from django.conf import settings from django.core.urlresolvers import reverse register = template.Library() ### Show an update instance ### @register.inclusion_tag("feeds/update.html", takes_context=True) def show_update(context, update): feed_object = update.feed.feed_object ...
iption.startswith('edit'): icon = 'edit' update_line = update.action_description % feed_object_link elif update.action_description.startswith('added to the discussion'): icon = 'comment' update_line = update.action_description % feed_object_link elif update.action_descripti...
' update_object_link = '<a class="update-object" href="%s">%s</a>' % (update_object.get_absolute_url(), update_object) update_line = update.action_description % (update_object_link, feed_object_link) elif update.action_description.startswith('started following'): icon = 'follow' ...
# # 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 us...
by applicable law or agreed to in writing, software # distri
buted 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. # from __future__ import print_function # $example on$ from pyspark.ml.feature i...
# -*- coding: utf-8 -*- """T
he scwapi pac
kage"""
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2018-02-15 23:16 from __future__ import unicode_literals from django.db import migrations import image_cropping.fields class Migration(migrations.Migration): dependencies = [ ('gardens', '0023_auto_20180215_2314'), ] operations = [ ...
'image', '600x400', adapt_rotation=False, allow_fullsize=F
alse, free_crop=False, help_text=None, hide_image_field=False, size_warning=False, verbose_name='large'), ), ]
# Imports operators dynamically while keeping the package API clean, # abstracting the underlying modules from airflow.utils.helpers import import_module_attrs as _import_module_attrs # These need to be integrated first as other operators depend on them _import_module_attrs(globals(), { 'check_operator': [ ...
'], 'pig_operator': ['PigOperator'], 'presto_check_operator': [ 'PrestoCheckOperator', 'PrestoValueCheckOperator', 'PrestoIntervalCheckOperator',
], 'dagrun_operator': ['TriggerDagRunOperator'], 'dummy_operator': ['DummyOperator'], 'email_operator': ['EmailOperator'], 'hive_to_samba_operator': ['Hive2SambaOperator'], 'mysql_operator': ['MySqlOperator'], 'sqlite_operator': ['SqliteOperator'], 'mysql_to_hive': ['MySqlToHiveTransfer...
#!/usr/bin/python import ldns pkt = ldns.ldns_pkt.new_query_frm_str("www.goog
le.com",ldns.LDNS_RR_TYPE_ANY, ldns.LDNS_RR_CLASS_IN, ldns.LDNS_QR | ldns.LDNS_AA) rra = ldns.ldns_rr.new_frm_str("www.google.com. IN A 192.168.1.1",300) rrb = ldn
s.ldns_rr.new_frm_str("www.google.com. IN TXT Some\ Description",300) list = ldns.ldns_rr_list() if (rra): list.push_rr(rra) if (rrb): list.push_rr(rrb) pkt.push_rr_list(ldns.LDNS_SECTION_ANSWER, list) print("Packet:") print(pkt)
from util import hash256, hash_pks from copy import deepcopy class AggregationInfo: """ AggregationInfo represents information of how a tree of aggregate signatures was created. Different tress will result in different signatures, due to exponentiations required for security. An AggregationInfo i...
self.tree[(self.message_hashes[i], self.public_keys[i])]) for i in range(len(self.public_keys))] combined_other = [(other.message_hashes[i], other.public_keys[i], other.tree[(other.message_h
ashes[i], other.public_keys[i])]) for i in range(len(other.public_keys))] for i in range(max(len(combined), len(combined_other))): if i == len(combined): return True if i == len(combined_other): ...
sel
f.LOG.debug( 'Marking token %s as unauthorized in memcache', token_id) self._cache_store(token_id, 'invalid') def cert_file_missing(self, proc_output, file_name): return (file_name in proc_output and not os.path.exists(file_name)) def verify_uuid_token(self,
user_token, retry=True): """Authenticate user token with keystone. :param user_token: user's token id :param retry: flag that forces the middleware to retry user authentication when an indeterminate response is received. Optional. :return toke...
stdout() as output: call_command('dumpdata', 'tests', format='class') self.assertTrue(output.getvalue().startswith('# -*- coding: utf-8 -*-\n')) def test_correct_imports_in_output(self): band = Band.objects.create(name="Brutallica") musician = Musician.objects.create(name="L...
os", date_joined="1982-01-01") roadie = Roadie.objects.create(name="Ciggy Tardust") roadie.hauls_for.add(band) with string_stdout() as output: call_command('dumpdata', 'tests', format='class', exclude=[ 'tests.Party', 'tests.Politician'])
lines = output.getvalue().split('\n') fixture_import, model_imports = lines[3], lines[4] self.assertEqual(fixture_import, "from class_fixtures.models import Fixture") self.assertEqual(model_imports, "from tests.models import Band, Membership, Musician, Roadie") def test_correct...
## Absolute locat
ion where all raw files are RAWDATA_DIR = '/home/cmb-06/as/skchoudh/dna/Oct_
10_2016_HuR_Human_Mouse_Liver/rna-seq/Penalva_L_08182016/human' ## Output directory OUT_DIR = '/staging/as/skchoudh/Oct_10_2016_HuR_Human_Mouse_Liver/RNA-Seq_human' ## Absolute location to 're-ribo/scripts' directory SRC_DIR = '/home/cmb-panasas2/skchoudh/github_projects/re-ribo/scripts' ## Genome fasta location ...
countTestCases() return cases def addTest(self, test): if not hasattr(test, '__call__'): raise TypeError('{} is not callable'.format(repr(test))) if isinstance(test, type) and issubclass(test, ( case.TestCase, TestSuite)): raise TypeError('TestCases and Tes...
return try: module = sys.modules[previousModule] except KeyError: return tearDownModule = getattr(module, 'tearDownModule', None) if tearDownModule is not None: _call_if_exists(result, '_setupStdout') try: ...
ult): raise errorName = 'tearDownModule (%s)' % previousModule self._addClassOrModuleLevelException(result, e, errorName) finally: _call_if_exists(result, '_restoreStdout') return def _tear...
""" This module is deprecated -- use scipy.linalg.blas instead """ from __future__ import division, print_function, absolute_import try: from ._cblas imp
ort * except ImportError: empty_module =
True import numpy as _np @_np.deprecate(old_name="scipy.linalg.cblas", new_name="scipy.linalg.blas") def _deprecate(): pass _deprecate()