prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
from . import _ccallback_c import ctypes PyCFuncPtr = ctypes.CFUNCTYPE(ctypes.c_void_p).__bases__[0] ffi = None class CData(object): pass def _import_cffi(): global ffi, CData if ffi is not None: return try: import cffi ffi = cffi.FFI() CData = ffi.CData except...
] if pointer_level > 0: name += " " + "*"*pointer_level return name def _get_ctypes_data(data): # Get voidp pointer return ctypes.cast(data, ctypes.c_void_p).value # # CFFI helpers # def _get_cffi_func(func, signature=None): # Get function point
er func_ptr = ffi.cast('uintptr_t', func) # Get signature if signature is None: signature = ffi.getctype(ffi.typeof(func)).replace('(*)', ' ') return func_ptr, signature def _get_cffi_data(data): # Get pointer return ffi.cast('uintptr_t', data)
#!/usr/bin/env python # coding: utf-8 """ Copyright 2015 SmartBear Software 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 Unle...
""" Swagger model :param dict
swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'status': 'str', 'message': 'str' } self.attribute_map = { ...
# -*- coding: utf-8 -*- appid = 'example' apikey = 'c5dd7e7dkjp27377l903c42c032b413b' sender = '01000000000'
# FIXME - MUST BE CHANGED AS REAL PHONE NUMBER receivers = ['01000000000', ]
# FIXME - MUST BE CHANGED AS REAL PHONE NUMBERS content = u'나는 유리를 먹을 수 있어요. 그래도 아프지 않아요'
## # Copyright 2009-2017 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (F...
lib/spack/spack/build_environment.py#L416 options.append('-DCMAKE_SKIP_RPATH=ON') # show what CMake is doing by default options.append('-DCMAKE_VERBOSE_MAKEFILE=ON') options_string = ' '.join(options) command = "%s cmake %s %s %s" % (self.cfg['preconfigopts'], srcdir, opti...
elf.cfg['configopts']) (out, _) = run_cmd(command, log_all=True, simple=False) return out
# coding=utf-8 from __future__ import unicode_literals """ Name: MyArgparse Author: Andy Liu Email : andy.liu.ud@hotmail.com Created: 3/26/2015 Copyright: All rights reserved. Licence: This program is free software: you can redistribute it and/or modify it under the te...
.org/licenses/>. """ import argparse import logging def parse_command_line(): parser = argparse.ArgumentParser(prog='PROG', description='%(prog)s can ...') parser.add_argument('NoPre', action="store", help='help information') parser.add_argument('-t', action="store_true",
dest='boolean_switch', default=False, help='Set a switch to true') parser.add_argument('-f', action="store_false", dest='boolean_switch', default=True, help='Set a switch to false') parser.add_argument('-s', action="store", dest='simple_value', help="Store a simple value") parser.add_argument('-st', action...
from dj
ango.contrib import admin from trainer.models import Language, Word, Card, Set admin.site.register(Language) admin.site.register(Word) admin.site.register(Card) admin.site.regis
ter(Set)
oint registration or to quit event_first_of( event_healthy, event_stop, ).wait() while True: data_or_stop.wait() if event_stop.is_set(): return # The queue is not empty at this point, so this won't raise Empty. # This task being the only consume...
_max_timeout, ) acknowledged = retry_with_recovery( protocol, data, receiver_address, event_stop, event_healthy, event_unhealthy, backoff, ) i
f acknowledged: queue.get() # Checking the length of the queue does not trigger a # context-switch, so it's safe to assume the length of the queue # won't change under our feet and when a new item will be added the # event will be set again. if no...
# Copyright (C) 2012-2015 ASTRON (Netherlands Institute for Radio Astronomy) # P.O. Box 2, 7990 AA Dwingeloo, The Netherlands # # This file is part of the LOFAR software suite. # The LOFAR software suite is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as p...
her version 3 of the License, or # (at your option) any later version. # # The LOF
AR software suite is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along...
convertPrio(cal.vtodo.priority.value) if hasattr(cal.vtodo, 'priority') else None } fakePOST = QueryDict(mutable=True) fakePOST.update(params) form = SimpleTickets(fakePOST) if form.is_valid(): cd = form.cleaned_data ...
else: tic.customer_id = settings.KEEP_IT_SIMPLE_DEFAULT_CUSTOME if hasattr(settings, 'KEEP_IT_SIMPLE_DEFAULT_COMPONENT') and settings.KEEP_IT_SIMPLE_DEFAULT_COMPONENT: tic.component_id = settings.KEEP_IT_SIMPLE_DEFAULT_COMP...
tic.uuid = cal.vtodo.uid.value tic.save(user=request.user) if tic.assigned: touch_ticket(tic.assigned, tic.pk) for ele in form.changed_data: form.initial[ele] = '' ...
# -*- coding: utf-8 -*- # Copyright 2020 Green Valley Belgium NV # # 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 appl...
om mcfw.properties import bool_property, unicode_list_property, unicode_property, typed_property class BankDataTO(object): bankCode = unicode_property('bankCode') name = unicode_property('name') bic = unicode_property('bic') class OpenIbanResultTO(object): valid = bool_property('valid') messages...
bankData = typed_property('bankData', BankDataTO) # type: BankDataTO checkResults = typed_property('checkResults', dict)
# -*- coding: utf-8 -*- # Copyright(C) 2012 Romain Bignon # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it
under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # weboob is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABI...
icense for more details. # # You should have received a copy of the GNU Affero General Public License # along with weboob. If not, see <http://www.gnu.org/licenses/>. from .module import CmsoModule __all__ = ['CmsoModule']
if self.status == self.INACTIVE: # If these fields have already been changed, don't # override those changes. Don't unset the name field # if no further data is available. if self.name == self.feed_url: self.name = video_iter.title or self.name ...
show it.")) parent = models.ForeignKey( 'self', blank=True, null=True, related_name='child_set', verbose_name='Category Parent', help_text=_("Categories, unlike tags, can have a hierarchy.")) class MPTTMeta: order_insertion_by = ['name'] class Meta: unique_t...
lf): return self.name def dashes(self): """ Returns a string of em dashes equal to the :class:`Category`\ 's level. This is used to indent the category name in the admin templates. """ return mark_safe('&mdash;' * self.level) @models.permalink def g...
from rest_framework import exceptions as drf_exceptions from rest_framework import versioning as drf_versioning from rest_framework.compat import unicode_http_header from rest_framework.utils.mediatypes import _MediaType from api.base import exceptions from api.base import utils from api.base.renderers import Browsabl...
verse(self, viewname, args=None, kwargs=None, request=None, format=None, **extra): url_path_version = self.get_url_path_version(kwargs) major_version = get_major_version(url_path_version) query_parameter_version = self.get_query_param_version(request, major_version) kwargs = {} if (kwar...
rsion': query_parameter_version} if query_parameter_version else None return utils.absolute_reverse( viewname, query_kwargs=query_kwargs, args=args, kwargs=kwargs, )
# -*- coding: utf-8 -*- from module.plugins.internal.XFSAccount import XFSAccount class FilerioCom(XFSAccount): __name__ = "FilerioCom" __type__ = "ac
count" __version__ = "0.07" __status__ = "testing" __description__ = """FileRio.in account plugin""" __license__ = "GP
Lv3" __authors__ = [("zoidberg", "zoidberg@mujmail.cz")] PLUGIN_DOMAIN = "filerio.in"
import pytest from ray.train.callbacks.results_preprocessors import ( ExcludedKeysResultsPreprocessor, IndexedResultsPreprocessor, SequentialResultsPreprocessor, AverageResultsPreprocessor, MaxResultsPreprocessor, WeightedAverageResultsPreprocessor, ) def test_excluded_keys_results_preprocess...
ss(results) assert preprocessed_results == expected def test_weighted_average_results_preprocessor(): from copy import deepcopy import numpy
as np results = [{"a": 1, "b": 2}, {"a": 3, "b": 4}, {"a": 5, "b": 6}, {"a": 7, "b": 8}] expected = deepcopy(results) total_weight = np.sum([result["b"] for result in results]) for res in expected: res.update( { "weight_avg_b(a)": np.sum( [result...
import re from django.core.exceptions import ImproperlyConfigured from sqlalchemy import create_engine, MetaData from sqlalchemy.orm import sessionmaker from tranquil.models import Importer __all__ = ( 'engine', 'meta', 'Session', ) class EngineCache(object): __shared_state = dict( engine = None, meta = None, ...
self.engine = backend.engine else: options = { 'protocol': self._mappings.get( settings.DATABASE_ENGINE ), 'name': settings.DATABASE_NAME, 'user': settings.DATABASE_USER,
'pass': settings.DATABASE_PASSWORD, 'host': settings.DATABASE_HOST, 'port': settings.DATABASE_PORT, } if options['protocol'] is None: raise ImproperlyConfigured( 'Unknown database engine: %s' % settings.DATABASE_ENGINE ) url = '{protocol}://{user}:{pass}@{host}{port}/{name}' for p in option...
""" Tests outgoing calls created with InitialAudio and/or InitialVideo, and exposing the initial contents of incoming calls as values of InitialAudio and InitialVideo """ import operator from servicetest import ( assertContains, assertEquals, assertLength, wrap_channel, EventPattern, call_async, make_channel_...
ath), cs.CHANNEL_TYPE_STREAMED_MEDIA, ['MediaSignalling']) props = chan.Properties.GetAll(cs.CHANNEL_TYPE_STREAMED_MEDIA) assertContains(('InitialAudio', False), props.items()) assertContains(('InitialVideo', False), props.items()) # W
e shouldn't have started a session yet, so there shouldn't be any # session handlers. Strictly speaking, there could be a session handler # with no stream handlers, but... session_handlers = chan.MediaSignalling.GetSessionHandlers() assertLength(0, session_handlers) def check_iav(jt, q, conn, bus, stre...
e('\n'.join(lines).encode('utf-8')) pipeline = TestPipeline() pcoll = pipeline | 'Read' >> ReadFromText( file_name, compression_type=CompressionTypes.BZIP2) assert_that(pcoll, equal_to(lines)) pipeline.run() def test_read_corrupted_bzip2_fails(self): _, lines = write_...
\n'.join(lines).encode('utf-8')) with open(file_name, 'wb') as f: f.write(b'corrupt') pipeline = TestPipeline() pcoll = pipeline | 'Read' >> ReadFromText( fi
le_name, compression_type=CompressionTypes.BZIP2) assert_that(pcoll, equal_to(lines)) with self.assertRaises(Exception): pipeline.run() def test_read_bzip2_concat(self): with TempDir() as tempdir: bzip2_file_name1 = tempdir.create_temp_file() lines = ['a', 'b', 'c'] ...
fro
m django.dispatch import receiver from pretix.base.signals import register_payment_providers
@receiver(register_payment_providers, dispatch_uid="payment_paypal") def register_payment_provider(sender, **kwargs): from .payment import Paypal return Paypal
from django.db import models class AdjacencyListModel(models.Model): title = models.CharField(max_length=100) parent = models.ForeignKey( 'self', related_name='%(class)s_parent', on_delete=models.CASCADE, db_index=True, null=True, blank=True) def __str__(self): return 'adjacencylistmode...
dex=True) level = models.IntegerField(db_index=Tru
e) def __str__(self): return 'nestedsetmodel_%s' % self.title
# -*- coding: utf-8 -*- # Generate
d by Django 1.11.13 on 2019-04-10 03:58 from __future__ import
unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('netdevice', '0006_auto_20190409_0325'), ] operations = [ migrations.RenameField( model_name='vrf', old_name='vrf_name', new_name='name', ...
from functools import reduce class ScopedString (object): def __init__ (self): self._stack = [] def push (self, frame): self._stack.append (frame) def pop (self): frame = self._stack.pop() return frame def __str__ (self...
self._stack.insert (0, {}) def pop (self): if (len (self._stack) <= 1): raise IndexError ("Attempt to pop global scope") tem
p = self._stack[0] del (self._stack[0]) return temp def _normalize (self): normal = {} for frame in self._stack: for key, value in frame.items(): if key not in normal: ...
"""A likelihood function representing a Student-t distribution. Author: Ilias Bilionis Date: 1/21/2013 """ __all__ = ['StudentTLikelihoodFunction'] import numpy as np import scipy import math from . import GaussianLikelihoodFunction class StudentTLikelihoodFunction(GaussianLikelihoodFunction): """An...
Likelihood Function'): """Initialize the object. Arguments: nu --- The degrees of freedom of the dist
ribution. Keyword Arguments num_input --- The number of inputs. Optional, if mean_function is a proper Function. data --- The observed data. A vector. Optional, if mean_funct...
# coding: utf-8 # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # --------------------------------------------------------------------...
eld(name="state", type=SearchFieldDataType.String), ], collection=True) ] cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) scoring_profile = ScoringProfile( name="MyProfile" ) scoring_profiles = [] scoring_profiles.append(scoring_profile) index = Sear...
wait client.create_or_update_index(index=index) # [END update_index_async] async def delete_index(): # [START delete_index_async] name = "hotels" await client.delete_index(name) # [END delete_index_async] async def main(): await create_index() await get_index() await update_index() ...
def RGB01ToHex(rgb): """ Return an RGB color
value as a hex color string. """ return '#%02x%02x%02x' % tuple([int(x * 255) for x in rgb]) def hexToRGB01(hexColor): """ Return a hex color string as an RGB tuple of floats in the range 0..1 """ h = hexColor.lstrip('#') return tuple([x / 255.0 for x in [int(h[i:i + 2], 16) for i in (0, 2...
]])
""" Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this ...
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 languag...
): import params env.set_params(params) # run fs list command to make sure ECS client can talk to ECS backend list_command = format("fs -ls /") if params.security_enabled: Execute(format("{kinit_path_local} -kt {hdfs_user_keytab} {hdfs_principal_name}"), user=params.hdfs_user )...
# Copyright (c) 2008 Mikeal Rogers # # 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...
imitations under the License. from dealer.git import git from django.template import RequestContext requestcontext = None class MakoMiddleware(object): def process_request(self, request): global requestcontext requestcontext = RequestContext(request)
requestcontext['is_secure'] = request.is_secure() requestcontext['site'] = request.get_host() requestcontext['REVISION'] = git.revision
""" Module with functionality for splitting and shuffling datasets. """ import numpy as np from sklearn.utils import murmurhash3_32 from spotlight.interactions import Interactions def _index_or_none(array, shuffle_index): if array is None: return None else: return array[shuffle_index] de...
random_state=random_state) cutoff = int((1.0 - test_percentage) * len(interactions)) train_idx = slice(None, cutoff) test_idx = slice(cutoff, None) train = Interaction
s(interactions.user_ids[train_idx], interactions.item_ids[train_idx], ratings=_index_or_none(interactions.ratings, train_idx), timestamps=_index_or_none(interactions.timestamps, ...
, {'primary_key': 'True'}), 'mep': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['meps.MEP']"}), 'party': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['reps.Party']"}) }, 'meps.delegation': { 'Meta': {'object_name': 'Delegation'}, ...
s.fields.AutoField', [], {'primary_key': 'True'}), 'opinion': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['reps.Opinion']"}), 'representative': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['reps.Representative']"}) }, 'reps.party': { ...
unique': 'True', 'max_length': '255'}) }, 'reps.partyrepresentative': { 'Meta': {'object_name': 'PartyRepresentative'}, 'current': (
# importing libraries: import maya.cmds as cmds import maya.mel as mel # global variables to this module: CLASS_NAME = "Arm" TITLE = "m028_arm" DESCRIPTION = "m029_armDesc" ICON = "/Icons/dp_arm.png" def Arm(dpAutoRigInst): """ This function will create all guides needed to compose an arm. """ # chec...
langName]['e001_GuideNotChecked'] +' - '+ (", ").join(checkResultList) +'
\";')
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-03-28 15:26 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.
Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('genevieve_client', '0003_variant_myvariant_dbsnp'), ] operations = [ migrations.CreateModel( name='OpenHumansUser', fields=[ ('id', models.AutoField(aut...
ize=False, verbose_name='ID')), ('access_token', models.CharField(blank=True, max_length=30)), ('refresh_token', models.CharField(blank=True, max_length=30)), ('token_expiration', models.DateTimeField(null=True)), ('connected_id', models.CharField(max_leng...
from __future__ import print_function, division import sys import os sys.path.append(os.path.abspath(".")) sys.dont_write_bytecode = True from distribution import * import operator as o from utils.lib import gt, lt, gte, lte, neq, eq __author__ = "bigfatnoob" def sample(values, size=100): return np.random.choice(v...
"uniform": Uniform, "random": Random, "exp": Exponential, "binomial": Binomial, "geometric": Geometric, "triangular": Triangular } operations = { "+": o.add, "-": o.sub, "*": o.mul, "/": o.div, "|": max, "&": o.mul, ">": to_int(gt),
"<": to_int(lt), ">=": to_int(gte), "<=": to_int(lte), "==": to_int(eq), "!=": to_int(neq) }
#!/usr/bin/env python """Distutils setup file, used to install or test 'setuptools'""" import textwrap import sys try: import setuptools except ImportError: sys.stderr.write("Distribute 0.7 may only upgrade an existing " "Distribute 0.6 installation") raise SystemExit(1) long_description = textwr...
Topic :: Software Development :: Libraries :: Python Modules Topic :: System :: Archiving :: Packaging Topic :: System :: Systems Administration Topic :: Utilities """).strip().splitlines(), install_requires=[ 'setuptools>=0.7', ], )
if __name__ == '__main__': setuptools.setup(**setup_params)
from django.core.management.base import BaseCommand, CommandError from t
weets.tasks import stream #The class must be named
Command, and subclass BaseCommand class Command(BaseCommand): # Show this when the user types help help = "My twitter stream command" # A command must define handle() def handle(self, *args, **options): stream()
#!/usr/bin/env python # coding=utf-8 """ Created on April 15 2017 @author: yytang """ from scrapy import Selector from libs.misc import get_spider_name_from_domain from libs.polish import polish_title, polish_subtitle, polish_content from novelsCrawler.spiders.novelSpider import NovelSpider class PiaotianSpider(No...
# sel = Selector(response) # content = sel.xpath('//div[@id="content"]/p/text()').extract() # content = polish_content(content) html = str(response.body.decode('GBK')) pattern = r'&nbsp;&nbsp;&nbsp;&nbsp;(.*)' import re m = re.search(pattern, html) if m: ...
p(1) else: content = '' content = content.replace('<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;', '\n\n') return content
a, b = <warning descr="Need more val
ues to unpack">None
</warning>
""" @author: dhoomake
thu """ from __future__ import absolute_import
, unicode_literals
#!/usr/env/bin/ python3 from setuptools import setup, Extension # #CXX_FLAGS = "-O3 -std=gnu++11 -Wall -Wno-comment" # ## List of C/C++ sources that will conform the library #sources = [ # # "andrnx/clib/android.c", # #] setup(name="andrnx", version="0.1", description="Package to convert from GNSS log...
nfo@rokubun.cat', url='https://www.rokubun.cat', packages=['andrnx'], te
st_suite="andrnx.test", scripts=['bin/gnsslogger_to_rnx'])
class DrawingDimensioningWorkbench (Workbench): # Icon generated using by converting linearDimension.svg to xpm format using Gimp Icon = ''' /* XPM */ static char * linearDimension_xpm[] = { "32 32 10 1", " c None", ". c #000000", "+ c #0008FF", "@ c #0009FF", "# c #000AFF", "$ c ...
weldingCommandList = weldingSymbols.weldingCmds self.appendToolbar('Drawing Dimensioning Welding Symbols', weldingCommandList)
self.appendToolbar('Drawing Dimensioning Help', [ 'dd_help' ]) FreeCADGui.addIconPath(iconPath) FreeCADGui.addPreferencePage( os.path.join( __dir__, 'Resources', 'ui', 'drawing_dimensioing_prefs-base.ui'),'Drawing Dimensioning' ) Gui.addWorkbench(DrawingDimensioningWorkbench())
# Copyright (c) 2009-2010 LOGILAB S.A. (Paris, FRANCE). # http://www.logilab.fr/ -- mailto:contact@logilab.fr # # 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, o...
ibuted in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with # this program; if not,...
Boston, MA 02110-1301 USA. from tortoisehg.util import hglib, patchctx from tortoisehg.hgqt.qtlib import geticon, getoverlaidicon from PyQt4.QtCore import * from PyQt4.QtGui import * nullvariant = QVariant() def getSubrepoIcoDict(): 'Return a dictionary mapping each subrepo type to the corresponding icon' ...
"""Maya initialisation for Mindbender pipeline""" from maya import cmds def setup(): assert __import__("pyblish_maya").is_setup(), ( "pyblish-mindbender dep
ends on pyblish_maya which has not " "yet
been setup. Run pyblish_maya.setup()") from pyblish import api api.register_gui("pyblish_lite") from mindbender import api, maya api.install(maya) # Allow time for dependencies (e.g. pyblish-maya) # to be installed first. cmds.evalDeferred(setup)
""":mod:`kinsumer.checkpointer` --- Persisting positions for Kinesis shards ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ import abc import json import os.path from typing import Optional, Dict class Checkpointer(abc.ABC, object): """Checkpointer is the interface for persisting ...
of the last record processed for its shard """ @abc.abstractmethod def checkpoint(self, shard_id: str, sequence: str) -> None: """Persist the sequence number for a given shard""" @abc.abstractmethod def get_checkpoint(self, shard_id: str) -> Optional[str]: "
""Get the sequence number of the last successfully processed record""" class InMemoryCheckpointer(Checkpointer): def __init__(self) -> None: self._checkpoints = {} def get_checkpoints(self) -> Dict[str, str]: return self._checkpoints.copy() def checkpoint(self, shard_id: str, sequence: s...
class ParametrizedError(Exception): def __init__(self, problem, invalid): self.problem = str(problem) self.invalid = str(invalid) def __str__(self): print('--- Error: {0}\n--- Caused by: {1}'.format(self.problem, self.invalid)) class InvalidToken(ParametrizedError): pass class ToneError(Parametri...
class ComposingError(P
arametrizedError): pass
# Copyright 2016 F5 Networks Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
get_status(self, request, mgmt_root): failover_status =
mgmt_root.tm.cm.failover_status assert failover_status._meta_data['uri'].endswith( "/mgmt/tm/cm/failover-status/") failover_status.refresh() des =\ (failover_status.entries['https://localhost/mgmt/tm/cm/failover-status/0'] ['nestedStats'] ['entri...
# third party # third party import numpy as np import pytest # syft absolute # absolute from syft.core.tensor.smpc.share_tensor import ShareTensor @pytest.mark.smpc def test
_bit_extraction() -> None: share = ShareTensor(rank=0, parties_info=[], ring_size=2**32) data = np.array([[21, 32], [-54, 89]], dtype=np.int32) share.child = data exp_res1 = np.array([[False
, False], [True, False]], dtype=np.bool_) res = share.bit_extraction(31).child assert (res == exp_res1).all() exp_res2 = np.array([[True, False], [False, False]], dtype=np.bool_) res = share.bit_extraction(2).child assert (res == exp_res2).all() @pytest.mark.smpc def test_bit_extraction_exceptio...
/Code/AltAnalyze/AltDatabase/EnsMart72/ensembl/Mm/Mm_Ensembl_exon.txt' reference_rows=0 if '.gtf' in refExonCoordinateFile: firstLine = False else: firstLine = True for line in open(refExonCoordinateFile,'rU').xreadlines(): if firstLine: firstLine=False else: line = line.rstr...
elif opt == '--m': ### Run each BAM file on a different processor if arg == 'yes': useMultiProcessing=True elif arg == 'True': useMultiProce
ssing=True else: useMultiProcessing=False else: print "Warning! Command-line argument: %s not recognized. Exiting..." % opt; sys.exit() if len(analysisType) == 0: analysisType = ['exon','junction','reference'] try: refExonCoordi...
#!/usr/bin/env python3 from django.shortcuts import render # Create your views here. from CnbetaApis.datas.Models import * from CnbetaApis.datas.get_letv_json import get_letv_json from CnbetaApis.datas.get_youku_json import get_youku_json from django.views.decorators.csrf import csrf_exempt from django.http import...
ds_arr def get_home_data(request): if not request.method == 'GET': raise HttpResponseNotAllowed('GET') lastID = request.GET.get('lastid') limit = request.GET.get('limit') or 20 session = DBSession() datas = None
if lastID: datas = session.query(Article).order_by(desc(Article.id)).filter(and_(Article.introduction != None, Article.id < lastID)).limit(limit).all() else: datas = session.query(Article).order_by(desc(Article.id)).limit(limit).all() values = [] for data in datas: values.append({...
ET, CONF_DEVICE_ID, CONF_ENTITIES, CONF_NAME, CONF_TRACK, DEVICE_SCHEMA, SERVICE_SCAN_CALENDARS, do_setup, ) from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.helpers.template import DATE_STR_FORMAT from homeassistant.setup import async_setup_component from homeassistant...
AME, "message": event["summary"], "all_day": True, "offset_reached": False, "start_time": week_from_today.strftime(DATE_STR_FORMA
T), "end_time": end_event.strftime(DATE_STR_FORMAT), "location": event["location"], "description": event["description"], } async def test_future_event(hass, mock_next_event): """Test that we can create an event trigger on device.""" one_hour_from_now = dt_util.now() + dt_util.dt.ti...
# Copyright (C) 2012,2013 # Max Planck Institute for Polymer Research # Copyright (C) 2008,2009,2010,2011 # Max-Planck-Institute for Polymer Research & Fraunhofer SCAI # # This file is part of ESPResSo++. # # ESPResSo++ is free software: you can redistribute it and/or modify # it under the terms of t...
pp.__Int3D.x(v, [0) :param v: :param [0: :type v: :type [0: :rtype: .. funct
ion:: espressopp.__Int3D.y(v, [1) :param v: :param [1: :type v: :type [1: :rtype: .. function:: espressopp.__Int3D.z(v, [2) :param v: :param [2: :type v: :type [2: :rtype: .. function:: espressopp.toInt3DFromVector(\*args) :param \*args: :type \*args: .. function:: espressopp.t...
# -*- coding: utf-8 -*- # Copyright (C) Duncan Macleod (2018-2020) # # This file is part of GWpy. # # GWpy 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)...
c.get_paths()) == len(segments) assert ax.get_epoch() == segments[0][0] # test y p = ax.plot_segmentlist(segments).get_paths()[0].get_extents() assert p.y0 + p.height/2. == 1.
p = ax.plot_segmentlist(segments, y=8).get_paths()[0].get_extents() assert p.y0 + p.height/2. == 8. # test kwargs c = ax.plot_segmentlist(segments, label='My segments', rasterized=True) assert c.get_label() == 'My segments' assert c.get_rasterize...
# Copyright (c) 2008 Chris Moyer http://coredumped.org/ # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, ...
R IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. class Qualifications: def __init__(self, requirements=None): if requirements == None: requirements = [] self.requirements = requireme...
self.requirements.append(req) def get_as_params(self): params = {} assert(len(self.requirements) <= 10) for n, req in enumerate(self.requirements): reqparams = req.get_as_params() for rp in reqparams: params['QualificationRequirement.%s.%s' % ((n+1...
# Determine whether an integer is a palindrome. Do this without extra space. class Solution: # @return a boolean def isPalindrome1(self, x): if x < 0 or x % 10 == 0 and x:
return False xhalf = 0 while x > xhalf: xhalf = xhalf * 10 + x % 10 x /= 10 return (x == xhalf or x == xhalf/10 ) def isPalindrome(self, x): if x < 0: return False
size, xreverse = x, 0 while size: xreverse = xreverse * 10 + size % 10 size = (size - (size % 10)) / 10 return True if xreverse==x else False if __name__ == '__main__': s = Solution() print s.isPalindrome1(0)
''' Created on Aug 27, 2013 @author: De
von Define gui events ''' from pyHopeEngine import BaseEvent class Event_ButtonPressed(BaseEvent): '''Sent when a button is pressed''' eventType = "ButtonPressed" def
__init__(self, value): '''Contains a value identifying the button''' self.value = value class Event_ScreenResize(BaseEvent): '''Sent when a screen resize is requestsed''' eventType = "ScreenResize" def __init__(self, width, height): self.width = width self.height = hei...
#!/usr/bin/env python # -*- coding: utf-8 -*- import mysql.connector import time import datetime conn = mysql.connector.connect(host="localhost",user="spike",password="valentine", database="drupal") cann = mysql.connector.connect(host="localhost",user="spike",password="valentine", database="content_delivery_weather")...
at(row[1], row[0])) cursar.execute("""UPDATE new_v4_users_probes_edit SET email = %s WHERE userid = %s""",
(row[1], row[0])) cursar.execute("""SELECT probename, probeid FROM new_v4_sonde""") rows = cursar.fetchall() for row in rows: cursar.execute("""SHOW TABLES LIKE %s""",("%" + row[0] + "%",)) rowsbis = cursar.fetchall() for rowbis in rowsbis: result = rowbis[0].split("_") month = 1 + int(result[4])...
# I made some modifications to termcolor so you can pass HEX colors to # the colored function. It then chooses the nearest xterm 256 color to # that HEX color. This requires some color functions that I have added # in my python path. # # 2015/02/16 # # # coding: utf-8 # Copyright (c) 2008-2011 Volvox Development Team ...
, color) RGB = rgb(color) x256_color_index = from_rgb(RGB[0], RGB[1], RGB[2]) text = "\033[38;5;%dm
%s" % (x256_color_index, text) else: text = fmt_str % (COLORS[color], text) if on_color is not None: if "#" in on_color: on_color = re.sub("[#]", "", on_color) RGB = rgb(on_color) x256_color_index = from_rgb(RGB[0], RGB[1],...
#! /usr/bin/python ''' Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). Find the minimum element. ''' class Solution: # @param num, a list of integer # @return an integer # You may assume no duplicate exists in the array. def fi...
array. def findMinDuplicate(self, num): INT_MIN_VALUE = -(2**32) size = len(num) if size == 0: return INT_MIN_VALUE elif size == 1: return num[0] low_index = 0 high_index = size - 1 while (low_index < high_index - 1): mid_i...
[mid_index] > num[high_index]): low_index = mid_index elif (num[mid_index] < num[high_index]): high_index = mid_index else: high_index -= 1 return min(num[low_index], num[high_index]) if __name__ == '__main__': solution = Solution() ...
import pytest import re import capybara class TestHasSelector: @pytest.fixture(autouse=True) def setup_session(self, session): session.visit("/with_html") def test_is_true_if_the_given_selector_is_on_the_page(self, session): assert session.has_selector("xpath", "//p") assert sess...
test_only_matches_elements_that_match_exactly_when_exact_text_true(self, session): assert session.has_selector("id", "h2one", text="Header Class Test One", exact_text=True) assert not session.has_selector("id", "h2one", text="Header Class Test", ex
act_text=True) def test_matches_substrings_when_exact_text_false(self, session): assert session.has_selector("id", "h2one", text="Header Class Test One", exact_text=False) assert session.has_selector("id", "h2one", text="Header Class Test", exact_text=False) class TestHasNoSelector: @pytest.f...
# # Copyright (C) 2017 Smithsonian Astrophysical Observatory # # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. #...
h this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # """ This is based on sherpa/sim/tests_sim_unit.py. """ from sherpa.astro import sim # This is part of #3
97 # def test_list_samplers(): """Ensure list_samplers returns a list.""" mcmc = sim.MCMC() samplers = mcmc.list_samplers() assert isinstance(samplers, list) assert len(samplers) > 0 def test_list_samplers_contents(): """Are the expected values included""" # Test that the expected value...
from impl import FixedClientDeauthAttack,\ SniffedClientDeauthAttack,\ GlobalDisassociationAttack class WiFiDeauthAttackBuilder(object): '''This object finds the appropriate attack for the options supplied by the user.''' @classmethod def build_from(cls, opt...
ons = self.options.executions persistence_times = self.options.persistence_times return attack.run(exe
cutions, persistence_times) class FixedClientDeauthAttackWrapper(WiFiDeauthAttackWrapper): @classmethod def handles(cls, options): return len(options.client) > 0 def _get_attack_implementor(self): interface = self.options.interface bssid = self.options.bss...
[0], input_ids.shape[-1] - 1) ) outputs_cache = model( input_ids[:, :-1], attention_mask=attention_mask_cache, past_key_values=past_key_values, position_ids=position_ids, ) position_ids = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1...
prepared_inputs_di
ct["attention_mask"][batch_idx, start_index:] = 1 # make sure weights are tied in PyTorch pt_model.tie_weights() with torch.no_grad(): pt_outputs = pt_model(**pt_inputs).to_tuple() fx_outputs = fx_model(**prepared_inputs_dict).to_tup...
from xyz.location import build_location def test_build_location_simple(): # test Location = build_location() location = Location("C
anada", "Charlottetown") assert location.country ==
"Canada" assert location.city == "Charlottetown"
# -*- coding: utf-8 -*- # # =================================================================== # The contents of this file are dedicated to the public domain. To # the extent that dedication to the public domain is not available, # everyone is granted a worldwide, perpetual, royalty-free, # non-exclusive license to e...
can continue updating the object after calling this function. :Return: A byte string of `digest_size` bytes. It may contain non-ASCII charac
ters, including null bytes. """ bfr = create_string_buffer(self.digest_size) result = _raw_sha224_lib.SHA224_digest(self._state.get(), bfr) if result: raise ValueError("Error %d while instantiating SHA224" ...
""" Braces for type definition(class / struct / union / enum) should be located in the seperate line. == Violation == class K() { <== ERROR } struct K { <== ERROR } == Good == struct A() { <== CORRECT } class K() { <== CORRECT public : void Hello...
t ########################################################################## class testRule(nct): def setUpRule(self): ruleManager.AddTypeNameRule(RunRule) def test1(self): self.Analyze("thisfile.c", """ public class A { } """) self.ExpectError(__name__) def test...
ame__) def test3(self): self.Analyze("thisfile.c", """ class K { void function() const { } class T { } } """) self.ExpectSuccess(__name__) def test4(self): self.Analyze("thisfile.c", """ class K { void function() const { } class T { ...
svReader def main(): file_name = "../data/disease/uniprot/humdisease.txt" mim_to_mesh_values = get_mim_to_mesh(file_name) print len(mim_to_mesh) print mim_to_mesh["600807"] return from time import clock parser = UniprotXMLParser("../data/Q12888.xml") #parser = UniprotXMLParser("../../da...
ession": sub_ids.append
(elem.text) if elem.tag == self.NS+"entry": ids.append(sub_ids) sub_ids = [] elem.clear() root.clear() return ids def parse(self): ignored_modification_types = set() context = iterparse(self.file_name, ["sta...
"""Add autoincrement Revision ID: 73b63ad41d3 Revises: 331f2c45f5a Create Date: 2017-07-25 17:09:5
5.204538 """ # revision identifiers, used by Alembic. revision = '73b63ad41d3' down_revision = '331f2c45f5a' from alembic import op from sqlalchemy import Integer import sqlalchemy as sa def upgrade(): op.alter_column("RepositoryApp2languages", "id", existing_type=Integer, autoincrement=True, nullable=False)
def downgrade(): pass
# -*- coding: utf-8 -*- # Copyright 2022 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...
te a client client = certificate_manager_v1.CertificateManagerAsyncClient() # Initialize request argument(s) dns_authorization = certificate_manager_v1.DnsAuthorization() dns_authorization.domain = "domain_value" request = certificate_manager_v1.UpdateDnsAuthorizationRequest( dns_authoriza...
) # Make the request operation = client.update_dns_authorization(request=request) print("Waiting for operation to complete...") response = await operation.result() # Handle the response print(response) # [END certificatemanager_v1_generated_CertificateManager_UpdateDnsAuthorization_async]
#!/usr/bin/env python #---coding=utf8--- from HomeHandler import HomeHandl
er from LoginHandler import LoginHandler from LogoutHandler import LogoutHandler from ArchivesHandler import ArchivesHandler from CategoryHandler import CategoryHandler from TagHandler import TagHandler from PageHandler import PageHandler from SearchHandler import SearchHandler from AdminHome import AdminHome from List...
tegory from ListHtml import ListHtml handlers = [ (r"/", HomeHandler), (r"/login", LoginHandler), (r"/logout",LogoutHandler), (r"/archives/([\d]*)",ArchivesHandler), (r"/category",CategoryHandler), (r"/tag",TagHandler), (r"/page",PageHandler), (r"/search",SearchHandler), (r"/admin/"...
from __future__ import absolute_import from collections import defaultdict from django.db import transaction from django.utils.translation import ugettext as _ from zerver.lib.exceptions import JsonableError from zerver.models import UserProfile, Realm, UserGroupMembership, UserGroup from typing import Dict, Iterable,...
ealm) group_member_ids = get_user_group_members(user_group) msg = _("Only group members and organization administrators can administer this group.") if (not user_profile.is_realm_admin and user_profile.id not in group_member_ids): raise JsonableError(msg) except UserGroup.DoesNot...
user_groups = UserGroup.objects.filter(realm=realm) return list(user_groups) def user_groups_in_realm_serialized(realm: Realm) -> List[Dict[str, Any]]: """This function is used in do_events_register code path so this code should be performant. We need to do 2 database queries because Django's ORM ...
from bing_search_api import BingSearchAPI my_key = "MEL5FOrb1H5G1E78YY8N5mkfcvUK2hNBYsZl1aAEEbE" def query(query_string): b
ing = BingSearchAPI(my_key) params = {'ImageFilters':'"Face:Face"', '$format': 'json', '$top': 10, '$skip': 0} results = bing.search('web',query_string,pa
rams).json() # requests 1.0+ return [result['Url'] for result in results['d']['results'][0]['Web']] if __name__ == "__main__": query_string = "Your Query" print query(query_string)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migr
ations, models class Migration(migrations.Migration): dependencies = [ ('editorial', '0062_auto_20171202_1413'), ] operations = [ migrations.AddField( model_name='assignment', name='complete', field=mode
ls.BooleanField(default=False, help_text=b'Is the assignment complete?'), ), ]
.read_gld_service(gld_bean) return "1" # 置为草稿按钮 @http.route('/WechatGLD/gld_state_draft', type='http', auth="public", csrf=False) def gld_state_draft(self, wechat_gldid, userid): gld_bean = request.env['syt.oa.gld'].sudo().search([('name', '=', wechat_gldid)]) if gld_bean: ...
, type='http', auth="public", csrf=False) def add_approver_service(self, wechat_gldid, employee_id, name, userid): gld_bean = request.env['syt.oa.gld'].sudo().search([('name', '=', wechat_gldid)]) employee = reque
st.env['hr.employee'].sudo().search([('id', '=', int(employee_id))]) request.uid = userid if name == u"添加抄送人": result = request.env['syt.oa.gld.add.peoper.wizard'].sudo(userid).add_copy_peoper_service(gld_bean, ...
#!/usr/bin/env python # ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are ...
yglet.window.xlib import * _have_xlib = True except ImportError: _have_xlib = False # Subclass Window class MyWindow(pyglet.window.Window): if _have_carbon: @CarbonEventHandler(kEventClassWindow, kEventWindowClickDragRgn) def _on_window_click_drag_rgn(self, next_handler, event, data): ...
carbon.CallNextEventHandler(next_handler, event) return noErr if _have_win32: @Win32EventHandler(WM_DISPLAYCHANGE) def _on_window_display_change(self, msg, lParam, wParam): print 'Display resolution changed.' return 0 if _have_xlib: @XlibEv...
e(self, volume): """Create a volume.""" opts = huawei_utils.get_volume_params(volume) smartx_opts = smartx.SmartX().get_smartx_specs_opts(opts) params = huawei_utils.get_lun_params(self.xml_file_path, smartx_opts) pool_name = volume_ut...
wait_interval = huawei_utils.get_wait_interval(self.xml_file_path, event_type) def _volume_ready(): result = self.restclient.get_lun
_info(lun_id) if (result['HEALTHSTATUS'] == constants.STATUS_HEALTH and result['RUNNINGSTATUS'] == constants.STATUS_VOLUME_READY): return True return False huawei_utils.wait_for_condition(self.xml_file_path, _volume_...
></script> <script type="text/javascript" src="source/includes/scripts/genjscript.js"></script> <script type="text/javascript" src="source/includes/scripts/phpjs_00029.js"></script> <script type="text/javascript" src="source/includes/scripts/jquery.jdMenu.js"></script> <script type="text/javascript" s...
size:17px;padding:5px;display:none;"></div> <div id="all"> <div class="members_bar">
<div class="guest_links"> <a onmouseover="loginMenu();" id="loginTab" class="button3" href="#">Log In</a>&nbsp; <a href="signup" class="button3" >Register</a> <div id="loginMenu" class="button5" style="display: none;"> <form action="users.php?act=login-d...
atus_code == 200 def test_reminderState_with_embed_20(self): filter_response = call_ref_url("get", make_booking_filter_url("reminderState=notReminded&embed=eventBooking,seasonBooking")) assert filter_response.status_code == 200 def test_reminderState_with_embed_21(self): filter_response = call_ref_url("get", ...
arted&recordingState=notStarted,inProgress")) assert filter_response.status_code == 200 def test_downloadState_with_recordingContentState_4(self): filter_response = call_ref_url("get", make_booking_filter_url("downloadState=notStarted&recordingContentState=partial")) assert filter_response.status_code == 200 ...
ntentState=complete")) assert filter_response.status_code == 200 def test_downloadState_with_recordingContentState_6(self): filter_response = call_ref_url("get", make_booking_filter_url("downloadState=notStarted&recordingContentState=partial,complete")) assert filter_response.status_code == 200 def test_downl...
tions to export object detection inference graph.""" import logging import os import tensorflow as tf from tensorflow.python import pywrap_tensorflow from tensorflow.python.client import session from tensorflow.python.framework import graph_util from tensorflow.python.framework import importer from tensorflow.python.pl...
'num_detections,detection_scores,' 'detection_boxes,detection_classes')): """Writes inference graph to disk with the option to bake in weights. If checkpoint_path is not None bakes the weights into the graph thereby eliminating the need of checkpoint file...
averages to true restores the moving averages, otherwise the original set of variables is restored. Args: inference_graph_path: Path to write inference graph. checkpoint_path: Optional path to the checkpoint file. use_moving_averages: Whether to export the original or the moving averages of the...
import os import glob ##################################################### ######Init the files################################## ##################################################### os.remove("a0.txt") os.remove("a1.txt") os.remove("a2.txt") os.remove("a3.txt") os.remove("a4.txt") os.remove("a5.txt") os.remove("a6...
e = open(f,"r+") normal_words.extend([e.read().split()]) e.close()
for f in the_vali_files: e = open(f,"r+") vali_words.extend([e.read().split()]) e.close() files_a = len(attack_words)/10 files_n = len(normal_words)/10 files_v = len(vali_words)/10 print("Normal Words: " + str(len(normal_words))) print("Average normal words per formatted file: " + str(files_n)) print("A...
import random from django.dispatch import receiver from django.conf import settings from readthedocs.restapi.signals import footer_response from readthedocs.donate.models import SupporterPromo from readthedocs.donate.constants import INCLUDE, EXCLUDE from readthedocs.donate.utils import offer_promo PROMO_GEO_PATH =...
ramming_language=project.programming_language, gold_project=gold_project, gold_user=gold_user, ) # If we don't have anything to show, don't show it. if not promo_obj: show_promo = False if show_promo: promo_dict = offer_promo(promo_obj=promo_obj, project=pro...
eturn JSON resp_data['promo'] = show_promo
"""Device tracker support for OPNSense routers.""" from homeassistant.components.device_tracker import DeviceScanner from . import CONF_TRACKER_INTERFACE, OPNSENSE_DATA async def async_get_scanner(hass, config, discovery_info=None): """Configure the OPNSense device_tracker.""" interface_client = hass.data[OP...
ces and return a list with found device IDs.""" self.update_info() return list(self.last_results) def
get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if device not in self.last_results: return None hostname = self.last_results[device].get("hostname") or None return hostname def update_info(self): """Ensure the in...
#!/usr/bin/env python # Convert line elements with overlapping endpoints into polylines in an # SVG file. import os import sys try: from lxml import etree except ImportError: import xml.etree.ElementTree as etree from collections import defaultdict from optparse import OptionParser SVG_NS = 'http://www.w...
return 2 infile = args[0] outfile = args[1] svg = parse_svg(infile) polylines = optimize(svg) print '%s polyline(s) found in total' % len(polylines) write_svg(polylines, out
file) print_size_stats(infile, outfile) return 0 if __name__ == '__main__': try: sys.exit(main()) except KeyboardInterrupt: sys.exit(1)
lock: raise EmptyPoolError( self, "Pool reached maximum size and no more connections are allowed.", ) pass # Oh well, we'll create a new connection then # If this is a persistent connection, check if it got disconnected ...
# Python 2.7, use buffering of HTTP responses httplib_response = conn.getresponse(buffering=True) except TypeError: # Python 3 try: httplib_response = conn.getresponse()
except BaseException as e: # Remove the TypeError from the exception chain in # Python 3 (including for exceptions like SystemExit). # Otherwise it looks like a bug in the code. six.raise_from(e, None) except (SocketTim...
import os import sys here = os.path.
abspath(os.path.split(__file__)[0]) sys.path.insert(0, os.path.join(here, os.pardir, os.pardir, os.pardir)) import localpaths a
s _localpaths # noqa: F401
import sys import time import json import logging import random import tornado.options from tornado.options import define, options from tornado import gen define('srp_root',default='http://192.168.56.1') #define('srp_root',default='https://remote-staging.utorrent.com') #define('srp_root',default='https://remote.utorre...
t=False) tasks.append( gen.Task( httpclient.fetch, request ) ) while tasks: some_tasks = [tasks.pop() for _ in range(5)] logging.info('executing tasks of len %s' % len(some_tasks)) responses = yield gen.Multi( some_tasks ) logging.info('responses %s' % [(r.code, len(...
se: tasks = [] for hash, torrent in client.torrents.items(): if torrent.get('progress') == 1000: link = torrent.webseed_link() print torrent.get('name'), torrent.get('progress'), link request = tornado.httpclient.HTTPRequest(link, ...
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2010 Benny Malengier # Copyright (C) 2011 Tim G L Lyons # # 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 in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even
the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor,...
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
ute test pipeline and verify results. """ # Protect against environments where dataflow runner is not available. # pylint: disable=wrong-import-order, wrong-import-position from __future__ import absolute_import try: from apache_beam.runners.dataflow.test_dataflow_runner import TestDataflowRunner from apache_beam...
ImportError: pass # pylint: enable=wrong-import-order, wrong-import-position
# Copyright (c) 2020, Manfred Moitzi # License: MIT License import sys import time from datetime import datetime from pathlib import Path from ezdxf.acc import USE_C_EXT from ezdxf.render.forms import ellipse if USE_C_EXT is False: print("C-extension disabled or not available.") sys.exit(1) from ezdxf.math._...
d Cython implementations:") profile( f"detect {RUNS}x clockwise orientation of {len(ellipse_vertices)} vertices:", "c2d_has_clockwise_orientation", profile_py_has_clockwise_orientation, profile_cy_has_clockwise_orientation, ellipse_vertices, RUNS, ) profile( f"detect {RUNS}x real 2D line int...
UNS}x no 2D line intersections:", "c2d_no_intersection_line_line_2d", profile_py_no_intersection_line_line_2d, profile_cy_no_intersection_line_line_2d, RUNS, )
from pylab import * from scipy.io import loadmat, savemat import time import dicom Rel = 4.5 # assumed Relaxivity of Gd-DTPA at 3 T [s^-1 [mmol Gd-DTPA]^{-1}] flip_angle = 30 * pi / 180.0 # rad TR = 5e-3 # sec nx = 80 ny = 50 nt = 1321 noise_sigma = 0.2 random_seed = 1337 seed(random_seed) dx = 1 deltat = 1 data...
speed up the run data_dce = data_dce[::deltat,:,:] data_aif = data_aif[::deltat] # TODO: do this better t = t[::deltat] nt = len(t) # ## 2. Derive the AIF ## # turn Sb into Cp print 'co
nverting plasma ROI to AIF' def dce_to_r1eff(S, S0, R1, TR, flip): S = S.T S0 = S0.T A = S.copy() / S0 # normalize by pre-contrast signal E0 = exp(-R1 * TR) E = (1.0 - A + A*E0 - E0*cos(flip)) /\ (1.0 - A*cos(flip) + A*E0*cos(flip) - E0*cos(flip)) R = (-1.0 / TR) * log(E) return R.T def r1eff_to_conc...
# Copyright (C) 2015 – 2021 Noa-Emil Nissinen (4shadoww) from core.hakkuframework import *
from core import getpath import http.client import socket conf = { "name": "apache_users", # Module's name (should be same as file's name) "version": "1.1", # Module version "shortde
sc": "scan directory of apache users", # Short description "github": "4shadoww", # Author's github "author": "4shadoww", # Author "email": "4shadoww0@gmail.com", "initdate": "2016-03-01", "lastmod": "2021-07-11", "apisupport": True } # List of the variables variables = OrderedDict(( ("targe...
from __futur
e__ import unicode_literals from django.apps import AppConfig class MergeserverConfig(AppConfig): name = 'Mer
geServer'
## # Copyright 2009-2013 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en), # the Hercules foundation (htt...
neric.packedbinary import PackedBinary class EB_FastQC(PackedBinary): """Easyblock implementing the build step for
FastQC, this is just give execution permission to the `fastqc` binary before installing. """ def install_step(self): """Overwrite install_step from PackedBinary""" os.chdir(self.builddir) os.chmod("FastQC/fastqc", os.stat("FastQC/fastqc").st_mode | stat.S_IXUSR | stat.S_IXGRP | stat...
# -*- coding: utf-8 -*- """ plotting.py Part of douglib. Used for general data plotting. Created on Tue June 06 08:44:12 2014 @author: dthor """ # -------------------------------------------------------------
-------------- ### Imports # --------------------------------------------------------------------------- # Standard Library # Third-Party import matplotlib.pyplot as pyplot # Package / Application from .core import rc_to_radius def radius_plot(rcd_list, die_xy, center_rc): """ Plots up data by ra...
rcd_list: x_data.append(rc_to_radius((rcd[0], rcd[1]), die_xy, center_rc)) y_data.append(rcd[2]) pyplot.figure() pyplot.plot(x_data, y_data, 'bo') pyplot.xlabel("Radius") pyplot.ylabel("Value") pyplot.show() def main(): """ Runs only when module is called dir...
#!/usr/bin/env python # ********************************************************************** # # Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved. # # This copy of Ice is licensed to you under the terms described in the # ICE_LICENSE file included in this distribution. # # *************************************...
n(sys.argv) > 1: command += sys.argv[1:] p = subprocess.Popen(command, shell = False, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.STDOUT, bufsize = 0) def signal_handler(signal, frame): if p: p.terminate() sys.exit(0) signal.signal(signal.SIGINT, sig...
gnal.SIGTERM, signal_handler) if TestUtil.isDarwin(): # # On OS X, we set the trust settings on the certificate to prevent # the Web browsers from prompting the user about the unstrusted # certificate. Some browsers such as Chrome don't provide the # option to set this trust settings. # ser...
None): self._dict = {} self._contained_type = contained_type self._container = container if container is not None else self def __eq__(self, other): try: return ( # quick check for comparing, e.g., XigtCorpus and Igt self._contained_type =...
except AttributeError: return False def __getitem__(self, obj_id): if isinstance(obj_id, (int, slice)): return list.__getitem__(self, obj_id) elif obj_id in self._dict: return self._dict[obj_id] else: try: return list.__getite...
ict keys (IDs) # NOTE: this method is destructive. check for broken refs here? self._assert_type(obj) try: cur_obj = list.__getitem__(self, idx) except TypeError: idx = int(idx) cur_obj = list.__getitem__(self, idx) if cur_obj.id is not None: ...
""" def dist(m, i, j, what = lambda m: m.decisions): "Euclidean distance 0 <= d <= 1 between decisions" n = len(i.cells) deltas = 0 for c in what(m): n1 = norm(m, c, i.cells[c]) n2 = norm(m, c, j.cells[c]) inc = (n1 - n2) ** 2 deltas += inc n += abs(m.w[c]) return deltas ** 0.5 ...
prune = False, wriggle = 0.3) return The def _where(m = nasa93): m = m() see
d(1) told = N() for r in m._rows: s = scores(m, r) told += s g
# Exercise 16: Reading and Writing Files from sys import argv script, filename = argv print "We're going to erase %r." % filename print "If you don't want that, hit CTRL-C (^C)." print "If you do want that, hit RETURN." raw_input("?") print "Opening
the file..." target = open(filename, 'w') print "Truncating the file. Goodbye!" target.truncate() print "Now I'm going to ask you for three lines." line1 = raw_input("line 1: ") line2 = raw_input("line 2: ") line3 = raw_input("
line 3: ") print "I'm going to write these to the file." target.write(line1) target.write("\n") target.write(line2) target.write("\n") target.write(line3) target.write("\n") print "And finally, we close it." target.close() # $ python ex16.py test.txt
import unittest class StringProcessingTestBase(unittest.TestCase): # The backslash character. Needed since there are limitations when # using backslashes at the end of raw-strings in front of the # terminating " or '. bs = "\\" # Basic test strings all StringProcessing functions should test. ...
})) def assertResultsEqualEx(self, func, invocation_and_results, postprocess=lambda result: result):
""" Tests each given invocation against the given results with the specified function. This is an extended version of ``assertResultsEqual()`` that supports also ``**kwargs``. :param func: The function to test. :param invocation_and_results: A dict con...
# -*- coding: utf-8 -*- import os import KBEngine from KBEDebug import * def onBaseAppReady(isBootstrap): """ KBEngine method. baseapp已经准备好了 @param isBootstrap: 是否为第一个启动的baseapp @type isBootstrap: BOOL """ INFO_MSG('onBaseAppReady: isBootstrap=%s, appID=%s, bootstrapGroupIndex=%s, bootstrapGlobalIndex=%s' % \ ...
tdown了,脚本是否准备好了? 如果返回True,则进程会进入shutdown的流程,其它值会使得进程在过一段时间后再次询问。 用户可以在收到消息时进行脚本层的数据清理工作,以让脚本层的工作成果不会因为shutdown而丢失。 """ INFO_MSG('onReadyForShutDown()') return True def onBaseAppShutDown(state): """ KBEngine method. 这个baseapp被关闭前的回调函数 @param state: 0 : 在断开所有客户端之前 1 : 在将所有entity写入数据库之前 2 : 所有entity被...
KBEngine method. 当引擎启动后初始化完所有的脚本后这个接口被调用 @param isReload: 是否是被重写加载脚本后触发的 @type isReload: bool """ INFO_MSG('onInit::isReload:%s' % isReload) def onFini(): """ KBEngine method. 引擎正式关闭 """ INFO_MSG('onFini()') def onCellAppDeath(addr): """ KBEngine method. 某个cellapp死亡 """ WARNING_MSG('onCellAppDeath: %...
''' This module controls the dialog to set filter criteria ''' from PyQt5 import QtCore, Qt, QtWidgets from views.filter_dialog import Ui_FilterDialog class FilterGamesController(QtWidgets.QDialog): ''' Controller object for the filter games dialog. ''' def __init__(self, table, parent=None): ...
nnect(self.cancel_clicked) def
ok_clicked(self): ''' Callback for when the user clicks the 'ok' button. The dialog is closed and the parent is informed by means of an attribute that the changes have to take effect ''' self.canceled = False self.hide() def cancel_clicked(self): ''' ...
from interface.design.ui_screen import Ui_wnd_gifextract from PyQt5 import QtWidgets import sys import listener import config import ffmpeg import queue import interface.menus.Frame_CreateGif import interface.menus.Frame_ExtractFrames import interface.menus.Frame_Queue class Screen(QtWidgets.QMainWindow): def ...
bs() setupFFMpeg() setupQueue() def createLinks(self): self.ui.actionPrefe
rences.triggered.connect(self.openOptions) def openOptions(self): import interface.menus.ConfigMenu options = interface.menus.ConfigMenu.ConfigMenu(self, self.config) options.show() if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) program = Screen() pro...
# # Copyright 2007 Zuza Software Foundation # # This file is part of translate. # # translate 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 ve...
self.extraction_msg = None self.output_file = output_file self.source_store = self.SourceStoreClass(input_file) self.target_store = self.TargetStoreClass() self.template_store = None if template_file is not None: self.template_store = self.
SourceStoreClass(template_file) def convert_unit(self, unit): """Convert a source format unit to a target format unit.""" target_unit = self.TargetUnitClass(encoding="UTF-8") target_unit.addlocation("".join(unit.getlocations())) target_unit.addnote(unit.getnotes("developer"), "devel...