prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
type='TrueType' name='Calligrapher-Regular' desc={'Ascent':899,'Descent':-234,'CapHeight':731,'Flags':32,'FontBBox':'[-50 -234 1328 899]','ItalicAngle':0,'StemV':70,'MissingWidth':800} up=-200 ut=20 cw={ '\x00':800,'\x01':800,'\x02':800,'\x03':800,'\x04':800,'\x05':800,'\x06':800,'\x07':800,'\x08':800,'\t':800,'\n':8...
\xc4':743,'\xc5':743, '\xc6':1060,'\xc7':598,'\xc8':608,'\xc9':608,'\xca':608,'\xcb':608,'\xcc':308,'\xcd':308,'\xce':308,'\xcf':308,'\xd0':0,'\xd1':817,'\xd2':729,'\xd3':729,'\xd4':729,'\xd5':729,'\xd6':729,'\xd7':0,'\xd8':729,'\xd9':805,'\xda'
:805,'\xdb':805, '\xdc':805,'\xdd':0,'\xde':0,'\xdf':688,'\xe0':581,'\xe1':581,'\xe2':581,'\xe3':581,'\xe4':581,'\xe5':581,'\xe6':792,'\xe7':440,'\xe8':450,'\xe9':450,'\xea':450,'\xeb':450,'\xec':283,'\xed':283,'\xee':283,'\xef':283,'\xf0':800,'\xf1':595, '\xf2':508,'\xf3':508,'\xf4':508,'\xf5':508,'\xf6':508,'\xf7':...
"""Thin wrapper around the microdata library.""" from __future__ import absolute_import import microdata class Item(microdata.Item): """Add an "extra" field to microdata Items, so people won't feel the need to make up ad-hoc properties. Also add __eq__() and __repr__(). """ def __init__(self, *a...
item = super(Item, self).json_dict() if self.extra: item['extra'] = self.ext
ra return item def __eq__(self, other): if not isinstance(other, microdata.Item): return False return (self.itemid == other.itemid and self.itemtype == other.itemtype and self.props == other.props and self.extra == getattr(other,...
# -*- coding: utf-8 -*- # # Copyright (©) 2013 Marcelo Jorge Vieira <metal@alucinados.com> # Copyright (©) 2013 Gustavo Noronha Silva <gustavo@noronha.eti.br> # # 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 F...
of the first legislature to the end # of the last, which makes more sense to our purposes. first = institution.legislature_set.order_by('date_start')[0] last = institution.legislature_set.order_by('-date_end')[0] else: first = Legislature.objects.order_by('date_start')[0] la...
if cdf < min_date: cdf = min_date if cdt > max_date: cdt = max_date cdf_string = cdf.strftime('%B de %Y') cdt_string = cdt.strftime('%B de %Y') d = dict(current_date_from=cdf_string, current_date_to=cdt_string) if include_date_objects: d.update(dict(cdf=cdf, cdt=cdt)) ...
eption())) results.DidRunPage(self.pages[0]) results.WillRunPage(self.pages[1]) results.DidRunPage(self.pages[1]) self.assertEqual(set([self.pages[0]]), results.pages_that_failed) self.assertEqual(set([self.pages[1]]), results.pages_that_succeeded) self.assertEqual(2, len(results.all_page_run...
results.AddValue(trace.TraceValue(None, trace_data.TraceData({'test' : 2}))) results.DidRunPage(self.pages[1]) results.PrintSummary() values = results.FindAllTraceValues() self.assertEquals(2, len(values)) def testCleanUpCleansUpTraceValues(self
): results = page_test_results.PageTestResults() v0 = trace.TraceValue(None, trace_data.TraceData({'test': 1})) v1 = trace.TraceValue(None, trace_data.TraceData({'test': 2})) results.WillRunPage(self.pages[0]) results.AddValue(v0) results.DidRunPage(self.pages[0]) results.WillRunPage(self....
from __future__ import absolute_import from Plugins.Plugin import PluginDescriptor from Components.PluginComponent import plugins from enigma import eDBoxLCD from .qpip import QuadPipScreen, setDecoderMode def main(session, **kwargs): session.open(QuadPipScreen) def autoStart(reason, **kwargs): if reason == 0: ...
ist = [] list.append( PluginDescriptor(name=_("Enable Quad PIP"), description="Quad Picture in Picture", where=[PluginDesc
riptor.WHERE_EXTENSIONSMENU], fnc=main)) list.append( PluginDescriptor( where=[PluginDescriptor.WHERE_AUTOSTART], fnc=autoStart)) return list
""" create_org_data_czar_policy.py Creates an IAM group for an edX org and applies an S3 policy to that group that allows for read-only access to the group. """ import argparse import boto3 from botocore.exceptions import ClientError from string import Template import sys template = Template("""{ "Version":"2012-1...
= argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument('-o', '--org', help='Name of the org for which to create an IAM '
'role and policy, this should have the same ' 'name as the S3 bucket') group.add_argument('-f', '--file', help='The path to a file containing one org name ' 'per line.') args = parser.parse_args() iam_connection = bot...
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import unicode_literals from .exceptions import TransactionValidationError AVAIABLE_PAYMENT_METHOD = ['credit_card', 'boleto'] def validate_transaction(attrs): if len(attrs) <= 0: raise TransactionValidationError('Need a vali...
e(transaction_attributes, dict): raise TransactionValidationError( 'Transaction attributes need be an dict') self.attributes.update(transaction_attributes) def charge(self): self.validate_attrs def validate_attrs(self): validate_transaction(self.attri
butes)
pp = Flask(__name__) def login_required(func): #函数装饰器,用于装饰登陆是否有session,检验身份 @wraps(func) def wrapper(*args, **kwargs): if session.get('user') is None: return redirect('/') rt = func(*args, **kwargs) return rt return wrapper ''' 打开用户登录页面 ''' @app...
.html', _id=_id,error=_error, username=username, password=password, age=age) @app.route('/user/delete/') @login_required def delete_user(): _id = request.args.get('id') _user,_error = user.get_info(_id=_id) if _user is None: _error = '用户信息不存在' else: username = _user[0]['username'] ...
t.form.get('username','') users,_error = user.get_info(username=username) if users: return render_template('users.html',users = users) flash("Sorry,没有查到相关数据!") return render_template('users.html') @app.route('/user/logs/',methods=['POST','GET']) @login_required def logs(): count = request.f...
import os from django.core.management.base import CommandError, AppCommand from django_extensions.management.utils import _make_writeable from optparse import make_option class Command(AppCommand): option_list = AppCommand.option_list + ( make_option('--name', '-n', action='store', dest='command_name', de...
ethod = "handle_label(self, label, **options)" elif base_command == 'NoArgsCommand': handle_method = "handle_noargs(self, **options)" # walks the template structure and copies it for d, subdirs, files in os.walk(template_dir): relative_dir = d[len(templat
e_dir) + 1:] if relative_dir and not os.path.exists(os.path.join(copy_to, relative_dir)): os.mkdir(os.path.join(copy_to, relative_dir)) for i, subdir in enumerate(subdirs): if subdir.startswith('.'): del subdirs[i] for f in files: if f.endswith...
#PBS -N UnBalance #PBS -m ae #PBS -q long #PBS -l nodes=1:opteron:ppn=2 """Test handling of extreme load-unbalancing.""" from asap3 import * from asap3.md import MDLogger from ase.lattice.cubic import FaceCenteredCubic import numpy as np from asap3.mpi import world #DebugOutput("UnBalance.%d.out") #set_verbose(1) pr...
#AsapThreads() cpulayout = (1,1,2) element = 'Pt' size = (20,20,100) master = world.rank == 0 if master: atoms = FaceCenteredCubic(symbol=element, size=size, pbc=(True,
True, False)) atoms.center(vacuum=10.0, axis=2) atoms.set_momenta(np.zeros((len(atoms),3))) # Select an atom to get a kick r = atoms.get_positions() uc = atoms.get_cell() x = r[:,0] - 0.5 * uc[0,0] y = r[:,1] - 0.5 * uc[1,1] z = r[:,2] zprime = z - 0.01 * (x * x + y * y) n = np....
" __credits__ = ["Ponzoni Nelson"] __maintainer__ = "Ponzoni Nelson" __contact__ = "npcuadra@gmail.com" __email__ = "npcuadra@gmail.com" __license__ = "GPL" __version__ = "1.0.0" __status__ = "Production" """ """ import numpy import theano from cupydle.dnn.funciones import sigmoideaThea...
# Log-Probabilities (call it LP) with one row per example and # one column per class LP[T.arange(y.shape[0]),y] is a vector # v containing [LP[0,y[0]], LP[1,y[1]], LP[2,y[2]], ..., # LP[n-1,y[n-1]]] and T.mean(LP[T.arange(y.shape[0]),y]) i
s # the mean (across minibatch examples) of the elements in v, # i.e., the mean log-likelihood across the minibatch. return -theano.tensor.mean(theano.tensor.log(self.activate())[theano.tensor.arange(y.shape[0]), y]) def errors(self, y): """Return a float representing the number of...
# SecuML # Copyright (C) 2016 ANSSI # # SecuML 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. # # SecuML is distributed in the hope t...
ilies_supervision=None): SemiSupervisedProjectionConfiguration.__init__( self, Sdml, families_supervision=families_supervision) @staticmethod def fromJson(obj): conf = SdmlConfiguration( families_supervision=obj['families_supervision']) conf.num_components = obj[...
conf = SemiSupervisedProjectionConfiguration.toJson(self) conf['__type__'] = 'SdmlConfiguration' return conf DimensionReductionConfFactory.getFactory().registerClass('SdmlConfiguration', SdmlConfiguration)
"""Support for sending data to Emoncms.""" import logging from datetime import timedelta import requests import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.const import ( CONF_API_KEY, CONF_WHITELIST, CONF_URL, STATE_UNKNOWN, STATE_UNAVAILABLE, CONF_SCAN_INTERVAL)...
"Send whitelisted entities states regularly to Emoncms.""" payload_dict = {} for entity_id in whitelist: state = hass.states.get(entity_id) if state is None or state.state in ( STATE_UNKNOWN, '', STATE_UNAVAILABLE): continue try:...
if payload_dict: payload = "{%s}" % ",".join("{}:{}".format(key, val) for key, val in payload_dict.items()) send_data(conf.get(CONF_URL), conf.get(CONF_API_KEY), str(conf.get(CONF_INPUTNODE)), ...
), name='dateRange', description='Filters results to a provided date range.', overwrite_flag=True, parameters=[ g.NamedViewParameter( name="start", description="A date string for the start of date range.", ...
transient_proper
ties=[ g.Property('busCount', 'java.lang.Long') ], pre_aggregation_filter_functions=[ g.PredicateContext( selection=['startDate'], ...
# encoding: utf-8 # module samba.dcerpc.drsblobs # from /usr/lib/python2.7/dist-packages/samba/dcerpc/drsblobs.so # by generator 1.135 """ drsblobs DCE/RPC """ # imports import dcerpc as __dcerpc import talloc as __talloc class DsCompressedChunk(__talloc.Object): # no doc def __init__(self, *args, **kwargs):...
pack """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass data = property(lambda self: object(), lambda self, v: None, lambda self: No...
marker = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
ow to be # valid solution (Project EULER says that it should be possible to # find an algorithm that solves the problem in less than 60 secs). # # # In the end, method number five ended up solving this problem in # 0.024 secs which is really nice seeing as how the first three # attempts could not solve the problem...
basically each sequence of exactly N R's and also N D's will # represent a path through an NxN grid, and at the same time each path # through a NxN grid will be represented by exactly one such sequence. # # Thus, what we want to know is "In how many ways can be re-order a # sequence of N R's and N D's". The answer goe...
object which is supposed to go first and at that # time you have X objects to choose from, after that you choose the # object that should go after the first object and at this time you # have only X-1 choices because you can't choose the already choosen # object again. And thus you end up with X * (X - 1) * (X - 2) * ...
# This file is part of BHMM (Bayesian Hidden Markov Models). # # Copyright (c) 2016 Frank Noe (Freie Universitaet Berlin) # and John D. Chodera (Memorial Sloan-Kettering Cancer Center, New York) # # BHMM is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public Licen...
cense # along with this program. If not, see <http://www.gnu.org/licenses/>. __author__ = 'noe'
#!/usr/bin/env python # coding: utf-8 """ Given two strings A and B, find the minimum number of times A has to be repeated such that B is a substring of it. If no such solution, return -1. For example, with A = "abcd" and B = "cdabcdab". Return 3, because by repeating A three times (“abcdabcdabcd”), B is a substrin...
repeats = int(ceil(len(B) / len(A))) container = "" for _ in range(repeats): container += A if container.find(B) != -1: return repeats container += A if
container.find(B) != -1: return repeats + 1 return -1 if __name__ == '__main__': sol = Solution().repeatedStringMatch print(sol("abcd", "cdabcdab")) print(sol("abc", "cdabcdab")) print(sol("abc", "cdabcdab"))
from Chip import OpCodeDefinitions from Tests.OpCodeTests.OpCodeTestBase import OpCodeTestBase class TestRtiOpCode(OpCodeTestBase): def te
st_execute_rti_implied_command_calls_and_method(self): self.assert_opcode_execution(OpCodeDefinitions.rti_implied_command, self.targe
t.get_rti_command_executed)
ordering: overrides["ordering"] = ordering if list_display: overrides["list_display"] = list_display return type(model_class.__name__ + "Admin", (admin.ModelAdmin,), overrides) class CDEPermittedValueAdmin(admin.StackedInline): model = CDEPermittedValue extra = 0 fieldsets = ( ...
gistryYaml, RegistryYa
mlAdmin), ] NORMAL_MODE_ADMIN_COMPONENTS = [ (Registry, RegistryAdmin), (QuestionnaireResponse, QuestionnaireResponseAdmin), (Prec
import math def is_palindrome(n): s = str(n) return s == s[::-1] def is_prime(n): if n <= 1: return False if n % 2 == 0 and n != 2: return False if n == 2:
return True root = math.sqrt(n) i = 3 while i <= root: if n % i == 0: return False i += 2 return True i = 999 while i > 0: if not is_palindrome(i): i -= 1 continue if not is_prime(i): i -= 1
continue print i break
if self.show_advanced_options: return await self.async_step_user_advanced(errors=errors) return self.async_show_form(step_id="user", errors=errors) async def async_step_user_advanced(self, user_input=None, errors=None): """Handle an advanced mode flow initialized by the user.""...
r_input=None, errors=None): """Begin manual configuration.""" if user_input is not None and errors is None: user_input.pop(CONF_URL, None) host = user_input.get(CONF_HOST) if host: port = user_input[CONF_PORT] prefix = "https" if user_i...
return await self.async_step_manual_setup( user_input=user_input, errors={"base": "host_or_token"} ) return await self.async_step_server_validate(user_input) previous_input = user_input or {} data_schema = vol.Schema( { vol...
alse: self.proc_vad_info[pid].extend(["NA", Address(0), Hex(0), "NA", "NA"]) else: self.proc_vad_info[pid].extend(["No VAD", Address(0), Hex(0), "No VAD", "No VAD"]) def get_proc_peb_info(self): return self.proc_peb_info ...
lit(','): fil_pid = int(p)
if int(fil_pid) == hol_pid: yield (proc_peb_info[hol_pid], proc_vad_info[hol_pid], hol_pid, hol_type, similar_procs, parent_proc_info[hol_pid]) ...
"""Context processors, these get called and add things to template contexts""" from .
models import Tag def pinned_tags(request): """ Adds the list of tags this user has pinned """ out = {} if request.user.is_authenticated(): out["pinned_tags"] = Tag.by_user(request.user).filter(
pinned=True) return out
import datetime from django.conf import settings from django.contrib.auth import get_user_model, login from django.shortcuts import get_object_or_404 from django.template.response import TemplateResponse from django.views.decorators.csrf import csrf_exempt from oauth2client import client, crypt from rest_framework.de...
zer. if metric.type == 'C': qs = (CategoryCollection.objects.select_related('dataset', 'metric') .get(dataset=dataset, metric=metric, population='All')) serializer = CategoryDistributionSerializer(qs, populations=po...
elif metric.type == 'N': qs = (NumericCollection.objects.select_related('dataset', 'metric') .get(dataset=dataset, metric=metric, population='All')) serializer = NumericDistributionSerializer(qs, populations=pops) ...
r('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class PermissionsOperations: """PermissionsOperations async operations. You should not instantiate this class directly.
Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.authorization.v2018_01_01_preview.models :param client: Client for service requests. :param config:...
serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self...
"""Definitions for the `RProcess` class.""" from math import isnan import numpy as np from astrocats.catalog.source import SOURCE from mosfit.constants import C_CGS, DAY_CGS, IPI, KM_CGS, M_SUN_CGS from mosfit.modules.engines.engine import Engine from scipy.interpolate import RegularGridInterpolator # Important: Onl...
d, bounds_error=False, fill_value=None) def process(self, **kwargs): """Process module.""" self._times = kwargs[self.key('dense_times')] self._mass = kwargs[self.key('mejecta')] * M_SUN_CGS self._rest_texplosion = kwargs[self.key('resttexplosion')] self._vejecta = kwargs[sel...
/ M_SUN_CGS, self._vejecta / self.ckm])[0] self._d = self.therm_func_d( [self._mass / M_SUN_CGS, self._vejecta / self.ckm])[0] ts = [ np.inf if self._rest_texplosion > x else (x - self._rest_texplosion) for x in self._times ] self._lscale...
from PyQt5.QtCore import QObject, pyqtSignal class Player(QObject): updated = pyqtSignal(object, object) newCurrentGame = pyqtSignal(object, object, object) """ Represents a player the client knows about. """ def __init__(self, id_, login, gl...
f): return self.global_rating[1] @property def ladder_rating_mean(self): return self.ladder_rating[0] @property def ladder_rating_deviation(self): return self.ladder_rating[1] def __re
pr__(self): return self.__str__() def __str__(self): return ("Player(id={}, login={}, global_rating={}, " "ladder_rating={})").format( self.id, self.login, self.global_rating, self.ladder_rating ) @property def current...
rn redirect('/download/table/{0}/{1}/{2}/{3}'.format( file_identifier, request.args['table'].replace('%', '%25').replace('\\', '%5C'), version, output_format)) else: abort(404) elif record is not None: # this happens when we access an id of a data record # in wh...
r {} {}'.format(' '.join(copy_command), submission_temp_path + '/.', submission_path)) subprocess.check_output(copy_command + ['-r', submission_temp_path + '/.', submission_path]) rmtree(submission_temp_path, ignore_errors=True) # can uncomment when this is definitely working submission_found ...
le_path = os.path.join(file_save_directory, 'oldhepdata') if not os.path.exists(file_path): os.makedirs(file_path) print('Saving file to {}'.format(os.path.join(file_path, filename))) file.save(os.path.join(file_path, filename)) submission_found = False if submission_f...
# Copyright 2021 The Kubeflow 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 applicable law o
r 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 # limitations under the License. """Helper utils used in artifact and onto...
upported Schema field types.""" NUMBER = 'number' INTEGER = 'integer' STRING = 'string' BOOL = 'bool' OBJECT = 'object' ARRAY = 'array' def parse_schema(yaml_schema: str) -> Tuple[str, Dict[str, SchemaFieldType]]: """Parses yaml schema. Ensures that schema is well-formed and returns d...
rigin server which the WSGI spec says we should # act like. So we drop them and add our own. # # In the future, concatenation server header values # might be better, but nothing else does it and # dropping them is easier. hop_headers = set(""" connection keep-alive proxy-authenticate proxy-authorization te trai...
level = 0 for character in name: if character != '.': break level += 1 name = _resolve_name(name[level:], package, level) __import__(name) return sys.modules[name] def load_class(uri, default="sync", section="gunicorn.worke...
ri.startswith("egg:"): # uses entry points entry_str = uri.split("egg:")[1] try: dist, name = entry_str.rsplit("#", 1) except ValueError: dist = entry_str name = default try: return pkg_resources.load_entry_point(dist, section, nam...
# https://oj.leetcode.com/problems/add-two-numbers/ # 1555 / 1555 test cases passed. # You are given two linked lists representing two non-negative numbers. # The digits are stored in reverse order and each of their nodes contain # a single digit. Add the two numbers and return it as a linked list. # # Input: (2 -> 4 -...
7 -> 0 -> 8 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @return a ListNode def addTwoNumbers(self, l1, l2): carry = 0 head = ListNode(0) curr = head while l1 and l2:
sum = l1.val + l2.val + carry carry = sum / 10 curr.next = ListNode(sum % 10) l1 = l1.next l2 = l2.next curr = curr.next while l1: sum = l1.val + carry carry = sum / 10 curr.next = ListNode(sum % 10) ...
#! /usr/bin/env python ################################################################################################# # # Script Name: bip.py # Script Usage: This script is the menu system and runs everything else. Do not u
se other # files unless you are comfortable with the code. # # It has the following: # 1. # 2. # 3. # 4. # #
You will probably want to do the following: # 1. Make sure the info in bip_config.py is correct. # 2. Make sure GAM (Google Apps Manager) is installed and the path is correct. # 3. Make sure the AD scripts in toos/ are present on the DC running run.ps...
HOST = '127.0.0.1' PORT = 8080 from Tkinter import * import tkColorChooser import socket import thread import spots ################################################################################ def main(): global hold, fill, draw, look hold = [] fill = '#000000' connect() root = Tk() root...
() ################################################################################ def connect(): try: start_client() except: s
tart_server() thread.start_new_thread(processor, ()) def start_client(): global QRI server = socket.socket() server.connect((HOST, PORT)) QRI = spots.qri(server) def start_server(): global QRI server = socket.socket() server.bind(('', PORT)) server.listen(1) QRI = spots.qri(ser...
# 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
efix in the _toc.yaml'
) FLAGS = flags.FLAGS def ignore_proto_method(path, parent, children): """Remove all the proto inherited methods. Args: path: A tuple of name parts forming the attribute-lookup path to this object. For `tf.keras.layers.Dense` path is: ("tf","keras","layers","Dense") parent: The parent obje...
import difflib, re from pymongo.objectid import ObjectId class CollectionDoc(object): def __init__(self, db, docs, find_links=True): self._db = db self._collection_names = db.collection_names() self._docs = docs self._find_links = find_links @property def text(self): ...
for i, row in enumerate(text[collection_start:]): j = row.find('{0}:'.format(key)) if -1 < j < 20: break found = False for k, ro
w in enumerate(text): j = row.find('{0} '.format(collection_name)) if -1 < j < 20: found=True if found: l = row.find('_id:') if -1 < l < 20: break start, end = sorted([k, i + collection_start]) for i ...
# !/usr/bin/python # -*- coding=utf-8 -*- import json import urllib2 from books.models import Book domain = "http://smartebook.zmapp.com:9026" # 同步图书详情 def sync_book(bid, cm): # 完结了的图书不更新信息 if Book.objects.filter(id=bid, status=1).count() == 0: page = urllib2.urlopen("http://wap.cmread.com/r/p/view...
return True except Exception, e: print e.message return False # 同步书架 def sync_bookshelf(): url = "%s/smart_boo
k/get_bookshelf" % domain page = urllib2.urlopen(url) result = json.loads(page.read()) print result books = result['bookshelf'] update_count = 0 for index, b in enumerate(books): if sync_book(b['book_id'], 'zm'): update_count += 1 return len(books), update_count print s...
This is based on ifcopenshell.app.geom""" if instance.is_a("IfcOpeningElement"): # We skip opening elements as they are nameless. # We use this function to get usable collections. return _get_parent(instance.VoidsElements[0].RelatingBuildingElement) if instance.is_a("IfcElement"): ...
[m[3], m[4], m[5], 0], [m[6], m[7], m[8], 0], [m[9], m[10], m[11], 1]) )
if transpose_matrices: mat.transpose() if process_relations: id_to_matrix[ob.id] = mat else: bob.matrix_world = mat get_collection(ob.parent_id).objects.link(bob) bpy.context.view_layer.objects.active = bob bpy.ops.object.mode_set(mode="EDIT...
#!python """Script for plotting distributions of epitopes per site for two sets of sites. Uses matplotlib. Designed to analyze output of epitopefinder_getepitopes.py. Written by Jesse Bloom.""" import os import sys import random import epitopefinder.io import epitopefinder.plot def main(): """Main body of sc...
fy information for any sites" % xf) set1name = epitopefinder.io.ParseStringValue(d, 'set1name') set2name = epitopefinder.io.ParseStringValue(d, 'set2name') title = epitopefinder.io.ParseStringValue(d, 'title').strip() if title.upper() in ['NONE', 'FALSE']: title = None pvalue = epitopefinder...
ent = None else: pvalue = int(pvalue) pvaluewithreplacement = epitopefinder.io.ParseBoolValue(d, 'pvaluewithreplacement') if pvalue < 1: raise ValueError("pvalue must be >= 1") if len(epitopesbysite2_list) >= len(epitopesbysite1_list): raise ValueError("You ca...
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
port pytest with open("pytest.ini", "w") as ini_file: ini_file.write("[pytest]\n") ini_file.write("addopts = -r=a\n") ini_file.write("rootdir = py\n") ini_file.write("python_files =
test_*.py *_tests.py\n") raise SystemExit(pytest.main())
#!/usr/bin/env python import subprocess import sys from gi.repository import GLib, Gio def main(): bus = Gio.bus_get_sync(Gio.BusType.SESSION, None) proxy = Gio.DBusProxy.new_sync(bus, Gio.DBusProxyFlags.NONE, None, 'org.freedesktop.ScreenSaver', '/ScreenSaver', 'org.freedesktop.ScreenSaver',...
d the screensaver') if __name__ == '__main__': if len(sys.argv) >= 2: main() else: import os.path print("usage: {} <program-to-wrap> [arguments
to pass to program]" .format(os.path.basename(sys.argv[0])))
# Test behaviour of
inf and nan in basic float operations inf = float("inf") nan = float("nan") values = (-2, -1, 0, 1, 2, inf, nan) for x in values: for y in values: print(x, y) print(" + - *", x + y, x - y, x * y) try: print(" /", x / y) except ZeroDivisionError: print(" ...
w", x ** y, pow(x, y)) except ZeroDivisionError: print(" ** pow ZeroDivisionError") print(" == != < <= > >=", x == y, x != y, x < y, x <= y, x > y, x >= y)
otImplemented @staticmethod def _generate_items(bytestream): """Yield PDU item data from `bytestream`. Parameters ---------- bytestream : bytes The encoded PDU variable item data. Yields ------ int, bytes The variable item's 'Ite...
with Python indexing). Items are always encoded using Big Endian. +--------+-------------+-------------+ | Offset | Length | Description | +========+=============+=============+ | 0 | 1 | Item type | +--------+-------------+-------------+ | 1 ...
+--------+-------------+-------------+ | 4 | Item length | Item data | +--------+-------------+-------------+ References ---------- * DICOM Standard, Part 8, :dcm:`Section 9.3 <part08/sect_9.3.html>` * DICOM Standard, Part 8, :dcm:`Section 9.3.1<par...
# -*- coding: utf-8 -*- def command(): return "edit-instance-vmware" def init_argument(parser): parser.add_argument("--instance-no", required=True) parser.add_argument("--instance-type", required=True) parser.add_argument("--key-name", required=True) parser.add_argument("--compute-resource", requi...
= instance_no parameters["InstanceType"] = instance_ty
pe parameters["KeyName"] = key_name parameters["ComputeResource"] = compute_resource parameters["IsStaticIp"] = is_static_ip if (ip_address != None): parameters["IpAddress"] = ip_address if (subnet_mask != None): parameters["SubnetMask"] = subnet_mask if (default_gateway != No...
# -*- coding: iso-8859-1 -*- # Copyright (C) 2001-2007, 2009, 2010 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright
notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL...
SS 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. """DNS Opcodes.""" import wc.dns.exception QUERY = 0 IQUERY = 1 STATUS = 2 NOTIFY = 4 UPDATE = 5 _by_text = { 'QUERY' : QUERY, ...
import codecs import sys from setuptools import setup version_file = "schema.py" with open(version_file) as f: for line in f.read().split("\n"): if line.startswith("__version__ ="): version = eval(line.split("=", 1)[1]) break else: print("No __version__ attribute found ...
gramming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: Implementation :: PyPy", "License :
: OSI Approved :: MIT License", ], )
# # Copyright (c) 2004 Conectiva, Inc. # # Written by Gustavo Niemeyer <niemeyer@conectiva.com> # # This file is part of Smart Package Manager. # # Smart Package Manager 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 Fou...
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # from smart.transaction import Transaction, PolicyInstall, sortUpgrades from smart.transaction import INSTALL, REINSTALL from smart.option import OptionParser from smart.cache import Package from smart import * import string import re import os USAGE=_("sm...
kages in the system. If a new version of an already installed package is available, it will be selected for installation. """) EXAMPLES=_(""" smart install pkgname smart install '*kgna*' smart install pkgname-1.0 smart install pkgname-1.0-1 smart install pkgname1 pkgname2 smart install ./somepackage.file smart install...
""" This module contains the final mixin implementation, for whatever version of Django is present. """ from django.db.models import ForeignKey, ManyToManyField try: # Django 1.9+ from .iterable import GroupByIterableMixinBase as GroupByMixinBase except ImportError: # Django 1.8- from .queryset import...
ield_name].append(
related_field) else: # Simple field, get the field instance model_field = model._meta.get_field(field_name) if isinstance(model_field, (ForeignKey, ManyToManyField)): # It's a related field, get model related_model = m...
scription'), 'thumbnails': thumbnails, 'duration': float_or_none(info.get('duration'), 1000), 'webpage_url': info.get('permalink_url'), 'license': info.get('license'), 'view_count': extract_count('playback'), 'like_count': extract_count('favoriting...
65082', 'title
': 'Soft Cell (Albums)', }, 'playlist_mincount': 1, }, { 'url': 'https://soundcloud.com/jcv246/sets', 'info_dict': { 'id': '12982173', 'title': 'Jordi / cv (Sets)', }, 'playlist_mincount': 2, }, { 'url': 'https://soundcloud.com/jcv2...
#! /usr/bin/env python import os
import sys from barf.barf import BARF if __name__ == "__main__": # # Open file # try: filename = os.path.abspath("../../samples/toy/arm/branch4") barf = BARF(filename) except Exception as err: print err print "[-] Error opening file : %s" % filename sys.e...
in barf.translate(): print("0x{0:08x} : {1}".format(addr, asm_instr)) for reil_instr in reil_instrs: print("{0:14}{1}".format("", reil_instr)) try: # Some instructions cannot be translate to SMT, i.e, # UNKN, UNDEF, JCC. In those cases, an excep...
from django.conf.urls import patterns, include, url
from django.conf import settings from django.views.generic import ListView
from django.views.generic.detail import DetailView from foo.hotel.models import Hotel from foo.hotel.views import HotelLimitListView from foo.hotel.views import HotelLimitNoOrderListView urlpatterns = patterns('', url(r'^$', HotelLimitListView.as_view(model=Hotel), name='hotel'), ...
# Copyright 2015 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://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, W
ITHOUT # 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 oslo_serialization import jsonutils from oslo_utils import versionutils from nova.db import api as db from nova import exceptio...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migra
tion): dependencies = [ ('fruit', '0003_apple_size'), ('fruit', '0002_cranberry_bacon'),
] operations = [ ]
name=None): self._num_k = None self._num_atoms = None self._sample_form = None self._ab_initio_program = None self._clerk = AbinsModules.IOmodule(input_filename=input_ab_initio_filename, group_name=AbinsModules.AbinsParameters.ab_initi...
:param data: dictionary with the data to rearrange :returns: Returns an object of type AbinsData """ k_points = AbinsModules.KpointsData(num_atoms=self._num_atoms, num_k=self._num_k) # 1D [k] (one entry corresponds to weight of one k-point) k_points.set({"weights": data["weig...
# 2D [k][3] (one entry corresponds to one coordinate of particular k-point) "k_vectors": data["k_vectors"], # 2D array [k][freq] (one entry corresponds to one frequency for the k-point k) "frequencies": data["frequencies"], # ...
date=end) self.assertEquals(grp.formatted_start_date(), "01/05/2007") self.assertEquals(grp.formatted_end_date(), "12/25/2007") def test_is_active(self): start = date(2007, 1, 5) end = date(2007, 12, 25) grp = SchoolGroupFactory(start_date=start, end_date=end) self...
ps = self.student.profile.get_managed_groups() self.assertEquals(groups.count(), 0) groups = teacher.profile.get_managed_groups() self.assertEquals(groups[0], teacher_grp) groups = school.profile.get_managed_groups() self.assertEquals(groups.count(), 3) self.assertTrue(...
self.assertTrue(school_grp in groups) groups = country.profile.get_managed_groups() self.assertEquals(groups.count(), 4) self.assertTrue(alt_teacher_grp in groups) self.assertTrue(teacher_grp in groups) self.assertTrue(school_grp in groups) self.assertTrue(country_grp in...
""" R
estores the uplifted horizons while restricting slip along the fault to the specified azimuth. """ import numpy as np import matplotlib.pyplot as plt from fault_kinematics.homogeneous_simple_shear import inv
ert_slip import data import basic def main(): azimuth = data.fault_strike + 90 # azimuth = 304 # Plate motion from Loveless & Meade def func(*args, **kwargs): return forced_direction_inversion(azimuth, *args, **kwargs) slips, heaves, variances, planar_variances = basic.restore_horizons(func) ...
# Copyright (C) 2011 Statoil ASA, Norway. # # The file 'fortio.py' is part of ERT - Ensemble based Reservoir Tool. # # ERT 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,...
er(object): def __init__(self, fortio): self.__fortio = fortio def __enter__(self): return self.__fortio def __exit__(self, exc_type, exc_val, exc_tb): self.__fortio.close() return exc_type is not None def openFortIO(file_name, mode=FortIO.READ_MODE, fmt_file=False, endi...
p_header=True): """Will create FortIO based context manager for use with with. The with: statement and context managers is a good alternative in the situation where you need to ensure resource cleanup. import sys from ert.ecl import FortIO, EclFile rst_file = EclFile(sys.argv[1]) ...
from gi.repository import Gtk class ChannelWindow: def __init__(self, sources, client_thread): self.sources = sources self.client_thread = client_thread self.changes = {} self.widgets = {} self.gtkwin = Gtk.Window() self.gtkwin.set_position(Gtk.WindowPosition.CENTER) self.gtkwin.set_default_size(320,...
for uuid in self.sources: self.widgets[uuid] = {} source = self.sources[uuid] frame = Gtk.Frame() frame.set_label(source["username"]) self.sources_list.pack_start(frame, False, False, 0) table = Gtk.Table(n_rows=3, n_columns=3) frame.add(table) hop_button = Gtk.RadioButton.new_with_label_fr...
_widget(None, 'Hop') if source["hop"] > 0: hop_button.clicked() hop_button.connect("clicked", self.on_change_mode, uuid, "hop") hop_button.set_alignment(0,0) table.attach(hop_button, 0, 1, 0, 1) field = Gtk.SpinButton() field.set_numeric(True) field.set_max_length(3) field.set_increments...
import gtk import highgtk.entity import highgtk.present.default.layout def add (inquiry): window = getattr (inquiry, "present_window", None) if window is None: inquiry.present_window = gtk.Dialog() title = getattr (inquiry, "title", None) if title is None: root = highgtk.e...
resent_window.get_content_area()) inquiry.present_report = gtk.Label() inquiry.present_report.set_line_wrap (True) inquiry.present_report.set_alignment (0.0, 0.5) inquiry.present_window.get_content_area().pack_end (inquiry.present_report) inquiry.present_window.show_all() els...
uiry.present_window def cancel (inquiry): method_name = getattr (inquiry, "cancel_method", None) if method_name is not None: method = getattr (inquiry.parent, method_name) method (inquiry) inquiry.remove (inquiry) def okay (inquiry): method_name = getattr (inquiry, "ok_method", "inquir...
"""kaxabu URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en
/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL
to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin urlpa...
# -*- coding: utf-8 -*- from uuid import uuid4 from gluon import current def rlpcm_person_anonymize(): """ Rules to anonymize a case file """ auth = current.auth s3db = current.s3db ANONYMOUS = "-" # Standard anonymizers from s3db.pr import pr_address_anonymise as anonymous_address, \ ...
], }, # Rules to unlink and remove user account {"name": "account", "title": "User Account", "cascade": [("pr_person_user", { "key": "pe_id", "match": "p
e_id", "cascade": [account, ], "delete": True, }), ], }, ] return rules
from functools import reduce from mahjong.constants import HONOR_INDICES, TERMINAL_INDICES from mahjong.hand_calculating.yaku import Yaku class Honroto(Yaku): """ All tiles are terminals
or honours """ def __init__(self, yaku_id=None): super(Honroto, self).__init__(yaku_id) def set_attributes(self): self.tenhou_id = 31 self.name = "Honroutou" self.han_open = 2 self.han_closed = 2 self.is_yakuman = False def is_condition_met(self, ha...
es)
'''Experimental! This is an experimental module for converting ColumnTS into dynts.timeseries. It requires dynts_. .. _dynts: https://github.com/quantmind/dynts ''' from collections import Mapping from . import models as columnts import numpy as ny from dynts import timeseries, tsname class ColumnT...
ts[0] class ColumnTSField(columnts.ColumnTSField): def structure_class(self): return
ColumnTS
import unittest import datetime import uuid import sys import json import sys, os, os.path root_directory = os.path.join(os.path.
dirname(os.path.realpath(__file__)), '..', '..', '..', '..') if root_directory not in sys.path: sys.path.append(root_directory) from applicationinsights.channel.contracts import * from .Utils import TestJsonEncoder class TestData(unittest.TestCase): def test_construct(self): item = Data() self...
est string' item = Data() item.base_type = expected actual = item.base_type self.assertEqual(expected, actual) expected = 'Other string' item.base_type = expected actual = item.base_type self.assertEqual(expected, actual) def test_base_data_proper...
# -*- coding: utf-8 -*- import sys import os sys.path.insert(0, os.path.a
bspath(os.path.join(os.path.dirname(__file
__), '..'))) import pypro
from units import runner import numpy as np def job_gen(): for N in range(4, 21, 2): for rate_power in [1, 3/2.]: rate = np.power(N, rate_power) test = { 'test': {}, 'net': {'topology': 'grid', 'N': N}, 'pattern': {'type': 'random_one...
yield test
runner.run_parallel(15, job_gen, 'grid1')
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: anze@reciprocitylabs.com # Maintained By: anze@reciprocitylabs.com """Add missing constraints for vendors Revision ID: 35e5344803b4 Revises: 27684...
ision = '27684e5f313a' def upgrade(): resolve_duplicates(Vendor, "slug") op.create_uniq
ue_constraint('uq_slug_vendors', 'vendors', ['slug']) def downgrade(): op.drop_constraint('uq_slug_vendors', 'vendors', 'unique')
.COOKIES[settings.CSRF_COOKIE_NAME] = b"" CsrfViewMiddleware().process_view(req, token_view, (), {}) resp = token_view(req) token = get_token(req) self.assertIsNotNone(token) self._check_token_present(resp, token) def test_token_node_with_csrf_cookie(self): """ ...
Test to verify CSRF cookie age can be set using settings.CSRF_COOKIE_AGE.
""" req = self._get_GET_no_csrf_cookie_request() MAX_AGE = 123 with self.settings(CSRF_COOKIE_NAME='csrfcookie', CSRF_COOKIE_DOMAIN='.example.com', CSRF_COOKIE_AGE=MAX_AGE, CSRF_COOKIE_PATH='/test/', ...
from scrapy.spiders import Spider from scrapy.selector import Selector from scrapy.http import HtmlResponse from FIFAscrape.items import PlayerItem from urlparse import urlparse, urljoin from scrapy.http.request import Request from scrapy.conf import settings import random import time class fifaSpider(Spider...
ector and hence need to extract it to obtain unicode object print urljoin(response.url, relative_url) #urljoin is able to mer
ge absolute and relative paths to form 1 coherent link req = Request(urljoin(response.url, relative_url),callback=self.parse_playerURL) #pass on request with new urls to parse_playerURL req.headers["User-Agent"] = self.random_ua() yield req next_url=sel.xp...
port cligraph import utils """ TODO: - Auto-detect number of bins - Fixed width or variable width bins - Stacked bins, overlapped bins or bins next to each other - Change which side of bin is open (default: bins are half-open, closed on left, except final bin which is closed both sides) """ class Histogram(cligrap...
lpha=self.alphas.next(), normed=cli_args.normed, cumulative=cli_args.cumulative, log=cli_args.logscale, label=self.legends.next(), hatch=self.markers.next(),
histtype=self.histtypes.next()) def __get_bins(self, cli_args, index): """ Get the bin histogram parameter for the data at the given index. Use the supplied number of bins if given. Otherwise, calculate based on the supplied bin width. """ # Short-circuit if we are given ...
lass InvalidAuthenticationTypeException(exceptions.NeutronException): message = _('Invalid authentication type: %(auth_type)s, ' 'valid types are: %(valid_auth_types)s') def __init__(self, **kwargs): if 'valid_auth_types' not in kwargs: kwargs['valid_auth_types'] = ', '.join...
): """Instance section of a keepalived configuration.""" def __init__(self, state, interface, vrouter_id, ha_cidrs, priority=HA_DEFAULT_PRIORITY, advert_int=None, mcast_src_ip=None, nopreempt=False, garp_master_repeat=GARP_MASTER_REPEAT, garp_...
refresh=GARP_MASTER_REFRESH): self.name = 'VR_%s' % vrouter_id if state not in VALID_STATES: raise InvalidInstanceStateException(state=state) self.state = state self.interface = interface self.vrouter_id = vrouter_id self.priority = priority self.nop...
#!/usr/bin/env python3 # Copyright 2009-2017 BHG http://bw.org/ import sqlite3 def main(): print('connect') db = sqlite3.connect('db-api.db') cur = db.cursor() print('create') cur.execute("DROP TABLE IF EXISTS test") cur.execute(""" CREATE TABLE test (
id INTEGER PRIMARY KEY, string TEXT, number INTEGER ) """) print('insert row') cur.execute(""" INSERT INTO test (string, number) VALU
ES ('one', 1) """) print('insert row') cur.execute(""" INSERT INTO test (string, number) VALUES ('two', 2) """) print('insert row') cur.execute(""" INSERT INTO test (string, number) VALUES ('three', 3) """) print('commit') db.commit() print...
# # Copyright (C) 2009-2016 Nexedi SA # # 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. # # This program is distributed...
0, master_count=1, temp_dir=dst_temp_dir) self.neo_dst.stop() self.neo_dst.setupDB() self.neo_dst.start() self._dst = self.neo.getZODBStorage() self._dst_db = ZODB.DB(self._dst) def _tearDown(self, success): super(RecoveryTests, self)._tearDown(succes...
eck') unittest.main(defaultTest='suite')
rt TaskOptionsError class GenerateAndLoadData(BaseSalesforceApiTask): """ Orchestrate creating tempfiles, generating data, loading data, cleaning up tempfiles and batching.""" task_docs = """ Orchestrate creating tempfiles, generating data, loading data, cleaning up tempfiles and batching. CCI has f...
current_batch_size} " f"index={index} total_records={self.num_records}" ) self._generate_batch( self.database_url, self.working_directory or tempdir, self.mapping_file, current_batch_size,...
ns}) data_gen_task = self.data_generation_task( self.project_config, task_config, org_config=self.org_config ) data_gen_task() def _dataload(self, subtask_options): subtask_config = TaskConfig({"options": subtask_options}) subtask = LoadData( project_...
from __future__ import unicode_literals from django.db.models import signals from django.dispatch import receiver from django.test import TestCase from django.utils import six from .models import Person, Car # #8285: signals can be any callable class PostDeleteHandler(object): def __init__(self, data): ...
ix.text_type ) signals.post_delete.disconnect(post_delete_test) signals.pre_delete.disconnect(pre_delete_test) signals.post_save.disconnect(post_save_test) signals.pre_save.disconnect(pre_save_test) signals.pre_save.disconnect(pre_save_decorator_test) signals.pre...
that all our signals got disconnected properly. post_signals = ( len(signals.pre_save.receivers), len(signals.post_save.receivers), len(signals.pre_delete.receivers), len(signals.post_delete.receivers), ) self.assertEqual(pre_signals, post_signals)...
#!/usr/bin/env python import os import sys import time path = 'gh-pages' if l
en(sys.argv) == 1 else sys.argv[1] indexName = 'index.html' template = """<html> <head><title>large_image_wheels</title></head> <body> <h1>large_image_wheels</h1> <pre> %LINKS% </pre> </body> """ link = '<a href="%s" download="%s">%s</a>%s%s%11d' wheels = [(name, name) for name in os.listdir(path) if name.endswith('wh...
n wheels) index = template.replace('%LINKS%', '\n'.join([ link % ( url, name, name, ' ' * (maxnamelen + 3 - len(name)), time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getmtime( os.path.join(path, name)))), os.path.getsize(os.path.join(path, name)), ) for name, url in ...
# -*- encoding: utf-8 -*- from __future__ import division import math from FrameshiftSite import * class FrameshiftSequence( object ): def __init__( self, sequence, path ): self.path = path self.path_str = ",".join( map( str, [ a for a,b in path ])) self.frameshifted_sequence, self.fragments, self.fragment_posi...
f,j in path: frameshifted_sequence += sequence[i+(f-f_i):j] fragments.append( sequence[i+(f-f_i):j] ) fragment_positions.append( fragment_positions[-1] + len( sequence[i+(f-f_i):j] )) f
rameshift_signals.append( sequence[j-3:j+3] ) i = j f_i = f # we could factor in the last trivial nucleotide... frameshifted_sequence += sequence[-1] fragments[-1] += sequence[-1] return frameshifted_sequence, fragments, fragment_positions, frameshift_signals[:-1] #*****************************...
from os import listdir from os.path import isfile, join from Utilities.Text import Text from Utilities.TermFrequencyInverseDocumentFrequency import TermFrequencyInverseDocumentFrequency as TFIDF from sklearn import svm from pprint import pprint import numpy as np from sklearn.decomposition import PCA def main(): p...
[1]) x = { "train" : pca.fit_transform(features[[0, 2, 4, 5, 6, 7], :]), "test" : pca.transform(features[
[1, 3], :]) } else: x = { "train" : features[[0, 2, 4, 5, 6, 7], :], "test" : features[[1, 3], :] } # Unfortunately, it does not appear to be possible to derive a perfect # accuracy solution in the grid search specified below. However, it is # provided here anyway for educational purposes. grid_se...
from django.db.models import Prefetch, prefetch_related_objects from django.test import TestCase from .models import Author, Book, Reader class PrefetchRelatedObjectsTests(TestCase): """ Since prefetch_related_objects() is just the inner part of prefetch_related(), only do basic tests to ensure ...
r) for r in b.rea
d_by.all()] for b in a.books.all()] for a in authors ], [ [['Amy'], ['Belinda']], # Charlotte - Poems, Jane Eyre [['Amy']], # Anne - Poems [['Amy'], []], # Emily - Poems, Wuther...
#!/usr/bin/env python3 import functools import struct KEY_SIZE = 8 BLOCK_SIZE = 8 # yapf: disable # Note the 1-based indexing in all the following tables. IP = [ 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17...
1, 2, 12, 5, 10, 14, 7], [1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12], ] S4 = [ [7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15], [1
3, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9], [10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4], [3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14], ] S5 = [ [2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9], [14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6], [4, 2, 1, 11, 10, 13, ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for the Chrome Cache files pars
er.""" import unittest from plaso.parsers import chrome_cache from tests.parsers import test_lib class ChromeCacheParserTest(test_lib.ParserTestCase): """Tests for the Chrome Cache files parser.""" def testParse(self): """Tests the Parse
function.""" parser = chrome_cache.ChromeCacheParser() storage_writer = self._ParseFile(['chrome_cache', 'index'], parser) number_of_events = storage_writer.GetNumberOfAttributeContainers('event') self.assertEqual(number_of_events, 217) number_of_warnings = storage_writer.GetNumberOfAttributeCont...
import abc import datetime import decimal import functools import json import uuid import pytz import msgpack import six from lymph.utils import Undefined @six.add_metaclass(abc.ABCMeta) class ExtensionTypeSerializer(object): @abc.abstractmethod def serialize(self, obj): raise NotImplementedError ...
obj = { '__type__': obj_type.__name__, '_': serializer.serialize(obj), } elif hasattr(obj, '_lymph_dump_'): obj = obj._lymph_dump_() return obj def load_object(self, obj): obj_
type = obj.get('__type__') if obj_type: serializer = _extension_type_serializers.get(obj_type) return serializer.deserialize(obj['_']) return obj def dumps(self, obj): return self._dumps(obj, default=self.dump_object) def loads(self, s): return self._loa...
fro
m flask import Flask # from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config.from_object('config') # db = SQLAlchemy(app) from app import vie
ws #, models
# A comment, this is so yo
u can read your program later. # Anything after the # is ignored by python. print "I could have code like this." # and the comment after is ignored # You can also use a c
omment to "disable" or comment out a piece of code: # print "This won't run." print "This will run."
:param roidb: must be preprocessed :param batch_size: must divide BATCH_SIZE(128) :param shuffle: bool :param ctx: list of contexts :param work_load_list: list of work load :param aspect_grouping: group images with similar aspects :return: AnchorLoader """...
r = tensor_vstack([batch['data'] for batch in data_list]) for data, data_pad in zip(data_list, data_tensor): data['data'] = data_pad[np.newaxis, :] new_label_list = [] for data, label in zip(data_list, label_list): # infer label shape data_shape = {k: v.shape...
at_shape = [int(i) for i in feat_shape[0]] # add gt_boxes to data for e2e data['gt_boxes'] = label['gt_boxes'][np.newaxis, :, :] # assign anchor for label label = assign_anchor(feat_shape, label['gt_boxes'], data['im_info'], self.cfg, s...
import collections, unittest from bibliopixel.colors import closest_colors closest = closest_colors.closest_colors class ClosestC
olorsTest(unittest.TestCase): def exhaustive(self, metric, start=32, skip=64, report=4): for color in closest_colors.all_colors(start, skip=skip): cl = closest(color, metric) if len(cl) >= report: yield color, cl def test_simple(self): self.asser
tEqual(closest((255, 0, 0)), ['red', 'red 1']) def test_far(self): c = closest((0, 0, 64), metric=closest_colors.taxicab) self.assertEqual(c, ['black', 'navy', 'none', 'off']) c = closest((64, 0, 0), metric=closest_colors.taxicab) self.assertEqual(c, ['black', 'maroon', 'none', 'of...
# -*- coding: utf-8 -*- """This module implements a class that...""" from __future__ import print_function, unicode_literals import collections import pprint from npfl103.io.document import Document __version__ = "0.0.1" __author__ = "Jan Hajic jr." class DocumentVectorizer: """The DocumentVectorizer class tra...
second question might be "1" or "term frequency in the document" or "pivot-normalized term frequency". Both of these decisions are done in the :meth:`DocumentSparseVectorizer.transform` method. Th
e input of this method is a :class:`Document`, the output is a dict with term keys and term weight values. However, for the second part -- how weights are decided -- it's better to defer transformations of term weights later down the line. """ def __init__(self, zones=None, **vtext_to_stream_kw...
# Generated from ChordLabel.g4 by ANTLR 4.7 from antlr4 import * if __name__ is not None and "." in __name__: from .ChordLabelParser import ChordLabelParser else: from ChordLabelParser import ChordLabelParser # This class defines a complete listener for a parse tree produced by ChordLabelParser. class ChordLab...
Degree(self, ctx:ChordLabelParser.DegreeContext): pass # Exit a parse tree produced by ChordLabelParser#degree. def exitDegree(self, ctx:ChordLabelParser.DegreeContext): pass # Enter a parse tree produced by ChordLabelParser#interval. def enterInterval(self, ctx:ChordLabelParser.Inter...
pass # Enter a parse tree produced by ChordLabelParser#bass. def enterBass(self, ctx:ChordLabelParser.BassContext): pass # Exit a parse tree produced by ChordLabelParser#bass. def exitBass(self, ctx:ChordLabelParser.BassContext): pass # Enter a parse tree produced by ChordLabelP...
import sys def inputText(): input = sys.stdin.re
adline()
return input.strip() def inputChoices(list, backcmd = "b", backtext = "back"): repeat = True while repeat: repeat = False count = 0 for item in list: print count, "-", item count += 1 print backcmd, "-", backtext input = inputText() if input == backcmd: return None action = int(input) if...
the fjords, # metaphorically speaking, when one *is* dead. But that's an # error in knowledge discovery or entry, not in programming. make_test(type = 'VALUE', getargs = test_short_answer_3_getargs, testanswer = test_short_answer_3_testanswer, expected_val = "2", name = test_sh...
'alice lays eggs')), 'alice is a good flyer')) def backchain_to_goal_tree_2_testanswer(val, original_val = None): return ( tree_map(type_enco
de(val), frozenset) == tree_map(type_encode(result_bc_2), frozenset)) # This test checks to make sure that your backchainer produces # the correct goal tree given the hypothesis 'alice is an # albatross' and using the ZOOKEEPER_RULES. make_test(type = 'FUNCTION_ENCODED_ARGS', getargs = backchai...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import datetime from django.utils.timezone import utc class Migration(migr
ations.Migration): dependencies = [ ('app', '0025_auto_20150923_0843'), ] operations = [ migrations.CreateModel( name='BlogEntry', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ...
(max_length=10000)), ('pub_date', models.DateField()), ('author', models.ForeignKey(to='app.Account')), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='BlogEntryTag', fields=[ ...
#!/usr/local/bin/python3.4 # -*- coding: utf-8 -*- import threading import time import sys import trace from inspect import isgeneratorfunction import format class KillableThread(threading.Thread): """A subclass of threading.Thread, with a kill() method provided by courtsey of Connelly Barnes.""" def __init_...
lass \'generator\'>': for i in ret: self._callback(i.format(color=format.color)) else: # TODO: make function to be only generators, not normal functions print('DEPRECATED: function "', self._f.cmdname, '" is using the return statement', sep='') ...
rmat.color)) class ControlThread(threading.Thread): def __init__(self, _f, _callback, *args, **kwargs): super().__init__() self.watched_thread = FunctionExecutor(_f, _callback, args, kwargs) self._callback = _callback def run(self): self.watched_thread.start() time.sle...
idual WikiPage object. **Typical Attributes** This table describes attributes that typically belong to objects of this class. Since attributes are dynamically provided (see :ref:`determine-available-attributes-of-an-object`), there is not a guarantee that these attributes will always be present, n...
he settings for this WikiPage."""
url = API_PATH["wiki_page_settings"].format( subreddit=self.wikipage.subreddit, page=self.wikipage.name ) return self.wikipage._reddit.get(url)["data"] def update(self, listed, permlevel, **other_settings): """Update the settings for this WikiPage. :param listed: (boole...
lassification levels can be given. If they are, an assignment will be made at each level. This differs from assignPathsToReadsFromBlast.py in that: (1) it can handle CAZy and SEED, (2) it will output multiple levels in one file, (3) multiple assignments are always printed on multiple lines. This script will work with...
ebug( "Could not parse group
from %s with r'%s'" % (gene, cazyRE.pattern)) cazygroup = gene return cazygroup # levels equivalent to returning just the ko/gene koSyns = [None, 'ko', 'gene', 'ortholog', 'family', 'role'] level3Syns = ['subsystem', 'pathway', 'group'] koMapRE = re.compile(r'\sko:K\d{5}') seedMapRE = re.compi...
#!/usr/bin/env python """ 4c. Create a script that connects to both routers (pynet-rtr1 and pynet-rtr2) and prints out both the MIB2 sysName and sysDescr. """ from snmp_helper import snmp_get_oid, snmp_e
xtract COMMUNITY_STRING = 'galileo' SYS_DESCR = '1.3.6.1.2.1.1.1.0' SYS_NAME = '1.3.6.1.2.1.1.5.0' def main(): pynet_rtr1 = ('184.105.247.70', COMMUNITY_STRING, 161) pynet_rtr2 = ('184.105.247.71', COMMUNITY_STRING, 161) for a_device in (pynet_rtr1, pynet_rtr2): print "\n" for the_oid in...
snmp_extract(snmp_data) print output print "\n" if __name__ == "__main__": main()
#!/usr/bin/env python # -*- coding: utf-8 -*- """This file is part of the prometeo project. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option...
NESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/> """ __author__ = 'Emanuele Bertoldi <emanuele.bertoldi@gmail.com>' __copyright__ = 'Copyrig...
t (c) 2011 Emanuele Bertoldi' __version__ = '0.0.5' from django.db import models from django.utils.translation import ugettext_noop as _ import django.dispatch from models import * ## UTILS ## def manage_bookmarks(cls): models.signals.post_save.connect(create_bookmarks, cls) models.signals.post_delete.conne...
import requests import os print('\n***数据与算法 GitHub自动上传脚本***\n') username = input('输入你在GitHub上的用户名,如 Robert Ying:') email = input('输入你注册GitHub用的Email:') print('\n开始配置Git...') os.system('git config --global user.name "' + username + '"') os.system('git config --global user.email ' + email) print('\n你输入的信息如下:') os.syst...
md.write( '|:----------:|:------------------------------:|:------------------------------:|\n') run_results = results[0]['run_results'] for i in range
(len(run_results)): md.write( '|' + str(i + 1) + '|' + str(run_results[i][1]) + ' ms|' + str(run_results[i][2]) + ' KB|\n') with open('./data-and-algorithms/' + result['problem_title'] + '/' + name + '/source.cpp', 'w', encoding='utf-8') as source: ...
#!/usr/bin/env python2 import wx import time TRAY_TOOLTIP = 'Personal Legend' TRAY_ICONS = { 'main': 'icon-main.png', 'c1': 'icon-1card.png', 'c2': 'icon-2cards.png', 'c3': 'icon-3cards.png', 'timer': 'icon-zero.png' } TRAY_TIMER = 30 * 60 def create_menu_item(menu, label, func): item = wx.Me...
tus(self, st): self.set_icon(TRAY_ICONS[st]) self.status = st def on_left_down(self, event): if self.status == 'main': self.set_status('c1') elif self.status == 'c1': self.set_status('c2') elif self.
status == 'c2': self.set_status('c3') elif self.status == 'c3': self.set_status('main') def on_hello(self, event): print('Hello, world!') def on_exit(self, event): wx.CallAfter(self.Destroy) def stop_watch(self, event): now = time.time() fut...
"""Tests for the login flow.""" from . import async_setup_auth from tests.async_mock import patch from tests.common import CLIENT_ID, CLIENT_REDIRECT_URI async def test_fetch_auth_providers(hass, aiohttp_client): """Test fetching auth providers.""" client = await async_setup_auth(hass, aiohttp_client) re...
er": ["insecure_example", None], "redirect_uri": CLIENT_REDIRECT_URI, }, ) assert resp.status == 200 step = await resp.json() resp = await client.post( f"/auth/login_flow/{step['flow_id']}", json={"client_id": CLIENT_ID, "username": "test-user", "password": "test-pas...
len(step["result"]) > 1
from django.core.management.base import BaseCommand from explorer.models import Author, AuthorExternalResource, ExternalResource import os import csv class Command(BaseCommand): help = """Load data about external authority records for authors.""" def add_arguments(self, parser): parser.add_argument...
wer()] % identifier defaults = { 'resource_type': sources[source.lower()], 'resource_location': location, } resource,_ = ExternalResource.objects.get_or_create(resource_location=location, defaults=defaults) if confidence: c
onfidence = float(confidence) else: confidence = 1.0 AuthorExternalResource( author_id=pk, resource=resource, confidence=confidence ).save() self.stdout.write(self.style.SUCCESS(' | '.join[pk, name, identif...