prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
language governing permissions and # limitations under the License. import socket import sys import time import eventlet eventlet.monkey_patch() from oslo_config import cfg from oslo_log import log as logging import oslo_messaging from oslo_service import loopingcall from neutron.agent.l2.extensions import manager...
elf.eswitch_mgr.get_assigned_devices_info() device_info = {} device_info['current'] = curr_devices device_info['added'] = curr_devices - registered_devices # we don't want to process updates for devices that don't exist device_info['updated'] = updated_devices & curr_devices ...
ice_info def _device_info_has_changes(self, device_info): return (device_info.get('added') or device_info.get('updated') or device_info.get('removed')) def process_network_devices(self, device_info): resync_a = False resync_b = False self.sg_age...
from conn import Connection import dispatch import socket class Acceptor(Connection): def __init__(self, port): self.dispatcher = dispatch.Dispatch(1) self.dispatcher.start() self.sock = socket.
socket(socket.AF_INET, socket.SOCK_STREAM, 0) self.sock.bind(("127.0.0.1", port)) self.sock.listen(1024) def handleRead(self): cli, addr = self.sock.accept() # cli.setblocking(0) self.disp
atcher.dispatch(cli)
from flask import Flask from flask.ext.script import Manager app = Flask(__name__) manager = Manager(app) @app.route(
'/') def index(): return
'<h1>Hello World!</h1>' @app.route('/user/<name>') def user(name): return '<h1>Hello, {name}!</h1>'.format(**locals()) if __name__ == '__main__': manager.run()
# # Copyrigh
t (c) 2017 Sugimoto Takaaki # # 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 t
o in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import urllib import json from collections impor...
is_admin=False) self.flags( osapi_compute_extension=[ 'nova.api.openstack.compute.contrib.select_extensions'], osapi_compute_ext_list=['Simple_tenant_usage']) def _test_verify_index(self, start, stop): req = webob.Request.blank( ...
res = req.get_response(fakes.wsgi_app( fake_auth_context=self.alt_user_context, init_only=('os-simple-tenant-usage',))) self.assertEqual(res.status_int, 403) finally: policy.reset() def test_get_tenan...
imedelta(hours=HOURS) tenant_id = 0 req = webob.Request.blank( '/v2/faketenant_0/os-simple-tenant-usage/' 'faketenant_%s?start=%s&end=%s' % (tenant_id, future.isoformat(), NOW.isoformat())) req.method = "GET" req.headers["content-type...
#!/usr/bin/env python3 """ This housekeeping script reads a GFF3 file and writes a new one, adding a 'gene' row for any RNA feature which doesn't have one. The coordinates of the RNA will be copied. The initial use-case here was a GFF file dumped from WebApollo which had this issue. In this particular use case, the...
s[8], 'ID') parent = gff.column_9_value(cols[8], 'Parent') if cols[2].endswith('RNA') and parent i
s None: gene_cols = list(cols) gene_cols[2] = 'gene' gene_cols[8] = gff.set_column_9_value(gene_cols[8], 'ID', "{0}.gene".format(id)) ofh.write("{0}\n".format("\t".join(gene_cols)) ) cols[8] = gff.set_column_9_value(cols[8], 'Parent', "{0}.gene".format(id)) ...
import numpy as np from numpy.testing import assert_equal, assert_array_equal from scipy.stats import rankdata, tiecorrect class TestTieCorrect(object): def test_empty(self): """An empty array requires no correction, should return 1.0.""" ranks = np.array([], dtype=np.float64) c = tiecor...
): data = np.array([2**60, 2**60
+1], dtype=np.uint64) r = rankdata(data) assert_array_equal(r, [1.0, 2.0]) data = np.array([2**60, 2**60+1], dtype=np.int64) r = rankdata(data) assert_array_equal(r, [1.0, 2.0]) data = np.array([2**60, -2**60+1], dtype=np.int64) r = rankdata(data) assert...
import logging from ...engines.light import SimEngineLight from ...error
s import SimEngineError l = logging.getLogger(name=__name__) class SimEnginePropagatorBase(SimEngineLight): # pylint:disable=abstract-method def __init__(self, stack_pointer_tracker=None, project=None): super().__init__() # Used in the VEX engine self._project = project self.bas...
): self.project = kwargs.pop('project', None) self.base_state = kwargs.pop('base_state', None) self._load_callback = kwargs.pop('load_callback', None) try: self._process(state, None, block=kwargs.pop('block', None)) except SimEngineError as ex: if kwargs.p...
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import unittest import frappe from frappe.utils import flt, get_datetime from erpnext.stock.doctype.purchase_receipt.test_purchase_receipt import set_p...
o_doc.submit() # add raw materials to stores test_stock_entry.make
_stock_entry(item_code="_Test Item", target="Stores - _TC", qty=100, incoming_rate=100) test_stock_entry.make_stock_entry(item_code="_Test Item Home Desktop 100", target="Stores - _TC", qty=100, incoming_rate=100) # from stores to wip s = frappe.get_doc(make_stock_entry(pro_doc.name, "Material Transfer for...
import numpy as np import cv2 from matplotlib import pylab as plt # Ref: http://www.pyimagesearch.com/2015/07/16/where-did-sift-and-surf-go-in-opencv-3/ picNumber = 1 filename = "/home/cwu/project/stereo-calibration/calib_imgs/3/left/left_" + str(picNumber) +".jpg" i
mg = cv2.imread(file
name) gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) orb = cv2.ORB_create() # find the keypoints with STAR kp = orb.detect(img,None) # compute the descriptors with BRIEF kp, des = orb.compute(img, kp) img = cv2.drawKeypoints(img,kp,None,(0,255,0),4) cv2.imshow('img',img) cv2.waitKey(1000) cv2.imwrite('orb_keypoints.j...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import mezzanine.core.fields class Migration(migrations.Migration): dependencies = [ ('pages', '__first__'), ] operations = [ migrations.CreateModel( name='Gallery', ...
k=True)), ], options={ 'ordering': ('_order',), 'verbose_name': 'Gallery', 'verbose_name_plural': 'Galleries', }, bases=('pages.page', models.Model), ), migrations.CreateModel( name='GalleryImage'...
alse, auto_created=True, primary_key=True)), ('_order', models.IntegerField(null=True, verbose_name='Order')), ('file', mezzanine.core.fields.FileField(max_length=200, verbose_name='File')), ('description', models.CharField(max_length=1000, verbose_name='Description', bla...
# -*- coding: utf-8 -*- from wikitools.api im
port APIRequest from wikitools.wiki import Wiki from wikitools.page import Page from urllib2 import quote pairs = [ ['"', '"'], ['(', ')'], ['[', ']'], ['{', '}'], ['
<!--', '-->'], ['<', '>'], ['<gallery', '</gallery>'], ['<includeonly>', '</includeonly>'], ['<noinclude>', '</noinclude>'], ['<onlyinclude>', '</onlyinclude>'], ['<small>', '</small>'], ['<table>', '</table>'], ['<td>', '</td>'], ['<tr>', '</tr>'], ] wiki = Wiki('http://wiki.teamfortress.com/w/api.p...
''' Created on Jun 6, 2012 @author: vr274 ''' import numpy as np from generic import TakestepSlice, TakestepInterface from pele.utils import rotations __all__ = ["RandomDisplacement", "UniformDisplacement", "RotationalDisplacement", "RandomCluster"] class RandomDisplacement(TakestepSlice): '''Random...
placement(Tak
estepSlice): '''Displace each atom be a uniform random vector The routine generates a proper uniform random unitvector to displace atoms. ''' def takeStep(self, coords, **kwargs): c = coords[self.srange] for x in c.reshape(c.size/3,3): x += self.steps...
impor
t _plotly_utils.basevalidators class SizemodeValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__( self, plotly_name="sizemode", parent_name="scatterpolar.marker", **kwargs ): super(SizemodeValidator, self).__init__( plotly_name=plotly_name, parent_...
ameter", "area"]), **kwargs )
#!/usr/bin/python
# $Id:$ from base import Display, Screen, ScreenMode, Canvas from pyglet.libs.win32 import _kernel32, _user32, t
ypes, constants from pyglet.libs.win32.constants import * from pyglet.libs.win32.types import * class Win32Display(Display): def get_screens(self): screens = [] def enum_proc(hMonitor, hdcMonitor, lprcMonitor, dwData): r = lprcMonitor.contents width = r.right - r.left ...
import re import sys def i
s_self_describing(n): for i in range(len(n)): c = n[i] if int(c) != len(re.findall(str(i), n)): return False return True with open(sys.argv[1], 'r') as fh: for line in fh.readlines(): line = line.strip() if line == '': continue print 1 if i...
scribing(line) else 0
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### P
LEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Creature() result.template = "object/mobile/shared_dressed_rebel_brigadier_general_rodian_female_01.iff" result.attribute_template_id = 9 result.stfName("npc_name","rodian_base_female") #### BEGIN MODIFI...
MODIFICATIONS #### return result
from app import db from app.model import DirectionStatistic import random import numpy as np import matplotlib.pyplot as plt from matplotlib.figure
import Figure def create_range_figure2(sender_id): fig = Figure() axis = fig.add_subplot(1, 1, 1) xs = range(100) ys = [random.randint(1, 50) for x in xs] axis.plot(xs, ys) return fig def create_range_figure(se
nder_id): sds = db.session.query(DirectionStatistic) \ .filter(DirectionStatistic.sender_id == sender_id) \ .order_by(DirectionStatistic.directions_count.desc()) \ .limit(1) \ .one() fig = Figure() direction_data = sds.direction_data max_range = max([r['max_range'] / 10...
# coding: utf-8 # # Copyright 2014 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
cls.visualizations_dict.clear() # Add new visualization instances to the registry.
for name, clazz in inspect.getmembers( models, predicate=inspect.isclass): if name.endswith('_test') or name == 'BaseVisualization': continue ancestor_names = [ base_class.__name__ for base_class in inspect.getmro(clazz)] if 'Ba...
__all__ = [ "getMin" ] __doc__ = "Different algorithms used for optimization" import Optizelle.Unconstrained.S
tate import Optizelle.Unconstrained.Functions from Optizelle.Utility import * from Optizelle.Properties import * from Optizelle.Functions import * def getMin(X, msg, fns, state, smanip=None): """Solves an unconstrained o
ptimization problem Basic solve: getMin(X,msg,fns,state) Solve with a state manipulator: getMin(X,msg,fns,state,smanip) """ if smanip is None: smanip = StateManipulator() # Check the arguments checkVectorSpace("X",X) checkMessaging("msg",msg) Optizelle.Unconstrained.Functions.ch...
# Copyright 2020 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
data = self._get_data() return data.get('username', 'Unknown') def __str__(self): """Returns a string representation of the username.""" use
r_strings = [self.username] if self.is_active: user_strings.append('[active]') else: user_strings.append('[inactive]') if self.is_admin: user_strings.append('<is admin>') return ' '.join(user_strings)
#!/usr/bin/python # -*- coding: utf-8 -*- import os import sys class Options: d
ef __init__(self): self.color =
"black" self.verbose = False pass
_response('stats.contributions_series', group='day', format='csv') assert r.status_code == 200 self.csv_eq(r, """date,count,total,average 2009-06-02,2,4.98,2.49 2009-06-01,1,5.00,5.0""") # Test the SQL query by usin...
', 'week', 'month']: self.client.get(reverse('stats.site', args=['json', period])) assert _site_query.call_args[0][0] == period def tests_period_day(self, _site_query): _site_query.return_value = ['.', '.'] start = (datetime.date.today() - datetime.timedelta(days=3)) ...
d = datetime.date.today() self.client.get(reverse('stats.site.new', args=['day', start.strftime('%Y%m%d'), end.strftime('%Y%m%d'), 'json'])) assert _site_query.call_args[0][0] == 'date' assert _site_query.call_args[0][1] == start asse...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('core', '0015_auto_20150928_0850'), ] ...
e='UserVote', fields=[ ('id', models.AutoField(auto_created=True, verbose_n
ame='ID', serialize=False, primary_key=True)), ('bidrag', models.ForeignKey(to='core.Bidrag')), ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)), ], ), migrations.AlterUniqueTogether( name='uservote', unique_together=set([('bidr...
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
integer_buckets = math_ops._bucketize(inputs, boundaries=self.bins) #
pylint: disable=protected-access if self.output_mode == INTEGER: if isinstance(inputs, sparse_tensor.SparseTensor): return sparse_tensor.SparseTensor( indices=array_ops.identity(inputs.indices), values=integer_buckets, dense_shape=array_ops.identity(inputs.dense_sh...
# The contents of this file are subject to the BitTorrent Open Source License # Version 1.1 (the License). You may not copy or use this file, in either # source code or executable form, except in compliance with the License. You # may obtain a copy of the License at http://www.bittorrent.com/license/. # # Software di...
under the License is distributed on an AS IS basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License # for the specific language governing rights and limitations under the # License. from sha import sha from random import randint #this is ugly, hopefully os.entropy will be in 2.4 try: f...
opy(n): s = '' for i in range(n): s += chr(randint(0,255)) return s def intify(hstr): """20 bit hash, big-endian -> long python integer""" assert len(hstr) == 20 return long(hstr.encode('hex'), 16) def stringify(num): """long int -> 20-character string""" str = ...
""" ex_compound_nomo_1.py Compound nomograph: (A+B)/E=F/(CD) Copyright (C) 2007-2009 Leif Roschier 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 L...
GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import sys sys.path.insert(0, "..") from pynomo.nomographer import * # type 1 A_params={ 'u_min':0.0, 'u_max':10.0, 'function':lambda u:u, 'title':r'$A$', 'tick_levels':2, ...
':2, 'tick_text_levels':1, } R1a_params={ 'u_min':0.0, 'u_max':10.0, 'function':lambda u:-u, 'title':'', 'tick_levels':0, 'tick_text_levels':0, 'tag':'r1' } block_1_params={ 'block_type':'type_1', ...
from django.contrib import admin from general.models import StaticPage admin
.site.register(StaticPag
e)
import sys from Bio import SeqIO SNPTOPEAKFILENAME = sys.argv[1] GENOMEFILENAME = sys.argv[2] DISTANCE = int(sys.argv[3]) BINDALLELESEQFILENAME = sys.argv[4] NONBINDALLELEFILENAME = sys.argv[5] FIRSTPEAKCOL = int(sys.argv[6]) # 0-INDEXED def getSNPInfo(SNPToPeakLine): # Get the SNP and peak location from ...
bindAlleleSeqFile = open(BINDALLELESEQFILENAME, 'w+') nonBindAlleleSeqFile = open(NONBINDALLELEFILENAME, 'w+') numSharingPeak = 0 for seqRecord in SeqIO.parse(GENOMEFILENAME, "fasta"): # Iterate through the chromosomes and get the sequences surrounding each SNP in each chromosome # Combine SNPs that are i...
k, and ASSUME THAT THEY ARE IN LD AND THE BINDING ALLELES CORRESPOND TO EACH OTHER while seqRecord.id == SNPLocation[0]: # Iterate through all SNPs on the current chromosome if peakLocation != lastPeakLocation: # At a new peak if lastPeakLocation[0] != "": # Record the last peak bindAll...
on types, some non-trivial type conversion could have place. Basically a type is replaced with another one that has the closest match, and sometimes one argument of generated function comprises several arguments of the original function (usually two). Functions having error code as the return value and returning effec...
s): """__init__(NBestIterator self, ps_nbest_t * ptr) -> NBestIterator""" this = _pocketsphinx.new_NBestIterator(*args) try: self.this.append(this) except: self.this = this __swig_destroy__ = _pocketsphinx.delete_NBestIterator __del__ = lambda self : None; def next(self): ...
t""" return _pocketsphinx.NBestIterator_next(self) def __next__(self):
from pagarme import card from pagarme import plan from tests.resources import pagarme_test from tests.resources.dictionaries import card_dictionary from tests.resources.dictionaries import customer_dictionary from tests.resources.dictionaries import plan_dictionary from tests.resources.dictionaries import transaction_d...
TRIAL_PLAN = plan.create(plan_dictionary.NO_TRIAL_PLAN) POSTBACK_URL = pagarme_test.create_postback_url() BOLETO_PERCENTAGE_SPLIT_RULE_SUBSCRIPTION = { "plan_id": NO_TRIAL_PLAN['id'], "customer": customer_dictionary.CUSTOMER, "payment_method": "boleto", "postback_url": POSTBACK_URL, "split_rules":...
hod": "boleto", "postback_url": POSTBACK_URL } CHARGES = { "charges": "1" } CREDIT_CARD_PERCENTAGE_SPLIT_RULE_SUBSCRIPTION = { "plan_id": NO_TRIAL_PLAN['id'], "customer": customer_dictionary.CUSTOMER, "card_id": CARD['id'], "payment_method": "credit_card", "postback_url": POSTBACK_URL, ...
s file is part of pyasn1-modules software. # # Created by Russ Housley # Copyright (c) 2019, Vigil Security, LLC # License: http://snmplabs.com/pyasn1/license.html # import sys import unittest from pyasn1.codec.der.decoder import decode as der_decoder from pyasn1.codec.der.encoder import encode as der_encoder from pya...
PE4qqJ5CllN0CSVWqz4CxGDFIQXzR6ohn8f3dR3+DAaLYvAjBVMLJjk7+nfnB2L0HpanhT Fz9AxPPIDf5pBQQwM14l8wKjEHIyfqclupeKNokBUr1ykioPyCr3nf4Rqe0Z4EKIY4OCpW6n hrkWHmvF7OKR+bnuSk3jnBxjSN0Ivy5q9q3fntYrhscMGGR73umfi8Z29tM1vSP9jBZvirAo geGf/sfOI0ewRvJf/5abnNg/78Zyk8WmlAHVFzNGcM3u3vhnNpTI
VRuUyVkdSmOdbzeSfmqQ 2HPCEdC9HNm25KJt1pD6v6aP3Tw7qGl+tZyps7VB2i+a+UGcwQcClcoXcPSdG7Z1gBTzSr84 MuVPYlePuo1x+UwppSK3rM8ET6KqhGmESH5lKadvs8vdT6c407PfLcfxyAGzjH091prk2oRJ xB3oQAYcKvkuMcM6FSLJC263Dj+pe1GGEexk1AoysYe67tK0sB66hvbd92HcyWhW8/vI2/PM bX+OeEb7q+ugnsP+BmF/btWXn9AxfUqNWstyInKTn+XpqFViMIOG4e2xC4u/IvzG3VrTWUHF 4pspH3k...
# You are climbing a stair case. It takes n steps to reach to the top. # # Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? # # Note: Given n will be a positive integer. # # Example 1: # # Input: 2 # Output: 2 # Explanation: There are two ways to climb to the top. # 1. ...
1 step class
Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ table = [1, 2] i = 2 while i < n: table.append(table[i-1] + table[i-2]) i += 1 return table[n-1] # Note: # Generate two trees one with 1 step and othe...
from django.h
ttp import Ht
tpResponse def hello_world(request): return HttpResponse("Hello, world.")
#-*- coding: utf-8 -*- from __future__ import un
icode_literals from __future__ import print_function import sys if sys.version_info[0] == 2: reload(sys) sys.setdefaultencoding('utf-8') from . i
mport config from . import parsers def main(): if len(sys.argv) == 2: filename = sys.argv[1] filename = parsers.to_unicode(filename) parsers.run(filename) else: msg = 'Usage: {} <metadata>'.format(sys.argv[0]) print(msg) print('\nPredefined Variables') fo...
# Copyright 2018 Red Hat, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
ONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.api.image import base from tempest.lib.common.utils import data_utils from tempest.lib import decorators class BasicOperationsImagesAdminTest(base.Base...
') def test_create_image_owner_param(self): # NOTE: Create image with owner different from tenant owner by # using "owner" parameter requires an admin privileges. random_id = data_utils.rand_uuid_hex() image = self.admin_client.create_image( container_format='bare', disk_...
""" File: DaqDevDiscovery01.py Library Call Demonstrated: mcculw.ul.get_daq_device_inventory() mcculw.ul.create_daq_device() mcculw.ul.release_daq_device() Purpose: Discovers DAQ devices and assigns board number to ...
ice_id_label = tk.Label(device_id_frame) self.device_id_label.grid(row=0, column=1, sticky=tk.W, padx=3, pady=3) self.flash_led_button = tk.Button(results_group) self.flash_led_button["text"] = "Flash LED" self.flash_led_button["command"] = self.flash_led self.flash_led_button["...
= tk.Frame(self) button_frame.pack(fill=tk.X, side=tk.RIGHT, anchor=tk.SE) quit_button = tk.Button(button_frame) quit_button["text"] = "Quit" quit_button["command"] = self.master.destroy quit_button.grid(row=0, column=1, padx=3, pady=3) # Start the example if this module is be...
from django.db.models import Q from django_filters import rest_framework as filters from adesao.models import SistemaCultura, UFS from planotrabalho.models import Componente class SistemaCulturaFilter(filters.FilterSet): ente_federado = filters.CharFilte
r( field_name='ente_federado__nome__unaccent', lookup_expr='icontains') estado_sigla = filters.CharFilter(method='sigla_filter') cnpj_prefeitura = filters.CharFilter( field_name='sede__cnpj', lookup_expr='contains') situacao_adesao = filters.CharFilter( field_name='estado_processo', ...
.DateFilter( field_name='data_publicacao_acordo', lookup_expr=('gte')) data_adesao_max = filters.DateFilter( field_name='data_publicacao_acordo', lookup_expr=('lte')) data_componente_min = filters.DateFilter( field_name='data_componente_acordo', lookup_expr=('gte'), method='data_...
lass InvalidQuery(Exception): """ The query passed to raw isn't a safe query to use with raw. """ pass class QueryWrapper(object): """ A type that indicates the contents are an SQL fragment and the associate parameters. Can be used to pass opaque data to a where-clause, for examp...
f = opts.get_field(name) link_field = opts.get_ance
stor_link(f.model) if f.primary_key and f != link_field: return getattr(instance, link_field.attname) return None class RegisterLookupMixin(object): def _get_lookup(self, lookup_name): try: return self.class_lookups[lookup_name] except KeyError: ...
# 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, s...
keras.optimizers.Adam(1e-4, beta_1=0.5, beta_2=0.9) discriminator_optimizer = tf.keras.optimizers.Adam(1e-4, beta_1=0.5, beta_2=0.9) get_waveform = lambda magnitude:\ save_helper.get_waveform_from_normalized_magnitude( magnitude, magnitude_stats, GRIFFIN_LIM_ITERATIONS, FFT_FRAME_L
ENGTH, FFT_FRAME_STEP, LOG_MAGNITUDE ) save_examples = lambda epoch, real, generated:\ save_helper.save_wav_data( epoch, real, generated, SAMPLING_RATE, RESULT_DIR, get_waveform ) spec_gan_model = wgan.WGAN( normalized_raw_dataset, generator, [discrimina...
# # 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...
unks of report's data self.log.info("Downloading Search Ads report %s", self.report_id) with NamedTemporaryFile() as temp_file: for i in range(fragments_count): byte_content = hook.get_file( report_fragment=i, report_id=self.report_id ) ...
else self._handle_report_fragment(byte_content) ) temp_file.write(fragment) temp_file.flush() gcs_hook.upload( bucket_name=self.bucket_name, object_name=report_name, gzip=self.gzip, fil...
from fruits import validate_fruit fruits = ["bana
na", "lemon", "apple", "orange", "batman"] print fruits def list_fruits(fruits, byName=True): if byName: # WARNING: this won't make a copy of the list and return it. It will change the list FOREVER fruits.sort() for index, fruit in enumerate(fruits): if validate_fruit(fruit): ...
uit) list_fruits(fruits) print fruits
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
S" 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. import json from kazoo.client import KazooClient from libzookeeper.conf impor
t PRINCIPAL_NAME def get_children_data(ensemble, namespace, read_only=True): zk = KazooClient(hosts=ensemble, read_only=read_only, sasl_server_principal=PRINCIPAL_NAME.get()) zk.start() children_data = [] children = zk.get_children(namespace) for node in children: data, stat = zk.get("%s/%s" % (name...
#!/usr/bin/env python # Copyright (c) 2010-2013 by Yaco Sistemas <goinnn@gmail.com> or <pmartin@yaco.es> # # This program is free soft
ware: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the Lic
ense, or # (at your 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 Lesser General Public License for more details. # # You should have re...
# 每个人都有一个preference的排序,在不违反每个人的preference的情况下得到总体的preference的排序 拓扑排序解决(https://instant.1point3acres.com/thread/207601) import itertools import collections def preferenceList1(prefList): # topological sort 1 pairs = [] for lis in prefList: for left, right in zip(lis, lis[1:]): pairs += (left...
, res = set(itertools.chain(*pairs)), [] while pairs: free = allItems - set(zip(*pairs)[1]) if not free: None res += list(free) pairs = filter(free.isdisjoint, pairs) allItems -= free
return res + list(allItems) print(preferenceList1([[1, 2, 3, 4], ['a', 'b', 'c', 'd'], ['a', 1, 8], [2, 'b', 'e'], [3, 'c']]))
ributor( read_contrib, permissions=[ permissions.READ], save=True) private_node_one.add_contributor( write_contrib, permissions=[ permissions.READ, permissions.WRITE], save=True) return private_node_one @pytest.fixture() def private_node_one_...
[1] in valid_contributors
# test_public_node_with_link_anonymous_does_not_expose_user_id res = app.get(public_node_one_url, { 'view_only': public_node_one_anonymous_link.key, 'embed': 'contributors', }) assert res.status_code == 200 embeds = res.json['data'].get('embeds', None) ...
from io import BytesIO import sys from mitmproxy.net import wsgi from mitmproxy.net.http import Headers def tflow(): headers = Headers(test=b"value") req = wsgi.Request("http", "GET", "/", "HTTP/1.1", headers, "") return wsgi.Flow(("127.0.0.1", 8888), req) class ExampleApp: def __init__(self): ...
equest.port = 80
wfile = BytesIO() err = w.serve(f, wfile) assert ta.called assert not err val = wfile.getvalue() assert b"Hello world" in val assert b"Server:" in val def _serve(self, app): w = wsgi.WSGIAdaptor(app, "foo", 80, "version") f = tflow() f...
# Copyright (c) 2014 Mirantis 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 in writing, so...
, src_cloud, dst_cloud, info, body, resources, types): dst_storage = dst_cloud.resources[resources] src_compute = src_cloud.resources[resources] src_backend = src_compute.config.compute.backend dst_backend = dst_storage.config.compute.backend ssh_driver ...
ect_compute_transfer else TRANSPORTER_MAP[src_backend][dst_backend]) transporter = task_transfer.TaskTransfer( self.init, ssh_driver, resource_name=types, resource_root_name=body) transporter.run(info=info) def copy_ephemeral(sel...
""" Weather Underground PWS Metadata Scraping Module Code to scrape PWS network metadata """ import pandas as pd import urllib3 from bs4 import BeautifulSoup as BS import numpy as np import requests # import time def scrape_station_info(state="WA"): """ A script to scrape the station information published ...
nd.com/weatherstation/ListStations.asp? selectedState=WA&selectedCountry=United+States&MR=1 :param state: US State by which to subset WU S
tation table :return: numpy array with station info """ url = "https://www.wunderground.com/" \ "weatherstation/ListStations.asp?selectedState=" \ + state + "&selectedCountry=United+States&MR=1" raw_site_content = requests.get(url).content soup = BS(raw_site_content, 'html.parser...
ing-skeinforge-export-module/>' __date__ = '$Date: 2008/21/04 $' __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' def getCraftedTextFromText(gcodeText, repository=None): 'Export a gcode linear move text.' if gcodec.isProcedureDoneOrFileIsEmpty( gcodeText, 'export'): return g...
= fileName[: fileName.rfind('.')] if repository.addExportSuffix.value: fileNameSuffix += '_export' gcodeText = gcodec.getGcodeFileText(fileName, '') procedures = skeinforge_craft.getProcedures('export', gcodeText)
gcodeText = skeinforge_craft.getChainTextFromProcedures(fileName, procedures[: -1], gcodeText) if gcodeText == '': return None if repository.addProfileExtension.value: fileNameSuffix += '.' + getFirstValue(gcodeText, '(<profileName>') if repository.addDescriptiveExtension.value: fileNameSuffix += getDescript...
import logging import os import shutil import subprocess DEVNULL = open(os.devnull, 'wb') class ShellError(Exception): def __init__(self, command, err_no, message=None): self.command = command self.errno = err_no self.message = message def __str__(self): string = "Command '%s...
stdout=stdout, stderr=stderr, shell=isinstance(cmd, str), env=env) stdout_dump = None stderr_dump = None return_code = 0 if message is
not None or stdout == subprocess.PIPE or stderr == subprocess.PIPE: stdout_dump, stderr_dump = process.communicate(message) return_code = process.returncode elif not background: return_code = process.wait() if background: return process else: if stdout_dump is not No...
import numpy from chainer.backends import cuda from chainer import optimizer _default_hyperparam = optimizer.Hyperparameter() _default_hyperparam.lr = 0.01 _default_hyperparam.alpha = 0.99 _default_hyperparam.eps = 1e-8 _default_hyperparam.eps_inside_sqrt = False class RMSpropRule(optimizer.UpdateRule): """Up...
ault values of the hyperparameters. Args: parent_hyperparam (~chainer.optimizer.Hyperparameter): Hyp
erparameter that provides the default values. lr (float): Learning rate. alpha (float): Exponential decay rate of the second order moment. eps (float): Small value for the numerical stability. eps_inside_sqrt (bool): When ``True``, gradient will be divided by :mat...
""" Kodi urlresolver plugin Copyright (C) 2016 tknorris 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...
le not found') url += '|%s' % urllib.urlencode(headers) return url raise ResolverError(
'Unable to locate link') def get_url(self, host, media_id): return 'http://www.tudou.com/programs/view/%s/' % media_id
import warnin
gs from .file import File, open, read, create, write, CfitsioError try: from healpix import read_map, read_mask except: warnings.warn('Cannot import read_map and read_mask if healpy is not install
ed') pass
### Copyright
(C) 2010 Peter Williams <peter_ono@users.sourceforge.net> ### ### 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; ver
sion 2 of the License only. ### ### 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 cop...
# Copyright 2020 Red Hat, 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 agre...
_CDLL = None def get_cdll(): global _CDLL if not _CDLL: # NOTE(ralonsoh): from https://docs.python.org/3.6/library/ # ctypes.html#ctypes.PyDLL: "Instances of this c
lass behave like CDLL # instances, except that the Python GIL is not released during the # function call, and after the function execution the Python error # flag is checked." # Check https://bugs.launchpad.net/neutron/+bug/1870352 _CDLL = ctypes.PyDLL(ctypes_util.find_library('c...
try: #comment x = 1<caret> y =
2 exc
ept: pass
# -*- coding: utf-8 -*- # Author: Mikhail Polyanskiy # Last modified: 2017-04-02 # Original data: Djurišić and Li 1999, https://doi.org/10.1063/1.369370 import numpy as np import matplotlib.pyplot as plt # LD model parameters - Normal polarization (ordinary) ωp = 27 εinf = 1.070 f0 = 0.014 Γ0 = 6.365 ω0 = 0 ...
====== plt.rc('font', family='Arial', size='14') #plot ε vs eV plt.figure(1) plt.plot(eV, ε.real, label="ε1") plt.plot(eV, ε.imag, label="ε2") plt.xlabel('Photon energy (eV)') plt.ylabel('ε') plt.legend(bbox
_to_anchor=(0,1.02,1,0),loc=3,ncol=2,borderaxespad=0) #plot n,k vs eV plt.figure(2) plt.plot(eV, n, label="n") plt.plot(eV, k, label="k") plt.xlabel('Photon energy (eV)') plt.ylabel('n, k') plt.legend(bbox_to_anchor=(0,1.02,1,0),loc=3,ncol=2,borderaxespad=0) #plot n,k vs μm plt.figure(3) plt.plot(μm, n, label="n") pl...
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on
201
7-06-01 15:57 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pec', '0006_auto_20170601_0719'), ] operations = [ migrations.AddField( model_name='cours', name='type', ...
# -*- coding:utf-8 -*- from django import forms try: from django.utils.encoding import smart_unicode as smart_text except ImportError: from django.utils.encoding import smart_text from cached_modelforms.tests.utils import SettingsTestCase from cached_modelforms.tests.models import SimpleModel from cached_mode...
ield_objects_assignment(self): field = CachedModelMultipleChoiceField(objects=self.cached_list) field2 = CachedModelMultipleChoiceField(objects=self.cached_list[:2]) field.objects = self.cac
hed_list[:2] self.assertEqual(field.objects, field2.objects) self.assertEqual(field.choices, field2.choices)
# coding: utf-8 import copy from google.appengine.ext import ndb import flask from apps import auth from apps.auth import helpers from core import task from core import util import config import forms import models bp = flask.Blueprint( 'user', __name__, url_prefix='/user', template_folder='templates...
') @auth.login_required def verify_email(token): user_db = auth.current_user_db() if user_db.token != token: flask.flash('That link is either invalid or expired.', category='danger') return flask.redirect(flask.url_for('user.profile_update')) user_db.verifi
ed = True user_db.token = util.uuid() user_db.put() flask.flash('Hooray! Your email is now verified.', category='success') return flask.redirect(flask.url_for('user.profile_update')) @bp.route('/merge/', methods=['GET', 'POST']) @auth.admin_required def merge(): user_keys = util.param('user_keys', list) i...
from django.conf import settings from geopy import distance, geocoders import pygeoip def get_geodata_by_ip(addr): gi = pygeoip.GeoIP(settings.GEO_CITY_FILE, pygeoip.MEMORY_CACHE) geodata = gi.record_by_addr(addr) return geodata def get_geodata_by_region(*args): gn = geocoders.GeoNames() retu...
Arguments: location1 A tuple of (lat, long). location2 A tuple of (lat, long). """
return distance.distance(location1, location2).miles
#!/usr/bin/env python # # Copyright 2007 Google 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 L
icense at # # http://w
ww.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 and ...
def
isPrime(num): if num <= 1: return False i = 2 while i < num / 2 + 1: if num % i == 0: return False i += 1 return True big = 600851475143 test = 1 while test < big: test += 1 if big % test == 0: print(test, ' divides evenly') div = big / test...
#!/usr/bin/python3 from scrapers.scrape import scrape_page # if you want to use this scraper without the RESTful api webservice then # change this import: from scrape import scrape_page import re try: import pandas as pd pandasImported = True except ImportError: pandasImported = False BASE_URL = "http://...
le on a stock's finviz page, if it exists as a Python dictionary :param page: HTML tree structure based on the html markup of the scraped web
page. :return: a dictionary of all the financial statistics listed on a stock's finviz page, otherwise will return a empty dictionary """ value_names = page.xpath(VALUE_NAMES_XPATH) values = page.xpath(VALUES_XPATH) values = [value if value != "-" else None for value in values] table = di...
from w3lib.html import remove_tags from requests import session, codes from bs4 import BeautifulSoup # Net/gross calculator for student under 26 years class Student: _hours = 0 _wage = 0 _tax_rate = 18 _cost = 20 def __init__(self, hours, wage, cost): self._hours = hours ...
eader_data.items(): data['data[StaffContractHeader][%s]' % k] = v # Send the request to the server try: request = c.post(WfirmaPlBot._url, data=data, timeout=3) except: print('Przekroczon
o maksymalny czas oczekiwania na odpowiedź serwera') return None # There was some error (most likely server-side), so use offline fallback if request.status_code != codes.ok: print('Wystąpił błąd podczas pobierania danych do rachunku') retur...
import logging; logger = logging.getLogger("morse." + __name__) import socket import select import json import morse.core.middleware from functools import partial from morse.core import services class MorseSocketServ: def __init__(self, port, component_name): # List of socket clients self._client_s...
._base_port] = serv self._component_nameservice[component_name] = self._base_port self._base_port = self._base_port + 1 # Ext
ract the information for this middleware # This will be tailored for each middleware according to its needs function_name = mw_data[1] fun = self._check_function_exists(function_name) if fun != None: # Choose what to do, depending on the function being used # Dat...
# -*- coding: utf-8 -*- from __
future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('interpreter', '0010_auto_20141215_0027'), ] operations = [ migrations.RemoveField( model_name='band', name='members', ), ...
field=models.ManyToManyField(related_name='members', null=True, to='interpreter.Band', blank=True), preserve_default=True, ), ]
# # SPDX-FileCopyrightText: 2016 Dmytro Kolomoiets <amerlyq@gmail.com> and contributors. # # SPDX-License-Identifier: GPL-3.0-only # from miur.cursor import state, update, message as msg class Dispatcher: """Apply actions to any unrelated global states""" def _err_wrong_cmd(self): # Move err processi...
e.entries else None def shift_node_current(self): if state.cursor is None or state.entries is None: return # WARN: must send both (p, e) for *core* # => to check if (p, e) is still available in fs update.handle(msg.NodeGetChildMsg()) update.handle(msg.Li
stNodeMsg()) state.cursor = 0 if state.entries else None
# # noif : False # # nostate : False # # insec : False # # i_am_s : False ...
le.append(True) # System-Fwd rule.append(1) # Rule-Nr. rule.append(1) # Pair-Nr. rule.append(False) # i_am_s rule.append(True) # i_am_d rule.append(IP...
b8:2::11')) # destin rule.append('eth0') # source-if rule.append(1) # source-rn rule.append('eth1') # destin-if rule.append(3) # destin-rn rule.append('udp') ...
""" Classes and functions for interacting with system management daemons. arkOS Core (c) 2016 CitizenWeb Written by Jacob Cook Licensed under GPLv3, see LICENSE.md """ import ldap import ldap.modlist import xmlrpc.client from .utilities import errors from dbus import SystemBus, Interface class ConnectionsManager:...
f):
self.DBus = SystemBus() self.SystemD = self.SystemDConnect( "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager") self.Supervisor = supervisor_connect() def connect_ldap(self): self.LDAP = ldap_connect( config=self.config, passwd=self.secrets.get("l...
"""Commands for argparse for basket command""" import textwrap from PyBake import Path from PyBake.commands import command @command("basket") class BasketModuleManager: """Module Manager for Basket""" longDescription = textwrap.dedent( """ Retrieves pastries from the shop. """) def createArguments(self...
action="append_const", const="install", help="Perform an install, regardless whether the pastry is already installed or not.") basketParser.add_argument("--force", dest="force", ...
ketParser.set_defaults(func=execute_basket) def execute_basket(args): """Execute the `basket` command.""" from PyBake import log force = args.force or [] del args.force args.forceDownload = any(arg in ("all", "download") for arg in force) args.forceInstall = any(arg in ("all", "install") for arg in force) ...
#! /usr/bin/python3 # # This source code is part of icgc, an ICGC processing pipeline. # # Icgc 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 ...
proved_symbol from hgnc where ensembl_gene_id in (%s)" % gene_id_string gene_symbols = dict(hard_landing_search(cursor, qry)) for gene in gene_ids: print("\t"*de
pth, gene_symbols.get(gene,""), gene_names.get(gene,"")) return ############## def characterize_subtree(cursor, graph, pthwy_id, gene_groups, depth, verbose=True): # this is the whole subtree # children = [node for node in nx.dfs_preorder_nodes(graph, pthwy_id)] # A successor of n is a node m such that there exi...
ile) return set( os.path.realpath(os.path.join(util.GetChromiumSrcDir(), os.pardir, path)) for path in deps_paths) def FindPythonDependencies(module_path): logging.info('Finding Python dependencies of %s' % module_path) # Load the module to inherit its sys.path modifications. imp.load_source( ...
me # location in the archive. This can be confusing for users. gsutil_path = os.path.realpath(cloud_storage.FindGsutil()) if cloud_storage.SupportsProdaccess(gsutil_path): gsutil_base_dir = os.path.join(
os.path.dirname(gsutil_path), os.pardir) gsutil_dependencies = path_set.PathSet() gsutil_dependencies.add(os.path.dirname(gsutil_path)) # Also add modules from depot_tools that are needed by gsutil. gsutil_dependencies.add(os.path.join(gsutil_base_dir, 'boto')) gsutil_dependencies.add(os.p...
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- # This file is part of Guadalinex # # This software 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, ...
print msg % ('organization',) try: self.set_notes(conf['notes']) except KeyError as e:
print msg % ('notes',) try: self.set_gem_repo(conf['gem_repo']) except KeyError as e: print msg % ('gem_repo',) try: self._chef_conf.load_data(conf['chef']) except KeyError as e: print msg % ('chef',) try: self._gcc_co...
VShowID, IMDb, Title, Rating, Votes, TVDB, TMDB #episode: EpisodeID, IMDb, Title, Rating, Votes, TVDB, TMDB, season, episode global num_threads if IMDb == None or IMDb == "" or "tt" not in IMDb: IMDb = None Top250 = None if dType == "movie": Top250 = TVDB if Top250 == None: Top250 = 0 TVDB = None defaultLo...
addonLanguage(32500) % ( Title,
str( updatedRating ), str( updatedVotes ), str( updatedTop250 ) ) ) else: defaultLog( addonLanguage(32502) % ( Title ) ) lock.acquire() num_threads -= 1 lock.release() return class Movies: def __init__( self ): defaultLog( addonLanguage(32255) ) statusLog( "\n" + "--> " + addonLanguage(32255).rsplit(' ',...
d also serving static from the same directory. """ import os from path import Path as path from tempfile import mkdtemp from openedx.core.release import RELEASE_LINE CONFIG_ROOT = path(__file__).abspath().dirname() TEST_ROOT = CONFIG_ROOT.dirname().dirname() / "test_root" ########################## Prod-like settin...
RY_DELAY=0, ) ###################### Grade Downloads #
##################### GRADES_DOWNLOAD = { 'STORAGE_TYPE': 'localfs', 'BUCKET': 'edx-grades', 'ROOT_PATH': os.path.join(mkdtemp(), 'edx-s3', 'grades'), } # Configure the LMS to use our stub XQueue implementation XQUEUE_INTERFACE['url'] = 'http://localhost:8040' # Configure the LMS to use our stub EdxNotes ...
import os ADDRESS = '127.0.0.1' PORT = 12345 BACKUP_DIR = 'Backup' BASE_P
ATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
import os import requests if __name__ == "__main__": session = requests.Session() data = {"email": "admin@knex.com", "password": "admin"} session.post("http://localhost:5000/api/users/login", data=data) for file in os.listdir("."): if file.
endswith(".json"): text = open(file, "r").read() res = session.post("http://localhost:5000/api/projects", data=text.encode('utf-8'), headers={'Content-Type': 'application/json'}) print(file + " " + str(res)) elif file.endswith(".json5"): ...
//localhost:5000/api/projects", data=text.encode('utf-8'), headers={'Content-Type': 'application/json5'}) print(file + " " + str(res)) session.get("http://localhost:5000/api/users/logout")
if self.closed: raise ValueError('I/O operation on closed file') return False @property def encoding(self): return self.response.charset class ResponseStreamMixin(object): """Mixin for :class:`BaseRequest` subclasses. Classes that inherit from this mixin will automatical...
to a location other than the Request-URI for completion of the request or identification of a new resource.''') age = header_property('Age', None, parse_date, http_date, doc=''' T
he Age response-header field conveys the sender's estimate of the amount of time since the response (or its revalidation) was generated at the origin server. Age values are non-negative decimal integers, representing time in seconds.''') content_type = header_property('Content-Type'...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2012-2013 University of Dundee & Open Microscopy Environment # All Rights Reserved. # # 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 Foundat...
License for more details. # # You should have received a copy 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. from builtins import str from builtins import range from builtins import object ...
m/ome/snoopys-sandbox.git" class SandboxTest(object): def setup_method(self, method): # Basic logging configuration so if a test fails we can see # the statements at WARN or ERROR at least. logging.basicConfig() self.method = method.__name__ self.cwd = os.getcwd() ...
from django.conf import settings from images.models import S3Connection from shutil import copyfileobj import tinys3 import os import urllib class LocalStorage(object): def __init__(self, filename): self.filename = filename def get_file_data(self): """ Returns the raw data for the spec...
args_list = ['%s-%s' % (key, value) for key, value in arguments_dict.items()] return '--'.join(args_list) class S3Storage(LocalStorage): def __init__(self, *args, **kwargs): """ Overrides the LocalStorage and initializes a shared S3 connection """ super(S3Storage, self)....
) self.conn = tinys3.Connection(self.S3_ACCESS_KEY, self.S3_SECRET_KEY, default_bucket=self.S3_BUCKET, tls=True) def get_remote_path(self): """ Returns an absolute remote path for the filename from the S3 bucket """ return 'https://%s.%s/%s' % (self.conn.default_bucket, self...
import os import uuid from django.db import models from django.utils import timezone from django.contrib.auth.models import User def avatar_upload(instance, filename): ext = filename.split(".")[-1] filename = "%s.%s" % (uuid.uuid4(), ext) return os.path.join("avatars", filename) class Profile(models.M...
avatar_upload, blank=True) bio = models.TextField(blank=True) affiliation = models.CharField(max_length=1
00, blank=True) location = models.CharField(max_length=100, blank=True) website = models.CharField(max_length=250, blank=True) twitter_username = models.CharField("Twitter Username", max_length=100, blank=True) created_at = models.DateTimeField(default=timezone.now) modified_at = models.DateTimeFie...
) l.close() def writeStoOutputFiles(s, out_bh_file): global best_query_taxon_score, BestInterTaxonScore, options try: (cutoff_exp, cutoff_mant) = best_query_taxon_score[(s.query_id,
s.subject_taxon)] if ( s.query_taxon != s.subject_taxon and s.evalue_exp < options.evalueExponentCutoff and s.percent_match > options.percentMatchCutoff and (s.evalue_mant < 0.01 or s.evalue_exp==cutoff_exp and s.evalue_mant==cutoff_mant) ): out_bh_file.write('{0}\t{1}\t{2}\t{3}\n'.format(s.query...
try: (cutoff_exp, cutoff_mant) = BestInterTaxonScore[s.query_id] if (s.query_taxon == s.subject_taxon and s.query_id != s.subject_id and s.evalue_exp <= options.evalueExponentCutoff and s.percent_match >= options.percentMatchCutoff and (s.evalue_mant < 0.01 or s.evalue_exp<cutoff_exp or (s.evalu...
es, we could make a Patch of exterior ax.add_patch(PolygonPatch(poly, facecolor=facecolor, alpha=alpha)) ax.plot(a[:, 0], a[:, 1], color=edgecolor, linewidth=linewidth) for p in poly.interiors: x, y = zip(*p.coords) ax.plot(x, y, color=edgecolor, linewidth=linewidth) def plot_multipolygon(...
: str (default None) The name of the column to be plotted. categorical : bool (default False) If False, colormap will reflect numerical values of the column being plotted. For non-numerical columns
(or if column=None), this will be set to True. colormap : str (default 'Set1') The name of a colormap recognized by matplotlib. alpha : float (default 0.5) Alpha value for polygon fill regions. Has no effect for lines or points. lin...
must_exist=False) ganesha.os.listdir.assert_called_once_with( self.fake_conf_dir_path) ganesha.LOG.info.assert_called_once_with( mock.ANY, self.fake_conf_dir_path) self.assertFalse(mockopen.called) self.assertFalse(ganesha.ganesha_manager....
self.assertRais
es(OSError, self._helper._load_conf_dir, self.fake_conf_dir_path) ganesha.os.listdir.assert_called_once_with(self.fake_conf_dir_path) def test_load_conf_dir_error_conf_dir_present_must_exist_false(self): self.mock_object( ganesha.os, 'listdir', mock...
# setup.py: based off setup.py for toil-vg, modified to install this pipeline # instead. import sys import os # Get the local version.py and not any other version module execfile(os.path.join(os.path.dirname(os.path.realpath(__file__)), "version.py")) from setuptools import find_packages, setup from setuptools.comman...
tions(self) self.test_args = [] self.test_suite = True def run_tests(self): import pytest # Sanitize command line arguments to avoid confusing Toil code # attempting to parse them sys.argv[1:] = [] errno = pytest.main(self.pytest_args) sys.exit(errno)...
a good Toil with cloud support print(""" Thank you for installing the hgvm-builder pipeline! If you want to run this Toil-based pipeline on a cluster in a cloud, please install Toil with the appropriate extras. For example, To install AWS/EC2 support for example, run pip install toil[aws,mesos]{} on every EC2 instan...
# -*- coding: utf-8 -*- """
QGIS Unit tests for QgsMultiEditToolButton. .. note:: 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. """ __author__ = 'Nyall D...
t QgsMultiEditToolButton from qgis.testing import start_app, unittest start_app() class TestQgsMultiEditToolButton(unittest.TestCase): def test_state_logic(self): """ Test that the logic involving button states is correct """ w = QgsMultiEditToolButton() self.assertEqual...
import os import json import logging import ConfigParser from framework.db import models from framework.dependency_management.dependency_resolver import BaseComponent from framework.dependency_management.interfaces import MappingDBInterface from framework.lib.exceptions import InvalidMappingReference class MappingDB...
lf.mapping_types def GetMappings(self, mapping_type): if mapping_type in self.mapping_types: mapping_objs = self.db.session.query(models.Mapping).all() mappings = {} for mapping_dict in self.
DeriveMappingDicts(mapping_objs): if mapping_dict["mappings"].get(mapping_type, None): mappings[mapping_dict["owtf_code"]] = mapping_dict["mappings"][mapping_type] return mappings else: raise InvalidMappingReference("InvalidMappingReference %s requeste...
# for back compatibility class Logger(object): def __init__(self): pass def write(self, message): intp.appendOutput(message) def reset(self): pass def flush(self): pass class PyZeppelinContext(object): """ A context impl that uses Py4j to communicate to JVM """ def __init__(self, z...
ce, as in Spark print("%table " + header_buf.read() + body_buf.read()) # + # ("\n<font color=red>Results are limited by {}.</font>" \ # .format(self.max_result) if limit else "") #) body_buf.close
(); header_buf.close() def show_matplotlib(self, p, fmt="png", width="auto", height="auto", **kwargs): """Matplotlib show function """ if fmt == "png": img = BytesIO() p.savefig(img, format=fmt) img_str = b"data:image/png;base64," img_str += base64.b64encode(...
f
rom c3nav.editor.models.changedobject import ChangedObject # noqa from c3nav.editor.models.changeset import ChangeSet #
noqa from c3nav.editor.models.changesetupdate import ChangeSetUpdate # noqa
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone import django.core.validators import django.contrib.auth.models class Migration(migrations.Migration): dependencies = [ ('auth', '0006_require_contenttypes_0002'), ] ...
ser belongs to. A user will get all permissions granted to each of their groups.', verbose_name='groups')), ('user_permissions', models.ManyToManyField(related_query_name='user', related_name='user_set', to='auth.Permission', blank=True, help_text='Specific permissions for this user.', verbose_name='use...
'verbose_name_plural': 'Users', }, managers=[ ('objects', django.contrib.auth.models.UserManager()), ], ), ]
import socket from heapq import h
eappush, heappop, heapify from collections import defaultdict ##defbig def encode(symb2freq): """Huffman encode the given dict mapping symbols to weights""" heap = [[wt, [sym, ""]]
for sym, wt in symb2freq.items()] heapify(heap) while len(heap) > 1: lo = heappop(heap) hi = heappop(heap) for pair in lo[1:]: pair[1] = '1' + pair[1] for pair in hi[1:]: pair[1] = '0' + pair[1] heappush(heap, [lo[0] + hi[0]] + lo[1:] + hi[1:]) ...
_insert(tx): existing_user = await check_valid_new_user(tx, username, login_id, is_developer, is_service_account) if existing_user is not None: return False await tx.execute_insertone( ''' INSERT INTO users (state, username, login_id, is_developer, is_service_account) VA...
aller'] = 'login' session['flow'] = flow_data return aiohttp.web.HTTPFound(flow_data['authorization_url']) @routes.get('/oauth2callback') async def callback(request): session = await aiohttp_session.get_session(request) if 'flow' not in session: raise web.HTTPUnauthorized() nb_url = depl...
next_page = session.pop('next', nb_url) flow_dict = session['flow'] flow_dict['callback_uri'] = deploy_config.external_url('auth', '/oauth2callback') cleanup_session(session) try: flow_result = request.app['flow_client'].receive_callback(request, flow_dict) login_id = flow_result.log...
else: vars_matrix = self.dcm(otherframe) * Matrix(otherframe.varlist) mapping = {} for i, x in enumerate(self): if Vector.simp: mapping[self.varlist[i]] = trigsimp(vars_matrix[i], method='fu') else: mapping[s...
[0, sin(angle), cos(angle)]]) elif axis == 2: return Matrix([[cos(angle), 0, sin(angle)], [0, 1, 0], [-sin(angle), 0, cos(angle)]]) elif axis == 3: return Matrix([[cos(angle), -sin(angle), 0], [sin(...
213', '321', '121', '131', '212', '232', '313', '323', '') rot_order = str( rot_order).upper() # Now we need to make sure XYZ = 123 rot_type = rot_type.upper() rot_order = [i.replace('X', '1') for i in rot_order] rot_order = [i.replace('Y', '2') fo...
"""PEP 656 support. This module implements logic to detect if the currently running Python is linked against musl, and what musl version is used. """ import contextlib import functools import operator import os import re import struct import subprocess import sys from typing import IO, Iterator, NamedTuple, Optional,...
) if not m: return None return _MuslVersion(major=int(m.group(1)), minor=int(m.group(2))) @functools.lru_cache() def _get_musl_version(executable: str) -> Optional[_MuslVersion]: """Detect currently-running musl runtime version. This is done by checking the specified executable's dynamic link...
ing. If the loader is musl, the output would be something like:: musl libc (x86_64) Version 1.2.2 Dynamic Program Loader """ with contextlib.ExitStack() as stack: try: f = stack.enter_context(open(executable, "rb")) except IOError: return None ...
self.settings.setValue('testqgissettings/name', 'qgisrocks') self.settings.sync() self.assertEqual(self.settings.value('testqgissettings/name'), 'qgisrocks') def test_defaults(self): self.assertIsNone(self.settings.value('testqgissettings/name')) self.addToDefaults('testqgissetting...
e will be resumed!!! self.settings.beginGroup('connections-xyz') self.settings.remove('OSM') self.settin
gs.endGroup() # Check it again! self.settings.beginGroup('connections-xyz') self.assertEqual(self.settings.value('OSM'), 'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png') self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png') self.sett...
s import ( compat_urllib_request, compat_urllib_error, ContentTooShortError, encodeFilename, sanitize_open, format_bytes, ) class HttpFD(FileDownloader): _TEST_FILE_SIZE = 10241 def real_download(self, filename, info_dict): url = info_dict['url'] tmpfilename = self.te...
if (err.code < 500 or err.code >= 600) and err.code != 416: # Unexpected HTTP error raise elif err.code == 416: # Unable to resume (requested range not satisfiable) try:
# Open the connection again without the range header data = self.ydl.urlopen(basic_request) content_length = data.info()['Content-Length'] except (compat_urllib_error.HTTPError, ) as err: if err.code < 500 or err...
from jx_elasticsearch.es52.painless._utils import Painless, LIST_TO_PIPE from
jx_elasticsearch.es52.painless.add_op import AddOp from jx_elasticsearch.es52.painless.and_op import AndOp from jx_elasticsearch.es52.painless.basic_add_op import BasicAddOp from jx_elasticsearch.es52.painless.basic_eq_op import BasicEqOp from jx_elasticsearch.es52.painless.basic_index_of_op import BasicIndexOfOp from ...
icsearch.es52.painless.basic_substring_op import BasicSubstringOp from jx_elasticsearch.es52.painless.boolean_op import BooleanOp from jx_elasticsearch.es52.painless.case_op import CaseOp from jx_elasticsearch.es52.painless.coalesce_op import CoalesceOp from jx_elasticsearch.es52.painless.concat_op import ConcatOp from...
# Building inheritance class MITPerson(Person): nextIdNum = 0 #next ID number to assing def __init__(self, name): Person.__init__(self, name) #initialize Person attributes # new MITPerson atrribute: a unique ID number self.idNum = MITPerson.nextIdNum MITPerson.nextIdNum += ...
- def __init__(self, name, classYear): MITPerson.__init__(self, name) self.year = classYear def getClass(self): # getter
method return self.year class Grad(Student): ##---- pass class TransferStudent(Student): pass def isStudent(obj): return isinstance(obj, Student)