prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
from django.test import TestCase from django.contrib.auth import authenticate from userena.backends import UserenaAuthenticationBackend from userena.utils import get_user_model User = get_user_model() class UserenaAuthenticationBackendTests(TestCase): """ Test the ``UserenaAuthenticationBackend`` which shou...
f test_get_user(self): """ Test that the user is returned """ user = self.backend.get_user(1) self.failUnlessEqual(user.username, 'john') # None should be returned when false id. user = s
elf.backend.get_user(99) self.failIf(user)
# # genxmlif, Release 0.9.0 # file: __init__.py # # genxmlif package file # # history: # 2005-04-25 rl created # # Copyright (c) 2005-2008 by Roland Leuthe. All rights reserved. # # -------------------------------------------------------------------- # The generic XML interface is # # Copyright (c) 200...
NY # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE # OF THIS SOFTWARE. # --------------------------------------------
------------------------ ###################################################################### # PUBLIC DEFINITIONS ###################################################################### # supported XML interfaces XMLIF_MINIDOM = "XMLIF_MINIDOM" XMLIF_4DOM = "XMLIF_4DOM" XMLIF_ELEMENTTREE =...
ls.command.install_data import install_data from distutils.command.build import build from distutils.dep_util import newer from distutils.log import warn, info, error from distutils.errors import DistutilsFileError import glob import os import sys import subprocess import platform from terminatorlib.version import APP...
t subprocess import sys errno = subprocess.call(['bash', 'run_tests']) raise SystemExit(errno) if platform.system() in ['FreeBSD', 'OpenBSD']: man_dir = 'man' else: man_dir = 's
hare/man' setup(name=APP_NAME, version=APP_VERSION, description='Terminator, the robot future of terminals', author='Chris Jones', author_email='cmsj@tenshu.net', url='https://gnometerminator.blogspot.com/p/introduction.html', license='GNU GPL v2', scripts=['terminator', 'remo...
# ---------------------------------------------------------------- # Copyright 2016 Cisco Systems # # 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 t
he 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 License for the specific langua...
import subprocess import math def launch(script_name, num_partitions, num_machines, pos, coordinator, machine_name, debug=False): if num_machines > num_partitions: raise RuntimeError("Need mor
e partitions than machine") machine_size = int(math.ceil(float(num_partitions) / float(num_machines))) start = pos * machine_size end = min((pos+1)*machine_size, num_partitions) processes = [] #launch content server processes for i in range(start, end): print("Starting processs #" +...
me, coordinator, machine_name, str(i)]) processes.append(p) while processes: p = processes.pop() p.wait()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # frc_rekt documentation build configuration file, created by # sphinx-quickstart on Wed Apr 12 00:19:47 2017. # # 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 # a...
s.path.abspath(os.path.join(os.path.dirname(__file__), os.pa
th.pardir))) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or you...
: disable def test_conversion_from_keras_v2(self): x = [-1, 0, 1, 2, 3, 4] y = [-3, -1, 1, 3, 5, 7] model = tf.keras.models.Sequential( [tf.keras.layers.Dense(units=1, input_shape=[1])]) model.compile(optimizer='sgd', loss='mean_squared_error') model.fit(x, y, epochs=1) converter = li...
rt_and_check_location_info(self, converter, expected_type, expected_sources=None): # The custom attribute of ConverterError can't be accessed with # assertRaises so use try-catch block instead. ...
tIsNone(tflite_model) except ConverterError as converter_error: # pylint: disable=g-assert-in-except self.assertLen(converter_error.errors, 1) location = converter_error.errors[0].location self.assertEqual(location.type, expected_type) if expected_sources: debug_string = str(l...
# Copyright 2015-2017 Cisco Systems, Inc. # All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless req...
rning permissions and limitations # under the License. from .linkstate import LinkState # noqa from .node.local_router_id import LocalRouterID # noqa from .node.name import NodeName # noqa from .node.isisarea import ISISArea # noqa from .node.sr_capabilities import SRCapabilities # noqa from .node.sr_algori...
msd import NodeMSD # noqa from .node.nodeflags import NodeFlags # noqa from .node.opa_node_attr import OpaNodeAttr # noqa from .node.sid_or_label import SIDorLabel # noqa from .node.srlb import SRLB # noqa from .link.admingroup import AdminGroup # noqa from .link.remote_router_id import RemoteRouterID # noqa...
n the prefix header is instead compiled, and all other compilations in the project get an additional |-include path_to_compiled_header| instead. + Compiled prefix headers have the extension gch. There is one gch file for every language used in the project (c, cc, m, mm), since gch files for diff...
(empty if the plist shouldn't be preprocessed, * |extra_env| is a dict of env variables that should be exported when invoking |mac_tool copy-info-plist|. Only call thi
s for mac bundle targets. Args: product_dir: Path to the directory containing the output bundle, relative to the build directory. xcode_settings: The XcodeSettings of the current target. gyp_to_build_path: A function that converts paths relative to the current gyp file to paths ...
import time from random import random
import traceback WARN_TIME = 3600. def wait(check,timeout=None,delay=0.5, *args,**kwarg): start_time = time.time() warned = False while True: try: result = check(*args,**kwarg) break except Exception as exc: if timeo
ut and (time.time()-start_time) > timeout: raise exc #if (time.time()-start_time) > WARN_TIME and not warned: #print "wait(): warning, waiting for a long time - \n%s" % traceback.format_exc() #warned = True time.sleep( delay*...
': 'public'}), ('last_name', {'label': _('Last Name'), 'identifier': 'user.last_name', 'visibility': 'public'}), ('organization', {'label': _('Organization'), 'identifier': 'user.organization', 'visibility': 'public'}), ('make_info_public', {'label': _('Make Info Visib...
ser': user} def _small_feature_photo_url(feature): feature = feature.cast_to_subtype() if feature.is_plot: tree = feature.current_tree() i
f tree: photos = tree.photos() else: photos = MapFeaturePhoto.objects.none() else: photos = feature.photos() if len(photos) > 0: return photos[0].thumbnail.url else: return None def user(request, username): user = get_object_or_404(User, usernam...
import re import json import sqlite3 import nltk stop = nltk.corpus.stopwords.words("english") stop.append('rt') contractions = [] with open('contractions.txt', 'rb') as f: contractions = [c.strip() for c in f.readlines()] lemmatizer = nltk.stem.wordnet.WordNetLemmatizer() tokenizer = nltk.tokenize....
ut_file: for row in c.execute("SELECT tweet FROM tweets"): if first_tweet is None: first_tweet = row[0] j = json.loads(row[0]) tweet_id = j['id'] timestamp = j['timestamp_ms'] text = j['text'] text = text.lower() text = url_regex.sub('...
kens = tokenizer.tokenize(text) tokens = [] for token in all_tokens: token = lemmatizer.lemmatize(token) if token not in stop: tokens.append(token) #items = [str(id), json.dumps(text)] + [token.encode('utf8') for token in tokens] items = [...
# Copyright (c) 2013 Alon Swartz <alon@turnkeylinux.org> # # This file is part of OctoHub. # # OctoHub is free software; you can redistribute it and/or modify it under the # terms of the GNU General Public License as published by the Free Software # Foundation; either version 3 of the License, or (at your
option) any later # version.
import simplejson as json class ResponseError(Exception): """Accessible attributes: error error (AttrDict): Parsed error response """ def __init__(self, error): Exception.__init__(self, error) self.error = error def __str__(self): return json.dumps(self.error, indent=...
lename = os.path.basename(fieldfile.name) if filename.endswith('.fastq.gz') or filename.endswith('.fastq'): print('File extension for {} confirmed valid'.format(filename)) else: raise ValidationError( _('%(file)s does not end with .fastq or .fastq.gz'), params={'filename'...
name='gdcs_results') # GDCS.csv strain = models.CharField(max_length=256, default="N/A") genus = models.CharField(max_length=256, default="N/A") matches = models.CharField(max_length=256, default="N/A") meancoverage = models.CharField(max_length=128, default="N/A") passfail = models.CharField(m...
verbose_name_plural = 'Confindr Results' def __str__(self): return '{}'.format(self.sample) sample = models.ForeignKey(Sample, on_delete=models.CASCADE, related_name='confindr_results') strain = models.CharField(max_length=256, default="N/A") genera_present = models.CharField(max_length=256,...
# Copyright 2016 Open Source Robotics Foundation, 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...
ted 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 ament_flake8.main import main_with_errors def test_flake8(): rc, errors = main_with_errors(argv=[]) a...
:\n' % len(errors) + \ '\n'.join(errors)
import os from setuptools import setup, find_packages from jw2html import VERSION setup( name='JW2HTML', version=VERSION, description='JW2HTML converts an issue of the Jungle World from the website to a single HTML file to be used for epub conversion by e.g. calibre.', long_description='Alas
, there is no epub version of the Jungle World, http://jungle-world.com . Hence this little module to download the current issue and pack it into one HTML file which can then be converted to epub (using e.g. http://calibre-ebook.com). It also downloads the cover image for easy inclusion when creating the book in calib...
morkuchen/jw2html', author='marmorkuchen', author_email='marmorkuchen@kodeaffe.de', packages=find_packages(), include_package_data=True, data_files=[ ('doc', ['README.rst', 'LICENSE']), (os.path.join(os.sep, 'etc'), ['jw2html.ini',]), ], entry_points={ 'console_script...
# coding: utf8 from functools import wraps from logging import getLogger logger = getLogger(__name__) __author__ = 'marcos.costa' class request_logger(object): def __init__(self, method=None): self.method = method def __call__(self, func): method = self.method if method is None: ...
ps(func) def wrapper(instance, request, *args, **kwargs): response = func(instance, request, *args, **kwargs) msg = ("\nCalled method: {method}\nrequest: {request}" "\nresponse: {response}").format(method=method, requ...
response return wrapper
from werkzeug.local import LocalProxy from . import extension_access def extension_access_proxy(name):
return LocalProxy(lambda: getattr(extension_access, name, None)) # Mostly for backwards compatibility cache = extension_access_proxy("cache") mongo = extension_access_proxy("mongo") mai
l = extension_access_proxy("mail") admin = extension_access_proxy("admin") rest_api = extension_access_proxy("rest_api") markdown = extension_access_proxy("markdown") assets = extension_access_proxy("assets")
import AI.pad import AI.state class Character: def __init__(self, pad_path): self.action_list = [] self.last_action = 0 self.pad = AI.pad.Pad(pad_path) self.state = AI.state.State() #Set False to enable character selection self.test_mode = True self.sm = AI....
f advance(self): while self.action_list: wait, func, args = self.action_list[0] if self.state.frame - self.last_action < wait: return else: self.action_list.pop(0)
if func is not None: func(*args) self.last_action = self.state.frame else: self.logic() '''Methods simulate controller input; appends necessary tuple to action_list''' def press_button(self, wait, button): self.action_list.append((wait, self.pa...
import sys folder_loc = sys.argv[1] filename =sys.argv[2] fileobj = open(folder_loc + filename); flag=0 real_rev = open(folder_loc + "real_"+filename,"w+") fake_rev = open(folder_loc + "fake_"+filename,"w+") for line in fileobj: for i in range(len(line)): if (line[i] == '['
and flag == 0): #for beginning of real reviews flag = 1 elif (line[i-1]==']' and flag == 1): #for end of real reviews flag = 2 elif (line[i]=='[' and flag == 2)
: #for beginning of fake reviews flag = 3 elif (line[i-1] == ']' and flag == 3): #for end of fake reviews flag = 4 if(flag ==1): real_rev.write(line[i]) elif(flag==3): fake_rev.write(line[i])
# -*- coding: utf-8 -*- """tests decoration handling functions that are used by checks""" from translate.filters import decoration def test_spacestart(): """test operation of spacestart()""" assert decoration.spacestart(" Start") == " " assert decoration.spacestart(u"\u0020\u00a0Start") == u"\u0020\u0...
ot decoration.isvalidaccelerator(u"") assert decoration.isvalidaccelerator(u"a") assert decoration.isvalidaccelerator(u"1") assert not decoration.isvalidaccelerator(u"ḽ") # Test new code path where we actually have an acceptlist assert decoration.isvalidaccelerator(u"a", u"aeiou") assert decorat...
elerator(u"a", u"ḓṱḽṋṅ") def test_find_marked_variables(): """check that we can identify variables correctly, the first returned value is the start location, the second returned value is the actual variable sans decoations""" variables = decoration.findmarkedvariables("The <variable> string", "<", ">"...
# POS Census v0.1 # Copyright (c) 2012 Andrew Austin # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ...
ets.assets: if asset.locationID == systemID: if asset.typeID == 17621: rawCHAList.append(asset.itemID) if asset.typeID == 12237: rawSMAList.append(asset.itemID) print "Bui
lding POS List..." for pos in starbases.starbases: locationapi = auth.corp.Locations(IDs=pos.itemID).locations[0] moon = c.execute("SELECT name from mapDenormalize WHERE id = %s" % pos.moonID).fetchone()[0] poslist.append(POS(name=locationapi.itemName, location=moon, smas=[], cha...
# -*- coding: utf-8 -*- # # Copyright (c) 2017 F5 Networks Inc. # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json import sys from nose.plugins.skip import SkipTest i...
y.modules.bigip_vcmp_guest import Parameters from library.modules.bigip_vcmp_guest import ModuleManager from library.modules.bigip_vcmp_guest import ArgumentSpec
# In Ansible 2.8, Ansible changed import paths. from test.units.compat import unittest from test.units.compat.mock import Mock from test.units.compat.mock import patch from test.units.modules.utils import set_module_args except ImportError: try: from ansible.modules.network.f5.bigip_vcmp_...
from __future__ import division, print_function from os.path import join, split, dirname import os import sys from distutils.dep_util import newer from distutils.msvccompiler import get_build_version as get_msvc_build_version def needs_mingw_ftime_workaround(): # We need the mingw workaround for _ftime if the msv...
'distributions.c']]+[generate_librar
ies], libraries=libs, depends=[join('mtrand', '*.h'), join('mtrand', '*.pyx'), join('mtrand', '*.pxi'),], define_macros=defs, ) config.add_data_fil...
# -*- coding: UTF-8 -*- """ Options quotes. """ import os import json import logging from datetime import datetime import collections import requests from landscape.finance import consts, database, dates, utils from landscape.finance.volatility import math OptionQuote = collections.namedtuple( 'OptionQuote', ...
iv_bid = math.calc_iv(quote, bid) * 100 iv_ask = math.calc_iv(quote, ask) * 100 quote = OptionQuote( symbol,
type_, expiration, strike, date, time, bid, ask, stock_price, iv_bid, iv_ask) save_quote(db, quote) quotes.append(quote) logger.info('... quotes parsed: %d', len(quotes)) return quotes def fetch_realtime(symbol, db_name=None): """Fetches realtime (delay...
import string # Manages Local "database" for ZBWarDrive: # This keeps track of current ZBWarDrive and Sniffing Device State. # It is different from the online logging database. class ZBScanDB: """ API to interact with the "database" storing information for the zbscanning program. """ def __init_...
B def store_devices(self, devid, devstr, devserial): self.devices[devid] = (devstr, devserial, 'Free', None) # R
eturns the devid of a device marked 'Free', # or None if there are no Free devices in the DB. def get_devices_nextFree(self): for devid, dev in self.devices.items(): if dev[2] == 'Free': return devid def update_devices_status(self, devid, newstatus): if devid not...
"""Support for interfacing with Monoprice 6 zone home audio controller.""" import logging import voluptuous as vol from homeassistant.components.media_player import MediaPlayerDevice, PLATFORM_SCHEMA from homeassistant.components.media_player.const import ( SUPPORT_SELECT_SOURCE, SUPPORT_TURN_OFF, SUPPORT...
device.snapshot() elif service.service == SERVICE_RESTORE: device.restore() hass.services.register( DOMAIN, SERVICE_SNAPSHOT, service_handle, schema=MEDIA_PLAYER_SCHEMA ) hass.services.register( DOMAIN, SERVICE_RESTORE, service_handle, schema=MEDIA_PLAYER...
"""Initialize new zone.""" self._monoprice = monoprice # dict source_id -> source name self._source_id_name = sources # dict source name -> source_id self._source_name_id = {v: k for k, v in sources.items()} # ordered list of all source names self._source_nam...
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-01-13 18:08 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migration...
ry_key=True, serialize=False, verbose_name='ID')), ('session_key', models.CharField(max_length=255)), ('ticket', models.CharField(max_length=255)), ], ), migrations.AlterUniqueTogether( name='proxygrantingticket', unique_together
=set([('session_key', 'user')]), ), ]
from numpy.testing import * import numpy as np import lulu import lulu.connected_region_handler as crh class TestLULU: img = np.zeros((5, 5)).astype(int) img[0, 0:5] = 0 img[:, 4] = 1 img[1:3, 1:4] = 2 """ [[0 0 0 0 1] [0 2 2 2 1] [0 2 2 2 1] [0 0 0 0 1] [0 0 0 0 1]] ""...
onnected_regions(self.img) assert_array_equal(labels, self.img) assert_equal(len(regions), 3) crh.set_value(regions[0], 5) assert_array_equal(crh.todense(regions[0]), [[5, 5, 5, 5, 0], [5, 0, 0, 0, 0], ...
[5, 5, 5, 5, 0], [5, 5, 5, 5, 0]]) assert_array_equal(crh.todense(regions[1]), [[0, 0, 0, 0, 1], [0, 0, 0, 0, 1], [0, 0, 0, 0, 1], [0, 0, 0, 0, 1], ...
#!/usr/bin/env python from hts_barcode_checker import Taxon, TaxonDB import logging, datetime, argparse, sqlite3 # NCBI taxonomy tree database 10.6084/m9.figshare.4620733 parser = argparse.ArgumentParser(description = 'Create a table containing the CITES species') parser.add_argument('-db', '--CITES_db', metavar='C...
logging.basicConfig(filename=args.lf, filemode='a', format=log_format, level=log_level) # instantiate DB object, parse CITES dump db = TaxonDB(date=str(datetime.datetime.now())) db.from_dump(args.dmp) # configure local sqlite database conn = sqlite3.connect(args.n) curr = conn.cursor() # iterate over parse...
xon.expand(cursor=curr) for taxid in result.keys(): expanded.append(Taxon( appendix=taxon.appendix, name=taxon.name, description=taxon.description, footnotes=taxon.footnotes, ncbi={taxid:result[taxid]} )) logging.info('%d/%d' % ( counter, len(db.taxa) )) counter += 1 # write output f...
{ 'name': 'client_referred_to_backend_%s_short_stream_%s' % (transport_sec, balancer_short_stream), 'skip_langs': skip_langs, 'transport_sec': transport_sec, 'balancer_configs'...
if transport_sec == 'tls': skip_langs += ['java'] if balancer_short_stream: skip_langs += ['java'] config = { 'name': 'client_referred_to_backend_multiple_balancers_%s_short_stream_%s' % (trans
port_sec, balancer_short_stream), 'skip_langs': skip_langs, 'transport_sec': transport_sec, 'balancer_configs': [ { 'transport_sec': balancer_sec, 'short_stream': b...
# postgresql/ext.py # Copyright (C) 2005-2015 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is r
eleased under # the MIT License: http://www.opensource.org/licenses/mit-license.php from ...sql import expression from ...sql import elements from ...sql import functions from ...sql.schema import ColumnCollectionConstraint from .array import ARRAY class aggregate_order_by(expression.ColumnElement): """Represent...
expr = func.array_agg(aggregate_order_by(table.c.a, table.c.b.desc())) stmt = select([expr]) would represent the expression:: SELECT array_agg(a ORDER BY b DESC) FROM table; Similarly:: expr = func.string_agg( table.c.a, aggregate_order_by(literal_column...
# """test_python_compat - Python output compatibility tests""" # Copyright © 2012-2018 James Rowe <jnrowe@gmail.com> # # SPDX-License-Identifier: GPL-3.0-or-later # # This file is part of versionah. # # versionah is free software: you can redistribute it a
nd/or modify it under # the terms of the GNU General Public License
as published by the Free Software # Foundation, either version 3 of the License, or (at your option) any later # version. # # versionah 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...
''' Test bug 389: http://bugs.openbossa.org/show_bug
.cgi?id=389''' import sys import unittest from helper import UsesQApplication from PySide import QtCore,QtGui class BugTest(UsesQApplication): def testCase(self): s = QtGui.QWidget().style() i = s.standardIcon(QtGui.QStyle.SP_TitleBarMinButton) self.assertEqual(type(i), QtGui.QIcon)
if __name__ == '__main__': unittest.main()
from django.contrib import admin from models import * from cards.
actions import export_as_xls class ScanAdmin(admin.ModelAdmin): list_filter = ['readerLocation', 'added'] search_fields = ['card__code'] # Register your models here. admin.site.register(Batch) admin.site.register(Card) admin.site.register(Reader) admin.site.register(Location) admin.site.register(ReaderLocatio...
n(export_as_xls)
from django.contrib.
auth.backends import ModelBackend from django.contrib.sites.models import Site from socialregistration.contrib.twitter.models import TwitterProfile class TwitterAuth(ModelBackend): def authenticate(self, twitter_id=None): try: return TwitterProfile.objects.get( twitter_id=...
return None
import _plotly_utils.basevalidators class SizeValidator(_plotly_utils.basevalidators.AnyValidator): def __init_
_(self, plotly_name="size", parent_name="histogram2d.xbins", **kwargs): super(SizeValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), **kwargs
)
info=[] for line in open('./info_mappable_50.txt').read().rstrip().split('\n'): a=line.split('\t') info.append(a[0]) line_out='' line_out2='' seq='' index=0 for line in open('./seqList_mappable_50.fa'): if line[0]=='>': if seq: replace=seq[7:-7]
if replace!=ref: print header seq_alt=seq[:7]+alt+seq[-7:] line_out+='>'+header+'_ref'+'\n'+seq+'\n' line_out2+='>'+header+'_alt'+'\n'+seq_alt+'\n' header=info[index] ref_alt=header.split('_')[1] [ref,alt]=re
f_alt.split('>') index+=1 seq='' if index/1000000==index/1000000.0: print index else: seq+=line.split('\n')[0] if seq: replace=seq[7:-7] if replace!=ref: print header seq_alt=seq[:7]+alt+seq[-7:] line_out+='>'+header+'_ref'+'\n'+seq+'\n' line_...
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "clone.settings") from django.co
re.management import execute_from_command_line execute_from_command_line(sys.ar
gv)
# coding: utf8 # OeQ autogenerated lookup function for 'Window/Wall Ratio East in correlation to year of construction, based on the source data of the survey for the "German Building Typology developed by the "Institut für Wohnen und Umwelt", Darmstadt/Germany, 2011-2013' import math import numpy as np import oeqLooku...
0,0.03, 1941,0.03, 1942,0.03, 1943,0.03, 1944,0.03, 1945,0.03, 1946,0.029, 1947,0.026, 1948,0.02, 1949,0.012, 1950,0.003, 1951,0, 1952,0, 1953,0, 1954,0.014, 1955,0.036, 1956,0.062, 1957,0.09, 1958,0.118, 1959,0.144, 1960,0.165, 1961,0.18, 1962,0.18, 1963,0.18, 1964,0.18, 1965,0.18, 1966,0.173
, 1967,0.166, 1968,0.158, 1969,0.15, 1970,0.141, 1971,0.133, 1972,0.125, 1973,0.12, 1974,0.118, 1975,0.117, 1976,0.118, 1977,0.12, 1978,0.121, 1979,0.12, 1980,0.113, 1981,0.1, 1982,0.078, 1983,0.053, 1984,0.028, 1985,0.01, 1986,0.002, 1987,0.002, 1988,0.006, 1989,0.01, 1990,0.011, 1991,0.01, 1992,0.009, 1993,0.01, 1994...
try: from django.contrib.auth.tests.utils import skipIfCustomUser except ImportError:
def skipIfCustomU
ser(wrapped): return wrapped
rmitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following discl...
except IndexError: wx.MessageBox(t("ui.message.sharp.missing"), t("ui.message.error"), wx.OK | wx.ICON_ERROR) else:
dialog = AddEditFunctionDialog(self.engine, self.sharp_engine, function, self.object, self.attribute, escape=self.escape) dialog.ShowModal() self.populate_existing() self.existing.SetFocus() def OnEdit(self, e): """The 'edit' button is pressed.""...
try: import exceptions except ImportError: # Python 3 import builtins as exceptions class ObjectToReturn:
def __init__(s
elf, name): self.name = name def __str__(self): return self.name def exception(self, name, msg=""): exception = getattr(exceptions, name) raise exception(msg)
# encoding: utf-8 """ Test lldb data formatter subsystem. """ from __future__ import print_function import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil from ObjCDataFormatterTestCase import ObjCDataFormatterTestCase class ObjCDataFormatterNS...
oobar" - code: 12']) self.expect( 'frame variable nserrorptr', substrs=['domain: @"Foobar" - code: 12']) self.expect( 'frame variable nserror->_userInfo', substrs=['2 key/value pairs']) self.expect( 'frame variable nserror->_us
erInfo --ptr-depth 1 -d run-target', substrs=['@"a"', '@"b"', "1", "2"])
from app import write_entries import datetime import ra
ndom ts = datetime.datetime.now().strftime("%Y-%m-%d%H:%M-%S") offset = random.randrange(0, 1475) print("Enter user=%s" % ts) print("Enter email=%s" % offset) prime = write_entries.delay(ts, offset)
fro
m enum import Enum class ImageAlignType(Enum): """Image alignment""" Default = 1 Left = 2 Right = 3 Cente
r = 4
import decor from flask import Blueprint, redirect, request, url_for import os, json def construct_bp(gcal, JSON_DENT): ALLOWED_ORIGIN = "*" # JSON_DENT = 4 gcal_api = Blueprint('gcal_api', __name__, url_prefix="/gcal") # GOOGLE CALENDAR API Routes # Authenication routes @gcal_api.route('...
print request.form redirect(url_for('setcal'
)) # return json.dumps(gcal.get_ucals(), indent=JSON_DENT) return '<meta http-equiv="refresh" content ="0; URL=http://localhost:5000/setcal">' # Get todays events @gcal_api.route('/mail', methods=['GET']) def gcal_mail(): return json.dumps(gcal.get_mail(), indent=JSON_DENT) # =...
#!/usr/bin/python # -*- coding: utf-8 -*- # thumbor imaging service # https://github.com/thumbor/thumbor/wiki # Licensed under the MIT license: # http://www.opensource.
org/licenses/mit-license # Copyright (c) 2011 globo.com thumbor@google
groups.com from thumbor.filters import BaseFilter, filter_method from thumbor.utils import logger ALLOWED_FORMATS = ["png", "jpeg", "jpg", "gif", "webp"] class Filter(BaseFilter): @filter_method(BaseFilter.String) async def format(self, file_format): if file_format.lower() not in ALLOWED_FORMATS: ...
import numpy as np import json import scipy as sci def get_decimal_delta(data, index,decimals): ''' This function calculates the difference between the values of one column :param data: the data array :param time_index: the index of the column of interest :param decimals: Number of decimal places t...
ta, int(diff_Value2_Index))): diff_Value.append(v1 / t1) return np.asarray(diff_Value) def trapez_for_each(data, index_x, index_y): """ This method integrates the given Values with the Trapeziodal Rule :param index_x: index der X Achse :param index_y: index der Y Achse ...
.loads(data),dtype=np.float64) #data =np.array(json.loads(data),dtype=np.float_) while i < len(data[:,index_x]): res = sci.trapz(data[0:i, index_y], data[0:i, index_x]) res = np.float_(res) sol.append(res) i += 1 i = 0 realsol = [] ...
import Adafruit_BBIO
.GPIO as GPIO import time a=0 b=0 def derecha(channel): global a a+=1 print 'cuenta derecha es {0}'.format(a) def izquierda(channel): global b b+=1 print 'cuenta izquierda es {0}'.format(b) GPIO.setup("P9_11", GPIO.IN) GPIO.setup("P9_13", GPIO.IN) GPIO.add_event_detect("P9_11", GPIO.BOTH) GPIO.add_ev...
O.add_event_callback("P9_11",derecha) GPIO.add_event_callback("P9_13",izquierda) #if GPIO.event_detected("GPIO_31"): # print "event detected" while True: print "cosas pasan" time.sleep(1)
, 'compare_genome_features'] async_check_methods['GenomeFeatureComparator.compare_genome_features_check'] = ['GenomeFeatureComparator', 'compare_genome_features'] class AsyncJobServiceClient(object): def __init__(self, timeout=30 * 60, token=None, ignore_authrc=True, trust_all_ssl_certificates=Fa...
rns it value.""" method = self.method_data[request['method']]['method'] params = request['params'] result = None try: if isinstance(params, list): # Does it have enough arguments? if len(params) < self._man_args(method) - 1: ...
if(not self._vargs(method) and len(params) > self._max_args(method) - 1): raise InvalidParamsError('too many arguments') result = method(ctx, *params) elif isinstance(params, dict): # Do not accept keyword arguments if...
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
ut dimensions. temp: A float denoting the temperature parameter controlling
label noise. rng_key: JAX random number generator key. Returns: x: An array of size dim x num denoting data points. y_pm: An array of size num x odim denoting +/-1 labels. """ rng_subkey = jax.random.split(rng_key, 3) x = jax.random.normal(rng_subkey[0], (dim, num)) prob = jax.nn.sigmoid(-(1 / t...
rt_almost_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_raises_regexp from sklearn.utils.testing import assert_true from sklearn.utils.testing import ignore_warnings from sklearn.utils.testing import assert_not_equal f...
# and doesn't make any assumptions about the estimator apart from having a # fit. scores = cross_val_score(EstimatorWithFit(), [[1], [2], [3]], [1, 0, 1], scoring=DummyScorer()) assert_array_equal(scores, 1) def test_make_scorer(): # Sanity check on the make_scorer fac...
eeds_threshold=True, needs_proba=True) def test_classification_scores(): # Test classification scorers. X, y = make_blobs(random_state=0, centers=2) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf = LinearSVC(random_state=0) clf.fit(X_train, y_train)...
# Purpose: dxf engine for R2007/AC1021 # Created: 12.03.2011 # Copyright (C) , Manfred Moitzi # License: MIT License from __future__ import unicode_literals __author__ = "mozman <mozman@gmx.at>" from .headervars import VARMAP from ..ac1018 import AC1018Factory class AC1021Factory(AC1018Factory):
HEADERVARS
= dict(VARMAP)
from audio.io i
mpo
rt *
# -*- encoding: utf-8 -*- import ast import inspect class NameLower(ast.NodeVisitor): def __init__(self, lowered_names): self.lowered_names = lowered_names def visit_FunctionDef(self, node): code = '__globals = globals()\n' code += '\n'.join("{0} = __globals['{0}']".format(name) for ...
amelist
): def lower(func): srclines = inspect.getsource(func).splitlines() for n, line in enumerate(srclines): if '@lower_names' in line: break src = '\n'.join(srclines[n + 1:]) if src.startswith(' ', '\t'): src = 'if...
.41361256, 1.22474487] assert_allclose(cA, cA_expect) assert_allclose(cD, cD_expect) x_roundtrip = pywt.idwt(cA, cD, 'db2') assert_allclose(x_roundtrip, x, rtol=1e-10) # mismatched dtypes OK x_roundtrip2 = pywt.idwt(cA.astype(np.float64), cD.astype(np.float32), ...
cA_expect = np.asarray([5.65685425, 7.39923721, 0.22414387, 3.33677403, 7.77817459]) cA_expect = cA_expect + 0.5j*cA_expect cD_expect = np.asarray([-2.44948974, -1.60368225, -4.44140056, -0.41361256, 1.22474487]) cD_expect = cD_expect + 0.5j*cD_expec...
oundtrip = pywt.idwt(cA, cD, 'db2') assert_allclose(x_roundtrip, x, rtol=1e-10) def test_dwt_idwt_partial_complex(): x = np.asarray([3, 7, 1, 1, -2, 5, 4, 6]) x = x + 0.5j*x cA, cD = pywt.dwt(x, 'haar') cA_rec_expect = np.array([5.0+2.5j, 5.0+2.5j, 1.0+0.5j, 1.0+0.5j, ...
from .fields import BitField, Field from nettest.exceptions import NettestError import struct class PacketMeta(type): def __new__(cls, name, bases, attrs): fields = attrs.get('fields') if fields is None: raise NettestError(_("packet class must have 'fields' field")) _fields = []...
ef __eq__(self, other): for field_name in self.fields: field_value1 = getattr(self, field_name) field_value2 = getattr(other, field_name) if field_value1
!= field_value2: return False return True @property def length(self): total_len = 0 bit_len = 0 for field_name, field in self._fields: if isinstance(field, BitField): bit_len += field.length elif field.length > 0: ...
#!/usr/bin/python # -*- coding: utf-8 -*- """ utils ===== Utility functions for matching.py. """ import datetime import json import os #testme def parse_timestamp(t): """Parse MediaWiki-style timestamps and return a datetime.""" if t == '0000-00-00T00:00:00Z': return None else: return ...
in(filepath, 'config.json') with open(configfile, 'rb') as configf: config = json.loads(configf.read())
return config #testme def make_category_string(categories): """Given a list of categories, return the |-separated string.""" return '|'.join(categories) def timelog(run_time, filepath): """Get the timestamp from the last run, then log the current time (UTC). """ timelogfile = os.path.joi...
""" Filename: mc_tools.py Authors: John Stachurski and Thomas J. Sargent """ import numpy as np from discrete_rv import DiscreteRV def mc_compute_stationary(P): """ Computes the stationary distribution of Markov matrix P. Parameters =========== P : a square 2D NumPy array Returns: A fla...
P, init=0, sample_size=1000): """ Generates one sa
mple path from a finite Markov chain with (n x n) Markov matrix P on state space S = {0,...,n-1}. Parameters ========== P : A nonnegative 2D NumPy array with rows that sum to 1 init : Either an integer in S or a nonnegative array of length n with elements that sum to 1 ...
nce(j, slice): obj.times = self.times.__getitem__(j) elif isinstance(j, np.ndarray): raise NotImplementedError("Arrays not yet supported") else: raise TypeError("%s not supported" % type(j)) if isinstance(k, int)...
need to be the same if not (self.times == other.times).all(): raise ValueError('Times do not match: %s vs %s' % (self.times, other.times)) def _copy_data_complement(self, other): ''' Copy the metadata from another :class:`IrregularlySampledSignal`. ...
''' for attr in ("times", "name", "file_origin", "description", "annotations"): setattr(self, attr, getattr(other, attr, None)) def __add__(self, other, *args): ''' Addition (+) ''' return self._apply_operator(other, "__add__", *args) d...
from __future__ import unicode_literals from datetime import datetime, date import os import time from django.utils.dateformat import format from django.utils import dateformat, translation, unittest from django.utils.timezone import utc from django.utils.tzinfo import FixedOffset, LocalTimezone class DateFormatTes...
self.assertEqual(dateformat.format(my_birthday, 'A'), 'PM') self.assertEqual(dateformat.format(timestamp, 'c'), '2008-05-19T11:45:23.123456') self.assertEqual(dateformat.format(my_birthday, 'd'), '08') self.assertEqual(dateformat.format(my_birthday, 'j'), '8') self.assertEqual(dateform...
ssertEqual(dateformat.format(my_birthday, 'L'), 'False') self.assertEqual(dateformat.format(my_birthday, 'm'), '07') self.assertEqual(dateformat.format(my_birthday, 'M'), 'Jul') self.assertEqual(dateformat.format(my_birthday, 'b'), 'jul') self.assertEqual(dateformat.format(my_birthday, '...
realm=self._realm, scheme=self._scheme, host=self._host, port=self._port, **self._context) return self._cred_manager def _filter_stanza(self, stanza): for k in self.reserved_keys: if k in stanza: del stanza[k] return stanza d...
raise return False return True @retry(exceptions=[binding.HTTPError]) def get(self, stanza_name, only_current_app=False): '''Get stanza from configuration file. :param stanza_name: Stanza name. :type stanza_name: ``string`` :returns: Stanza, like: { ...
'eai:appName': 'solnlib_demo', 'eai:userName': 'nobody', 'k1': '1', 'k2': '2'} :rtype: ``dict`` :raises ConfStanzaNotExistException: If stanza does not exist. Usage:: >>> from solnlib import conf_manager >>> cfm = conf_manage...
settings from django.core.files.storage import default_storage as storage from django.test.client import RequestFactory from mock import patch from olympia import amo, core from olympia.addons import forms from olympia.addons.models import Addon, Category from olympia.amo.tests import TestCase, addon_factory, req_fa...
quest=self.request, instance=delicious) assert not form.is_valid() assert form.errors['slug'] == ( [u'The slug cannot be "submit". Please choose another.']) def test_name_trademark_mozilla(self): delicious = Addon.objects.get() form = ...
orm.is_valid() assert dict(form.errors['name'])['en-us'].startswith( u'Add-on names cannot contain the Mozilla or Firefox trademarks.') def test_name_trademark_firefox(self): delicious = Addon.objects.get() form = forms.AddonFormBasic( {'name': 'Delicious Firefox', '...
from collections import namedtuple import select StreamEvent = namedtuple( 'StreamEvent', [ 'fd', 'stream', 'data', 'direction', 'num_bytes', 'eof' ] ) class StreamWatcher(object): def __init__( self ): if _best_backend is None: raise Exception( "No poll/queue backend could be found for your OS." ) self.backe...
s=4, fd_data_map={}, fd_stream_map={} ): r_events = self.kq.control( None, max_events, timeout ) e = [] for event in r_events: fd = event.ident if fd in fd_data_map: stream = fd_stream_map.get( fd, None ) data = fd_data_map.get( fd, None )
direction = 'read' if event.filter == select.KQ_FILTER_READ else 'write' num_bytes = event.data eof = ( event.flags & select.KQ_EV_EOF != 0 ) e.append( StreamEvent( fd, stream, data, direction, num_bytes, eof ) ) return e if _best_backend is None: _best_backend = KQueueBackend try:...
from django.conf.urls import include, url from django.urls import path from login import views from django.contrib.auth.views import PasswordResetCompleteView, PasswordResetConfirmView, PasswordResetDoneView urlpatterns = [ path('password_reset/', views.PasswordResetView.as_view( html_email_template_name="...
views.GroupCreate.as_view(), name="input", ), url( r"^groups/(?P<group_id>[\w\d_\s]+)/$", views.GroupView
.as_view(), ), url( r"^groups/(?P<group_id>[\w\d_\s]+)/members$", views.GroupEdit.as_view(), name="input", ), url(r"^groups/new/$", views.GroupCreate.as_view(), name="input"), url(r"^register$", views.CreateUserView.as_view()), url(r"^detach$", views.DetachView.as_view())...
# Copyright 2020, The TensorFlow Federated Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Li
cense. # 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 Licen
se 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. """Libraries for interacting with a computation."""
# coding=utf-8 from abc import ABCMeta, abstractmethod from typing import Optional from weakref import ref from logging import getLogger from ultros.core.networks.base.connectors import base as base_connector from ultros.core.networks.base.networks import base as base_network __author__ = "Gareth Coles" class Base...
self._network = ref(network) self.logger = getLogger(self.name) # TODO: Logging @property def network(self) -> "base_network.BaseNetwork": return self._network() @abstractmethod async def connector_connected(self, connector: "base_connector.BaseConnector"):
pass @abstractmethod async def connector_disconnected(self, connector: "base_connector.BaseConnector", exc: Optional[Exception]): pass
from emburse.resource import ( EmburseObject, Account, Allowance, Card, Category, Company, Department, Label, Location, Member, SharedLink, Statement, Transaction ) class Client(EmburseObject): """ Emburse API Client API enables for the creation of ...
ken from the client :return: A configured emburse.resource.Department :rtype: Department """ return Department(auth_token=self.auth_token) @property def Label(self): """ Emburse Label Object, configured with the auth token from the client :return:...
:rtype: Label """ return Label(auth_token=self.auth_token) @property def Location(self): """ Emburse Location Object, configured with the auth token from the client :return: A configured emburse.resource.Location :rtype: Location """ retur...
_offset = "UTC Offset" self.messages.label_image = "Profile Image" self.messages.help_utc_offset = "The time difference between UTC and your timezone, specify as +HHMM for eastern or -HHMM for western timezones." self.messages.help_mobile_phone = "Entering a phone number is optional, but doing s...
messages.help_utc_offset)) try: from s3validators import IS_UTC_OFFSET table.utc_offset.requires = IS_EMPTY_OR(IS_UTC_OFFSET()) except: pass table[pa
ssfield].requires = [CRYPT(key=settings.hmac_key, min_length=self.settings.password_min_length, digest_alg="sha512")] if settings.username_field: table.username.requires = IS_NOT_IN_DB(db, ...
from setuptools import setup, find_packages try: long_description = open("README.rst").read() except IOError: long_description = "" setup( name='odin', version='0.4.2', url='https://github.com/timsavage/odin', license='LICENSE', author='Tim Savage', author_email='tim.savage@poweredbype...
tion='Object Data Mapping for Python', long_description=long_description, packages=find_packages(), install_requires=['six'], extras_require={ #
Documentation generation 'doc_gen': ["jinja2>=2.7"], # Pint integration 'pint': ["pint"], }, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent',...
# -*- coding: utf-8 -*- # # Yelandur documentation build configuration file, created by # sphinx-quickstart on Thu Jan 10 16:10:42 2013. # # 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. # # Al...
List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'yelandur', u'Yelandur Documentation', [u'Sébastien Lerique'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output --------------------------...
me, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'Yelandur', u'Yelandur Documentation', u'Sébastien Lerique', 'Yelandur', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false...
import logging try: create_external('xml2', build_helper = 'xml2-config', version_query = '--version', version_parser = lambda x: 'invalid') except Exception: logging.critical('external version parsing') try: tools['c'].std = 'latest' except Exception: logging.critical('std setting') try: shared_library('x', ...
eption: logging.critical('shared_library: empty input') try: static_library('x', []) except Exception:
logging.critical('static_library: empty input')
import os path = os.path.dirname(os.path.realpath(__file__)) sbmlFilePat
h = os.path.join(path, 'MODEL8687196544.xml') with open(sbmlFilePath,'r') as f: sbmlString = f.read() def module_exists(module_name): try: __import__(module_name) except ImportError: return False else:
return True if module_exists('libsbml'): import libsbml sbml = libsbml.readSBMLFromString(sbmlString)
# encoding: utf-8 from ztq_core import async import time @async def send(body): print 'START: ', body time.sle
ep(3) print 'END: ', body @async(queue='mail') def send_failed(body): pr
int 'FAIL START:', body raise Exception('connection error...') @async(queue='mail') def failed_callback(return_code, return_msg): print 'FAILED CALLBACK:', return_code, return_msg @async(queue='index') def index(data): print 'INDEX:', data time.sleep(1) def do_commit(): print 'COMMITTED' import ...
ty is the abstract base class of all Configuration properties.""" def __init__(self): abc.ABC.__init__(self) @abc.abstractmethod def copy(self) -> 'Property': raise NotImplementedError @abc.abstractmethod def unpack(self, value: 'Any', context: 'Context') -> bool: raise No...
ault: 'Any') -> None: P
roperty.__init__(self) self._default = default self._value = default def __repr__(self) -> str: return str(self._value) def __str__(self) -> str: return str(self._value) def __bool__(self) -> bool: return bool(self._value) def __int__(self) -> int: ret...
from __future__ import unicode_literals from django.test import TestCase from wtl.wtlib.models import Library, LibraryVersion from wtl.wtlib.tests.factories import (LibraryFactory, LibraryVersionFactory, ProjectFactory) class LibraryTestCase(TestCase): def test_str(self): ...
=l2v1.id).total_users, 1) self.assertEqual(LibraryVersion.objects.get(id=l2v2.id).total_users, 0) def test_often_used_with(self): lib1 = LibraryFactory() lib2 = LibraryFactory() lib3 = LibraryFactory() lib4 = LibraryFactory() ver1 = LibraryVersionFactory(library=lib1...
_2__2 = ProjectFactory() project_1_2__2.libraries.add(ver1) project_1_2__2.libraries.add(LibraryVersionFactory(library=lib2)) project_1_3 = ProjectFactory() project_1_3.libraries.add(LibraryVersionFactory(library=lib1)) project_1_3.libraries.add(LibraryVersionFactory(library=lib...
import os from configurations.wsgi import get_wsgi_application from whitenoise.django import Dj
angoWhiteNoise os.environ.setdefa
ult("DJANGO_SETTINGS_MODULE", "morgoth.settings") os.environ.setdefault("DJANGO_CONFIGURATION", "Production") application = DjangoWhiteNoise(get_wsgi_application())
#---------------------------------------------------------------------------- # # Copyright (c) 2014, Enthought, Inc. # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in /LICENSE.txt and may be redistributed only # under the conditions described in...
rent = self.module = sys.modules[self.modname] for part in self.objpath[:-1]: current = self.get_attr(current, part) name = self.objpath[-1] self.object_name = name self.object = None self.parent = current return True # this...
odules with side effects can raise # all kinds of errors. except Exception as err: if self.env.app and not self.env.app.quiet: self.env.app.info(traceback.format_exc().rstrip()) msg = ( 'autodoc can\'t import/find {0} {r1}, it reported error: ' ...
from scipy.spatial.distance i
mport cdist import numpy as np class KNNC1(object): def fit(self, X, Y): self.X = X self.Y = Y def predict(self, Z): dists = cdist(self.X, Z, 'correlation') indices = dists.argmin(axis = 0) return self.Y[indices] def predict_proba(self, Z): predictions = self.predict(Z) result = np.zeros((Z.s...
1 return result
elf, exploration_id, prerequisite_skills, acquired_skills): self.exploration_id = exploration_id self.prerequisite_skills = prerequisite_skills self.acquired_skills = acquired_skills def to_dict(self): return { 'exploration_id': self.exploration_id, 'prerequi...
'category': self.category, 'objective': self.objective, 'schema_version': self.schema_version, 'nodes': [ node.to_dict() for node in self.nodes ] } @classmethod def create_default_collection( cls, collection_id, title, ca...
ON_SCHEMA_VERSION, [], 0) @classmethod def from_dict( cls, collection_dict, collection_version=0, collection_created_on=None, collection_last_updated=None): collection = cls( collection_dict['id'], collection_dict['title'], collection_dict['category'], co...
__author__ = 'aakilomar' import requests, json, time requests.packages.urllib3.disable_warnings() host = "https://localhost:8443" #from rest_requests import add_user def add_user(phone): post_url = host + "/api/user/add/" + str(phone) return requests.post(post_url,None, verify=False).json() def add_group(use...
nenumbers): post_url = host + "/api/group/add/" + str(userid) + "/" + phonenumbers return requests.post(post_url,None, verify=False).json() #/add/{userId}/{groupId}/{issue} def add_vote(userid,groupid,issue): post_url = host + "/api/vote/add/" + str(userid) + "/" + str(groupid) + "/" + issue return req...
ist(): list_url = host + "/api/vote/listallfuture" r = requests.get(list_url) print r.json print r.text def set_event_time(eventid,time): post_url = host + "/api/event/settime/" + str(eventid) + "/" + time return requests.post(post_url,None, verify=False).json() def rsvp(eventid,userid,message...
if key in self.headers: value = self.headers[key] else: value = fallback or [] return value def add(self, key, value): """add header value""" if key not in self.headers: self.headers[key] = [] self.headers[key].append(value) ...
tachment(part)) else: raise TypeError('attach accepts an Attachment or str') if self.sent_time: self.modified_since_sent = True def construct_mail(self): """ compiles the information contained in this envelope into a :class:`email.Message`. "...
# convert the text to its canonical format (as per RFC 2015). canonical_format = self.body.encode('utf-8') textpart = MIMEText(canonical_format, 'plain', 'utf-8') # wrap it in a multipart container if necessary if self.attachments: inner_msg = MIMEMultipart() ...
# Copyright 2017 QuantRocket - 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 applicable law or ...
g as a dict """ response = houston.get("/ibgrouter/config") houston.raise_for_status_with_json(response) # It's possible to get a 204 empty response if not response.content: return {} return response.json() def _cli_loa
d_or_show_config(filename=None): if filename: return json_to_cli(load_ibg_config, filename) else: return json_to_cli(get_ibg_config)
# coding=utf-8 # Author: Nic Wolfe <nic@wolfeden.ca> # URL: https://sickrage.github.io # # This file is part of SickRage. # # SickRage 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 L...
not None: tempURL = url.split('-')[0] + "-" + str(imgNum) + ".jpg" else: tempURL = url logger.log("Fetching image from " + tempURL, logger.DEBUG) image_data = helpers.getURL(tempURL, session=meta_session, ret
urns='content') if image_data is None: logger.log("There was an error trying to retrieve the image, aborting", logger.WARNING) return return image_data
# Copyright 2013-2021 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) class PyAzureMgmtDeploymentmanager(PythonPackage): """Microsoft Azure Deployment Manager Client Library for Python.""...
pi = "azure-mgmt-deploymentmanager/azure-mgmt-deploymentmanager-0.2.0.zip" version('0.2.0', sha256='46e342227993fc9acab1dda42f2eb566b522a8c945ab9d0eea56276b46f6d730') depends_on('py-setuptools', type='build') depends_on('py-msrest@0.5.0:', type=('build', 'run')) depends_on('py-msrestazure@0.4.32:1', t...
', type=('build', 'run')) depends_on('py-azure-mgmt-nspkg', when='^python@:2', type=('build', 'run'))
for item in string.split(','): key = item.split(':')[0] var_offset = weechat.hdata_get_var_offset(ptr_hdata, key) var_array_size = \ weechat.hdata_get_var_array_size_string(ptr_hdata, '', ...
olist =
weechat.infolist_get('url_options', '', '') while weechat.infolist_next(infolist): url_options.append({ 'name': weechat.infolist_string(infolist, 'name').lower(), 'option': weechat.infolist_integer(infolist, 'option'), 'type': weechat.infolist_string(infolist, 'type'), ...
from django
.contrib.auth.decorators import login_required from django.views.generic import TemplateView from flop.cooking.forms import MealForm, MealContributionFormSet from flop.decorators import view_decorator @view_decorator(login_required) class IndexV
iew(TemplateView): template_name = 'dashboard/index.html'
""" Copyright (c) 2015 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the MIT license. See the LICENSE file for details. """ import os import shutil import grp import pwd from cct.module import Module from cct.lib.file_utils import create_dir class File(Module): ...
path: the path to operate on recursive: if path is a directory, recursively change ownership for all paths within """ # supplied owner/group might be symbolic (e.g. 'wheel') or numeric. # Try interpreting symbolically first try: gid ...
group,0) try: uid = pwd.getpwnam(owner).pw_uid except KeyError: uid = int(owner,0) # Beware: argument order is different os.chown(path, uid, gid) if recursive and os.path.isdir(path): for dirpath, dirnames, filenames in os.walk(path): ...
ref, remote_ip, payload) else: return (None, None, None) def get_url(self): href, remote_ip, payload = self._get_href() return href and "%s&key=%s" % (href, gom_stream_key(remote_ip, payload)) def get_proxy_url(self): href, remote_ip, payload = self._get_href() ...
s[-1]["href"]).group(1)) else: last = page vods = [] result = {"order": order, "page": page, "vods": vods, "has_previous": page is not 1, "has_next": page is not last} if page > last or page < 1: ...
for thumb_link in thumb_links: href = thumb_link.find("a", {'class': ["vod_link", "vodlink"]})["href"].replace("/./", "/") thumb = thumb_link.find("img", {'class': ["v_thumb", "vodthumb"]}) vods.append({"url": "http://www.gomtv.net%s" % href, "preview": thumb["src"], "title": thumb[...
.
./../../../share/pyshared/jockey/xorg_driver.
py
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2002-2006 Donald N. Allingham # # 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 2 of the License, or # (at you...
py of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # #------------------------------------------------------------------------- # # Standard Python modules # #--------------------------------...
---------------------------------------------------- # # Gramps modules # #------------------------------------------------------------------------- from .. import Rule from ....lib.familyreltype import FamilyRelType #------------------------------------------------------------------------- # # HasRelationship # #----...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os,sys, re, json, requests from oxapi import * def get_a_task(ox): folder = ox.get_standard_folder('tasks') task = list(ox.get_tasks(folder.id))[0] return task def upload(bean, args=[{'content':None,'file':None, 'mimetype':'text/plain','name':'attachme...
t', 'attach') params = ox._params() meta = {'module': bean.module_type, #'attached': bean.id, 'folder': bean.folder_id} counter = 0; fields = [] for data in args: # json metadata rf = RequestField(name='json_' + str(counter) ,data=json.
dumps(meta)) rf.make_multipart(content_disposition='form-data') fields.append(rf) # content: data or file to read filename = 'attachment.txt' mimetype = 'text/plain' content = None if 'content' in data: content = data['content'] else: ...
he unique versions for an objext can be retrieved.""" with reversion.revision: self.test.save() versions = Version.objects.get_unique_for_object(self.test) # Check correct version data. self.assertEqual(versions[0].field_dict["name"], "test1.0") self.assertEqual(versi...
ame="test1.0") with reversion.revision: self.test.name = "test1.1" self.test
.save() with reversion.revision: self.test.name = "test1.2" self.test.save() def testCustomRegistrationHonored(self): """Ensures that the custom settings were honored.""" self.assertEqual(tuple(reversion.revision.get_adapter(ReversionTestModel).get_fields...
# -*- encoding: utf-8 -*- ########################################################################### # Module Writen to OpenERP, Open Source Management Solution # # Copyright (c) 2011 Vauxoo - http://www.vauxoo.com/ # All Rights Reserved. # info Vauxoo (info@vauxoo.com) ####################################...
oo.com) # Planned by: Moises Augusto Lopez Calderon (info@vauxoo.com) ############################################################################ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free...
WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gn...
""" FEniCS tutorial demo program: Poisson equation with Dirichlet, Neumann and Robin conditions. The solution is checked to coincide with the exact solution at all nodes. The file is a modification of dn2_p2D.py. Note that the boundary is now also split into two distinct parts (separate objects and integrations) and w...
ative is not yet supported #A, b = assemble_system(a, L, bc, exterior_facet_domains=boundary_parts) u = Function(V) solve(A, u.vector(), b, 'lu') print mesh # Verification u_exact = Expression('1 + x[0]*x[0] + 2*x[1]*x[1]') u_e = interpolate(u_exact, V) print 'Max error:', abs(u_e.vector().array() - u.vector().array...
)).max() #interactive()
from .
basic import ProcFile from collections import namedtuple class Consoles(ProcFile): filename = '/proc/consoles' Console = namedtuple('Console', ['operations', 'flags', 'major', 'minor']) de
f names(self): return [line.split()[0] for line in self._readfile()] def get(self, name, default=None): for line in self._readfile(): console_info = line.replace('(', '').replace(')', '').split() if name == console_info[0]: major, minor = console_info[-1].spl...
'''@file cross_enthropytrainer_rec.py contains the CrossEnthropyTrainerRec for reconstruction of the audio samples''' import tensorflow as tf import trainer from nabu.neuralnetworks import ops class CostFeaturesRec(trainer.Trainer): '''A trainer that minimises the cross-enthropy loss, the output sequences mus...
ou want to have a different loss function, overwrite this method) Args: targets: a tupple of targets, the first one being a [batch_size x max_target_length] tensor containing the real targets, the second one being a [batch_size x max_audioseq_length x dim] ...
tensor containing the audio samples or other extra information. logits: a tuple of [batch_size, max_logit_length, dim] tensors containing the logits for the text and the audio samples logit_seq_length: the length of all the logit sequences as a tuple of ...
#!/usr/bin/env python # # 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 2 of the License, or (at your # option) any later version. See http://www.gnu.org/copyleft/gpl.html for # ...
earch-bugs query = bzapi.build_query( product="Fedora", component="python-bugzilla") # Since 'query' is just a dict, you could set your own parameters too, like # if your bugzilla had a custom field. This will set 'status' for example, # but for common opts
it's better to use build_query query["status"] = "CLOSED" # query() is what actually performs the query. it's a wrapper around Bug.search t1 = time.time() bugs = bzapi.query(query) t2 = time.time() print("Found %d bugs with our query" % len(bugs)) print("Query processing time: %s" % (t2 - t1)) # Depending on the siz...
"""Methods to set media related (resolution, length) scene properties""" import bpy def setup(animated, width, height, lengt
h): """ Sets up the type, resolution and length of the currently open scene The render resolution of the scene is set, and additionally ... ... for stills, sets the length of the scene to exact
ly 1 frame. ... for animations, enables animated seed for cycles, sets the fps to 24 and the fps_base to 1. """ bpy.context.scene.render.resolution_percentage = 100 bpy.context.scene.render.resolution_x = int(width) bpy.context.scene.render.resolution_y = int(height) if not animated: ...