prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
{ 'name': "Blockchain Waves Synchro", 'version': '1.0', 'depends': ['base', 'sale',
'sales_team', 'delivery', 'barcodes', 'mail', 'report', 'portal_sale', 'website_portal', 'website_payment',], 'author': "Sergey Stepanets", 'category': 'Application', 'description': """ ...
ta': [ 'views/setting.xml', 'data/cron.xml', 'views/clients.xml', 'views/sale_order.xml', 'views/journal_signature.xml', # 'views/report.xml', ], }
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-01-13 20:45 from __future__ import unicode_literals from django.db import migr
ations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('kriegspiel', '0003_auto_20170113_2035'), ] operations = [ migrations.AddField( model_name='move', name='created_at', field=models.DateTimeField(defaul...
# Copyright (c) 2017-presen
t, Facebook, Inc. # All Rights Reserved. # # This software may be used and distributed according to the terms of the # GNU General Public License version 2. from __future__ import absolute_import, division, print_function, unicode_
literals import pkgutil # Indicate that hgext3rd is a namspace package, and other python path # directories may still be searched for hgext3rd extensions. __path__ = pkgutil.extend_path(__path__, __name__) # type: ignore # noqa: F821
cat_probs_value = _swap_first_last_axes(cat_probs_value) # Add a new innermost dimension for broadcasting to mvn vector shape cat_probs_value = [np.e
xpand_dims(c_p, -1) for c_p in cat_probs_value] true_mean = sum( [c_p * m for (c_p, m) in zip(cat_probs_value, dist_means_value)]) self.assertAllClose(true_mean, mean_value) def testPr
obScalarUnivariate(self): with self.test_session() as sess: dist = make_univariate_mixture(batch_shape=[], num_components=2) for x in [ np.array( [1.0, 2.0], dtype=np.float32), np.array( 1.0, dtype=np.float32), np.random.randn(3, 4).astype(np.float32) ...
__author__ = 'Dominic Miglar <dominic.miglar@bitmovin.net>' import unittest import bitcodin from bitcodin.test.bitcodin_test_case impo
rt BitcodinTestCase from bitcodin.rest import RestClient class GetStatisticsCurrentMonthTestCase(BitcodinTestCase): def setUp(self): super(GetStatisticsCurrentMonthTestCase, self).setUp() def runTest(self): r
esponse = RestClient.get(url=bitcodin.get_api_base()+'/statistics', headers=bitcodin.create_headers()) def tearDown(self): super(GetStatisticsCurrentMonthTestCase, self).tearDown() if __name__ == '__main__': unittest.main()
le=protected-access redirect_field_name=auth.REDIRECT_FIELD_NAME )
) # Set the cookie and try again self.set_logged_in_cookies(request) self.assert_redirect_to_dashboard_looks_correct( actions.do_complete(request.backend, social_views._do_login, user=user)) self.assert_account_settings_context_looks_correct(accoun
t_settings_context(request)) def test_signin_fails_if_account_not_active(self): _, strategy = self.get_request_and_strategy( auth_entry=pipeline.AUTH_ENTRY_LOGIN, redirect_uri='social:complete') strategy.request.backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete...
#!/usr/bin/env #(C) Mugfoundation 2014 #Available under MIT license import click import hashlib c = hashlib.sha512() @click.command() @click.option('--setup', 'setup', help='Setup new project', type=str) @click.option('-x', '--major', 'major', help='major version setter', type=int) @click.option('-y', '--minor', 'min...
type=str) @click.option('-sr',
'--sign', 'sign', help='sign the release using open pgp (available only on linux)', type=str) def main():
if _event == self.peerQueueEvent["ping_peers"]: query(_p["address"], _p["port"], "*", self.logger) # Need to add all self.peerQueueEvent items here ''' Data Propagation Request ''' if _event == s...
ata) < 3: return("_INVALID_DATA_CHUNK_") # Ensure that we don't repeat ourselves if original_data in self.propagated: self.logger.info("Handler got request to propagate previously propageted data") return("_PREVIOUSLY_PROPAGETED_") ''' Inform...
(IP) - Broadcast received ''' if data[0] == "broadcast": ''' IP.0 ''' if data[1] == "new_client": # Ensure there isn't anything silly with \n happening ensured = ''.join(data[2:]) try: ...
lf._accepted = True # validate using schema if not self._validate_with_schema(message): # Some errors return invalid xml. self.logger.error("Message doesn't follow schema.") self._accepted = False # raise ValueError('Failed to validate against schema') ...
f element.tag == "{http://bxd.fi/xmldata/}Cust
omerExtension": self.logger.debug("{0}: {1}".format(element.tag, element.text)) self._customerextension = element if element.tag == "{http://bxd.fi/xmldata/}FileDescriptors": descriptors = element if element.tag == "{http://bxd.fi/xmldata/}FileType...
#!/usr/bin/env python # ********************************************************************** # # Copyright (c) 2003-2011 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. # # **************
******************************************************** import os, sys, traceback import Ice, AllTests def test(b): if not b: raise RuntimeError('test assertion failed') def usage(n): sys.stderr.write("Usage: " + n + " port...\n") def run(args, communicator): ports = [] for arg in args[1:]...
+ "'\n") usage(args[0]) return False ports.append(int(arg)) if len(ports) == 0: sys.stderr.write(args[0] + ": no ports specified\n") usage(args[0]) return False try: AllTests.allTests(communicator, ports) except: traceback.print_exc(...
input_name = '../examples/linear_elasticity/l
inear_viscoelastic.py' output_name_trunk = 'test_linear_viscoelastic' from tests_basic import TestInputEvolutionary class Test(TestInputEvolutionary):
pass
#!/usr/bin/env python3 """ Item Related Objects. """ #-*- coding: utf-8 -*- import re from datetime import datetime from db_related import DBConnect class Item_Lookup(object): """ Returned Item Lookup Dictionary Structure: item = { upc: text description: text ...
WHERE upc=(?)''' data = [self.upc,] returnd = DBConnect
(query, data).ALL()
# coding: utf-8 import sys from collections import defaultdict sys.path.append('/project/nakamura-lab01/Work/yusuke-o/python') from data.reader import dlmread def addfeature(fs, fid, name, mode): if mode == 'dev' or name in fid: fs.append(fid[name]) def main(): if len(sys.argv) != 6: print('USAGE: python3 mak...
us_in_pos)): data = [['<s>', '<s>']] * 2 + corpus_in_pos[i] + [['</s>', '</s>']] * 2 for j in range(len(data)-5): # ignore end of sentence jj = j+2 features = [] # unigram words # addfeature(features, fid, 'WORD[-2]=%s' % data[jj-2][0],
mode) addfeature(features, fid, 'WORD[-1]=%s' % data[jj-1][0], mode) addfeature(features, fid, 'WORD[0]=%s' % data[jj+0][0], mode) addfeature(features, fid, 'WORD[+1]=%s' % data[jj+1][0], mode) addfeature(features, fid, 'WORD[+2]=%s' % data[jj+2][0], mode) # unigram POSes # addfeature(features, ...
code, possibly JSON) and these are the only types with encoding handlers defined. There's no need to return the exact way the field was instantiated this time, just ensure that the resulting field is the same - prefer keyword arguments over positional ones, and omit parameters with thei...
e): """ Convert the value's type and run validation. Validation errors from to_python and validate are propagated. The correct value is returned if no error is rai
sed. """ value = self.to_python(value) self.validate(value, model_instanc
dle, new_bundle2) assert_raises(ValueError, StreamlineLinearRegistration, method='Whatever') def test_rigid_partial_real_bundles(): static = fornix_streamlines()[:20] moving = fornix_streamlines()[20:40] static_center, shift = center_streamlines(static) moving_center, shift2 = center_streamlines...
static = fornix_streamlines()[:20] moving = fornix_streamlines()[:20] moving = [m + np.array([10., 0., 0.]) for m in moving] slr = StreamlineLinearRegistration(evolution=True) from dipy.core.optimize import SCIPY_LESS_0_12 if not SCIPY_LESS_0_12: slm = slr.optimize(static, moving) ...
import torch def rmsprop(opfunc, x, config, state=None): """ An implementation of RMSprop ARGS: - 'opfunc' : a function that takes a single input (X), the point of a evaluation, and returns f(X) and df/dX - 'x' : the initial point - 'config` : a table with configura
tion parameters for the optimizer - 'config['learningRate']' : learning rate - 'config['alpha']' : smoothing constant - 'config['epsilon']' : value with which to initialise m - 'config['weightDecay']' : weight decay - 'state' : a table describing t...
squares of parameter gradients, - 'state['tmp']' : and the square root (with epsilon smoothing) RETURN: - `x` : the new x vector - `f(x)` : the function, evaluated before the update """ # (0) get/update state if config is None and state is None: raise ValueError...
f
rom .nuimo import
ControllerManager, ControllerManagerListener, Controller, ControllerListener, GestureEvent, Gesture, LedMatrix
# -*- coding: utf-8 -*- from django.shortcuts import render from django.http import HttpResponsePermanentRedirect, Http404, HttpResponseRedirect from django.views.decorators.http import require_GET from django.contrib.auth import login, authenticate from django.core.urlresolvers import reverse_lazy from django.contrib...
r of a queryset with users Url's. """ url_li
st = Url.objects.filter(user=user) paginator = Paginator(url_list, limit) try: url_list = paginator.page(page) except PageNotAnInteger: url_list = paginator.page(1) except EmptyPage: url_list = paginator.page(paginator.num_pages) return url_list def index(request): """ ...
# -*- coding: utf-8 -*- # Copyright (C) 2014 Universidade de Aveiro, DETI/IEETA, Bioinformatics Group - http://bioinformatics.ua.pt/ # # 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 vers...
ect_or_404 import sys from searchengine.models import * r
em = 1 qu = get_object_or_404(Questionnaire, id=rem) qsets = qu.questionsets() for qs in qsets: expected = qs.questions() for q in expected: slugs = Slugs.objects.filter(description__exact=q.text) if len(slugs)!=1: print "Error (multiple slugs to the description): " + q.number...
# Copyright 2012 NetApp # Copyright 2015 Chuck Fouts # All Ri
ghts 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 appl
icable 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 limitations # under the License. import sys impor...
# Generated by Django 1.11.13 on 2018-08-14 17:35 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): replaces = [ ("user", "0001_initial"), ("user", "0002_rename_account_tables"), ("user", "0003...
blank=True, max_length=254, verbose_name="email address", ), ), ( "is_staff", models.BooleanField( default=False, help_te...
status", ), ), ( "is_active", models.BooleanField( default=True, help_text="Designates whether this user should be treated as active. Unselect this instead of deleting accounts.",...
self.motherTongue = motherTongue # spell check rules are disabled by default self.disabled = {'HUNSPELL_RULE', 'HUNSPELL_NO_SUGGEST_RULE', 'YOUR_NN', 'TRY_AND', 'PRP_PAST_PART', 'MORFOLOGIK_RULE_' + self.language.replace('-', '_').upper()} self.enabled = set() self._i...
ServerError: if cls._MIN_PORT <= cls._port < cls._MAX_PORT: cls._port += 1 else: raise @classmethod def _start_server(cls): err = None try: serv
er_cmd = get_server_cmd(cls._port) except PathError as e: # Can't find path to LanguageTool. err = e else: # Need to PIPE all handles: http://bugs.python.org/issue3905 cls._server = subprocess.Popen( server_cmd, stdin=subpro...
def extractDanielyangNinja(item): ''' Parser for 'danielyang.ninja' ''' vol, chp, frag, postfix = extractVolChapterFragmentPo
stfix(item['title']) if n
ot (chp or vol) or "preview" in item['title'].lower(): return None if "WATTT" in item['tags']: return buildReleaseMessageWithType(item, "WATTT", vol, chp, frag=frag, postfix=postfix) return False
#!/usr/bin/env python # coding=utf-8 """30. Digit fifth powers https://projecteuler.net/pr
oblem=30 Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: > 1634 = 14 \+ 64 \+ 34 \+ 44 > 8208 = 84 \+ 24 \+ 04 \+ 84 > 9474 = 94 \+ 44 \+ 74 \+ 44 As 1 = 1
4 is not a sum it is not included. The sum of these numbers is 1634 + 8208 + 9474 = 19316. Find the sum of all the numbers that can be written as the sum of fifth powers of their digits. """
import unittest """ Given an unordered array of integers, find the length of longest increasing subsequence. Input: 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 Output: 6 (0, 2, 6, 9, 11, 15) """ """ A great explanation of
the approach appears here: http://www.geeksforgeeks.org/longest-monotonically-increasing-subsequence-size-n-log-n/ """ def find_ceil_index(list_of_numbers, ele): """ Returns the smallest element in list_of_numbers greater than or equal to ele
. """ low = 0 high = len(list_of_numbers)-1 ans = -1 while low <= high: mid = (low + high) / 2 if list_of_numbers[mid] >= ele: ans = mid high = mid - 1 else: low = mid + 1 return ans def find_longest_increasing_subsequence_length(li...
stance(dq1, _trep._Config) assert isinstance(q2, _trep._Config) return self._L_ddqdq(dq1, q2) def L_ddqdqdq(self, dq1, q2, q3): """ Calculate the third derivative of the Lagrangian with respect to the velocity of dq1, the value of q2, and the value of q3. """ ...
ics_indexing_deco
rator('duu') def f_dudu(self, q=None, u1=None, u2=None): self._update_cache(_trep.SYSTEM_CACHE_DYNAMICS_DERIV2) return self._f_dudu[u1, u2, q].copy() @dynamics_indexing_decorator('c') def lambda_(self, constraint=None): """ Calculate the constraint forces at the current sta...
__all__ = ( 'TokenList', ) import collections from .errors import TokenTypeError class TokenList(collections.Sized, collections.Iterable, collections.Container): def __init__(self, init=None, *, token_type=None): if token_type is None: token_type = object self._token_type = token_...
turn self._tokens.popleft() def remove(self, token): for c, t in enumerate(self._tokens): if t is token: break else: return del self._tokens[c] #self._tokens.remove(token)
def copy(self): return self.__class__(init=self, token_type=self.token_type) def __iter__(self): yield from self._tokens def __len__(self): return len(self._tokens) def clear(self): self._tokens.clear() def extend(self, values): if self._t...
addresses_args={"uselist": False}) assert_raises_message( exc.InvalidRequestError, "On relationship User.addresses, 'dynamic' loaders cannot be " "used with many-to-one/one-to-one relationships and/or " "uselist=False.", c...
1) def test_transient_access(self): User, Address = self._user_address_fixture() u1 = User() u1.addresses.append(Address())
eq_(u1.addresses[0], Address()) def test_custom_query(self): class MyQuery(Query): pass User, Address = self._user_address_fixture( addresses_args={"query_class": MyQuery}) sess = create_session() u = User() sess.add(u) ...
settings import json import os import re import nltk from nltk.corpus import * from nltk.collocations import * import string import logging logger = logging.getLogger('nltksite.nltkapp') # Create your views here. # this is horrible def clearencoding(str): try: json.dumps(str) if len(str) == 1 and ord(str) > 128:...
l', context) def sayhello(request): logger.debug("say hello.") return JsonResponse({'message': 'Hello World'}) def getdocuments(request): corpus_id = request.GET.get('corpus_id', None) c = Corpus.objects.get(pk=corpus_id) logger.debug("Getting list of documents for corpus %s (id=%s)" % (c.name,corpus_i
d)) documents = c.document_set.all() documents_list = [] for d in documents: documents_list.append({'id': d.id, 'name': d.file.name}) return JsonResponse({'documents': documents_list}) def get_sentences(request): corpus_id = request.GET.get('corpus_id', None) document_ids = json.loads(request.GET.get('document...
# 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...
nse is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. class ReferenceContribution: def __init__(self,src,dest,me,cont): self.theSource = src ...
eDestination = dest self.theMeansEnd = me self.theContribution = cont def source(self): return self.theSource def destination(self): return self.theDestination def meansEnd(self): return self.theMeansEnd def contribution(self): return self.theContribution
{"lv": {"containingPool": fake_pool_name, "lunIndex": fake_aoetarget, "name": fake_volume_name, "lvStatus": {"exportedLun": {"lun": fake_lun, "shelf": fake_shelf}} }, "repoName": fake_...
"tracking": False, "configState": "completedSuccessfully", "heldPending": False, "metaCROp": "noAction", "message": None} fake_group_fullpath = "admin group:%s" % (fake_esm_group) fake_group_id = 4 fake_login_reply = {"values": [ ...
"groupId": fake_group_id}], "message": "", "state": "adminSucceed", "metaCROp": "noAction"} fake_group_fail_fullpath = "fail group:%s" % (fake_esm_group) fake_group_fail_id = 5 fake_login_reply_group_fail = {"values": [ ...
# -*- coding: utf-8 -*- # Copyright (c) 2010-2017 Tuukka Turto # # 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,...
def __show_menu(self): """ Show menu """ menu_dialog = MenuDialog(self.surface_manager, self.application.world.player,
self.application.action_factory, self.application.config.controls, self, Qt.Dialog | Qt.CustomizeWindowHint) menu_dialog.exec_() def __show_end_screen(self): """ ...
': 'Oland\xc5\xb3', 'lv_LV': 'Latvi\xc5\xb3', 'el_GR': 'Graik\xc5\xb3', 'pt_BR_BR': 'Brazilian Portuguese', 'hu_HU': 'Vengr\xc5\xb3', 'lt_LT': 'Lietuvi\xc5\xb3', 'sl_SI': 'Slov\xc4\x97n\xc5\xb3', 'hr_HR': 'Kroat\xc5\xb3', 'en_EN': '...
'da_DK': 'Danese', 'ar_AE': 'Arabo', 'sk_SK': 'Slovacco', 'de_DE': 'Tedesco', 'sr_YU': 'Serbo', 'cs_CZ': 'Ceco', 'pl_PL': 'Polacco', 'uk_UA': 'Ucraino', 'fa_IR': 'Persiano', 'sv_S
E': 'Svedese', 'he_IL': 'Ebraico', 'T1': 'Selezionare la propria lingua utilizzando i tasti S\xc3\xb9/Gi\xc3\xb9. OK >> confermare.', 'T2': 'Selezione lingua'}, 'no_NO': {'tr_TR': 'Tyrkisk', 'fr_FR': 'Fransk', 'fi_FI': 'Finsk', 'pt_PT': 'Portugisisk', ...
# -*- coding: utf-8 -*- """WebUI.""" from .websocket import WebsocketProxyHandler def create_webapp(n
aumanni, **kwargs): """App factory. :param CircleCore core: CircleCore Core :param str base_url: ベースURL :param int ws_port: Websocket Port Number :return: WebUI App :rtype: CCWebApp """ from .app import Nauma
nniWebApp app = NaumanniWebApp(naumanni, **kwargs) return app
# # Copyright (c) 2014, Jim Bosch # All rights reserved. # # mcpib is distributed under a simple BSD-like license; # see the LICENSE file that should be prese
nt in the root # of the source distribution. # import unittest import os import sys buildPythonPath = os.path.join(os.path.split(__file__)[0], "..", "python") if os.path.exists(buildPythonPath): sys.path.insert(0, buildPythonPath) import mcpib import builtin_strings_mod as mod class BuiltinStringsTestCase(unittest....
f testString(self): """Test that to-Python and from-Python converters for std::string work as expected.""" self.assertEqual(mod.passthru_string("foo"), "foo") self.assertRaises(mcpib.FromPythonError, mod.passthru_string, 5) self.assertRaises(mcpib.FromPythonError, mod.passthru_string, ["...
#!/usr/bin/env python """FEM library Demonstrates some simple finite element definitions, and computes a mass matrix $ python fem.py [ 1/60, 0, -1/360, 0, -1/90, -1/360] [ 0, 4/45, 0, 2/45, 2/45, -1/90] [-1/360, 0, 1/60, -1/90, 0, -1/360] [ 0, 2/45, -1/90, 4/45, 2/45, 0] ...
(b3, o3) basis.append(fac*pow(b1, o1)*pow(b2, o2)*pow(b3, o3)) coeff.append(aij) if nsd == 3: b1, b2, b3, b4 = x, y, z, 1-x-y-z for o1 in range(0,order+1): for o2 in range(0,order+1): for o3 in range(0,order+1): ...
ge(0,order+1): if o1 + o2 + o3 + o4 == order: aij = Symbol("a_%d_%d_%d_%d" % (o1,o2,o3,o4)) fac = factorial(order)/ (factorial(o1)*factorial(o2)*factorial(o3)*factorial(o4)) sum += aij*fac*pow(b1, o1)*pow(b2, o2)*pow...
: file(filename, "w").write(data) else: raise FMBTX11Error('Unsupported image format "%s"...' % (data[:4],)) else: return False return True class FMBTX11Error(Exception): pass X11ConnectionError = fmbtx11_conn.X11ConnectionError _keyNames = [ "Vo...
"Hiragana", "Katakana", "Hiragana_Katakana", "Zenkaku", "Hankaku", "Zenkaku_Hankaku", "Touroku", "Massyo", "Kana_Lock", "Kana_Shift", "Eisu_Shift", "Eisu_toggle", "Kanji_Bangou", "Zen_Koho", "Mae_Koho", "Home", "Left", "Up", "Right", "Down", "Prior", "Page_U...
rint", "Execute", "Insert", "Undo", "Redo", "Menu", "Find", "Cancel", "Help", "Break", "Mode_switch", "script_switch", "Num_Lock", "KP_Space", "KP_Tab", "KP_Enter", "KP_F1", "KP_F2", "KP_F3", "KP_F4", "KP_Home", "KP_Left", "KP_Up", "KP_Right", "KP_Do...
# -*- coding: utf-8 -*- """ * Partial implementation of standard atmospheric model as described in * GOST 4401-81 useful for processing of data from meteorological balloon * sensors. * * Supported modelling of temperature and pressure over the altitude span from * 0 up to 51km. * * algorithm by Oleg Kocheto...
.0, 110.9056], [51000, 270.65, -0.0028, 6.69384] ] @staticmethod def geopotential_to_geometric(self, altitude): return altitude * self.E / (self.E - altitu
de) @staticmethod def geometric_to_geopotential(self, altitude): return altitude * self.E / (self.E + altitude) def get_altitude(self, pressure): """ Returns geometric altitude value for the given pressure. :param pressure: float pressure - pressure in pascals :ret...
"""SCons.Tool.sunf95 Tool-specific initialization for sunf95, the Sun Studio F95 compiler. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 20...
opy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # th
e following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS...
""" Django settings for untitled project. Generated by 'django-admin startproject' using Django 1.10.3. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import o...
] ROOT_URLCONF = 'kinksorter.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.deb...
.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'kinksorter.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'kinkso...
[2].eventId, False) pipe: rd.PipeState = self.controller.GetPipelineState() ssbo: rd.BoundResource = pipe.GetReadWriteResources(rd.ShaderStage.Compute)[0].resources[0] data: bytes = self.controller.GetBufferData(ssbo.resourceId, 0, 0) rdtest.log.print("Got {} bytes of ...
rdtest.log.success("{} empty draws are empty".format(level)) indirects = self.find_draw("{}: Indirect draws".format(level)) self.check('vkCmdDrawIndirect' in indirects.children[0].name) self.check('vkCmdDrawIndexedIndirect' in indirects.children[1].name) self.che...
at(level)) # vkCmdDrawIndirect(...) draw = indirects.children[0] self.check(draw.numIndices == 3) self.check(draw.numInstances == 2) self.controller.SetFrameEvent(draw.eventId, False) # Check that we have PostVS as expected postvs_da...
# This file is part of the Frescobaldi project, http://www.frescobaldi.org/ # # Copyright (c) 2008 - 2014 by Wilbert Berendsen # # 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 ...
latform.python_version() @_catch_unknown def operating_system(): import platform return platform.platform() @_catch_unknown def ly_version(): import ly.pkginfo return ly.pkginfo.version @_catch_unknown def poppler_version(): import popplerqt4 return '.'.join(format(n) for n in popplerqt4.popp...
ormat(n) for n in popplerqt4.version()) def version_info_named(): """Yield all the relevant names and their version string.""" yield appinfo.appname, appinfo.version yield "Python", python_version() yield "python-ly", ly_version() yield "Qt", qt_version() yield "PyQt", pyqt_version() yield...
from .bhtsn
e import bh_tsne __all__ = ["_bhtsne", "b
h_tsne"]
##!/usr/bin/env python from array import * import os import struct stats = os.stat('freqtest.dat') file_size = stats.st_size #print('file size ', +file_size, ' bytes') entries = file_size/4 #print('file has ', +entries, +' entries') freq_array = array('f', []) #create an array to hold the entries for a ...
st and exit)') #second part... we may want to add new frequencies to the list while x != "n": #similar to the modify loop new_freq = input('new frequency: ') freq_array.append(new_freq) #except we append the frequency at the end for indx i...
he modified list print(indx+1, +freq_array[indx]) x = raw_input("do you want to add another frequency? ") print freq_array #this is here as a troubleshooting tool f = open('freqtest.dat', 'wb') #everything done? dump the array to the file (over...
""" ==================================== Probabilistic Tracking on ODF fields ==================================== In this example we perform probabilistic fiber tracking on fields of ODF peaks. This example requires importing example `reconst_csa.py`. """ import numpy as np from reconst_csa import * from dipy.rec...
memory we can save the results to disk. For this purpose we can use the TrackVis format (``*.trk``). First, we need to create a header. """ import nibabel as nib hdr = nib.trackvis.empty_header() hdr['voxel_size'] = (2.,
2., 2.) hdr['voxel_order'] = 'LAS' hdr['dim'] = csapeaks.gfa.shape[:3] """ Save the streamlines. """ csa_streamlines_trk = ((sl, None, None) for sl in csa_streamlines) csa_sl_fname = 'csa_prob_streamline.trk' nib.trackvis.write(csa_sl_fname, csa_streamlines_trk, hdr) """ Visualize the streamlines with fvtk (pytho...
# Copyri
ght 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/
LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the...
# Creates graph of restaurant reviews for yelp or trip advisor. # writes graph to gml file for use in gephi # # Rob Churchill # # NOTE: I learned to do this in my data science class last semester. If you are looking for plagiarism things, you will almost certainly find similar clustering code. # I did not copy it, I l...
urant') G.add_node(y[13], type='reviewer') # add the edge between the reviewer and restaurant, weight is in different position in each file. if yelp == True: G.add_edge(y[13], y[4], weight=float(y[2])) else: G.add_edge(y[13], y[4], weight=float(y[1])) print nx.number_of_nodes(G) pri...
aph to gml file. nx.write_gml(G, 'ta_graph.gml')
# -*- coding: utf-8 -*- """Django URLconf file for ulm""" from __future__ import unicode_literals from django.conf import settings try: # pylint: di
sable=E0611 from django.conf.urls import patterns, include, url except (ImportError): # Django 1.3 compatibility from django.conf.urls.defaults import patterns, include, url from django.conf.urls.static import static from ulm.views import laptop, batteries, wifi # Uncomment the next two lin...
tterns('', url(r'^$', laptop), url(r'^batter(?:y|ies)/$', batteries), url(r'^(?:wifi|wlan)/$', wifi), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), ) + static(settings.MEDIA_URL, document_root=setti...
#!/usr/bin/env python import os from os.path import join as pjoin import sys import subprocess def get_output(cmd): s = subprocess.Popen(cmd, stdout=subprocess.PIPE) out = s.communicate()[0] s.wait() return out.strip() # you could use os.path.walk to calculate this... or you could use du(1). def duha...
mat=sitemap</loc></sitemap>\n" % (HOSTNAME, name)) else: part = (size / PARITION_SIZE) + 1 for i in range(0, part): count += 1 fp.write("<sitemap><loc>%s%s/?format=sitemap&amp;pmax=%d&amp;part=%d</loc></sitemap>\n" % (HOSTNAME, name, part, i)) if c...
fcount += 1 fp = open(BASEPATH % (fcount), 'w') write_sitemap_header(fp) write_sitemap_footer(fp)
import os import logging import MySQLdb import time import sys import Queue import threading import json createUserSQL = "INSERT IGNORE INTO users (name) VALUES (%s);" getUserByUsernameSQL = "SELECT * FROM users WHERE name=%s;" getAuthorByNameSQL = "SELECT * FROM authors WHERE name=%s;" createAuthorSQL = "INSERT...
] def createBook(username): logging.debug("Creating books... "+username) sys.stdout.flush() db = connect() cur = db.cursor() for j in lastNames: for k in range(0, 3): myname = "Author " + username + " " + j + "(" + str(k) + ")" cur.execute(getAuthorByNameSQL, (myname...
row = cur.fetchone() if not row == None: for i in range(0,2): bookname = myname+"'s book "+str(i) cur.execute(createBookSQL, [bookname, str(row[0]), i * 5]) else: print "Could not find ", myname db.commit() db...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from colour import Color from django.contrib.auth.decorators import user_passes_test from django.urls import reverse from django.db.models import Sum from django.http import HttpResponse, HttpResponseRedirect, StreamingHttpResponse from django.shortcuts ...
se(template.render(context, request)) def combineContactList(request): template = loader.get_template('viewsenators/combine.html') context = {'contactLists': ContactList.objects.all()} return HttpResponse(template.render(context, request)) def createContactList(request): #
if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = ChooseForm(request.POST) # check whether it's valid: if form.is_valid(): data = form.cleaned_data ...
#!/usr/bin/env python import sys import logging import argparse from gff3 import feature_lambda, feature_test_qual_value from CPT_GFFParser import gffParse, gffWrite from Bio.SeqFeature import FeatureLocation log = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def __get_features(child, interpro...
del x.qualifiers[y] except: pass fixed_features.append(x) replacement_features.extend(fixed_features) # We do this so we don't include the original set of features that we # were rebasing against in our resul...
description="rebase gff3 features against parent locations", epilog="" ) parser.add_argument( "parent", type=argparse.FileType("r"), help="Parent GFF3 annotations" ) parser.add_argument( "child", type=argparse.FileType("r"), help="Child GFF3 annotations to rebase again...
from __future__ import unicode_literals import binascii from pymacaroons import Caveat from pymacaroons.utils import ( convert_to_bytes, sign_first_party_caveat ) from .base_first_party import ( BaseFirstPartyCaveatDelegate, BaseFirstPartyCaveatVerifierDelegate ) class FirstPartyCaveatDelegate(BaseF...
n_first_party_caveat(encode_key, predicate) return macaroon class FirstPartyCaveatVerifierDelegate(BaseFirstPartyCaveatVerifierDelegate): def __init__(self, *args, **kwargs): super(FirstPartyCaveatVerifierDelegate, self).__init__(*args, **kwargs) def v
erify_first_party_caveat(self, verifier, caveat, signature): predicate = caveat.caveat_id caveat_met = sum(callback(predicate) for callback in verifier.callbacks) return caveat_met def update_signature(self, signature, caveat): return binascii.unhexlify( ...
#!/usr/bin/env python # -*- coding: utf-8 -*- #HW3 for EECS 598 Motion Planning import time import openravepy import userdefined as us import kdtree import transformationFunction as tf from random import randrange #### YOUR IMPORTS GO HERE #### handles = []; #### END OF YOUR IMPORTS #### if not __openravepy_buil...
oFloatList(path): path = path.split('\n') for line in xrange(len(path)): path[line] = path[line].split(',') for i in xrange(len(path[line])): path[line][i]=float(path[line][i]) return path def drawPath(path,robot,color,size): if type(path) is str: path = stringToFloatList...
for i in path: robot.SetActiveDOFValues(i) handles.append(env.plot3(points=robot.GetTransform()[0:3,3],pointsize=size,colors=color,drawstyle=1)) if __name__ == "__main__": env = Environment() env.SetViewer('qtcoin') collisionChecker = RaveCreateCollisionChecker(env,'ode') env.SetColl...
import sys import os import struct import binascii from time import sleep from ctypes import (CDLL, get_errno) from ctypes.util import find_library from socket import (socket, AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI, SOL_HCI, HCI_FILTER,) os.system("hciconfig hci0 down") os.system("hciconfig hci0 up") if not os.geteuid()...
, 1-filter out duplicates 1000 # timeout ) if err < 0: errnum = get_errno() raise Exception("{} {}".format( errno.errorcode[errnum], os.strerror(errnum) )) distanceAway = 1 # distance away from the estimote beacon in meter with open("RSSI_data" + str(distanceAway) + ".csv","w") as out...
24) RSSI = int(binascii.b2a_hex(data[-1]),16)-255 out_string = "" out_string += str(RSSI) out_string += "\n" out_file.write(out_string) sock.close() sys.exit()
""" Copyright 2014 Quentin Kaiser 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 dis...
self._name = str(value
) @property def type(self): return self._type @type.setter def type(self, value): self._type = str(value) @property def status(self): return self._status @status.setter def status(self, value): self._status = str(value) @property def scan_coun...
, arr) def FetchBlobs(names): """Fetches a list of blobs from the workspace. Inputs: names: list of names of blobs - strings or BlobReferences Returns: list of fetched blobs """ return [FetchBlob(name) for name in names] def FetchBlob(name): """Fetches a blob from the worksp...
nd support will be very # sparse. ################################################################################ _immediate_mode = False _immediate_workspace_name = "_CAFFE2_IMMEDIATE
" _immediate_root_folder = '' def IsImmediate(): return _immediate_mode @contextlib.contextmanager def WorkspaceGuard(workspace_name): current = CurrentWorkspace() SwitchWorkspace(workspace_name, True) yield SwitchWorkspace(current) def StartImmediate(i_know=False): global _immediate_mode ...
match: case
= 4
2
# 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, # bu...
'], package_data={"virttest": ["*.*"]}, data_files=get_data_files(), entry_points={ 'avocado.plugins.cli': [ 'vt-list = avocado_vt.plugins.vt_list:VTLister', 'vt = avocado_vt.plugins.vt:VTRun', ], 'avocado.plugins.cli.cmd': [ ...
ado_vt.plugins.vt_joblock:VTJobLock' ], }, )
# -*- coding:utf-8 -*- from django.urls import path from article.views.post import PostListApiV
iew, PostCreateApiView, PostDetailApiView urlpatterns = [ # 前缀:/api/v1/article/post/ path('create', PostCreateApiView.as_view(), name="create"), path('list', PostListApiV
iew.as_view(), name="list"), path('<int:pk>', PostDetailApiView.as_view(), name="detail"), ]
timeout = self._NOTIFICATION_DELAY else: timeout = None try: events = poll_obj.poll(timeout) except OSError as e: if e.errno == errno.EINTR: continue ...
core.decode(name))) else: self._force_notify = True elif wd == self._git_dir_wd: name = core.decode(name) if name == 'HEAD' or name == 'index': self._force_notify = True elif (wd in ...
d, mask, cookie, name in \ inotify.read_events(self._inotify_fd): if not self._force_notify: self._check_event(wd, mask, name) def stop(self): self._running = False with self._lock: if self._pipe_w is not None: ...
te_is_tuple=True)(x, ((m0, m1), (m2, m3))) sess.run([variables.global_variables_initializer()]) basic_res = sess.run([g, out_m0, out_m1, out_m2, out_m3], { x.name: x_values, m0.name: m0_val, m1.name: m1_val, m2.name: m2_val, m3.name: m3_val ...
) self.assertAllClose(f
used_grads, unfused_grads) for fused, unfused in zip(fused_wgrads, unfused_wgrads): self.assertAllClose(fused, unfused, rtol=1e-6, atol=1e-6) #### Benchmarking. class BenchmarkLSTMBlock(test.Benchmark): def benchmarkLSTMBlockCellFpropWithDynamicRNN(self): print("BlockLSTMCell forward propagation...
#!/usr/bin/env python # -*- coding: utf-8 -*- from core import FeatureExtractorRegistry from twinkle.connectors.core import ConnectorRegistry class FeatureExtractorPipelineFactory(object): """ Factory object for creating a pipeline from a file """ def __init__(self): """ """ pass def buildInput(self,...
self.output = output def addExtractor(self, extractor): """ add Extractor to the pipeline """ self.feature_extractors.append(extractor) def run(self): """ runs the pipeline """ processed_items = [] # iterate through each item for item in self.input: item_cookie = { "tweet": item, "text...
extractor.extract(item, item_cookie, output) print output # write output self.output.write(output)
from setuptools import setup setup( # general meta name='elasticity', version='0.7', author='Brian C. Dilley - Flipagram', author_email='brian@flipagram.com', description='Python based command line tool for managing ElasticSearch clusters.', platforms='any', url='https://github.com/Che...
], # dependencies install_requires=[ 'elasticsearch>=1.4.0', 'pyyaml>=3.10' ], # additional files to include include_pack
age_data=True, # the scripts scripts=['scripts/elasticity'], # wut? classifiers=['Intended Audience :: Developers'] )
matching_answer]) for key, value in temp_dict.items(): # Each value now has hint, votes, matching_answer. temp_dict[key] = value + [matching_answer] matching_hints.update(temp_dict) # matching_hints now maps pk's to lists of [hint, votes, matching_answer] ...
'answer': text of answer 'hint': text of the new hint that the user is adding Returns a thank-you message. """ # Do html escaping. Perhaps in the future do profanity filtering, etc. as well. hint = escape(data['hint']) answer = data['answer'] if not sel...
validate_answer(answer): log.exception('Failure in hinter submit_hint: Unable to parse answer: {ans}'.format( ans=answer)) return {'error': 'Could not submit answer'} # Only allow a student to vote or submit a hint once. if self.user_voted: r...
from __future__ import print_function import argparse import yaml from .bocca import make_project, ProjectExistsError def main(): parser = argparse.ArgumentParser() parser.add_argument('file', type=argparse.FileType('r'), help='Project description file') parser.add_argument('--cl...
make_project(yaml.load(args.file), clobber=args.clobber) except ProjectExistsError as error: print('The specified project (%s) already exists. Exiting.' % error) if __name__ == '__main__': m
ain()
from __future__ import unicode_literals, divi
sion, absolute_import from builtins import * # noqa pylint: disable=unused-import, redefined-builtin from flask import jsonify from flask_restplus import inputs from flexget.api import api, APIResource from flexget.api.app import NotFoundError, BadRequest, etag from flexget.plugins.internal.api_tvmaze import APITVMa...
api.namespace('tvmaze', description='TVMaze Shows') class ObjectsContainer(object): actor_object = { 'type': 'object', 'properties': { "last_update": {'type': 'string', 'format': 'date-time'}, "medium_image": {'type': 'string'}, "name": {'type': 'string'}, ...
import argparse import sys, os import numpy as np from copy import copy parser = argparse.ArgumentParser() parser.add_argument('qubit', help='qubit name') parser.add_argument('direction', help='direction (X or Y)') parser.add_argument('numPulses', type=i
nt, help='log2(n) of the longest sequence n') parser.add_argument('amplitude', type=float, help='pulse amplitude') args = parser.parse_args() from QGL import * q = QubitFactory(args.qubit) if args.direction == 'X': pPulse = Xtheta(q, amp=args.amplitude) mPulse = X90m(q) else: pPulse = Ytheta(q, amp=args....
ulses+1)] # measure each along Z or X/Y seqs = [s + m for s in seqs for m in [ [MEAS(q)], [mPulse, MEAS(q)] ]] # tack on calibrations to the beginning seqs = [[Id(q), MEAS(q)], [X(q), MEAS(q)]] + seqs # repeat each repeated_seqs = [copy(s) for s in seqs for _ in range(2)] fileNames = compile_to_hardware(repeated_se...
import requests import urllib2 import argparse from bs4 import BeautifulSoup def get_best_torrent(query): query = urllib2.quote(query) r = requests.get('http://kat.cr/usearch/{}/'.format(query)) soup = BeautifulSoup(r.content) torrents = soup.find('table', class_='data').find_all(has_class_odd_or_even...
.text print
"Seeds: {}".format(seeds) leeches = torrent.find(class_='red lasttd center').text print "Leeches: {}".format(leeches) try: seed_to_leech = float(seeds) / float(leeches) except ZeroDivisionError: seed_to_leech = int(seeds) print "Seed to leech ratio: {}".fo...
from xml.dom import minidom from object_classes import * from helpers import timeToSeconds class HindenburgInt(object): def __init__(self, project_file, version="Hindenburg Journalist 1.26.1936", version_num="1.26.1936"): self.projectFile = project_file self.version = version self.version...
t(fade.getAttribute('Gain')) except: endValue = 0 autoEnv.addPoint(startTime, startValue) autoEnv.addPoint(endTime, endValue) plugins = track.getElementsByTagName("Plugin") for plugin in plug...
) == 'Compressor': pluginType = "Native" else: pluginType = "Plugin" new_plugin = current_track.addFX(plugin.getAttribute('Name'), pluginType, int(plugin.getAttribute('Id'))) if pluginType == "Native": if plugin...
import numpy as np import theano import theano.tensor as T import lasagne as nn import data import load import nn_plankton import dihedral import tmp_dnn import tta features = [ # "hu", # "tutorial", "haralick", # "aaronmoments", # "lbp", # "pftas", # "zernike_moments", # "image_siz...
n.init.Constant(0.1), nonlinearity=None) l1 = nn_plankton.NonlinLayer(l0, T.log) ltot = nn.layers.ElemwiseSumLayer([l1, l3_size]) # norm_by_sum = lambda x: x / x.sum(1).dimshuffle(0, "x") lout = nn_plankton.NonlinLayer(ltot, nonlinearity=T.nnet.softmax) return [l0, l0_size], lout def build_obj...
# lambda_reg = 0.005 params = nn.layers.get_all_non_bias_params(l_out) # reg_term = sum(T.sum(p**2) for p in params) L2 = sum(T.sum(p**2) for p in params) L1 = sum(T.sum(T.abs_(p)) for p in params) def loss(y, t): return nn_plankton.log_loss(y, t) + reg_param*(alpha * L1 + (1-alpha) * L2...
# Copyright 2021 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Web test-specific impl of the unexpected passes' queries module.""" import os import posixpath from blinkpy.web_tests.stale_expectation_removal import co...
ist locally. filepaths = [] for f in query_result.get('expectation_files', []): if posixpath.isabs(f): continue f = f.replace('/', os.sep) f = os.path.join(constants.WE
B_TEST_ROOT_DIR, f) filepaths.append(f) return filepaths def _ShouldSkipOverResult(self, result): # WebGPU web tests are currently unsupported for various reasons. return 'webgpu/cts.html' in result['test_id'] def _GetQueryGeneratorForBuilder(self, builder, builder_type): ...
""" Copyright 2017-present, Airbnb Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. This file is the entry point for AWS Lambda. """ from streamalert.sche...
ent)
""" Query modules mapping functions to their query strings structured: module_name { query_string: function_for_query } """ from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function from __future__ import division # Standard imports from future import standar...
Month, 'get_most_recent': getRecentTrips, 'get_trips_by_mode': getTripsThroughMode}, # Utility Module 'utility': { 'get_training': getTrainingTrips }, # Recommender Module 'recommender': { 'get_improve': getCanonicalTri
ps }, #Perturbation Module 'perturbation': {}, #Alternatives Module # note: uses a different collection than section_db 'alternatives': { 'get_alternatives': getAlternativeTrips } }
import argparse import datetime import imutils import numpy as np import time import csv import cv2 import os.path #define variable click_frame = False divide_x = 0 divide_y = 0 channel_A = 0 channel_B = 0 area_A = 0 area_B = 0 #division fuction (divide_frame) def divide_frame(event,x,y,flags,param): global click_fr...
nue # compute the bounding box for the contour, draw it on the frame, # and update the text (x, y, w, h) = cv2.boundingRect(c) cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) text = "Occupied" fish_x = x+w/2 fish_y = y+h/2 if fish_x < divide_x and fish_y < divide_y: channel_A += 1
if fish_x > divide_x and fish_y < divide_y: area_A += 1 if fish_x < divide_x and fish_y > divide_y: channel_B += 1 if fish_x > divide_x and fish_y > divide_y: area_B += 1 #division lines #tags fontsize = 1 thickness = 1 cv2.putText(frame,"{0:.2f}".format(fps)+" fps",(25,25),cv2.FONT_HERSHEY_SI...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2005 onwards University of Deusto # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. # # This software consists of contributions made by many individual...
@note This method may block for a long time. It might hence be advisable to account for this delay and to call it from a worker thread. @note Implementations might require additional information, which should generally be provided through the configuration script and accessed through ...
. Failure and the ConfigureError should be either a PermanentConfigureError or a TemporaryConfigureError. Should a different kind of exception be raised however, it would be considered permanent. """ pass def cancel(self): self.cancelled = True
Y 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, Boston, MA # 02110-1301 USA #...
ge == 'certificate verify failed': raise (up2dateErrors.SSLCertificateVerifyFailedError(), None, sys.exc_info()[2]) else: raise (up2dateErrors.NetworkError(message), None, sys.exc_info()[2]) def __exception_from_fault(self, fault): if fault.faultCode == -3: ...
ationOrAccountCreationError(fault.faultString) elif fault.faultCode == -2: # Invalid username and password combination. exception = up2dateErrors.AuthenticationOrAccountCreationError(fault.faultString) elif fault.faultCode == -110: # Account is dis...
from setuptools import setup setup( name="sgf", version="0.5", description="Python library for reading and writing Smart Game Format", license="MIT", url="http://github.com/jtauber/sgf", author="James Tauber", author_email="jtauber@jtauber.com", py_modules=["sgf"], classifiers=[ ...
"Programming Language :: Python :: 2.7", "Top
ic :: Games/Entertainment :: Board Games", "Topic :: Utilities", ], )
hMedium(ctx, mach.id, dvd) return 0 def mountIsoCmd(ctx, args): if (len(args) < 3): print "usage: mountIso vm iso controller port:slot" return 0 mach = argsToMach(ctx, args) if mach is None: return 0 vbox = ctx['vb'] loc = args[2] try: dvd = vbox.openMedium(...
return (0, [msg]) else: nat.aliasMode = 0 if 'default' not in args: for a in range(1, len(args)): if not alias.has_key(args[a]): print 'Invalid alias mode: ' + args[a] print natAlias.__doc__ return (1,
None) nat.aliasMode = int(nat.aliasMode) | alias[args[a]] return (0, None) def natSettings(ctx, mach, nicnum, nat, args): """This command shows/alters NAT settings. usage: nat <vm> <nicnum> settings [<mtu> [[<socsndbuf> <sockrcvbuf> [<tcpsndwnd> <tcprcvwnd>]]]]
import glob json_files = glob.glob("tests/**/output/**/*.json", recursive=True) html_files = glob.glob("tests/**/out
put/**/*.html", recursive=True) html_list = "" for f_ in html_files: html_list += '\t<li><a href="{}">{}</li>\n'.format( f_[6:], f_.split(".")[-2], ) json_list = "" for f_ in json_files: json_list += '\t<li><a href="{}">{}</li>\n'.format( f_[6:], f_.split(".")[-2], ) h...
ul> <br/><br/> <h3>JSON</h3> <ul> {} </ul> </body> </html> """.format( html_list, json_list ) print(html_file)
from models import Comment from ..user.serializers import UserProfileSerializer from rest_framework import serializers class CommentSerializer(serializers.ModelSerializer): username = serializers.SerializerMethodF
ield() class Meta: model = Comment fields = ("id","user","username", "topic","comment","comment_html", "action", "date","is_removed","is_modified","ip_address", "modified_count","likes_count") read_only_fields = ("user",
"comment_html","action","date","is_removed","is_modified","modified_count","likes_count") def get_username(self,obj): return obj.user.username def create(self,**kwargs): comment = Comment.objects.create(user = kwargs['user'],**self.validated_data) return comment
import os.path import pkgutil from unittest import TestCase, TestSuite class TestImports(TestCase): def __init__(self, mod_name, import_error): name = f"test_{mod_name.replace('.', '_')}_import" def run(): try: __import__(mod_name) except ImportError as e: ...
__(name) def load_tests(*_args): expected_exceptions = { "blueman.main.NetworkManager": "NM python bindings not found.", "blueman.main.PulseAudioUtils": "Could not load pulseaudio shared library", } test_cases = TestSuite() home, subpath = os.path.dirname(__file__).rsplit("/test/", 1)...
for package in pkgutil.iter_modules([f"{home}/blueman/{subpath}"], f"blueman.{subpath.replace('/', '.')}."): test_cases.addTest(TestImports(package.name, expected_exceptions.get(package.name))) assert test_cases.countTestCases() > 0 return test_cases
# coding=utf-8 # # 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 a...
NS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """ REST URI ``http://localhost/mgmt/cm/device/licensing/pool/regkey`` REST Kind N/A -- HTTP GET returns an error """ from f5.bigiq.cm.device.licensing.pool imp...
(self, device): super(Licensing, self).__init__(device) self._meta_data['allowed_lazy_attributes'] = [ Pool ]
# -*- coding: utf-8 -*- # # Copyright 2018 BhaaL # # 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 lat...
description=__doc__)
parser.add_option("-r", "--root", action="store", dest="root", default="root", help='name of the XML root element (default: "root")') parser.add_option("-v", "--value", action="store", dest="value", default="str", help='name of...
# Made by mtrix import sys from com.l2scoria.gameserver.model.quest import State from com.l2scoria.gameserver.model.quest import QuestState from com.l2scoria.gameserver.model.quest.jython import QuestJython as JQuest qn = "345_MethodToRaiseTheDead" ADENA = 57 VICTIMS_ARM_BONE = 4274 VICTIMS_THIGH_BONE = 4275 VICTIMS_...
st.set("cond","2") htmltext = "30970-06.htm" elif event == "3" : if st.getQuestItemsCount(ADENA)>=1000 : st.takeItems(ADENA,1000) st.giveItems(POWDER_TO_SUMMON_DEAD_SOULS,1) st.set("cond","3") htmltext = "30912-03.htm" st.pl...
elif event == "4" : htmltext = "30973-02.htm" st.takeItems(POWDER_TO_SUMMON_DEAD_SOULS,-1) st.takeItems(VICTIMS_ARM_BONE,-1) st.takeItems(VICTIMS_THIGH_BONE,-1) st.takeItems(VICTIMS_SKULL,-1) st.takeItems(VICTIMS_RIB_BONE,-1) st.takeItems(VICTIMS_SPINE...
from django.db import models from django.contrib.auth.models import User from building.models import Building, Unit # Create your models here. class Listing(models.Model): """ An option to lease, rent, or sublease a specific Unit """ CYCLE_CHOICES = ( ('year', 'Year'), ('month', 'Mo...
#duplicating available_start and rent on unit with current listing #that will make database lookups simpler #but it will require coordination when adding a new listing. #optional available_start = models.DateTimeField() #might be useful for subleases: available_end = models.DateTimeField...
ield(max_length=10, choices=CYCLE_CHOICES, default="month") deposit = models.FloatField() description = models.TextField() #are pets allowed? if so what kind? #pets = models.CharField(max_length=200) #what utilities are included: (to help estimate total cost) # #this is set at the buildin...
import numpy as np from scipy.io import netcdf_file import bz2 import os from fnmatch import fnmatch from numba import jit @jit def binsum2D(data, i, j, Nx, Ny): data_binned = np.zeros((Ny,Nx), dtype=data.dtype) N = len(data) for n in range(N): data_binned[j[n],i[n]] += data[n] return data_binn...
dlat) self.Nx, self.Ny = len(self.lon), len(self.lat) self.lonc = self.lon
+ self.dlon/2 self.latc = self.lat + self.dlat/2 def binsum(self, data, lon, lat): """Bin the data into the lat-lon grid. Returns gridded dataset.""" i = np.digitize(lon.ravel(), self.lon) j = np.digitize(lat.ravel(), self.lat) return binsum2D(data.ravel(), i, j...
# -*- python -*- # Copyright (C) 2009-2013 Free Software Foundation, Inc. # 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. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the im
plied 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, see <http://www.gnu.org/licenses/>. import sys import gdb import os import os.path ...
def test_upgrade_atac_alignment_enrichment_quality_metric_1_2( upgrader, atac_alignment_enrichm
ent_quality_metric_1 ): value = upgrader.upgrade( 'atac_alignment_enrichment_quality_metric', atac_alignment_enrichment_quality_metric_1, current_version='1', target_version='2', ) assert value['schema_version'] == '2' asse
rt 'fri_blacklist' not in value assert value['fri_exclusion_list'] == 0.0013046877081284722
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( int_or_none, float_or_none, unified_strdate, ) class PornoVoisinesIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?pornovoisines\.com/videos/show/(?P<id>\d+)/(?P<display_id>[...
video_id, video_id, note='Getting settings URL')['video_settings_url'] settings = self._download_json(settings_url, video_id)['data'] formats = [] for kind, data in settings['variants'].items(): if kind == 'HLS': f
ormats.extend(self._extract_m3u8_formats( data, video_id, ext='mp4', entry_protocol='m3u8_native', m3u8_id='hls')) elif kind == 'MP4': for item in data: formats.append({ 'url': item['url'], 'height': item...
# -*- coding: utf-8 -*- # Copyright 2015 AvanzOsc (http://www.avanzosc.es) # Copyright 2015-2016 - Pedro M. Baeza <pedro.baeza@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl) from odoo import api, models class PurchaseOrder(models.Model): _inherit = 'purchase.order' @api.model ...
) retur
n super(PurchaseOrder, self).search( args, offset=offset, limit=limit, order=order, count=count) class PurchaseOrderLine(models.Model): _inherit = 'purchase.order.line' @api.model def search(self, args, offset=0, limit=None, order=None, count=False): # Restrict the empty return for th...
from abc import abstractmethod from typing import Callable, TypeVar, Protocol from typing_extensions import runtime_checkable TSource = TypeVar('TSource') TResult = TypeVar('TResult') @runtime_checkable class Applicative(Protocol[TSource, TResult]): """Applicative. Applicative functors are functors with so...
second one. """ raise NotImplementedError #def __mul__(self, something): # """(<*>) :: f (a -> b) -> f a -> f b. # Provide the * as an infix version of apply() since we cannot # represent the Haskell's <*> operator in Python. # """ # return self.apply(som...
# return func % self * b @classmethod @abstractmethod def pure(cls, fn: Callable[[TSource], TResult]) -> 'Applicative[TSource, TResult]': """Applicative functor constructor. Use pure if you're dealing with values in an applicative context (using them with <*>); otherwise, stick...
levels = self.spectrum # First we need to check for the tones. for noise_pause in self.noise_pauses: # Determine the indices of the tones in a noise pause tone_indices, bandwidth_for_tone_criterion = determine_tone_lines( levels, self.frequency_...
d except AttributeError: raise ValueError("Cannot show overview (yet). No tones have been determined.") tones = [("Tone", "{:4.1f} Hz: {:4.1f} dB".format(tone.center, tone.tone_level)) for tone in self.tones] table = [ ("Critical band", "{:4.1f} to {:4.1f} Hz".format(cb...
".format(cb.masking_noise_level)), ("Tonal level $L_{pt}$", "{:4.1f} dB".format(cb.total_tone_level)), ("Dominant tone", "{:4.1f} Hz".format(cb.tone.center)), ("3 dB bandwidth of tone", "{:2.1f}% of {:4.1f}".format(cb.tone.bandwidth_3db / cb.bandwidth * 100.0, ...
] step = _ast.Num( n=1 ) # TODO: should be an expression elif len( call.args ) == 3: start = call.args[0] stop = call.args[1] step = call.args[2] else: raise VerilogTranslationError( 'An invalid number of arguments provided to (x)range function!\n', node.lineno ...
------------ # ConstantToSlice #------------------------------------------------------------------------- class ConstantToSlice( ast.NodeTransformer ): def visit_Attribute( self, node ): self.ge
neric_visit( node ) if isinstance( node._object, slice ): if node._object.step: raise VerilogTranslationError( 'Slices with steps ([start:stop:step]) are not translatable!\n', node.lineno ) new_node = ast.Slice( ast.Num( node._object.start ), ...
""" Test the metropolis hastings algorithm. """ import numpy as np import chronometer as gc import matplotlib.pyplot as plt import corner import emcee def model(par, x): return par[0] + par[1]*x def lnlike(par, x, y, yerr, par_inds): y_mod = model(par, x) return sum(-.5*((y_mod - y)/ye
rr)**2) def test_metropolis_hastings(): # Straight line model x = np.arange(0, 10, .1) err = 2. yerr = np.ones_like(x) * err y = .7 + 2.5*x + np.random.randn(len(x))*err # Plot the data. plt.clf() plt.errorbar(x, y, yerr=yerr, fmt="k.") plt.savefig("data") print("Running Metr...
) N = 1000000 # N samples pars = np.array([.5, 2.5]) # initialisation t = np.array([.01, .01]) par_inds = np.arange(len(pars)) args = [x, y, yerr, par_inds] samples, par, probs = gc.MH(pars, lnlike, N, t, *args) results = [np.percentile(samples[:, i], 50) for i in range(2)] upper = [n...
# -*- coding: utf-8 -*- import pytest from boussole.exceptions import FinderException def test_001(finder): results = finder.get_relative_from_paths("/home/foo/plop", [ "/home/foo", "/home/bar", "/etc", ]) assert results == "plop" def test_002(finder): results = finder.get_...
"/etc", "/home/foo/pika/bim/bam", "/home/foo/pika/bim/bom", "/home/bar/pika", "/home/bar", ]) assert results == "plop" def test_009(finder): """ Unable to find relative path raise an exception """ with pytest.raises(FinderException): finder.get_...
"/home/bar/pika", "/home/bar", ])
odels") _models = [] for model in os.listdir(models_dir): model_dir = os.path.join(models_dir, model) if os.path.isdir(model_dir) and "__init__.py" in os.listdir(model_dir): _models.append(model) # Get the models from the directory structure of `src/transformers/models/` mod...
r(transformers.models, model) for submodule in dir(model_module): if submodule.startswith("modeling") and submodule not in _ignore_modules: modeling_module = getattr(model_module, submodule) if inspect.ismodule(modeling_module): ...
"""Get the objects in module that are models.""" models = [] model_classes = (transformers.PreTrainedModel, transformers.TFPreTrainedModel, transformers.FlaxPreTrainedModel) for attr_name in dir(module): if not include_pretrained and ("Pretrained" in attr_name or "PreTrained" in attr_name): ...
from django.http import HttpResponse from django.shortcuts import render def video_calling(request): return render(request,'video_
calling.html
')
sion = Revision.objects.get(id=r) if request.POST.__contains__('change'): article.current_revision = revision article.save() elif request.POST.__contains__('view'): redirectURL = wiki_reverse('wiki_view_revision', course=course,...
sorted(results, key=lambda article: (article.current_revision.deleted, article.get_path().lower())) if len(results) == 1 and querystring: return HttpResponseRedirect(wiki_reverse('wiki_view', article=results[0], course=course)) else: d = {'wiki_search_results': results, 'wiki_s...
render_to_response('simplewiki/simplewiki_searchresults.html', d) def search_add_related(request, course_id, slug, namespace): course = get_opt_course_with_access(request.user, course_id, 'load') (article, err) = get_article(request, slug, namespace if namespace else course_id) if err: return err...
plicates={}, index=index, tree=tree, base_dir='/') # Make sure all required docstrings are present. self.assertTrue(inspect.getdoc(TestClass) in docs) self.assertTrue(inspect.getdoc(TestClass.a_method) in docs) self.assertTrue(inspect.getdoc(TestClass.a_property) in ...
def test
_generate_markdown_for_function_with_kwargs(self): index = { 'test_function_with_args_kwargs': test_function_with_args_kwargs } tree = { '': ['test_function_with_args_kwargs'] } docs = parser.generate_markdown(full_name='test_function_with_args_kwargs', ...