prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
from vsg.vhdlFile.classify import range_
constraint def detect(iToken, lObjects): ''' integer_type_definition ::= range_constraint ''' return range_constraint.detect(iToken,
lObjects)
from __future__ impor
t absolute_import from tracer.query import Query from tracer.resources.package import Package from tracer.resources.applications import Application from tracer
.resources.processes import Process __all__ = [ Query, Package, Application, Process, ]
try: a
= 1 exce<
caret>
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2009-2010, Nicolas Clairon # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the abov...
n([i.__name__ for i in self._operands]) + '>' def validate(self, value): return isinstance(value, tuple(self._operands)) class NOT(SchemaOperator): repr = 'not' def __init__(self, *args): super(NOT, self).__
init__(*args) def __str__(self): repr = ', %s ' % self.repr return '<not '+repr.join([i.__name__ for i in self._operands]) + '>' def validate(self, value): return not isinstance(value, tuple(self._operands)) class IS(SchemaOperator): repr = 'is' def __init__(self, *args): ...
ry_key=True) fips = models.CharField(max_length=2,null=True,blank=True) iso = models.CharField(max_length=2,null=True,blank=True) iso3digit = models.CharField(max_length=3,null=True,blank=True) name = models.CharField(max_length=250,null=True,blank=True) capital = mod
els.CharField(max_length=250,null=True,blank=True) continent = models.CharField(max_length=250,null=True,blank=True) # area_km = models.FloatField(null=True,blank=True) def __unicode__(self): return self.fips def previous(self): try: previous_records = WorldCountry.o...
ountry.objects.get(id=previous_id) except: return None def next(self): try: next_records = WorldCountry.objects.filter(id__gt=self.id) next_id = next_records.order_by('id')[0].id return WorldCountry.objects.get(id=next_id) except: ...
from reader import * from dist import * from sys import * from table im
port * def project(z,data): d = anyi(data[z]) if d == len(data[z]): d-=1 x = [0]*len(data[z]) y = [0]*len(data[z]) east = furthest(d,data,z) west = furthest(data[z].index(east),data,z) inde = data[z].index(east) indw = data[z].index(west) project0(inde,indw,data,z,x,y,count)...
some = 0.000001 c = dist(data[z][east],data[z][west],data,z,indep,nump) for d in data[z]: ind = data[z].index(d) a = dist(data[z][ind],data[z][east],data,z,indep,nump) b = dist(data[z][ind],data[z][west],data,z,indep,nump) if a > c*bigger: return project0(east,ind...
xists on Local ERPNext System ''' def sync_product(id, setting): flag = frappe.db.get_value("Item", {"bcommerce_product_id":id}, as_dict=1) if flag: return flag.get("name") else: sync_options() sync_bulk_brands() conn = get_connection() product = get_resource("Products", id) if not product: retur...
name=["attribute_value", "abbr"], as_dict=True) for opt in options: args = {} item_code = "{0}-{1}".format(template.item_code, opt.get("abbr")) if not frappe.db.get_value("Item", item_code): args[attr_name] = opt.get("attribute_value") doc = create_variant(template.item_code, args) doc.save(ignore_per...
({ "item_name": item_name }) doc.save(ignore_permissions=True) create_item_price(product, doc, setting) ''' Parse the Product Options as Item attributes in ERPNext Then save the item attributes and return the attributes Which will further link to Item Master table to create Variants ''' def get_item_...
# 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 agreed to in...
operation = 'qos-key-unset' waiters.wait_for_qos_operations(self.admin_volume_qos_client, self.created_qos['id'], o
peration, keys) body = self.admin_volume_qos_client.show_qos( self.created_qos['id'])['qos_specs'] self.assertNotIn(keys[0], body['specs']) @test.idempotent_id('1dd93c76-6420-485d-a771-874044c416ac') def test_associate_disassociate_qos(self): """Test the following operations...
#!/usr/bin/env python # Standard library modules import ConfigParser import argparse import os import textwrap def create_config(configuration): """ Function used to create the configuration file if it does not exist in the program's path. It returns a ConfigParser object """ configuration.add_s...
python xkcd.py -n 158 **downloads comic number 158 python xkcd.py --range 300 # **downloads all comics from comic number 300 to the latest one. Inclusive of the latest one. python xkcd.py --latest **Downloads the lat...
l be saved\ (default: %(default)s)') # Only one of the arguments can be present in the command line. group = parser.add_mutually_exclusive_group() group.add_argument('-l', '--latest', action='store_true', help='\ Downloads the latest comic.') group.add_argument('-a...
# # This file is part of Dragonfly. # (c) Copyright 2007, 2008 by Christo Butcher # Licensed under the LGPL. # # Dragonfly 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 ...
----------------------------------------------- int_0 = MapIntBuilder({ "صفر": 0, }) int_1_9 = MapIntBuilder({ "واحد": 1, "اثنان": 2, ...
"ثلاثة": 3, "اربعة": 4, "خمسة": 5, "ستة": 6, "سبعة": 7, "ثمانية": 8, "تسعة"...
# import the ne
cessary packages from .mxalexnet import MxAlexNet from .mxvggnet import MxVGGNet from .mxgooglenet import MxGoogLeNet from .mxresnet import MxResNet from .mxsqueezenet import MxSqueezeNet from .mxagegendernet import MxAgeGen
derNet
#!/usr/bin/env python from setuptools import setup from gun import __version__ setup( name = 'gun', version = __version__, description = 'Gentoo Updates Notifier', author = 'Andriy Yurchuk', author_email = 'ayurchuk@minuteware.net', url = 'https://github.com/Ch00k/gun', licen...
'cons
ole_scripts': [ 'gun = gun.sync:main' ] }, packages = ['gun'], data_files = [('/etc/gun/', ['data/gun.conf'])], install_requires = ['xmpppy >= 0.5.0-rc1'] )
#!/usr/bin/env python # --!-- coding: utf8 --!-- """ The converters package provide functions to quickly convert on the fly from one format to another. It is responsible to check what external library are present, and do the job as best as possible with what we have in hand. """ from manuskript.converters.abstractCon...
sing pandoc if pandocConverter.isValid(): return pandocConverter.convert(html, _from="html", to="markdown") # Convert to plain text using QTextEdit
return HTML2PlainText(html) def HTML2PlainText(html): """ Convert from HTML to plain text. """ if pandocConverter.isValid(): return pandocConverter.convert(html, _from="html", to="plain") # Last resort: probably resource inefficient e = QTextEdit() e.setHtml(html) return e....
#coding=utf-8 #author: sloop ''' ÈÎÎñ PythonµÄos.pathÄ£¿éÌṩÁË isdir() ºÍ isfile()º¯Êý£¬Çëµ¼Èë¸ÃÄ£¿é£¬²¢µ÷Óú¯ÊýÅжÏÖ¸¶¨µÄĿ¼ºÍÎļþÊÇ·ñ´æÔÚ¡£ ×¢Òâ: 1. ÓÉÓÚÔËÐл·¾³ÊÇÆ½Ì¨·þÎñÆ÷£¬ËùÒÔ²âÊÔµÄÒ²ÊÇ·þÎñÆ÷ÖеÄÎļþ¼ÐºÍÎļþ£¬¸Ã·þÎñÆ÷ÉÏÓÐ/data/webroot/resource/pythonÎļþ¼ÐºÍ/data/webroot/resource/python/test.txtÎļþ£¬´ó¼Ò¿ÉÒÔ...
n/test.txt') ''' ''' µ¼ÈëÄ£¿é ҪʹÓÃÒ»¸öÄ£¿é£¬ÎÒÃDZØÐëÊ×Ïȵ¼Èë¸ÃÄ£¿é¡£PythonʹÓÃimportÓï¾äµ¼ÈëÒ»¸öÄ£¿é¡£ÀýÈ磬µ¼Èëϵͳ×Ô´øµÄÄ£¿é math£º import math Äã¿ÉÒÔÈÏΪmath¾ÍÊÇÒ»¸öÖ¸ÏòÒѵ¼ÈëÄ£¿éµÄ±äÁ¿£¬Í¨¹ý¸Ã±äÁ¿£¬ÎÒÃÇ¿ÉÒÔ·ÃÎÊmathÄ£¿éÖÐËù¶¨ÒåµÄËùÓй«¿ªµÄº¯Êý¡¢±äÁ¿ºÍÀࣺ >>> math.pow(2, 0.5) # powÊǺ¯Êý 1.4142135623730951 >>>...
ÄÓï¾ä£º from math import pow, sin, log ÕâÑù£¬¿ÉÒÔÖ±½ÓÒýÓà pow, sin, log Õâ3¸öº¯Êý£¬µ«mathµÄÆäËûº¯ÊýûÓе¼Èë½øÀ´£º >>> pow(2, 10) 1024.0 >>> sin(3.14) 0.0015926529164868282 Èç¹ûÓöµ½Ãû×Ö³åÍ»Ôõô°ì£¿±ÈÈçmathÄ£¿éÓÐÒ»¸ölogº¯Êý£¬loggingÄ£¿éÒ²ÓÐÒ»¸ölogº¯Êý£¬Èç¹ûͬʱʹÓã¬ÈçºÎ½â¾öÃû×Ö³åÍ»£¿ Èç¹ûʹÓÃimportµ¼ÈëÄ£¿éÃû£¬ÓÉÓÚ±ØÐ...
gma import * from Screens.Screen import Screen from Components.ActionMap import ActionMap from Components.Sources.List import List from Tools.Directories import resolveFilename, SCOPE_CURRENT_PLUGIN from Tools.LoadPixmap import LoadPixmap from Components.Button import Button from Components.Label import Label from Scre...
nded, ExtraActionBox, _("Partitioning..."), _("Initialize disk"), self.fdisk) def chooseFSType(self, result): if result != 5: self.result = result if self.isExt4Supported(): self.session.openWithCallback(self.initialaze, ExtraMessageBox, _("Format as"), _("Partitioner"), [ [ "Ext4", "partitionm...
], [ "Fat32", "partitionmanager.png" ], [ _("Cancel"), "cancel.png" ], ], 1, 4) else: self.session.openWithCallback(self.initialaze, ExtraMessageBox, _("Format as"), _("Partitioner"), [ [ "Ext3", "partitionmanager.png" ], [ "NTFS", "partitionmanager.png" ],...
#!/usr/bin/python2 # Written by Antonio Galea - 2010/11/18 # Distributed under Gnu LGPL 3.0 # see http://www.gnu.org/licenses/lgpl-3.0.txt import sys,struct,zlib,os from optparse import OptionParser from intelhex import IntelHex DEFAULT_DEVICE="0x0483:0xdf11" DEFAULT_REVISION="0.0" def named(tuple,names): return ...
uffix['crc']: print("CRC ERROR: computed crc32 is 0x%08x" % crc) data = data[16:] if data: print("PARSE ERROR") def build(file,targets,device=DEFAULT_DEVICE, revision="0.0"): data = b'' for t,target in enume
rate(targets): tdata = b'' for image in target: tdata += struct.pack('<2I',image['address'],len(image['data']))+image['data'] tdata = struct.pack('<6sBI255s2I',b'Target',0,1,b'ST...',len(tdata),len(target)) + tdata data += tdata data = struct.pack('<5sBIB',b'DfuSe',1,len(data)+11,len(targets)) ...
"""VMware vCenter plugin for integration tests.""" from __future__ import absolute_import, print_function import os from lib.cloud import ( CloudProvider, CloudEnvironment, ) from lib.util import ( find_executable, display, ) from lib.docker_util import ( docker_run, docker_rm, docker_in...
vcenter_host = self.DOCKER_SIMULATOR_NAME elif container_id: vcenter_host = self._get_simula
tor_address() display.info('Found vCenter simulator container address: %s' % vcenter_host, verbosity=1) else: vcenter_host = 'localhost' self._set_cloud_config('vcenter_host', vcenter_host) def _get_simulator_address(self): results = docker_inspect(self.args, self.c...
# coding=utf-8 """Provider code for Speed.cd.""" from __future__ import unicode_literals import logging from medusa import tv from medusa.bs4_parser import BS4Parser from medusa.helper.common import ( convert_size, try_int, ) from medusa.logger.adapters.style import BraceAdapter from medusa.providers.torren...
h = False # Torrent Stats self.minseed = None self.minleech = None # Cache self.cache = tv.Cache(self) def search(self, search_strings, age=0, ep_obj=None, **kwargs):
""" Search a provider and parse the results. :param search_strings: A dict with mode (key) and the search value (value) :param age: Not used :param ep_obj: Not used :returns: A list of search results (structure) """ results = [] if not self.login...
from abc import abstractmethod class VIFDriver(object): @abstractmethod def after_device_destroy(self, environ, domxml): return domxml @abstractmethod def after_device_create(self, environ, domxml): return domxml @abstractmethod def after_network_setup(self, environ, json_co...
return domxml @abstractmethod def before_nic_unplug(self, environ, domxml): return domxml @abstractmethod def before_device_create(self, environ, domxml): return domxml @abstractmethod def before_device_destroy(self, environ, domxml): return domxml @abstrac...
omxml @abstractmethod def before_network_setup(self, environ, json_content): return json_content @abstractmethod def before_vm_start(self, environ, domxml): return domxml
turn six.text_type(instance) class StringRelatedField(RelatedField): """ A read only field that represents its targets using their plain string representation. """ def __init__(self, **kwargs): kwargs['read_only'] = True super(StringRelatedField, self).__init__(**kwargs) def ...
elf.lookup_field = kwargs.pop('lookup_field', self.lookup_field) self.lookup_url_kwarg = kwargs.pop('lookup_url_kwarg', self.lookup_field) self.format = kwargs.pop('format', None) # We include this simply for dependency injection in tests. # We can't add it as a class attributes or it w...
icit `self` argument to be passed. self.reverse = reverse super(HyperlinkedRelatedField, self).__init__(**kwargs) def use_pk_only_optimization(self): return self.lookup_field == 'pk' def get_object(self, view_name, view_args, view_kwargs): """ Return the object corresp...
#!/usr/bin/env python from .HTMLElement import HTMLElement from .attr_property import attr_property from .compatibility import thug_long class HTMLImageElement(HTMLElement): def __init__(self, doc, tag): HTMLElement.__init__(self, doc, tag) align = attr_property("align") alt ...
erty("name") s
rc = attr_property("src") useMap = attr_property("usemap") vspace = attr_property("vspace", thug_long) width = attr_property("width", thug_long) @property def complete(self): return True
''' AceProxy default configuration script DO NOT EDIT THIS FILE! Copy this file to aceconfig.py and change only needed options. ''' import logging import platform from aceclient.acemessages import AceConst class AceDefConfig(object): acespawn = False acecmd = "acestreamengine --client-console" acekey = '...
0 videodestroydelay = 3 videotimeout = 40 fakeuas = ('Mozilla/5.0 IMC plugin Macintosh', ) fakeheaderuas = ('HLS Client/2.0 (compatible; LG NetCast.TV-2012)', 'Mozilla/5.0 (DirectFB; Linux armv7l) AppleWebKit/534.26+ (KHTML, like Gecko) Version/5.0 Safari/534.26+ LG Browser/5.00.00(...
;); LG NetCast.TV-2012 0' ) osplatform = platform.system()
""" ====================================================== Effect of the shrinkage factor in random over-sampling ====================================================== This example shows the effect of the shrinkage factor used to generate the smoothed bootstrap using the :class:`~imblearn.over_sampling.RandomOverSamp...
rst, we will generate a toy classification dataset with only few samples. # The ratio between the classes will be imbalanced. from collections import Counter from sklearn.datasets import make_classification X, y = make_classification( n_samples=100, n_features=2, n_redundant=0, weights=[0.1, 0.9],
random_state=0, ) Counter(y) # %% import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(7, 7)) scatter = plt.scatter(X[:, 0], X[:, 1], c=y, alpha=0.4) class_legend = ax.legend(*scatter.legend_elements(), loc="lower left", title="Classes") ax.add_artist(class_legend) ax.set_xlabel("Feature #1") _ = ax.set...
from django.conf.urls.defaults import * from searchv1.views import ( search, find_grids_autocomplete, find_packages_autocomplete, search_by_function_autocomplete, search_by_category_autocomplete) urlpatterns = patterns("", url( regex = '^$', view = search, name = ...
name = 'search_grids_autocomplete', kwargs = dict( search_function=find_grids_autocomplete, ) ), url( regex = '^packages/autocomplete/$', view = search_by_function_autocomplete, name = 'search_packages_autocomp...
search_function=find_packages_autocomplete, ) ), url( regex = '^packages/by-category/autocomplete/$', view = search_by_category_autocomplete, name = 'search_by_category_autocomplete', ), )
s 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, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY...
p1*(1-cos4a) # # Transformation # if debug: g = numpy.identity(n) g[i,i] = cosa g[j,j] = cosa g[i,j] = -sina g[j,i] = sina ug = u.dot(g) pijag = numpy.einsum('i
k,jl,ija->kla',ug,ug,pija0) # Urot ui = u[:,i]*cosa+u[:,j]*sina uj = -u[:,i]*sina+u[:,j]*cosa u[:,i] = ui.copy() u[:,j] = uj.copy() # Bra-transformation of Integrals tmp_ip = pija[i,:,:]*cosa+pija[j,:,:]*sina tmp_jp = -pija[i,:,:]*sina+pija[j,:,:]*cosa pija[i,:,:] = tmp_ip.copy() pija[j,:,:] = t...
from gensim.models.doc2vec import Doc2Vec, LabeledSentence from nltk.tokenize import sent_tokenize, word_tokenize from sup.progress import Progress def train_doc2vec(paths, out='data/model.d2v', tokenizer=word_tokenize, sentences=False, **kwargs): """ Train a doc2vec model on a list of files. """ kwar...
tences: for sent in sent_tokenize(line): tokens = tokenizer(sent) yield LabeledSentence(tokens, ['SENT_{}'.format(i)]) else: tokens = tokenizer(line)
yield LabeledSentence(tokens, ['SENT_{}'.format(i)])
from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import fro
m builtins import super from future import standard_library standard_library.install_aliases() from vcfx.field.nodes import Field class Categories(Field): KEY = "CATEGORIES" def __init__(self, *a, **kw): super(Categories, self).__init__(*a, **kw) def clean_values(self, v):
self.value = v.strip("\r\n").split(",") class Note(Field): KEY = "NOTE" def __init__(self, *a, **kw): super(Note, self).__init__(*a, **kw) class Prodid(Field): KEY = "PRODID" def __init__(self, *a, **kw): super(Prodid, self).__init__(*a, **kw) class Revision(Field): KEY = "RE...
from flask
import Flask from flask_socketio import SocketIO # создаем экземпляр класса Flask app = Flask(__name__) # создаем экземпляр класса SocketIO socketio = S
ocketIO(app) from app.views import home
# -*- coding: utf-8 -*- # auxilium # -------- # Python project for an automated test and deploy toolkit. # # Author: sonntagsgesicht # Version: 0.1.8, copyright Saturday, 02 October 2021 # Website: https://github.com/sonntagsgesicht/auxilium # License: Apache License 2.0 (see LICENSE file) from datetime import ...
c.replace('<email>', email) c = c.replace('<author>', author) c = c.replace('<doc>', slogan) c = c.replace('<name>', name) c = c.replace('<date>', date.today().strftime('%A, %d %B %Y')) f = open(pth, 'w') f.write(c) f.close(
) rp(pkg_path + sep + '__init__.py') rp(project_path + sep + 'setup.py') rp(project_path + sep + 'README.rst') rp(project_path + sep + 'HOWTO.rst') rp(project_path + sep + 'CHANGES.rst') rp(project_path + sep + 'doc' + sep + 'sphinx' + sep + 'doc.rst') rp(project_path + sep + 'doc' + sep + ...
import sys from injector import Injector def main(): path_exe = str(sys.argv[1]) path_dll = str(sys.argv[2]) injector = Injector() pid = injector.create_process(path_exe) inje
ctor.load_from_pid(pid) injector.inject_dll(path_dll) injector.unload
() if __name__ == "__main__": main()
#!/usr/bin/python """ Copyright 2014 The Trustees of Princeton University 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 ...
r("Failed to derive public key from private key") return None sealed_slice_secret = base64.b64decode( sealed_slice_s
ecret_b64 ) # decrypt it rc, slice_secret = c_syndicate.decrypt_data( observer_pubkey_pem, observer_pkey_pem, sealed_slice_secret ) if rc != 0: logger.error("Failed to decrypt '%s', rc = %d" % (sealed_slice_secret_b64, rc)) return None return slice_secret
# Copyright 2015 Google In
c. 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 agreed to in writing, softw...
ITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """A no-op implementation of status bar functions.""" from __future__ import absolute_i...
from elasticsearch import Elasticsearch import argparse import os import json import re def ExportDashboards(es, regex, kibana_index, output_directory): res = es.search( index=kibana_index, doc_type="dashboard", size=1000) try: reg_exp = re.compile(regex, re.IGNORECASE) ex...
=kibana_index, doc_type="visualization", id=visualization) # save visualization SaveJson("visualization", doc, output_directory) # save dependencies if "savedSearchId" in doc["_source"]: search = doc["_source"]['savedSearchId'] ExportSearch( es, ...
ry): doc = es.get( index=kibana_index, doc_type="search", id=search) # save search SaveJson("search", doc, output_directory) def SaveJson(doc_type, doc, output_directory): dir = os.path.join(output_directory, doc_type) if not os.path.exists(dir): os.makedirs(dir) ...
# -*- coding: utf-8 -*- from flask
import Blueprint from jotonce.api import route from jotonce.passphrases.models import Passphrase bp = Blueprint('passphrase', __name__, url_prefix='/passphrase') @route(bp, '/') def get(): p = Passphrase.get_random() ret
urn {"results": p}
rt click import requests from requests.exceptions import HTTPError except ImportError: print("Failed to load third-party libraries.") print("Please run: $ pip install -r requirements.txt") sys.exit(1) def __urljoin(*elements): return "/".join(elem.strip("/") for elem in elements) def __post(ur...
ra-2.2.5-bin.tar.gz", help="url of the cassandra package") @click.option("--jre-url", show_default=True, default="https://downloads.mesosphere.com/java/jre-8u121-linux-x64.tar.gz", help="url of the jre package") @click.option("--keyspace-override", default="", help="keyspace to...
of a randomized default") @click.option("--ip-override", default=[], help="list of node ips to use instead of what the framework returns") @click.option("--port-override", show_default=True, default=DEFAULT_PORT, help="node port to use. cassandra-stress lacks support for multiple ports.") de...
import bottle from config import app, Session from models.show_follow import ShowFollow @app.get("/rest/show-follow/<show_id>") def get_show_follow(session, show_id): user_id = session.get("user_id") if user_id: sa_session = Session() show_follow = sa_session.query(ShowFollow) \ ...
ssion.get("user_id") if user_id: sa_session = Session() if following: sa_session.query(ShowFollow) \ .filter(ShowFollow.show_id == show_id, ShowFollow.user_id == user_id) \ .delete() sa_session.commit()
return dict(following=False, success=True) show_follow = ShowFollow(show_id=show_id, user_id=user_id) sa_session.add(show_follow) sa_session.commit() return dict(following=True, success=True) return dict(redirect="/register")
#!/usr/bin/env python3 import json import re import sys def _decode_pattern_list(data): rv = [] contains_dict = False for item in data: if isinstance(item, list): item = _decode_pattern_list(item) elif isinstance(item, dict): item = _decode_pattern_dict(item) ...
= json.loads(s, object_hook=_decode_pattern_dict) except Exception as err: if debug: ## print some context info and return without any extracted query data.. msg = f'''json2pattern():json.loads Exception:\n Error: {err} : {sys.exc_info()[0]}\n saved_s: ({saved_s})\n s: ({s})\n''' ...
ror: saved_s: ({saved_s}) sys.exc_info():{sys.exc_info()[0]}''' ) raise try: return json.dumps(doc, sort_keys=True, separators=(', ', ': '), ensure_ascii=False) except Exception as err: ## print some context info and return without any extracted query data.. if debug: ...
""" WSGI config for pyday2016 project. It exposes the
WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ """ import os from dj
ango.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pyday2016.settings") application = get_wsgi_application()
#!/usr/bin/python3 import se
rial im
port time serialRFID = serial.Serial("/dev/ttyAMA0", 9600) while True: print (serialRFID.read(12)[1:11]) serialRFID.flushInput() time.sleep(0.2)
from django.conf import settings from django.conf.urls import patterns, include, url urlpatterns = patterns('', url(r'^', include('howtostor
eiosdata.wizard.urls', namespace="wizard")), ) if settings.DEBUG: urlpatterns += patterns('', (r'^media/(?P<path>.*)$', '
django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), )
# {x | n, js_escaped_string} is valid, if surrounded by quotes prior_character = mako_template[expression['start_index'] - 1] next_character = mako_template[expression['end_index'] + 1] has_surrounding_quotes = (prior_character == '\'' and next_character == '\'') ...
break return current_
context def _find_mako_expressions(self, mako_template): """ Finds all the Mako expressions in a Mako template and creates a list of dicts for each expression. Arguments: mako_template: The content of the Mako template. Returns: A list of dicts for ...
import numpy as np from rampwf.score_types.soft_accuracy import SoftAccuracy score_matrix_1 = np.array([ [1, 0, 0], [0, 1, 0], [0, 0, 1], ]) score_matrix_2 = np.array([ [1, 0.5, 0], [0.3, 1, 0.3], [0, 0.5, 1], ]) y_true_proba_1 = np.array([1, 0, 0]) y_true_proba_2 = np.array([0, 1, 0]) y_tr...
])) == 0.5 assert score_2(np.array([y_true_proba_1]), np.array([y_proba_4])) == 0.5 assert score_2(np.array([y_true_proba_2]), np.array([y_proba_1])) == 0.3 assert score_2(np.array([y_true_proba_2]), np.array([y_proba_2])) == 1 assert score_2(np.array([y_true_proba_2]), np.array([y_proba_3])) == 1 a...
rt score_2(np.array([y_true_proba_3]), np.array([y_proba_1])) == 0.65 assert score_2(np.array([y_true_proba_3]), np.array([y_proba_2])) == 0.75 assert score_2(np.array([y_true_proba_1]), np.array([y_proba_5])) == 0.0 assert score_2(np.array([y_true_proba_2]), np.array([y_proba_5])) == 0.0 assert score_2...
try: device, partition, account, container, obj = \ split_path(unquote(request.path), 5, 5, True) except ValueError, err: return HTTPBadRequest(body=str(err), request=request, content_type='text/plain') if self.mount_check and not che...
et('if-match') == '*': return HTTPPreconditionFailed(request=request) else: return HTTPNotFound(request=request) try: file_size =
file.get_data_file_size() except (DiskFileError, DiskFileNotExist): file.quarantine() return HTTPNotFound(request=request) if request.headers.get('if-match') not in (None, '*') and \ file.metadata['ETag'] not in request.if_match: file.close() ...
# -*- coding: utf-8 -*- """Librería para parsear entradas y salidas de Karel en XML.""" import xml.etree.ElementTree as ET import sys def load(): """Regresa (input, output, nombre de caso) para la ejecución actual""" with open('data.in', 'r') as data_in: return KarelInput(data_in.read()), KarelOutput(sys.stdin.re...
0 z = self._zumbadores[(x, y)] if z == 'INFINITO': return z return
int(z)
def extractForthemoneyTranslations(item): """ Forthemoney Translations """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol or frag) or 'preview' in item['title'].lower(): return None retur
n False
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2015-2016 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # # This file is part of qutebrowser. # # qutebrowser 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 S...
le caret browsing globally.""" settings = QWebSettings.globalSettings() old_value = settings.testAttribute(QWebSettings.CaretBrowsingEnabled) settings.setAttribute(QWebSettings.CaretBrowsingEnabled, True) yield settings.setAttribute(QWebSettings.CaretBrowsingEnabled, old_value) class CaretTester: ...
_tester fixture. """ def __init__(self, js_tester): self.js = js_tester def check(self): """Check whether the caret is before the MARKER text.""" self.js.run_file('position_caret.js') self.js.webview.triggerPageAction(QWebPage.SelectNextWord) assert self.js.webview....
# coding=utf-8 from rutermextract import Te
rmExtractor term_extractor = TermExtractor() text = u'Съешь ещё этих мягких французских булок да выпей же чаю.' for term in term_extractor(text):
print term.normalized, term.count
listofcricket=['kohli','mathews','morgan','
southee','tamim','smith'] print('Enter a name to search') name =
input() if name not in listofcricket: print(name+' is not in the list of cricketers') else: print(name+' is in this list')
# Generated by Django 2.1.7 on 2019-04-26 17:55 from django.db import migrations, models from scheduler.models import RepeatableJob from django.utils import timezone from django_rq import job @job("short") def install_generate_summaries_job(apps, schema_editor): job, created = RepeatableJob.objects.get_or_create...
enerate_summaries_job(apps, schema_editor): RepeatableJob.objects.filter(name="generate_summaries_job").delete() class Migration(migrations.Migration): atomic = False dependencies = [("testresults
", "0012_create_summaries")] operations = [ migrations.RunPython( install_generate_summaries_job, reverse_code=uninstall_generate_summaries_job, ) ]
# ----------------------------------------------------------------------------- # Copyright (c) 2014--, The Qiita Development Team. # # Distributed under the terms of the BSD 3-clause Lic
ense. # # The full license is in the file LICENSE, distributed with this software. # ----------------------------------------------------------------------------- def get_qiime2_type_name_and_predicate(element): """helper method to get the qiime2 type name and predicate Parameters ---------- element ...
ignature """ to_ast = element.qiime_type.to_ast() if to_ast['type'] == 'union': # union types allow to give choices to another type of parameter; for # example for a range(1, 10) give the choice `ignore`. These are not # necessary in Qiita as they are simply ignored if unchanged. Thu...
# -*- coding: utf-8 -*- """Model unit tests.""" import datetime as dt import pytest from blogaggregator.user.models import User, Role from .factories import UserFactory @pytest.mark.usefixtures('db') class TestUser: def test_get_by_id(self): user = User('foo', 'foo@bar.com') user.save() ...
password('myprecious') def test_check_password(self): user = User.create(username="foo", email="foo@bar.com", password="foobarbaz123") assert user.check_password('foobarbaz123') is True assert user.check_password("barfoobaz") is False def test_full_name(self): ...
full_name == "Foo Bar" def test_roles(self): role = Role(name='admin') role.save() u = UserFactory() u.roles.append(role) u.save() assert role in u.roles
import unittest from leafpy import Leaf from leafpy.auth import login import vcr USERNAME = 'dummyuser' PASSWORD = 'dummypass' class LoginTests(unittest.TestCase): @vcr.use_cassette('tests/unit/cassettes/test_login.yaml', filter_post_data_parameters=['UserId','Password']) def test_login(self): ...
w: leaf.BatteryStatusRecordsRequest() def test_login_with_only_username_raises_exception(self): with self.assertRaises(Exception): leaf = Leaf('username') def test_login_with_only_VIN_raises_exception(s
elf): with self.assertRaises(Exception): leaf = Leaf(VIN='vin123') def test_login_with_only_custom_sessionid_raises_exception(self): with self.assertRaises(Exception): leaf = Leaf(custom_sessionid='vin123') def test_login_with_no_args_raises_exception(self): wit...
# -*- coding: utf-8 -*- from __future__ import division from __future__ import unicode_literals from collections import namedtuple import json import logging import time from collections import namedtuple from slackclient import SlackClient class SlackBot(object): def __init__(self, settingsFilePath='settings.j...
n ({user['name']: user.get('id')}) else: return "could not find bot user with the name " + s["bot"]["name"] def autoping(self,last): ### hardcode the interval to 3 seconds now = int(time.time()) if last + 3 < now: self.sclient.server.ping()
return now def addCommand(self, command, action, help): self.commands[command] = self.CommandBody(action=action, help=help) def sendReply(self, msg): text = msg['text'][len(self.botcheck):] pos = len(text) try: pos = text.index(' ') except ValueError: ...
Future, Asset ) from . position import positiondict from catalyst.constants import LOG_LEVEL log = logbook.Logger('Performance', level=LOG_LEVEL) PositionStats = namedtuple('PositionStats', ['net_exposure', 'gross_value', 'gro...
del self._positions_store[asset] except KeyError: pass @expect_types(asset=Asset) de
f handle_commission(self, asset, cost): # Adjust the cost basis of the stock if we own it if asset in self.positions: self.positions[asset].adjust_commission_cost_basis(asset, cost) def handle_splits(self, splits): """ Processes a list of splits by modifying any position...
d (float): discards all overlapping boxes with IoU > iou_threshold Returns: Tensor: int64 tensor with the indices of the elements that have been kept by NMS, sorted in decreasing order of scores """ if not torch.jit.is_scripting() and not torch.jit.is_tracing(): _log_api_usage_once(...
x_area) boxes = _upcast(boxes) return (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1]) # implementation from https://github.com/kuangliu/torchcv/blob/master/torchcv/utils/box.py # with slight modifications def _box_inter_union(boxes1: Tensor, boxes2: Tensor) -> Tuple[Tensor, Tensor]: are
a1 = box_area(boxes1) area2 = box_area(boxes2) lt = torch.max(boxes1[:, None, :2], boxes2[:, :2]) # [N,M,2] rb = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) # [N,M,2] wh = _upcast(rb - lt).clamp(min=0) # [N,M,2] inter = wh[:, :, 0] * wh[:, :, 1] # [N,M] union = area1[:, None] + area2 - ...
from models.basemodel import BaseModel class Campus(BaseModel): CAMPUS_CODES = ['BD', 'DN', 'CS'] LONG_NAMES = { 'BD': 'University of Colorado, Boulder', 'DN': 'University of Colorado, Denver', 'CS': 'University of Colorado, Colorado Springs' } def requiredFields(self): ...
, 'courses', 'instructors', 'departments', 'colleges', 'id'] def fields(self): return { 'campus': (self.is_in_list(self.CAMPUS_CODES),
), 'fcqs': (self.is_list, self.schema_list_check(self.is_string, )), 'grades': (self.is_list, self.schema_list_check(self.is_string, ),), 'courses': (self.is_list, self.schema_list_check(self.is_string, )), 'instructors': (self.is_list, self.schema_list_check(self.is_str...
'''OpenGL extension NV.texture_env_combine4 This module customises the behaviour of the OpenGL.raw.GL.NV.textur
e_env_combine4 to provide a more Python-friendly API Overview (from the spec) New texture environment function COMBINE4_NV allows p
rogrammable texture combiner operations, including ADD Arg0 * Arg1 + Arg2 * Arg3 ADD_SIGNED_EXT Arg0 * Arg1 + Arg2 * Arg3 - 0.5 where Arg0, Arg1, Arg2 and Arg3 are derived from ZERO the value 0 PRIMARY_COLOR_EXT primary color of incoming ...
# Copyright (c) 2016 Cisco Systems # 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 require...
T # 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 aim import aim_manager from aim.api import infra from aim import config # noqa from aim.db import infra_model from aim.tests import base class TestAimInfraManager(base.TestAimDBBase): ...
from
dotenv import load_dotenv load_
dotenv('./.env')
""" Base classes for test cases Tests w
ill usually inherit from one of these classes to have the controller and/or dataplane automatically set up. """ import os
import logging import unittest import ptf from ptf.base_tests import BaseTest from ptf import config import ptf.dataplane as dataplane ################################################################ # # Thrift interface base tests # ################################################################ import p4_sai_rp...
rn = ['I', 'bII', 'II', 'bIII', 'III', 'IV', 'bV', 'V
', 'bVI', 'VI', 'bVII', 'VII'] header
= [] for n in rn: for next_n in rn: header.append(n + '-' + next_n) print(header) print(len(header))
from flask import Fla
sk from flask import render_template app = Flask(__name__) def info(): user = { 'nickname': 'Praful', 'key': 'A154XWA256' } posts = { 'company': 'Ethereal Machines', 'link': 'http://www.etherealmachines.com/', 'firmware' : 'Marlin Firmware', 'version': 'v1...
urn render_template( 'index.html', user=user, title= 'Try', posts=posts)
from __future__ import unicode_literals from os.path import abspath, basename, dirname, join, normpath from sys import path import markdown """Common settings and globals.""" # PATH CONFIGURATION # Absolute filesystem path to the Django project directory: DJANGO_ROOT = dirname(dirname(abspath(__file__))) # Absolut...
v/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { ...
dminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } # END LOGGING CONFIGURATION # AUTHENTICATION CONFIGURATION # https://docs.djangoproject.com/en/dev/ref/settings/#std:s...
# -*- coding: utf-8 -*- """ Django settings for puput_demo project. For more information on this file, see https://docs.djangoproject.com/en/dev/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/dev/ref/settings/ """ from __future__ import absolute_import, unicode_...
ngs/#static-url STATIC_URL = '/static/' # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) # MEDIA CONFIGURATION # ----------------...
# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root MEDIA_ROOT = str(APPS_DIR('media')) # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url MEDIA_URL = '/media/' # URL Configuration # ------------------------------------------------------------------------------ ROOT_URLCONF = 'con...
######## # Copyright (c) 2014 GigaSpaces Technologies Ltd. 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 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...
list. If not, we return negative. # # See :help input() for explanation of the use of inputsave() and inpput # restore(). It is done in try/finally in case vim.eval ever throws an # exception (such as KeyboardInterrupt) selected = GetIntValue( "inputlist( " + json.dumps( vim_items ) + " )" ) - 1 e...
which are not curerntly open in visible windows""" return len( [ f for f in file_list if not BufferIsVis
ible( GetBufferNumberForFilename( f, False ) ) ] ) def _OpenFileInSplitIfNeeded( filepath ): """Ensure that the supplied filepath is open in a visible window, opening a new split if required. Returns the buffer number of the file and an indication of whether or not a new split was opened. If the supplied fil...
tUp() from wiki.templatetags import wiki_tags wiki_tags._cache = {} def test_obj_arg_is_not_a_django_model(self): from wiki.templatetags import wiki_tags with self.assertRaises(TypeError): article_for_object({}, '') with self.assertRaises(TypeError): ...
len(cache), 1) self.render({'obj': obj
}) self.assertIn(obj, cache) self.assertIsNone(cache[obj]) self.assertEqual(len(cache), 1) def test_obj_is_not_in__cache_and_articleforobjec_is_exist(self): from wiki.templatetags.wiki_tags import _cache as cache a = Article.objects.create() content_type = ContentT...
# missileThermalDmgBonusHeavy # # Used by: # Implants named like: Zainou 'Snapshot' Heavy Missile
s HM (6 of 6) type = "passive" def handler(fit, container, context): fit.modules.filteredChargeBoost(lambda mod: mod.charge.requiresSkill("Heavy Missiles"), "thermalDamage", container.getMo
difiedItemAttr("damageMultiplierBonus"))
L, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) AR...
taWindow ) def test( self ) : n = GafferImage.ImageReader() n["fileName"].setValue( self.fileName ) self.assertEqual( n["out"]["dataWindow"].getValue(), IECore.Box2i( IECore.V2i( 0 ), IECore.V2i( 199, 149 ) ) ) self.assertEqual( n["out"]["format"].getValue().getDisplayWindow(), IECore.Box2i( IECore.V2i( 0 )...
"].getValue() self.failUnless( isinstance( channelNames, IECore.StringVectorData ) ) self.failUnless( "R" in channelNames ) self.failUnless( "G" in channelNames ) self.failUnless( "B" in channelNames ) self.failUnless( "A" in channelNames ) image = n["out"].image() image2 = IECore.Reader.create( self.fil...
on in an app, might include other, dependent apps, and these were being unmigrated. """ # Make the initial plan, check it executor = MigrationExecutor(connection) plan = executor.migration_plan([ ("migrations", "0002_second"), ("migrations2", "0001_initial...
to a custom user model defined in the same app are not resolved correctly. """
executor = MigrationExecutor(connection) self.assertTableNotExists("migrations_author") self.assertTableNotExists("migrations_tribble") # Migrate forwards executor.migrate([("migrations", "0001_initial")]) self.assertTableExists("migrations_author") self.assertTab...
import cv2 import numpy as np template = np.zeros((500,500,3),np.uint8) template[:,:,0] = 255 template[:,:,1] = 255 template[:,:,2] = 255 x = [50,250,250,50,50] y = [50,50,250,250,50] cnt = np.asarray(zip(x,y)) cv2.drawContours(template,[cnt],0,0,1)
x = [100,200,200,100,100] y = [300,300,150,150,300] cnt = np.asarray(zip(x,y)) cv2.drawConto
urs(template,[cnt],0,0,1) x = [150,400,400,150,150] y = [200,200,400,400,200] cnt = np.asarray(zip(x,y)) cv2.drawContours(template,[cnt],0,0,1) x = [150,200,200,150,150] y = [250,250,200,200,250] cnt = np.asarray(zip(x,y)) cv2.drawContours(template,[cnt],0,(255,0,0),-1) cv2.imwrite("/home/ggdhines/github/aggregatio...
d = ['GET', 'PUT', 'POST', 'SAY'] self.assertEqual([t.verb for t in l], expected) # ...the URIs... expected = ['*', '/foo*', '/bar*', '/derp*'] self.assertEqual([t.uri for t in l], expected) # ...the regexes... expected = ['.*', '/foo.*', '/bar.*', '/derp.*'] se...
bob.Request.blank("/%s" % username) else: request = webob.
Request.blank("/") request.method = "POST" request.body = self._request_data(verb, url) response = request.get_response(self.app) if "X-Wait-Seconds" in response.headers: self.assertEqual(response.status_int, 403) return response.headers["X-Wait-Seconds"] ...
# Copyright 2011 OpenStack Foundation # 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.or
g/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 ...
#!/usr/bin/env python # Raspberry Pi Rotary Encoder Class # $Id: rotary_class.py,v 1.7 2017/01/07 11:38:47 bob Exp $ # # Copyright 2011 Ben Buxton. Licenced under the GNU GPL Version 3. # Contact: bb@cactii.net # Adapted by : Bob Rathbone and Lubos Ruckl (Czech republic) # Site : http://www.bobrathbone.com # # This c...
OWN=3 BUTTONUP=4 def __init__(self, pinA, pinB, button,callback,revision): self.pinA = pinA self.pinB = pinB self.button = button self.callback = callback GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) if revision == 1: # For version...
GPIO.IN) else: # The following lines enable the internal pull-up resistors # on version 2 (latest) boards GPIO.setup(self.pinA, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(self.pinB, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(self.button, GPIO.IN...
########################################################################### # Copyright (c) 2011-2014 Unixmedia S.r.l. <info@unixmedia.it> # Copyright (c) 2011-2014 Franco (nextime) Lanza <franco@un
ixmedia.it> # # Domotika System Controller Daemon "domotikad" [http://trac.unixmedia.it] # # This file is part of domotikad. # # domotikad 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. # # 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 mor...
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2013, 2014, 2015 CERN. # # Invenio 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 optio...
s = RegistryProxy( 'output_formats_directories', ModuleAutoDiscoveryRegistry, 'output_formats' ) output_formats_files = RegistryProxy( 'output_formats_files', P
kgResourcesDirDiscoveryRegistry, '.', registry_namespace=output_formats_directories ) template_context_functions = RegistryProxy( 'template_context_functions', ModuleAutoDiscoverySubRegistry, 'template_context_functions' ) def create_format_templates_lookup(): """Create format templates.""" o...
############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # T...
request)
return ProxyFactory(ob2) class PublicationTraverser(PublicationTraverse): def traversePath(self, request, ob, path): if isinstance(path, StringTypes): path = path.split('/') if len(path) > 1 and not path[-1]: # Remove trailing slash path.pop()...
# -*- coding: UTF-8 -*- #/* # * Copyright (C) 2011 Ivo Brhel # * # * # * 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, or (at your option) # * any later version. #...
T ANY WARRANTY; without even the implied warranty of # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # * GNU General Public License for more details. # * # * You should have received a copy of the GNU General Public License # * along with this program; see the file COPYING. If not, write to # * t...
Cambridge, MA 02139, USA. # * http://www.gnu.org/copyleft/gpl.html # * # */ import re,os,urllib,urllib2,cookielib import util,resolver from provider import ContentProvider class HejbejseContentProvider(ContentProvider): def __init__(self,username=None,password=None,filter=None): ContentProvider.__init__(self,...
ompareSqueeze(self, x, squeeze_dims, use_gpu): with self.test_session(use_gpu=use_gpu): if squeeze_dims: np_ans = np.squeeze(x, axis=tuple(squeeze_dims)) tensor = tf.squeeze(x, squeeze_dims) tf_ans = tensor.eval() else: np_ans = np.squeeze(x) tensor = tf.squeeze(x...
ises(ValueError, tf.squeeze, np.zeros
([1, 2, 1]), [3]) self.assertRaises(ValueError, tf.squeeze, np.zeros([1, 2, 1]), [2, 3]) def testSqueezeGradient(self): with self.test_session(): inp = np.random.rand(4, 2).astype("f") a = tf.reshape(inp, [4, 1, 2]) squeezed = tf.squeeze(a, []) err = tf.test.compute_gradient_erro...
from .stop_words import STOP_WORDS from .lex_attrs import LEX_ATTRS from .punctuation import TOKENIZER_
SUFFIXES from ...language import Language, BaseDefaults class UrduDefaults(BaseDefaults): suffixes
= TOKENIZER_SUFFIXES lex_attr_getters = LEX_ATTRS stop_words = STOP_WORDS writing_system = {"direction": "rtl", "has_case": False, "has_letters": True} class Urdu(Language): lang = "ur" Defaults = UrduDefaults __all__ = ["Urdu"]
import MDAnalysis from MDAnalysis.tests.datafiles import GRO, XTC universe = MDAnalysis.Universe(GRO, XTC) #old selection all_selection = universe.selectAtoms('all') #additional old selectAtoms selection (this comment shouldn't be modified despite containing the method name) all_selection.selectAtoms('bynum 1:10') #...
raj = universe.trajectory #frame_count = traj.numframes frame_count = traj.numframes # From MDAnalysis.lib.distances #calc_torsions() -> calc_dihedrals() #from MDAnalysis.lib.
distances import calc_torsions from MDAnalysis.lib.distances import calc_torsions #MDAnalysis.lib.distances.calc_torsions() MDAnalysis.lib.distances.calc_torsions() result = MDAnalysis.lib.distances.calc_torsions() #dist.calc_torsions() dist.calc_torsions() #atomgroup method pluralizations #set_mass(new) --> set_masse...
# # QAPI introspection generator # # Copyright (C) 2015-2016 Red Hat, Inc. # # Authors: # Markus Armbruster <armbru@redhat.com> # # This work is licensed under the terms of the GNU GPL, version 2. # See the COPYING file in the top-level directory. from qapi import * # Caveman's json.dumps() replacement (we're stuck...
_used_types.append(typ) # Clients should examine commands and events, not types. Hide # type names to reduce the temptation. Also saves a few # characters. if isinstance(typ, QAPISchemaBuiltinType): return typ.name if isinstance(typ, QAPISchemaArrayType): ...
'event', 'builtin', 'array'): name = self._name(name) obj['name'] = name obj['meta-type'] = mtype self._jsons.append(obj) def _gen_member(self, member): ret = {'name': member.name, 'type': self._use_type(member.type)} if member.optional: ret['default...
# Copyright 2018 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...
'skipped_package': { 'when': 'DIB_FEATURE=0' }, 'not_skipped_package': { 'when': 'DIB_FEATURE=1' }, 'not_equal_package': { 'when': 'DIB_FEATURE!=0' }, 'not_equal_skipped_package': { ...
result = installs_squash.collect_data( self.final_dict, objs, 'test_element') expected = { 'install.d': { 'install': [('not_skipped_package', 'test_element'), ('not_equal_package', 'test_element')] } } self...
"""Provides VM delete parser.""" # Copyright (c) 2018 - I.T. Dev Ltd # # This file is part of MCVirt. # # MCVirt 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 ...
ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General
Public License # along with MCVirt. If not, see <http://www.gnu.org/licenses/> from argparse import SUPPRESS class DeleteParser(object): """Handle VM delete parser.""" def __init__(self, subparser, parent_parser): """Create subparser for deleting VMs.""" self.parent_subparser = subparser ...
st. Prefer kwargs over body. :param auth: An auth tuple or method as accepted by requests. :param username: Username used by LegacyApplicationClients. :param password: Password used by LegacyApplicationClients. :param method: The HTTP method used to make the request. Defaults ...
self.token = self._client.token log.debug('Obtained token %s.', self.token) return self.token def token_from_fragment(self, authorization_response): """Parse token from the URI fragment, used by MobileApp
licationClients. :param authorization_response: The full URL of the redirect back to you :return: A token dict """ self._client.parse_request_uri_response(authorization_response, state=self._state) self.token = self._client.token return self.token de...
""" This sample shows how to loop through the folders and print their titles Python 2/3 ArcREST version 3.5.x """ from __future__ import print_function from arcrest.security import AGOLTokenSecurityHandler import arcrest if __name__ == "__main__": username = ""#Username password = ""#password ...
password=password) admin = arcrest.manageorg.Administration(securityHandler=agolSH) content = admin.content user = content.users.user() for folder in user.folders: title = folder['title'] print("Analyzing {}".format(title)) user.currentFolder =...
{} items".format(len(user.items)))
# -*- coding: utf-8 -*-
""" sleepy.models.user ~~~~~~~~~~~~~~~~~~ User model. """ from django.contrib.auth.models import AbstractUser class User(AbstractUs
er): pass
#!/usr/bin/env python # # vim: tabstop=4 expandtab shiftwidth=4 noautoindent import sys import os import time import atexit from signal import SIGTERM class Daemon: """A generic daemon class. Usage: subclass the Daemon class and override the run() method""" def __init__(self, pidfile, stdin='/dev/null', ...
)) pf.close() def delpid(self): os.remove(self.pidfile) def start(self): """Start the daemon""" # Check for a pidfile to see if the daemon already runs try: pf = open(self.pidfile, 'r') pid = int(pf.re
ad().strip()) pf.close() except IOError: pid = None if pid: message = "pidfile %s already exists." % self.pidfile message += " Daemon already running?\n" sys.stderr.write(message) sys.exit(1) # Start the daemon sel...
from concurrent import futures import time import grpc import demo_pb2 import demo_pb2_grpc _ONE_DAY_IN_SECOND = 60 * 60 * 24 class Greeter(demo_pb2_grpc.GreeterServicer): def SayHello(self,request,context): return demo_pb2.HelloReply(mess
age='Hello, %s' % request.name) def serve(): #grpc服务器 server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) demo_pb2_grpc.add_GreeterServicer_to_server(Greeter(),server) server.add_insecure_port('[:
:]:50051') server.start() try: while True: time.sleep(_ONE_DAY_IN_SECOND) except KeyboardInterrupt: server.stop(0) if __name__ == '__main__': serve()
# Imports operators dynamically while keeping the package API clean, # abstracting the underlying modules from airflow.utils import import_module_attrs as _import_module_attrs # These need to be integrated first as other operators depend on them _import_module_attrs(globals(), { 'check_operator': [ 'CheckO...
ator', 'SlackAPIPostOperator'], 'generic_transfer': ['GenericTransfer'], } _import_module_attrs(globals(), _operators) from airflow.models import BaseOperator def integrate_plugins(): """Integrate plugins to the context
""" from airflow.plugins_manager import operators as _operators for _operator in _operators: globals()[_operator.__name__] = _operator
# Copyright 2019 DeepMind Technologies Limited # # 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, software # distributed under the License is di...
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. """Numerical information about some games or some specific settings of games. TODO(author2): Ideally, this should also be available from C++. ...
import discord import asyncio import datetime import time import aiohttp import threading import glob import re import json import os import urllib.request from discord.ext import commands from random import randint from random import choice as randchoice from random import choice as rndchoice from random import shuffl...
] comparexp = stat2[2] - stat1[2] await self.bot.say("```" + name2 + "'s ranking is " + str(comparerank) + " ranks higher than " + name1 + "'s rank.\n" + name2 + "'s level is " + str(comparelvl) + " levels higher than " + name1 + "'s.\n" + name2 + "'s total experience is " + str(comparexp) +...
`") except: await self.bot.say("Sorry... Something went wrong there. Did you type the name correctly?") def setup(bot): n = Runescapecompare(bot) bot.add_cog(n)
sion = __version__ currentdir = os.path.abspath(os.path.dirname(__file__)) sys.path.append(os.path.join(currentdir, 'tools')) # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path....
content
autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # Lis...
import sys import os.path sys
.path.insert(0, os.path.join(os.path.dirname(__file__), 'lib')) sys.pa
th.insert(0, os.path.join(os.path.dirname(__file__), 'py'))
# 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...
ng permissions and # limitations under the License. # ============================================================================== """Public API for tf.linalg.sparse namespace.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # go/tf-wildcard-import # p...
ps.linalg.sparse.sparse_csr_matrix_ops import * # pylint: enable=wildcard-import
olour_scheme["Task to run"]["fontcolor"] = "lightgrey" default_colour_scheme["Up-to-date Final target"]["fontcolor"] = '"#EFA03B"' return default_colour_scheme #_________________________________________________________________________________________ # # get_dot_fo...
ributes["style"]="dashed" #_________________________________________________________________________________________ # # write_legend_key #_________________________________________________________________________________________ def write_legend_key (stream, used_task_types, minimal_key_legend, colour_scheme, key
_name = "Key:", subgraph_index = 1): """ Write legend/key to dependency tree graph """ if not len(used_task_types): return stream.write( 'subgraph clusterkey%d\n' % subgraph_index) stream.write( '{\n') stream.write( 'rank="min";\n') stream.write( 'style=filled;\n') stream....
import tensorgraph as tg import numpy as np import time def test_SimpleBlocks(): X = np.random.rand(100, 200) with open('X.npy', 'wb') as f: np.save(f, X) db = tg.SimpleBlocks(['X.npy']*10, batchsize=32, allow_preload=True) t1 = time.time() count = 1 for blk in db: print(count...
batch in blk: print(time.sleep(0.1)) pass print('with preload time:', time.time() - t1) db = tg.SimpleBlocks(['X.npy']*10, batchsize=32, allow_preload=False)
t1 = time.time() count = 1 for blk in db: print(count) count += 1 for batch in blk: print(time.sleep(0.1)) pass print('without preload time:', time.time() - t1) db = tg.SimpleBlocks([('X.npy', 'X.npy'), ('X.npy', 'X.npy')], batchsize=32, allow_preloa...
r channel") _utils.check_parameter_valid('string', source, desc="monitor signal") monitor_sources = { 'none': _IIR_MON_NONE, 'adc1': _IIR_MON_ADC1, 'in1': _IIR_MON_IN1, 'out1': _IIR_MON_OUT1, 'adc2': _IIR_M...
r=False): """ Converts volts to bits depending on the signal source """ # Decimation gain is applied only when using precision mode data
if (not trigger and self.is_precision_mode()) or ( trigger and self.trig_precision): deci_gain = self._deci_gain() else: deci_gain = 1.0 if (source == _IIR_SOURCE_A): level = self._monitor_source_volts_per_bit( self.monitor_a, scales)...
#!/usr/bin/python # # mallocstacks Trace malloc() calls in a process and print the full # stack trace for all callsites. # For Linux, uses BCC, eBPF. Embedded C. # # This script is a basic example of the new Linux 4.6+ BPF_STACK_TRACE # table API. # # Copyright 2016 GitHub, Inc. # Licensed ...
ion from bcc import BPF from bcc.utils import printb from time import sleep import
sys if len(sys.argv) < 2: print("USAGE: mallocstacks PID [NUM_STACKS=1024]") exit() pid = int(sys.argv[1]) if len(sys.argv) == 3: try: assert int(sys.argv[2]) > 0, "" except (ValueError, AssertionError) as e: print("USAGE: mallocstacks PID [NUM_STACKS=1024]") print("NUM_STACKS ...
#!/usr/bin/env python # # @copyright Ipdea Land, S.L. # # LGPL v3 - GNU LESSER GENERAL PUBLIC LICENSE # # 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. #...
ee <http://www.gnu.org/licenses/>. # import sys from SOAPpy import WSDL url= 'https://secure.teenvio.com/v4/public/api/soap/wsdl.xml' server = WSDL.Proxy(url) # change to 1 for debug server.soapproxy.config.dumpSOAPOut = 0 server.soapproxy.config.dumpSOAPIn = 0 print print "Check login:" print "--------------" # ...
se: print "Login failed, check data!" sys.exit(0) print login_ok print print "Contacts for group 885:" print "--------------" server.loggin(usuario='user',plan='plan',password='pass') # change this!! contactos=server.getGroupContacts(id_grupo=885) for contacto in contactos : print contacto print print "User...