prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
from .formSubmission import FormSubmission from django.contrib.auth.models import User from django.db import models from django.template.defaultfilters import slugify class Log(models.Model): """ Form Submission Log Database Model Attributes: * owner - user submitting the message * submission - ...
ss Meta: db_table = "form_log" ordering = ("timestamp",) @property def extension(self):
return self.file.name.split(".")[-1] @property def content_type(self): if self.extension == "pdf": return "application/pdf" if self.extension == "txt": return "text/plain" if self.extension == "png": return "image/png" if self.extensio...
"""Utilities for working with data structures. Version Added: 2.1 """ from __future__ import unicode_literals from collections import OrderedDict from django_evolution.compat import six def filter_dup_list_items(items): """Return list items with duplicates filtered out. The order of items will be pre...
(type(dest[key]), key)) merge_dicts(dest[key], value) else:
raise TypeError( 'Key "%s" was not an expected type (found %r) ' 'when merging dictionaries.' % (key, type(value))) else: dest[key] = value
# -*- coding: utf-8 -*- ''' Copyright (c) 2015 Heidelberg University Library Distributed under the GNU GPL
v3. For full terms see the file LICENSE.md ''' from ompannouncements import Announcements def index(): a = Announcements(myconf, db, locale) news_l
ist = a.create_announcement_list() return locals()
def __init__(self, display: str, xauthority: str): env = dict(os.environ) if display: env[DISPLAY] = display if xauthority: env[XAUTHORITY] = xauthority self.env = env def apply(self, profile: Profile): """ Apply given profile by calling x...
Returns list of outputs with some properties missing (only name and status are guaranteed) """ outputs = [] items = self._xrandr
(self.QUERY_KEY) items = self._group_query_result(items) logger.debug("Detected total %d outputs", len(items)) crtcs = self._get_verbose_fields('CRTC') for i in items: o = self._parse_xrandr_connection(i) o.crtc = int(crtcs[o.name]) if o.name in crtcs and len(crt...
from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() from builtins import * import json import bson.json_util as bju import emission.core.get_database as...
pen(fn), object_hook = b
ju.object_hook) for i, entry in enumerate(entries): entry["user_id"] = override_uuid if not args.retain: del entry["_id"] if args.verbose is not None and i % args.verbose == 0: print("About to save %s" % entry) tsdb.save(entry)
".jpg" not in lvl1_url.text.lower()) and ( ".mp4" not in lvl1_url.text.lower()) and ( ".mp3" not in lvl1_url.text.lower()) and ( ".txt" not in lvl1_url.text.lower()) and ( ".png" not in lvl1_url.text.lower()) and ( ...
.lower()
) and ( ".bak" not in lvl1_url.text.lower()) and ( ".woff" not in lvl1_url.text.lower()) and ( "javascript:" not in lvl1_url.text.lower()) and ( "tel:" not in lvl1_url.text.lower()) and ( "mailto:" not in lvl1_url.t...
places)) ) if hasattr(obj, 'plot'): if obj.plot is not None: raise ValueError("object to be added already has 'plot' attribute set") obj.plot = self self.renderers.append(obj) if place is not 'center': getattr(self, place).append...
. This function will take care of creating and configurinf a Glyph object, and then add it to the plot's list of renderers. Args: source (DataSource) : a data source for the glyphs to all use glyph (Glyph) : the glyph to add to the Plot Keyword Arguments: ...
glyph : Glyph ''' if glyph is not None: source = source_or_glyph else: source, glyph = ColumnDataSource(), source_or_glyph if not isinstance(source, DataSource): raise ValueError("'source' argument to add_glyph() must be DataSource subclass") ...
import unittest from locust.util.timespan import parse_timespan from locust.util.rounding import proper_round class TestParseTimespan(unittest.TestCase): def test_parse_timespan_invalid_values(self): self.assertRaises(ValueError, parse_timespan, None) self.assertRaises(ValueError, parse_timespan, ...
ses(ValueError, parse_timespan, "q") def test_parse_timespan(self): self.assertEqual(7, parse_timespan("7")) self.assertEqual(7, parse_timespan("7s")) self.assertEqual(60, parse_timespan("1m")) self.assertEqual(7200, parse_timespan("2h")) self.assertEqual(3787, parse_tim...
tEqual(5, proper_round(5.499999999)) self.assertEqual(2, proper_round(2.05)) self.assertEqual(3, proper_round(3.05)) def test_rounding_up(self): self.assertEqual(2, proper_round(1.5)) self.assertEqual(3, proper_round(2.5)) self.assertEqual(4, proper_round(3.5)) self....
import socket import sys def set_keepalive(sock, interval=1, probes=5): sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, interval) if hasattr(socket, 'TCP_KEEPCNT'): sock.setsockopt(sock
et.SOL_TCP, socket.TCP_KEEPCNT, probes) if hasattr(socket, 'TCP_KEEPIDLE'): sock.setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE, interval) if hasattr(socket, 'TCP_KEEPINTVL'): sock.setsockopt(socket.SOL_TCP, socket.TCP_KEEPINTVL, interval) s = socket.s
ocket() s.bind(('', 0)) print s.getsockname() set_keepalive(s) s.listen(1) while True: csock, addr = s.accept() set_keepalive(csock) print csock.recv(512)
# -*- coding: utf-8 -*- # Copyright (c) Vispy Development Team. All Rights Reserved. # Distributed under the (new) BSD License. See LICENSE.txt for more info. """ A
PI Issues to work out: - MatrixTransform and STTransform both have 'scale' and 'translate' attributes, but the
y are used in very different ways. It would be nice to keep this consistent, but how? - Need a transform.map_rect function that returns the bounding rectangle of a rect after transformation. Non-linear transforms might need to work harder at this, but we can provide a default implementation that work...
import unittest from flumine import config class ConfigTest(unittest.TestCase): def test_init(self): self.assertFalse(config.simulated) self.assertTrue(config.simulated_strategy_isolation) self.assertIsInstance(config.customer_strategy_ref, str) self.assertIsInstance(config.proces...
lse(config.raise_errors) self.assertEqual(config.max_execution_workers, 32) self.assertFal
se(config.async_place_orders) self.assertEqual(config.place_latency, 0.120) self.assertEqual(config.cancel_latency, 0.170) self.assertEqual(config.update_latency, 0.150) self.assertEqual(config.replace_latency, 0.280) self.assertEqual(config.order_sep, "-") self.assertEqu...
import numpy import math def mkRamp(*args): ''' mkRamp(SIZE, DIRECTION, SLOPE, INTERCEPT, ORIGIN) Compute a matrix of dimension SIZE (a [Y X] 2-vector, or a scalar) containing samples of a ramp function, with given gradient DIRECTION (radians, CW from X-axis, default = 0), SLOPE (per pixel...
t is required") exit(1) else: sz = args[0] if isinstance(sz,
(int)): sz = (sz, sz) elif not isinstance(sz, (tuple)): print("first argument must be a two element tuple or an integer") exit(1) # OPTIONAL args: if len(args) > 1: direction = args[1] else: direction = 0 if len(args) > 2: slope = a...
from subprocess import * import gzip import string import os import time import ApplePythonReporter class ApplePythonReport: vendorId = YOUR_VENDOR_ID userId = 'YOUR_ITUNES_CONNECT_ACCOUNT_MAIL' password = 'ITUNES_CONNECT_PASSWORD' account = 'ACCOUNT_ID' mode = 'Robot.XML' dateType = 'Daily' ...
extract needed values (cancellations and new subscribers) def FetchSubscriptionEventData(self, date): fileName = 'Subscription_Event_'+self.vendorId+'_' + date + '.txt' attempts = 0 while not os.path.isfile(fileName): if(attem
pts >= self.maxAttempts): break attempts += 1 time.sleep(1) if os.path.isfile(fileName): print 'Fetching SubscriptionEvents..' with open(fileName, 'rb') as inF: text = inF.read().splitlines() for row in text[1:]: ...
ht scale = min(max_width/ float(input_width), max_height/float(input_height) ) scale_width = int(input_width*scale) scale_height = int(input_height*scale) padding_ofs_x = (max_width - scale_width)//2 padding_ofs_y = ...
",
help = "encoding profile for video [default: 1080p_36_23.97]")
import numpy as np def extrapolate(xs_name): """Extrapolate cross section based on thermal salt expansion feedback. Extrapolates cross section data at 900 K to 1500 K at 50 K intervals based on the thermal salt expansion feedback formula from [1]. Writes the extrapolated data back into the .txt cross...
Returns ------- None References ---------- [1] Tiberga et al., "Results from a multi-physics nurmerical benchmark for codes dedicated to molten salt fast reactors," Annals of Nuclear Energy, vol. 142, July 2020, 107428. """ rho_900 = 2.0e3 # Density at 900 K [kg m-3] ...
ion coeff [K-1] input_file = "benchmark_" + xs_name + ".txt" # Setup temperature values to extrapolate to temp = np.linspace(950, 1500, 12) # Read cross section data at 900K f = open(input_file, 'r+') lines = f.readlines() data_900 = list(lines[0].split()) f.close() # Setup space ...
#!/usr/bin/env python3 # Copyright (c) 2022 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test logic for setting nMaxTipAge on command line. Nodes don't consider themselves out of "initial block do...
lockchaininfo()['initialblockdownload'], False) def run_test(self): self.log.info("Test IBD with maximum tip age of 24 hours (default).") self.test_maxtipage(DEFAULT_MAX_TIP_AGE, set_parameter=False) for hours in [20, 10, 5, 2, 1]: maxtipage = h
ours * 60 * 60 self.log.info(f"Test IBD with maximum tip age of {hours} hours (-maxtipage={maxtipage}).") self.test_maxtipage(maxtipage) if __name__ == '__main__': MaxTipAgeTest().main()
import pytest from dateutil.parser import parse from django import forms from adhocracy4.forms.fields import DateTimeField class DateT
imeForm(forms.Form): date = DateTimeField(
time_format='%H:%M', required=False, require_all_fields=False, ) @pytest.mark.django_db def test_datetimefield_valid(user): data = {'date_0': '2023-01-01', 'date_1': '12:30'} form = DateTimeForm(data=data) assert form.is_valid() assert form.cleaned_data['date'] == \ parse('...
se. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # Li...
ntext, id=1): if id == "777": raise exception.ShareTypeNotFound(share_type_id=id) return stub_share_type(int(id)) def return_share_types_get_by_name(context, name): if name == "777": raise exception.ShareTypeNotFoundByName(share_type_name=name) return stub_share_type(int(name.split("_"...
controller = types.ShareTypesController() self.mock_object(policy, 'check_policy', mock.Mock(return_value=True)) @ddt.data(True, False) def test_share_types_index(self, admin): self.mock_object(share_types, 'get_all_types', return_share_types_ge...
# Copyright 2018-present Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
ckage_depths.update([len(components)]) for component in components: self._component_generator.add_string_sample(component) for i, name in enumerate(components): prefix = components[:i] dir_entries[tuple(prefix)].add(name) for base_path, nam...
s in build_file_entries.items(): self._build_file_sizes.update([len(names)]) for path, entries in dir_entries.items(): self._sizes_by_depth[len(path)].update([len(entries)]) def add_package_file_sample(self, package_path, relative_path): components = self._split_path_into_co...
x0c6\x94\xf3Q\x11\x02\x01\x1a\x02\n\x0c\n\xffL\x00\x10\x05\x04\x1c\x1df\x9a\xa0', b'\x04>\x0c\x02\x01\x04\x01\x93\x0c6\x94\xf3Q\x00\xa2', b'\x04>\x1d\x02\x01\x00\x01\x95|\xedj^V\x11\x02\x01\x1a\x02\n\x0c\n\xffL\x00\x10\x05\x13\x18}\xdf\x0c\xa7', b'\x04>\x0c\x02\x01\x04\x01\x95|\xedj^V\x00\xa7', b'\x04>(...
3\x18}\xdf\x0c\xa4', b'\x04>\x0c\x02\x01\x04\x01\x95|\xedj^V\x00\xa4', b'\x04>+\x02\x01\x03\x01\xbb5z\xa0\xabY\x1f\x1e\xffL\x00\x07\x19\x01\x02 \x0bU\x8f\x00\x00\x00\xe7p\xdc\xa2\x0fO\x8c\xc6.\xf3\xac\x07\xab\xc1\xf1\x06\xac', b'\x04>\x1e\x02\x01\x00\x01W\xc32c!K\x12\x02\x01\x1a\x02\n\x0c\x0b\xffL\x00\x10\x...
x02\x01\x1a\x02\n\x0c\n\xffL\x00\x10\x05\x01\x18N\xa5\xcb\xaa', b'\x04>(\x02\x01\x03\x00k\xa0\xd0.\x04\xf8\x1c\x1b\xffu\x00B\x04\x01\x80\xac\xf8\xd0\x00\xa0k\xfa\x04.\xd0\xa0j\x01\x17@\x00\x00\x00\x00\xa0\x04', b'\x04>\x1a\x02\x01\x00\x01\x07\xbb\xd8!p\\\x0e\x02\x01\x06\n\xffL\x00\x10\x05\x01\x10\xfd\xf3\xc6\xa...
from __future__ import absolute_import from __future__ import division from __future__ import print_function try: import torch except ImportError: pass # soft dep from ray.rllib.models.action_dist import ActionDistribution from ray.rllib.utils.annotations import override class TorchDistributionWrapper(Acti...
verride(ActionDistribution) def kl(self, other): return torch.distributions.kl.kl_divergence(self.dist, other) @override(ActionDistribution) def sample(self): return self.dist.sample() class
TorchCategorical(TorchDistributionWrapper): """Wrapper class for PyTorch Categorical distribution.""" @override(ActionDistribution) def __init__(self, inputs): self.dist = torch.distributions.categorical.Categorical(logits=inputs) class TorchDiagGaussian(TorchDistributionWrapper): """Wrapper ...
# Copyright (c)
2015, Matt Layman """Tests for tappy""" from tap.tests.testcase import Te
stCase # NOQA
dule: lemur.auth.views :platform: Unix :copyright: (c) 2015 by Netflix Inc., see AUTHORS for more :license: Apache, see LICENSE for more details. .. moduleauthor:: Kevin Glisson <kglisson@netflix.com> """ import jwt import base64 import requests from flask import g, Blueprint, current_app from flask.ext.r...
d=True, location='json') self.reqparse.add_argument('password', type=str, required=True, location='json') args = self.reqparse.parse_args() if '@' in args['username']: user = user_service.get_by_email(arg
s['username']) else: user = user_service.get_by_username(args['username']) if user and user.check_password(args['password']): # Tell Flask-Principal the identity changed identity_changed.send(current_app._get_current_object(), identi...
""" pluginconf.d configuration file - Files ======================================= Shared mappers for parsing and extracting data from ``/etc/yum/pluginconf.d/*.conf`` files. Parsers contained in this module are: PluginConfD - files ``/etc/yum/pluginconf.d/*.conf`` ---------------------------------------------------...
True >>> conf.get("main", "enabled") '0' >>> conf.getint("main", "timeout") 120 >>> conf.getboolean("main", "enabled") False >>> conf.get("test", "test_multiline_config") 'http://example.com/repos/test/ http://mirror_e
xample.com/repos/test/' """ pass
import collections class Solution: def numSimilarGroups(self, A): UF = {} for i in range(len(A)): UF[i] = i def find(x): if x != UF[x]: UF[x] = find(UF[x]) return UF[x] def union(x, y): UF.setdefault(x, x) UF.setdefault(...
return s1[i+1:] == s2[i+1:] N, W = len(A), len(A[0]) if N < W*W: for i in range(len(A)): UF[i] = i for i in range(len(A)): for j in range(i+1, len(A)): if matc
h(A[i], A[j]): union(i, j) else: d = collections.defaultdict(set) for idx, w in enumerate(A): lw = list(w) for i in range(W): for j in range(i+1, W): lw[i], lw[j] = lw[j], lw[i] ...
# -*- coding: utf-8 -*- from queue.producer import Producer from queue.consumer import Consumer from queue.bloom_fil
ter import Bl
oomFilter class Dytt: def main(): for i in range(15): # Producer().start() Consumer().start() if __name__ == '__main__': main()
""" Helper Methods """ import six de
f _get_key(key_or_id, key_cls): """ Helper method to get a course/usage key either from a string or a key_cls, where the key_cls (CourseKey or UsageKey) will simply be returned. """ return ( key_cls.from_string(key_or_id) if isinstanc
e(key_or_id, six.string_types) else key_or_id )
# -*- coding:utf-8 -*- import logging import warnings from flypwd.config import config wi
th warnings.catch_warnings(): warnings.simplefilter("ignore") from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_v1_5 log = logging.getLogger(__name__) def
check_key(keyfile): """ checks the RSA key file raises ValueError if not valid """ with open(keyfile, 'r') as f: return RSA.importKey(f.read(), passphrase="") def gen_key(): return RSA.generate(config.getint('keys', 'dimension')) def encrypt_with_pub(pwd, pub): cipher = PKCS...
_rd_en, mcb_rd_data, mcb_rd_empty, mcb_rd_full, mcb_rd_overflow, mcb_rd_count, mcb_rd_error): if os.system(build_cmd): raise Exception("Error running build command") return Cosimulation("vvp -m myhdl test_%s.vvp -...
rd_overflow=mcb_rd_overflow, rd_count=mcb_rd_count, rd_error=mcb_rd_error, name='port0') # DUT dut = dut_wb_mcb_32(clk, rst, current_test, ...
, wb_ack_o, wb_cyc_i, mcb_cmd_clk, mcb_cmd_en, mcb_cmd_instr, mcb_cmd_bl, mcb_cmd_byte_addr, mcb_cmd_empty, mcb_cmd_full, ...
s() def updateRadiOutBodePlots(ZarcFitWindow, value): ZarcFitWindow.updateFigs() def updateRadiOutComplexPlots(ZarcFitWindow, value): ZarcFitWindow.updateFigs() # # # Help # # # def ZarcFitHelp(ZarcFitWindow): print ("ZarcFitHelp") def AboutZarcFit(Za...
rs #### def updateSldOutLinf(ZarcFitWindow, value): Linf = 10**(value/1000.) ZarcFitWindow.SldOutLi
nf.setText("{:.2E}".format(Linf)) ZarcFitWindow.zarc.Linf = Linf # ZarcFitWindow.updateFigs() def updateSliderLinf(ZarcFitWindow, value): Linf = float(value) ZarcFitWindow.SliderLinf.setValue(int(np.log10(Linf)*1000.)) ZarcFitWindow.zarc.Linf = Linf ZarcFitW...
pend_page(self.__drives_page(), gtk.Label(_("Drives"))) if 'posix' == os.name: notebook.append_page( self.__languages_page(), gtk.Label(_("Languages"))) notebook.append_page(self.__locations_page( LOCATIONS_WHITELIST), gtk.Label(_("Whitelist"))) self.dial...
e given the option to view information about it. Then, you may manually download and
install the update.")) vbox.pack_start(cb_updates, False) updates_box = gtk.VBox() updates_box.set_border_width(10) self.cb_beta = gtk.CheckButton(_("Check for new beta releases")) self.cb_beta.set_active(options.get('check_beta')) self.cb_beta....
'sort_order': self._sort_order, }) base_qs.update(self._filters) return update_qs(self.url, base_qs) def sort(self, key, order='asc'): if not order in ('asc', 'desc'): raise ValueError("Order must be one of 'asc', 'desc'") self._sort_key = key ...
Field('Track') artists = ListField('Artist') credits = ListField('Artist', key='extraartists') labels = ListField('Label') companies = ListField('Label') def __init__(self, client, dict_): super(Release, self).__init__(client, dict_) self.data['resource
_url'] = client._base_url + '/releases/%d' % dict_['id'] @property def master(self): master_id = self.fetch('master_id') if master_id: return Master(self.client, {'id': master_id}) else: return None def __repr__(self): return '<Release %r %r>' % (sel...
#!/usr/bin/env python """ The LibVMI Library is an introspection library that simplifies access to memory in a target virtual machine or in a file containing a dump of a system's physical memory. LibVMI is based on the XenAccess Library. Copyright 2011 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000...
id
= vmi.read_32_va(next_process + pid_offset, 0) next_process = vmi.read_addr_va(next_process, 0) if (pid < 1<<16): yield pid, procname if (list_head == next_process): break def main(argv): vmi = pyvmi.init(argv[1], "complete") for pid, procname in get_processes(...
# Function to st
ack raster bands. import numpy as np from osgeo import gdal def stack_bands(filenames): """Returns a 3D array containing all band data from all files.""" bands = [] for fn in filenames: ds = gdal.Open(fn) for i in range(1, ds.RasterCount + 1): bands.append(ds.GetRasterBand(i).R...
ack(bands)
n[(idx*batch):(idx*batch+batch)]) if args.cuda: feature, target = feature.cuda(), target.cuda() logit = model(feature) loss = F.cross_entropy(logit, target) model.zero_grad() loss.backward() for layer_no, param in enumerate(model.p...
target.cuda() logit = model(feature) loss = F.cross_entropy(logit, target, size_average=False) avg_loss +=
loss.data.item() predictor = torch.exp(logit[:, 1]) / (torch.exp(logit[:, 0]) + torch.exp(logit[:, 1])) for xnum in range(1, 3): thres = round(0.2 * xnum, 1) idx_thres = (predictor > 0.5 + thres) + (predictor < 0.5 - thres) correct_part[thres] += (torch.max(logit, 1)...
the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied...
) self.logger.debug('Starting the %s
component', PROTOCOL_NAME) self.logger.warning( 'This middleware module is deprecated as of v0.11.0 in favor of ' 'keystonemiddleware.s3_token - please update your WSGI pipeline ' 'to reference the new middleware package.') self.reseller_prefix = conf.get('reseller_pr...
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from tapi_server.models.base_model_ import Model from tapi_server.models.tapi_oam_meg_ref import TapiOamMegRef # noqa: F401,E501 from tapi_server import util class T...
:param mip_local_id: The mip_local_id of this TapiOamMipRef. # noqa: E501 :type mip_local_id: str """ self.openapi_types = { 'meg_uuid': str,
'mip_local_id': str } self.attribute_map = { 'meg_uuid': 'meg-uuid', 'mip_local_id': 'mip-local-id' } self._meg_uuid = meg_uuid self._mip_local_id = mip_local_id @classmethod def from_dict(cls, dikt) -> 'TapiOamMipRef': """Returns the ...
#!/usr/bin/python import yaml import pprint import os import pdb import re import cgi import codecs import sys import cgitb cgitb.enable() if (sys.stdout.encoding is None): print >> sys.stderr, "please set python env PYTHONIOENCODING=UTF-8, example: export PYTHONIOENCODING=UTF-8, when write to stdout." ...
ceCloseBraceRegex.sub("}", syntax) syntax = spaceCloseBracketRegex.sub("]", syntax) syntax = spaceCloseBracketRegex.sub("]", syntax) return syntax def simplifySyntaxStringAddAnchors(syntax): syntax = simplifySyntaxString(syntax) for refName in names: if r...
[refName].sub("<a href=\"/documentation/syntax.php#" + refName + "\">" + refName + "</a>", syntax) return syntax def simplifySyntaxStringAddLinks(syntax): syntax = simplifySyntaxString(syntax) for refName in names: if refName == name: continue ...
en attribute on the object, so it cannot be used on objects which do not allow new attributes to be added. So this decorator must go *below* `@property`, `@classmethod`, or `@staticmethod`: ``` class Example(object): @property @do_not_generate_docs def x(self): return self._x ``` Args:...
dden attribute on the object, so it cannot be used on objects which do not allow new attributes to be added. So this decorator must go *below* `@property`, `@classmethod`, or `@staticmethod`: ``` class Example(object): @property @for_subclass_implementers def x(self): return self._x ``` ...
e to hide from the generated docs. Returns: obj """ setattr(obj, _FOR_SUBCLASS_IMPLEMENTERS, None) return obj do_not_doc_in_subclasses = for_subclass_implementers _DOC_PRIVATE = "_tf_docs_doc_private" def doc_private(obj: T) -> T: """A decorator: Generates docs for private methods/functions. For ...
#!/usr/bin/env pyth
on import os from setuptools import setup, find_packages from structure import __version__ # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to typ
e in the README file than to put a raw # string in below ... def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() # the setup setup( name='structure', version=__version__, description='An demonstration of PyPi.', # long_description=read('README'), url='https://git...
# # 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...
cept exceptions[(source, destination)] = e if exceptions: raise BeamIOError("Copy operation failed", exceptions) def rename(self, source_file_names, destination_file_names): """Rename the files at the source list to the destination list. Source and destination lists should be of the same s...
destination_file_names: List of destination_file_names for the files Raises: ``BeamIOError`` if any of the rename operations fail """ err_msg = ("source_file_names and destination_file_names should " "be equal in length") assert len(source_file_names) == len(destination_file...
####..#.##......##......##.....#..##...##.##.....#.##......##.....#.##...... # .##.....#.########.######..##.##.#..######.##......########.##.....#.########.######..########..######. # .##.....#.##.......##......##..###.......#.##......##...##..########.##.......##......##...##........## # .##.....#.##.......##........
openscrapers.modules import cleantitle from openscrapers.modules import client from openscrapers.modules import directstream from openscrapers.modules import dom_parser from openscrapers.modules import source_utils class source: def __init__(self): self.priority = 1 self.language = ['de'] ...
self.search_link = '/filme?suche=%s&type=alle' self.ajax_link = '/ajax/stream/%s' def movie(self, imdb, title, localtitle, aliases, year): try: url = self.__search_movie(imdb, year) return url if url else None except: return def tvshow(self,...
"""Support for the Hive devices.""" import logging from pyhiveapi import Pyhiveapi import voluptuous as vol from homeassistant.const import ( CONF_PASSWORD, CONF_SCAN_INTERVAL, CONF_USERNAME) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.discovery import load_platform _LOGGER = ...
Session Class.""" entities = [] core = None heating = None hotwater = None light = None sensor = None switch = None weather = None at
tributes = None def setup(hass, config): """Set up the Hive Component.""" session = HiveSession() session.core = Pyhiveapi() username = config[DOMAIN][CONF_USERNAME] password = config[DOMAIN][CONF_PASSWORD] update_interval = config[DOMAIN][CONF_SCAN_INTERVAL] devicelist = session.core.in...
import pickle from deap import tools from stats import record logbook = tools.Logbook() logbook.record(gen=0, evals=30, **record) print(logbook) gen, avg = logbook.select("gen", "avg") pickle.dump(logbook, open("logbook.pkl", "w")) # Cleaning the pickle file ... import os os.remove("logbook.pkl") logbook.header...
evals=15, **record) print(logbook.stream) from multistats import record logbook = tools.Logbook() logbook.record(gen=0, evals=30, **record) logbook.header = "gen", "evals", "fitness", "size" logbook.chapters["fitness"].header = "min", "avg", "max" logbook.chapters["size"].header = "min", "avg", "max" print(logbook...
g") import matplotlib.pyplot as plt fig, ax1 = plt.subplots() line1 = ax1.plot(gen, fit_mins, "b-", label="Minimum Fitness") ax1.set_xlabel("Generation") ax1.set_ylabel("Fitness", color="b") for tl in ax1.get_yticklabels(): tl.set_color("b") ax2 = ax1.twinx() line2 = ax2.plot(gen, size_avgs, "r-", label="Average...
def _is_edited_new(self): return self.edited is not None and self.edited.is_new def _fill(self): for i in range(self.rowcount): self.append(TestRow(self, i)) def _update_selection(self): self.updated_rows = self.selected_rows[:] def table_with_footer(): ...
.rows, table[1:]) def test_header_setting_to_none_removes_old_one(): table, header = table_with_header() table.header = None assert table.header is None eq_(len(table), 1) def test_header_stays_there_on_insert(): # Inserting another row at the top puts it below the header table, header = table...
we refresh the table's view on refresh() table = TestGUITable(1) table.refresh() table.view.check_gui_calls(['refresh']) table.view.clear_calls() table.refresh(refresh_view=False) table.view.check_gui_calls([]) def test_restore_selection(): # By default, after a refresh, selection goes on ...
from django.conf import settings from django.conf.urls.defaults import handler500, handler404, patterns, include, \ url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^admin/',
include(admin.site.urls)), url(r'^jsi18n/(?P<packages>\S+?)/$', 'django.views.i18n.javascript_
catalog'), url(r'^media/cms/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.CMS_MEDIA_ROOT, 'show_indexes': True}), url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}), url(r'^', include('cms.test_uti...
fr
om nanoplay import PayloadProtocol, ControlProtocol, Player, CustomServer
#!/usr/bin/
env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "eksi.settings") from django.core.management import execu
te_from_command_line execute_from_command_line(sys.argv)
#!/usr/bin/python # -*- coding: utf-8 -*- import email import mimetypes from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.MIMEImage import MIMEImage import smtplib from time import sleep def sendEmail(authInfo, fromAdd, toAdd, subject, plainText, htmlText): strFrom = fro...
ultipart('alternative') msgRoot.attach(msgAlternative) #设定纯文本信息 #msgText = MIMEText(plainText, 'plain', 'GB18030') msgText = MIMEText(plainText, 'plain', 'utf-8') msgA
lternative.attach(msgText) #设定HTML信息 #msgText = MIMEText(htmlText, 'html', 'GB18030') msgText = MIMEText(htmlText, 'html', 'utf-8') msgAlternative.attach(msgText) #设定内置图片信息 #fp = open('test.jpg', 'rb') #msgImage = MIMEImage(fp.read()) #fp.close() #msgImage.add_header('Content-ID', ...
bintype, template = get_params gal = Galaxy(request.param) gal.set_params(bintype=bintype, template=template) gal.set_filepaths() yield gal @pytest.fixture() def get_cube(newgalaxy, rsync): if not os.path.isfile(newgalaxy.cubepath): rsync.add('manga
cube', **newgalaxy.access_kwargs) rsync.set_stream() rsync.commit() yield newgalaxy @pytest.fixture(params=rmodes) def asurl(request): if request.param == 'full': return False elif request.param == 'url': return True @pytest.fixture() def make_paths(request, rsync, mode, ...
fullpaths = [] inputs = inputs if inputs else imagelist for plateifu in inputs: gal = Galaxy(plateifu) gal.set_params(release=release) gal.set_filepaths() if mode == 'local': path = rsync.__getattribute__(rmode)('mangaimage', **gal.access_kwargs) full...
# To change this license header, choose License Headers in Project Properties. # To change this template file, choose
Tools | Templates # and open the template in the editor.
), backend_port=dict( type='int' ), idle_timeout=dict( type='int', default=4 ), natpool_frontend_port_start=dict( type='int' ), natpool_frontend_port_end=dict( ...
backend_port=self.natpool_backend_port )] if self.natpool_protocol else None self.load_balancing_rules = [dict( name=lb_rule_name, frontend_ip_configuration=frontend_ip_name, backend_address_pool=backend_addre...
frontend_port=self.frontend_port, backend_port=self.backend_port, idle_timeout=self.idle_timeout, enable_floating_ip=False )] if self.protocol else None if load_balancer: # check update, NIE ...
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
self.network, self.subnetwork, self.preserve_instance_ip, self.zon
e) else: return ZonalManagedInstanceGroup(self.compute, self.project, self.instance_group_name, self.network, ...
# The Nexus software is licensed under the BSD 2-Clause license. # # You should have recieved a copy of this license with the software. # If you did not, you can find one at the following link. # # http://opensource.org/licenses/bsd-license.php
from core.plugins import ProtocolPlugin from core.decorators import * from cor
e.constants import * class FetchPlugin(ProtocolPlugin): commands = { "respawn": "commandRespawn", } @player_list @mod_only @only_username_command def commandRespawn(self, username, fromloc, rankoverride): "/respawn username - Mod\nRespawns the user." if u...
from .default import default import os import re class image_png(default): def __init__(self, key, stat): default.__init__(self, key, stat) self.data = {} def compile(self, prop): if not os.path.exists(prop['value']): print("Image '{}' not found.".format(prop['value'])) ...
').read()) dest_img = img.make_blob('png32') with open(dest, 'wb') as out: out.write(dest_img) return repr(dest) return rep
r(prop['value']) def stat_value(self, prop): if prop['value'] is None: return prop['value'] if os.path.exists(prop['value']): from wand.image import Image img = Image(filename=prop['value']) self.data[prop['value']] = img.size if not prop...
# -*- coding: utf-8 -*- """ Created on Sun Mar 10 10:43:53 20
19 @author: Heathro Description: Reduces a vcf file to meta section and one line for each chromosome number for testing and debugging purposes. """ # Open files to read from and write to vcfpath = open("D:/MG_GAP/Ali_w_767.vcf", "rU") testvcf = open("REDUCED_ali.vcf", "w") # Keep track of chromosome number so we c...
n get one of each temp_chrom = 0 counter = 0 for line_index, line in enumerate(vcfpath): # Found a chromosome line if line[0:8] == "sNNffold": column = line.split('\t') first_col = column[0].split('_') current_chrom = first_col[1] # Write up to 1000 lines of each chro...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """@package docstring Yowsup connector for wxpyWha (a simple wxWidgets GUI wrapper atop yowsup). Uses WhaLayer to build the Yowsup stack. This is based on code from the yowsup echo example, the yowsup cli and pywhatsapp. """ SECONDS_RECONNECT_DELAY = 10 import sys # ...
e) #not in jlguardi self.wantReconnect = True self.abortReconnectWait = queue.Queue() def setYowsupEventHandler(self, handler): interface = self.stack.getLayerInterface(WhaLayer)
interface.enventHandler = handler def sendMessage(self, outgoingMessage): interface = self.stack.getLayerInterface(WhaLayer) interface.sendMessage(outgoingMessage) def disconnect(self): interface = self.stack.getLayerInterface(WhaLayer) interface.disconnect() ...
from sqlalchemy.orm import joinedload from datetime import datetime from changes.api.base import APIView from changes.api.build_index import execute_build from changes.config import db from changes.constants import Result, Status from changes.models import Build, Job, JobStep, ItemStat class BuildRestartAPIView(API...
ild is None: return '', 404 if build.status != Status.finished: return '', 400 # ItemStat doesnt cascade by itself stat_ids
= [build.id] job_ids = [ j[0] for j in db.session.query(Job.id).filter(Job.build_id == build.id) ] if job_ids: step_ids = [ s[0] for s in db.session.query(JobStep.id).filter(JobStep.job_id.in_(job_ids)) ] ...
"""Print all records in the pickle for the specified test""" import sy
s import argparse from autocms.core import (load_configuration, load_records) def main(): """Print all records correspondin
g to test given as an argument""" parser = argparse.ArgumentParser(description='Submit one or more jobs.') parser.add_argument('testname', help='test directory') parser.add_argument('-c', '--configfile', type=str, default='autocms.cfg', help='AutoCMS configura...
# /usr/bin/env python ''' Written by Kong Xiaolu and CBIG under MIT license: https://github.com/ThomasYeoLab/CBIG/blob/master/LICENSE.md ''' import os import numpy as
np import torch import CBIG_pMFM_basic_functions as fc def CBIG_mfm_test_desikan_main(gpu_index=0): ''' This function is to implement the testing processes of mean field model. The objective function is the summation of FC correlation cost and FCD KS statistics cost. Args: gpu_index: ind...
arameters and costs on test set Returns: None ''' input_path = '../output/rsfcpc2_rsfc/validation/' output_path = '../output/rsfcpc2_rsfc/test/' if not os.path.isdir(output_path): os.makedirs(output_path) torch.cuda.set_device(gpu_index) torch.cuda.manual_seed(1) n_set...
#!/
usr/bin/env python3 # Uses the wikipedia module to define words on the command line import wikipedia import sys sys.argv.pop(0) for word in sys.argv: try: if word[0] != '-': if '-full' in sys.argv: print(wikipedia.summary(word)) else: print(wikipedia.summary(word, sentences=1)) except: print("* U...
)
import os import logging # standardize use of logging module in fs-drift def start_log(prefix, verbosity=0): log = logging.getLogger(prefix) if os.getenv('LOGLEVEL_DEBUG') != None or verbosity != 0: log.setLevel(logging.DEBUG) else: log.setLevel(logging.INFO) log_format = prefix + ' %(...
ance(h, logging.FileHandler): logger.info('changing log level of FileHandler to %s' % loglevel) h.setLevel(loglevel) if __name__ == '__main__': log = start_log('fsd_log_test') log.error('level %s', 'error') log.warn('level %s', 'warn') log.info('level %s', 'info
') log.debug('level %s', 'debug') change_loglevel(log, logging.DEBUG) log.debug('level %s', 'debug - should see this one in the log file /var/tmp/fsd.fsd_log_test.log') change_loglevel(log, logging.INFO) log.debug('level %s', 'debug - should NOT see this one there')
# DeepSpeed handles backward internally *([dict(name="backward", args=(ANY, None, None))] if not using_deepspeed else []), dict(name="Callback.on_after_backward", args=(trainer, model)), dict(name="on_after_backward"), # `manual...
e(batches): out.extend( [
dict(name="on_before_batch_transfer", args=(ANY, 0)), dict(name="transfer_batch_to_device", args=(ANY, device, 0)), dict(name="on_after_batch_transfer", args=(ANY, 0)), # TODO: `{,Callback}.on_batch_{start,end}` dict(name=f"Ca...
callable(func, 'deprecated') @functools.wraps(func) def new_func(*args, **kwargs): logging.warning( 'From %s: %s (from %s) is deprecated and will be removed ' 'after %s.\n' 'Instructions for updating:\n%s', _call_location(), decorator_utils.get_qualified_name(func),...
cstring of the function: ' (deprecated arguments)' is appended to the first line of the docstring and a deprecation notice is prepended to the rest of the docstring. Args: date: String. The date the function is scheduled to be removed. Must be ISO 8601 (YYYY-MM-DD). ins
tructions: String. Instructions on how to update code using the deprecated function. **deprecated_kwargs: The deprecated argument values. Returns: Decorated function or method. Raises: ValueError: If date is not in ISO 8601 format, or instructions are empty. """ _validate_deprecation_args(da...
__all__ = ["Transition"] class Transition(object): def __init__(self, startState, nextState, word,
suffix, marked): self.startState = startState self.nextState = nextState self.word = word self.suffix = suffix self.marked = False def similarTransitions(self, transitions): for transition in transitions: if (self.startState == transition.startState and ...
ield transition
from unittest import TestCase EXAMPLES_PATH = '../examples' SKIPPED_EXAMPLES = {472, 473, 477}
def _set_test_class(): import re from imp import load_module, find_module, PY_SOURCE from pathlib import Path def _load_module(name, file, pathname, description): try: load_module(name, file, pathname, description) finally: if file: file.close() ...
tuple) return _m sols_module_name = 'solutions' _load_module(sols_module_name, *find_module(sols_module_name, [EXAMPLES_PATH])) pat_example = re.compile(r'\d+\. .+\.py') attrs = {} for i, example_path in enumerate(Path(EXAMPLES_PATH).iterdir()): if not re.match(pat_example, examp...
# coding=utf-
8 import requests def download(url): resp = requests.get(url) # TODO add retries return resp.content, r
esp.headers
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 201
7-03
-19 02:09 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pos', '0001_initial'), ] operations = [ migrations.AddField( model_name='itemingredient', name='exclusive', ...
################################################################################ # 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...
www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions...
######################################################################## from pyflink.table import EnvironmentSettings from pyflink.testing.test_case_utils import PythonAPICompletenessTestCase, PyFlinkTestCase class EnvironmentSettingsCompletenessTests(PythonAPICompletenessTestCase, PyFlinkTestCase): """ Tes...
import logging logger = logging.getLogger(__name__) class Singleton(type): def __init__(cls, name, bases, dict): super(Singleton, cls).__init__(name, bases, dict) cls.instance = None def __call__(cls, keep=True, *args, **kwargs): logger.debug("Handle singleton instance for %s with arg...
s, kwargs)) if keep: if cls.instance is None: logger.debug("Return and keep singleton instance for %s with args (keep=%s): %s, %s" % (cls, keep, args, kwargs)) cls.instance = super(Singleton, cls).__call__(*args, **kwargs) return cls.instance ...
ug("Return cached singleton instance for %s with args (keep=%s): %s, %s" % (cls, keep, args, kwargs)) return cls.instance else: logger.debug("Return new singleton instance for %s with args (keep=%s): %s, %s" % (cls, keep, args, kwargs)) return super(Singleton, cls).__call...
from unittest import TestCase import validictory class Tes
tItems(TestCase): def test_property(self): schema = { "type": "object", "properties": { "foo": { "default": "bar" }, "baz": { "type": "integer" } } } d...
{'baz': 2} result = validictory.validate(data, schema, required_by_default=False) self.assertEqual(result, {"foo": "bar", "baz": 2}) def test_item(self): schema = { 'type': 'object', 'type': 'array', 'items': [ { 'type...
import os from airtng_flask.config import config_env_files from flask import Flask from flask_bcrypt import Bcrypt from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager db = SQL
Alchemy() bcrypt = Bcrypt() login_manager = LoginManager() def create_app(config_name='development', p_db=db, p_bcrypt=bcrypt, p_login_manager=login_manager): new_app = Flask(__name__) config_app(config_name, new_app) new_app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False p_db.init_app(new_app) ...
ig.from_object(config_env_files[config_name]) app = create_app() import airtng_flask.views
# -*- coding: utf-8 -*- """ Created on Wed Mar 2 10:56:34 2016 @author:
jmjj (Jari Juopperi, jmjj@juopperi.org)
""" from .main import *
_editor')) context.update(trans) kwargs.update(trans) record = None if model and kwargs.get('res_id'): record = request.registry[model].browse(cr, uid, kwargs.get('res_id'), context) kwargs.update(content=record and getattr(record, field) or "") return req...
tach(self, func, upload=None, url=None, disable_optimization=None, **kwargs): # the upload argument doesn't allow us to access the files if more than # one file is uploaded, as upload references the f
irst file # therefore we have to recover the files from the request object Attachments = request.registry['ir.attachment'] # registry for the attachment table uploads = [] message = None if not upload: # no image provided, storing the link and the image name name = ...
a= None, sigma= None, recovery_rate= None, market_name= None): self.time_horizon=0 self.recovery_rate = recovery_rate # initiate self.market_spread = None self.eigenval_hist_gen= None self.eigenvect_hist_gen= None self.historical_transition_matri...
n.T self.eigenval_hist_gen= eigenval_hist_gen self.eigenvect_hist_gen= eige
nvect_hist_gen def calibrate_spread(self, asset_data, AAA_AA): """ Method : calibrate_spread Function : calibrate the model on the market data of spread Parameter : 1. asset_data Type : instance of Ass...
ntime, the shared library must be installed BUILD_WITH_SYSTEM_ZLIB = os.environ.get('GRPC_PYTHON_BUILD_SYSTEM_ZLIB', False) # Export this variable to use the system installation of cares. You need to # have the header files installed (in /usr/include/) and during # runtime, the ...
LIBC_COMPATIBILITY = os.environ.get('GRPC_PYTHON_DISABLE_LIBC_COMPATIBILITY', False) # Environment variable to determine whether or not to enable coverage analysis # in Cython modules. ENABLE_CYTHON_TRACING = os.environ.get( 'GRPC_PYTHON_ENABLE_CYTHON_TRACING', False) # Environment variable specifying whether or ...
ATION_BUILD', False) def check_linker_need_libatomic(): """Test if linker on system needs libatomic.""" code_test = (b'#include <atomic>\n' + b'int main() { return std::atomic<int64_t>{}; }') cc_test = subprocess.Popen(['cc', '-x', 'c++', '-std=c++11', '-'], stdin=PIPE...
#-- # Copyright (c) 2012-2014 Net-ng. # All rights reserved. # # This software is licensed under the BSD License, as described in # the file LICENSE.txt, which you should have received as part of # this distribution. #-- import peak import datetime from nagare import presentation, security, ajax, i18n from nagare.i18...
te @peak.rules.when(ajax.py2js, (
datetime.date,)) def py2js(value, h): """Generic method to transcode a Datetime In: - ``value`` -- the datetime object - ``h`` -- the current renderer Return: - transcoded javascript """ dt = i18n.to_timezone(value) return 'new Date("%s", "%s", "%s")' % ( dt.year, dt....
port: description: - The port that the virtual listens for connections on. - When creating a new application, if this parameter is not specified, the default value of C(53) will be used. type: str default: 53 service_environment: description: - Spec...
virtual_destination: description: The destination of the virtual that was created. returned: ch
anged type: str sample: 6.7.8.9 inbound_virtual_netmask: description: The network mask of the provided inbound destination. returned: changed type: str sample: 255.255.255.0 inbound_virtual_port: description: The port the inbound virtual address listens on. returned: changed type: int sample: 80 ser...
#!/usr/bin/env python3 import os from i3_lemonbar_conf import * cwd = os.path.dirname(os.path.abspath(__file__)) lemon = "lemonbar -p -f '%s' -f '%s' -g '%s' -B '%s' -F '%s'" % (font, iconfont, geometry, color_back, color_fore) feed = "python3 -c 'import i3_lemonbar_feeder; i3_lemonbar_feeder.run()'" check_output('...
True)
from __future__ import unicode_literals from django.db import transaction from django.db import models from djang
o.contrib.auth.models import User # Create your models here. class UserProfile(models.Model): user = models.OneToOneField(User, unique=True, verbose_name=('user')) phone = models.CharField(max_length=20) USER_SOURCE = ( ('LO', 'Local'), ('WB', 'Weibo'), ('QQ', 'QQ'), ) ...
teTimeField(auto_now_add=True) last_updated_date = models.DateTimeField(auto_now=True) @transaction.atomic def createUser(self): self.user.save() self.save()
import os, unicodedata from django.utils.translation import ugettext_lazy as _ from django.core.files.storage import FileSystemStorage from django.db.models.fields.files import FileField from django.core.files.storage import default_storage from django.conf import settings from django.utils.safestring import mark_safe...
t) return mark_safe('<img src="%s" %s />' % (src, " ".join(attrs))) def thumbnail(self, obj): kwargs = {'options': self.thumbnail_options} if self.thumbnail_alt_field_name: kwargs['alt'] = getattr(
obj, self.thumbnail_alt_field_name) return self._thumb(getattr(obj, self.thumbnail_image_field_name), **kwargs) thumbnail.allow_tags = True thumbnail.short_description = _('Thumbnail') def file_cleanup(sender, **kwargs): """ File cleanup callback used to emulate the old delete behavior usin...
from d
jango.contrib.sitemaps import Sitemap from .models import BlogEntry class BlogEntrySitemap(Sitemap): changefreq = "yearly" priority = 0.6 protocol = 'https' def items(self): return BlogEntry.on_site.filter(is_visible=True) def lastmod(self, item): retu
rn item.modification
pecial_properties = ('service_notification_commands', 'host_notification_commands', 'service_notification_period', 'host_notification_period', 'service_notification_options', 'host_notification_options', 'host_notification_commands', 'contact_name'...
NTACTADDRESS4
': 'address4', 'CONTACTADDRESS5': 'address5', 'CONTACTADDRESS6': 'address6', 'CONTACTGROUPNAME': 'get_groupname', 'CONTACTGROUPNAMES': 'get_groupnames' } # For debugging purpose only (nice name) def get_name(self): try: return self.contact_name ex...
import torch from transformers import PreTrainedModel from .custom_configuration import CustomConfig, NoSuperInitConfig class CustomModel(PreTrainedModel): config_class = CustomConfig def __init__(self
, config): super().__init__(config) self.linear = torch.nn.Linear(config.hidden_size, config.hidden_size) def forward(self, x): return self.linear(x) def _init_weights(self, module): pass class NoSuperInitModel(PreTrainedModel):
config_class = NoSuperInitConfig def __init__(self, config): super().__init__(config) self.linear = torch.nn.Linear(config.attribute, config.attribute) def forward(self, x): return self.linear(x) def _init_weights(self, module): pass
import unittest try: from unittest import mock except ImportError: import mock from pi3bar.plugins.uptime import get_uptime_seconds, uptime_format, Uptime class GetUptimeSecondsTestCase(unittest.TestCase): def test(self): m = mock.mock_open(read_data='5') m.return_value.readline.return_val...
') self.assertEqual('817:00', s) class UptimeTestCase(unittest.TestCase): def test(self): plugin = Uptime() self.assertEqual('%d days %H:%M:%S up', plugin.full_format) self.assertEqual('%dd %H:%M up', plugin.short_format) @mock.
patch('pi3bar.plugins.uptime.get_uptime_seconds') def test_cycle(self, mock_get_uptime_seconds): plugin = Uptime() mock_get_uptime_seconds.return_value = 49020 plugin.cycle() self.assertEqual('0 days 13:37:00 up', plugin.full_text) self.assertEqual('0d 13:37 up', plugin.sho...
# -*- coding: utf-8 -*- import os import re try: import simplejson as json except ImportError: import json from ToolBoxAssistant.app import AppFactory from ToolBoxAssistant.helpers import get_svn_url, readfile, find_versionned_folders, yes_no, Color from ToolBoxAssistant.log import logger VERSION = '0.1' cl...
if (not os.path.exists(args.file)) or (not os.path.isfile(args.file)): logger.error('file not found: %s' % Color.GREEN+args.file+Color.END) return specs = self.load_sp
ecs(args.file) if specs is None: return self.setup_config_dir(specs['path']) rootpath = specs['path'] for app_name in specs['apps']: app_specs = specs['apps'][app_name] if not app_specs['path'].startswith(os.path.sep): app_specs['path']...
import numpy as np import random class ReplayBuffer: """ Buffer for storing values over timesteps. """ def __init__(self): """ Initializes the buffer. """ pass def batch_sample(self, batch_size): """ Randomly sample a batch of values from the buffer. """ ...
self.dones[self.current_index] = done # unstage and increment index self.staged = False self._increment_index() else: # not yet staged state and action raise IOError( 'Trying to complete unstaged insertion. Must insert action and state first.') d...
cadata.extend( ssl.PEM_cert_to_DER_cert( to_native(b_cert, errors='surrogate_or_strict') ) ) ...
ths_checked) def validate_proxy_response(self, response, valid_codes=None): ''' make sure we get back a valid code from the proxy ''' valid_codes = [200] if valid_codes is None else valid_codes try: (http_version, resp_code, msg) = re.match(br'(HTTP/\d\.\d) (\d\...
sp_code) not in valid_codes: raise Exception except Exception: raise ProxyError('Connection to proxy failed') def detect_no_proxy(self, url): ''' Detect if the 'no_proxy' environment variable is set and honor those locations. ''' env_no_proxy = os...
# -*- coding: utf-8 -*- from __future__ import unicode
_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('simsoexp', '0005_schedulingpolicy_class_name'), ] operations = [ migration
s.RemoveField( model_name='results', name='metrics', ), migrations.AddField( model_name='results', name='aborted_jobs', field=models.IntegerField(default=0), preserve_default=False, ), migrations.AddField( ...
lf.name, val) self._name = val @property def descr(self): """Array-interface compliant full description of the column. This returns a 3-tuple (name, type, shape) that can always be used in a structured array dtype definition. """ return (self.name, self.dtype.s...
Returns ------- str_vals : iterator Column values formatted as strings """ # Iterate over formatted values with no max number of lines, no column # name, no unit, and ignoring the returned header info in outs. _pformat_col_iter = self._formatter._pfo
rmat_col_iter for str_val in _pformat_col_iter(self, -1, show_name=False, show_unit=False, show_dtype=False, outs={}): yield str_val def attrs_equal(self, col): """Compare the column attributes of ``col`` to this object. The comparison a...
#!/usr/bin/env python from .util import Spec class Port(Spec): STATES = [ "listening", "closed", "open", "bound_to", "tcp", "tcp6", "udp" ] def __init__(self, portnumber): self.portnumber = portnumber self.get_state() self.state = { 'state': '...
, 'uid': uid, 'inode': inode, 'proto': proto, } def _make_sure(self, x, y): if x == y: return True else: return False def sb_listening(self, *args): if self._make_sure(self.state['state'...
is current %s not listening" % ( self.portnumber, self.state['state'] ) def sb_closed(self, *args): if self._make_sure(self.state['state'], "closed"): return True, "Port %s is closed" % self.portnumber return False, "Port %s is current %s not closed" % ( ...
import logging import warnings from collections import namedtuple logger = logging.getLogger(__name__) Field = namedtuple('Field', ('name', 'type_', 'default', 'desc', 'warn')) class Config: """配置模块 用户可以在 rc 文件中配置各个选项的值 """ def __init__(self): object.__setattr__(self, '_fields', {}) ...
if field.warn is not None: warnings.warn('Config field({}): {}'.format(name, field.warn), stacklevel=2) # TODO: 校验值类型 object.__setattr__(self,
name, value) else: logger.warning('Assign to an undeclared config key.') def deffield(self, name, type_=None, default=None, desc='', warn=None): """Define a configuration field :param str name: the field name. It SHOULD be capitalized except the field refers to a su...
f
rom sklearn2sql_heroku.tests.regression import generic as reg_gen reg_gen.test_model("XGBRegressor" , "RandomReg_500" , "db2"
)
# https://leetcode.com/problems/valid-parentheses/ class Solution(object): def isValid(self, s): "
"" :type s: str :rtype: boo
l """ if not s: return True stack = [] for i in xrange(len(s)): # if its opening it, its getting deeper so add to stack if s[i] in "([{": stack.append(s[i]) # if not it must be a closing parenth # in which case ...
import pytest from cleo.exceptions import LogicException from cleo.exceptions import ValueException from cleo.io.inputs.option import Option def test_create(): opt = Option("option") assert "option" == opt.name assert opt.shortcut is None assert opt.is_flag() assert not opt.accepts_value() a...
est_optional_value(): opt = Option("option", flag=False, requires_value=False) assert not opt.is_flag() assert opt.accepts_value() assert not opt.requires_value() assert not opt.is_list() assert opt.default is None def test_optional_value_with_default(): opt = Option("option", flag=False,...
sert not opt.requires_value() assert not opt.is_list() assert opt.default == "Default" def test_required_value(): opt = Option("option", flag=False, requires_value=True) assert not opt.is_flag() assert opt.accepts_value() assert opt.requires_value() assert not opt.is_list() assert opt...
from ctypes.util import find_library from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db.backends.sqlite3.base import ( DatabaseWrapper as SQLiteDatabaseWrapper, SQLiteCursorWrapper, ) from .client import SpatiaLiteClient from .features import DatabaseFeatures f...
tattr(settings, 'SPATIALITE_LIBRARY_PATH', find_library('spatialite')) if not self.spatialite_lib: raise ImproperlyC
onfigured('Unable to locate the SpatiaLite library. ' 'Make sure it is in your library path, or set ' 'SPATIALITE_LIBRARY_PATH in your settings.' ) super(DatabaseWrapper, self).__init__(*args, **...
# Xlib.__init__ -- glue for Xlib package # # Copyright (C) 2000-2002 Peter Liljenberg <petli@ctrl-c.liu.se> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License # as published by the Free Software Foundation; either version 2.1 # of th...
Foundation, Inc., # 59 Temple Place, # Suite 330, # Boston, MA 02111-1307 USA __version__ = (0, 31) __version_extra__ = '' __version_string__ = '.'.join(map(str, __version__)) + __version_extra__ __all__ = [ 'X', 'XK', 'Xatom', 'Xcursorfont', 'Xutil', 'display', 'error', 'rd...
# -*- coding: utf-8 -*- # # Copyright (C) 2015-2016 Bitergia # # 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 you
r option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU G...
, Boston, MA 02111-1307, USA. # # Authors: # Santiago Dueñas <sduenas@bitergia.com> # Alvaro del Castillo San Felix <acs@bitergia.com> # import logging import pickle import rq from .common import CH_PUBSUB logger = logging.getLogger(__name__) class ArthurWorker(rq.Worker): """Worker class for Arthur"...
from django.conf import settings def mask_toggle(number_
to_mask_or_unmask): return int(n
umber_to_mask_or_unmask) ^ settings.MASKING_KEY
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt import unittest import frappe from frappe.utils import cstr, flt, nowdate, random_string from erpnext.hr.doctype.employee.test_employee import make_employee from erpnext.hr.doctype.vehicle_log.vehicle_log import make_expense_claim...
_vehicle_log(self.license_plate, self.employee_id, with_services=True) expense_claim = make_expense_claim(vehicle_log.name) expenses = expense_claim.expenses[0].amount self.assertEqual(expenses, 27000) vehicle_log.cancel() frappe.delete_doc("Expense Claim", expense_claim.name) frappe.delete_doc("Vehicle L...
ense_plate": cstr(license_plate), "make": "Maruti", "model": "PCM", "employee": employee_id, "last_odometer": 5000, "acquisition_date": nowdate(), "location": "Mumbai", "chassis_no": "1234ABCD", "uom": "Litre", "vehicle_value": flt(500000) }) try: vehicle.insert() except frappe.Duplicat...