prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
# # Copyright (c) 2008--2010 Red Hat, Inc. # # This software is licensed to you under the GNU General Public License, # version 2 (GPLv2). There is NO WARRANTY for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. You should have received a c...
, value): self.value = value def __str__(self): return self.type_name class NUMBER(DatabaseDataType): type_name = "NUMBER" class STRING(DatabaseDataType): type_name = "STRING" def __init__(self, value=None, size=None): DatabaseDataType.__init__(self, value=value, size=size)...
RY(DatabaseDataType): type_name = "LONG_BINARY" # XXX More data types to be added as we find need for them
#!/usr/bin/python # # Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
t, help='The ID of the ad to target') def main(argv): # Authenticate and construct service. service, flags = sample_tools.init( argv, 'dfareporting', 'v2.2', __doc__, __file__, parents=[argparser], scope=['https://www.googleapis.com/auth/dfareporting', 'https://www.googleapis.com/auth/dfa...
= flags.ad_id try: # Retrieve the ad. ad = service.ads().get(profileId=profile_id, id=ad_id).execute() # Retrieve a single targetable remarketing list for the ad. lists = service.targetableRemarketingLists().list( profileId=profile_id, advertiserId=ad['advertiserId'], maxResults=1)....
""" Redis Blueprint =============== **Fabric environment:** .. code-block:: yaml blueprints: - blues.redis settings: redis: # bind: 0.0.0.0 # Set the bind address specifically (Default: 127.0.0.1) """ import re from fabric.decorators import task from fabric.utils import abort from ref...
op') restart = debian.service_task('redis-server', 'restart') @task def setup(): """ Install and configure Redis """ install() configure()
def install(): with sudo(): debian.apt_get('install', 'redis-server') def get_installed_version(): """ Get installed version as tuple. Parsed output format: Redis server v=2.8.4 sha=00000000:0 malloc=jemalloc-3.4.1 bits=64 build=a... """ retval = run('redis-server --version') ...
from django.conf.urls.defaults import patterns, url urlpatterns = patterns( 'show.views', url(r'^radioshow/entrylist/$', 'radioshow_entryitem_list', name='radioshow_entryitem_list'), url(r'^showcontributor
/list/(?P<slug>[\w-]+)/$', 'showcontributor_content_list', name='showcontributor_content_list'), url(r'^showcontributor/appearance/(?P<slug>[\w-]+)/$', 'showcontributor_appearance_list', name='showcontributor_appearance_list'), url(r'^showcontributor/(?P<slug>[\w-]+)/$', 'showcontributor_detail', name='showcont...
url(r'^showcontributor/content/(?P<slug>[\w-]+)/$', 'showcontributor_content_detail', name='showcontributor_content_detail'), url(r'^showcontributor/contact/(?P<slug>[\w-]+)/$', 'showcontributor_contact', name='showcontributor_contact'), )
n, k, l, c, d, p, nl, np = map(int,raw_inp
ut().split()) a = k*l x = a/nl y = c*d z = p/np print min(x,y
,z)/n
ds(json.dumps(float(n)))*1.0e8) if satoshis != 2000000000000003: raise RuntimeError("JSON encode/decode loses precision") def determine_db_dir(): """Return the default location of the bitcoin data directory""" if platform.system() == "Darwin": return os.path.expanduser("~/Library/Applicatio...
= config.get('testnet', '0') testnet = (int(testnet) > 0) # 0/1 in config file, convert to True/False if not 'rpcport' in config: config['rpcport'] = 51142 if testnet else 61142 connect = "http://%s:%s@127.0.0.1:%s"%(config['rpcuser'], config['rpcpassword'], config['rpcport']) try: res...
# but also make sure the bitcoind we're talking to is/isn't testnet: if result.getmininginfo()['testnet'] != testnet: sys.stderr.write("RPC server at "+connect+" testnet setting mismatch\n") sys.exit(1) return result except: sys.stderr.write("Error connecting to R...
# Copyright 2015-2016 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
m oslo_messaging._drivers.zmq_driver.client import zmq_routing_table from oslo_messaging._drivers.zmq_driver.client import zmq_senders from oslo_messaging._driv
ers.zmq_driver.client import zmq_sockets_manager from oslo_messaging._drivers.zmq_driver import zmq_address from oslo_messaging._drivers.zmq_driver import zmq_async from oslo_messaging._drivers.zmq_driver import zmq_names LOG = logging.getLogger(__name__) zmq = zmq_async.import_zmq() class DealerPublisherDirect(zm...
"""Gl
obal test fixtures.""" import uuid import pytest from s3keyring.s3 import S3Keyring from s3keyring.settings import config from keyring.errors import PasswordDeleteError @pytest.fixture def keyring(scope="module"): config.boto_config.activate_profile("test") return S3Keyring() @pytest.yield_fixture def ra...
keyring.delete_password(service, user) except PasswordDeleteError as err: if 'not found' not in err.args[0]: # It's ok if the entry has been already deleted raise
print(__doc__) from time import time import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn import metrics from sklearn.cluster import KMeans from sklearn.datasets import load_digits from sklearn.decomposition import PCA from sklearn.preprocessing import scale from sklearn.preprocessing i...
hed = min_max_scaler.fit_transform(patched)
#cluster data cluster = KMeans(n_clusters=n_clusters) cluster.fit_transform(patched) #assigned grouped labels to the crime data labels = cluster.labels_ #copy dataframe (may be memory intensive but just for illustration) skid_data = crime_data.copy() #print pd.Series(classified_data) #print pd.Series(prediction...
elf.ps == other.ps) def Print(self): """Prints the values and freqs/probs in ascending order.""" for val, prob in zip(self.xs, self.ps): print(val, prob) def Copy(self, label=None): """Returns a copy of this Cdf. label: string label for the new Cdf """ ...
nceInterval = CredibleInterval def _Round(self, multiplier=1000): """ An entry is added to the cdf only if the percentile differs from the previous value in a significant digit, where the number of significant digits is determined by multiplier. The default is 1000, which k...
uence of points suitable for plotting. An empirical CDF is a step function; linear interpolation can be misleading. Note: options are ignored Returns: tuple of (xs, ps) """ def interleave(a, b): c = np.empty(a.shape[0] + b.shape[0]) ...
# -*- coding: utf-8 -*- # Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless require...
tdout=True) mock_create_notification.assert_called_once_with( mock.ANY, # Client instance. 'foo_notification', pubsub_topic=mock.ANY, payload_format=mock.ANY, custom_attributes={'foo': 'bar:baz'},
event_types=None, object_name_prefix=mock.ANY, provider=mock.ANY) class TestNotification(testcase.GsUtilIntegrationTestCase): """Integration tests for notification command.""" @unittest.skipUnless(NOTIFICATION_URL, 'Test requires notification URL configuration.') def...
"%s team gets have been enqueued offset from %s.<br />" % (len(teams), offset)) # self.response.out.write("Reload with ?offset=%s to enqueue more." % (offset + len(teams))) # class TeamDetailsRollingEnqueue(webapp.RequestHandler): # """ # Handles enqueing updates to individual teams # Enqueues a c...
eam: team = TeamManipulator.createOrUpdate(team) # Clean up junk district teams # https://www.facebook.com/groups/moardata/permalink/1310068625680096/ dt_keys = DistrictTeam.query(
DistrictTeam.team == existing_team.key, DistrictTeam.year == year).fetch(keys_only=True) keys_to_delete = set() for dt_key in dt_keys: if not district_team or dt_key.id() != district_team.key.id(): keys_to_delete.add(dt_key) DistrictTeamManipulator.delete...
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016, 2017 CERN. # # Invenio is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any...
future__ import absolute_import, print_function from flask_assets import Bundle from invenio_assets import NpmBundle stats_js = NpmBundle( "node_modules/invenio-charts-js/dist/lib.bundle.js", "js/cds_records/stats.js", output="gen/cds.records.stats.%(version)s.js", npm={ "invenio-charts-js": "...
filters="node-scss,cleancssurl", ), output="gen/cds.stats.%(version)s.css", ) js = NpmBundle( Bundle( "node_modules/cds/dist/cds.js", "node_modules/angular-sanitize/angular-sanitize.js", "node_modules/angular-strap/dist/angular-strap.js", "node_modules/invenio-files...
from __future__ import absolute_import, unicode_literals from django.core.management.base import BaseCommand from molo.core.models import LanguageRelation from molo.core.models
import Page class Command(BaseCommand): def handle(self, *args, **options): for relation in LanguageRelation.objects.all(): if relation.page and relation.language: page = Page.objects.get(pk=relation.page.pk).specific page.language = relation.lang
uage page.save() else: self.stdout.write(self.style.NOTICE( 'Relation with pk "%s" is missing either page/language' % (relation.pk)))
''' @author: Michael Wan @since : 2014-11-08 ''' from math import log import operator def createDataSet(): dataSet = [[1, 1, 'yes'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']] labels = ['no surfacing','flippers'] #cha...
(dataSet) bestInfoGain = 0.0; bestFeature = -1 for i in range(numFeatures): #iterate over all the features featList = [example[i] for example in dataSet]#create a list of all the examples of this feature uniqueVals = set(featList) #get a set of unique values newEntropy ...
aSet)) newEntropy += prob * calcShannonEnt(subDataSet) infoGain = baseEntropy - newEntropy #calculate the info gain; ie reduction in entropy if (infoGain > bestInfoGain): #compare this to the best gain so far bestInfoGain = infoGain #if better than curr...
import random, inspect from sched import scheduler from time import time, sleep from datetime import datetime #################################################################################################### # Minimal implementation of the signaling library class Signal(object): def __init__(self, name): ...
ose' if effort > 0 else 'dropped' if sender.energy < 100: # and sender not in hardworkers: hardworkers.add(sender) else: hardworkers.discard(sender) return effort def print_person(person): print(person.name) print(person.energy) # Creating the people objects from a list of nam...
nergy levels have changed hardworkers = set([]) # Observing the people we just created monitor_changes_in_effort(people) # Starting a 2 second loop that makes each person work 20 times start_time = time() duration = 0.5 interval = duration / 20 while time() < start_time + duration: # print('Time: ') # print(d...
import os def get_terminal_columns(): terminal_rows, terminal_columns = os.popen('stty size', 'r').read().split() return int(terminal_columns) def get_terminal_rows(): terminal_rows, terminal_columns = os.popen('stty size', 'r').read().split() return int(terminal_rows) def get_header_l1(lines_li...
text_output.append('| {:<{width}}|'.format(line, width=width-3)) text_output.append('%s%s%s' % ('+', '-' * (width - 2), '+')) text_output.append('') return '\n'.join(text_output) def get_header_l2(lines_list, width=None): text_output = [] if width is None: width = 0 for line ...
h += 5 text_output.append('') text_output.append('#') text_output.append('##') for line in lines_list: text_output.append('### ' + line) text_output.append('-' * width) text_output.append('') return '\n'.join(text_output) def get_key_value_adjusted(key, value, key_width): ...
"""Utilities for B2share deposit.""" from flask import request from werkzeug.local import LocalProxy from werkzeug.routing import PathConverter def file_id_to_key(value): """Convert file UUID to value if in request context.""" from invenio_files_rest.models import ObjectVersion _, record = request.view_...
r key.""" def to_python(self, value): """Lazily convert va
lue from UUID to key if need be.""" return LocalProxy(lambda: file_id_to_key(value))
*- class SupportEncodings(object): """ Given the support encoding of piconv """ supports = [] def __init__(self): self.supports = ['ASCII','UTF-8','UTF-16','UTF-32',\ 'BIG5','GBK','GB2312','GB18030','EUC-JP', 'SHIFT_JIS', 'ISO-2022-JP'\ 'WINDOWS-1252'] def get_support_encodings(self): return self.suppo...
CSIBM11621162, CSISO4UNITEDKINGDOM, CSISO10SWEDISH, CSISO11SWEDISHFORNAMES, CSISO14JISC6220RO, CSISO15ITALIAN, CSISO16PORTUGESE, CSISO17SPANISH, CSISO18GREEK7OLD, CSISO19LATINGREEK, CSISO21GERMAN, CSISO25FRENCH, CSISO27LATINGREEK1, CSISO49INIS, CSISO50INIS8, CSISO51INISCYRILLIC, CSISO58GB1988,
CSISO60DANISHNORWEGIAN, CSISO60NORWEGIAN1, CSISO61NORWEGIAN2, CSISO69FRENCH, CSISO84PORTUGUESE2, CSISO85SPANISH2, CSISO86HUNGARIAN, CSISO88GREEK7, CSISO89ASMO449, CSISO90, CSISO92JISC62991984B, CSISO99NAPLPS, CSISO103T618BIT, CSISO111ECMACYRILLIC, CSISO121CANADIAN1, CSISO122CANADIAN2, CSISO139CSN369103, CSISO14...
# module
includes impor
t elliptic import heat import IRT print "Loading comatmor version 0.0.1"
from layers.receivers.base_receiever import BaseReceiver class ReceiptReceiv
er(BaseReceiver): def onReceipt(self, receiptEntity): ack =
ReceiptReceiver.getAckEntity(receiptEntity) self.toLower(ack)
from rest_framework.serializers import ModelSerializer from app.schedule.mo
dels.patient import Patient from app.schedule.serializers.clinic import ClinicListSerializer from app.schedule.serializers.dental_plan import DentalPlanSerializer class PatientSerializer(ModelSerializer): class Meta: model = Patient fields = ('id', 'name', 'last_name', 'sex', 'phone', 'clinic', 'c...
lizer()
# -- coding: utf-8 -- from flask import render_template, session, redirect, url_for, current_app, request from .. import db from ..model
s import Detail,Conte
nts,Keywords,WXUrls from . import main from .forms import NameForm import wechatsogou import hashlib from .errors import * from ..API.reqweb import * @main.route('/', methods=['GET', 'POST']) def index(): form = NameForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.name.da...
import argparse from collections import defaultdict, Counter, deque import random import json import time from tqdm import tqdm import wikipedia class MarkovModel(object): def __init__(self): self.states = defaultdict(lambda: Counter()) self.totals = Counter() def add_sample(self, state, foll...
ate = tuple(tokens[0:state_size]) for token in tokens[state_size:]: # Each additional token means last state to that token yield state, (token,) # New state is last {state_size} tokens we yielded state = state[1:] + (token,) # End is marked by None yield state, end_marker d...
if token is not None: yield token def eat_one_token(story): while len(story) > 0 and isinvalid(story[0]): story.popleft() if len(story) == 0: return None if isalnum(story[0]): return eat_word(story) if ispunctuation(story[0]): return eat_punctuation(stor...
if partner_payment_term: to_update = self.onchange_payment_term_date_invoice( cr, uid, ids, partner_payment_term, date_invoice) result['value'].update(to_update['value']) else: result['value']['date_due'] = False if partner_bank_id...
=','property_account_receivable'),('company_id','=',company_id)]) if not pay_pro_id: pay_pro_id = property_obj.search(cr, uid, [('name','=','property_account_payable'),('company_id','=',company_id)]) rec_line_data = property_obj.read(cr, uid, rec_pro_id, [...
pay_line_data = property_obj.read(cr, uid, pay_pro_id, ['name','value_reference','res_id']) rec_res_id = rec_line_data and rec_line_data[0].get('value_reference',False) and int(rec_line_data[0]['value_reference'].split(',')[1]) or False pay_res_id = pay_line_data and pay_l...
_component_infos = [] components_to_visit = sorted( set(self.component_infos), key = lambda c: c.name) while components_to_visit: visit_component_info(components_to_visit[0], [], set()) # Canonicalize children lists. for c in self.ordered_component_in...
---------------------------------------------------------===; ; ; This is an LLVMBuild description file for the components in this subdirectory. ; ; For more information on the LLVMBuild system, please see: ; ; http://llvm.org/docs/LLVMBuild.html ; ;===-----------------------------------------------------------------...
ragment in fragments: comment = comments_map.get(name) if comment is not None: f.write(comment) f.write("[%s]\n" % name) f.write(fragment) if fragment is not fragments[-1][1]: f.write('\n') ...
import os import logging from superdesk import get_resource_service from jinja2.loaders import FileSystemLoader, ModuleLoader, ChoiceLoader, DictLoader, PrefixLoader from liveblog.mongo_util import decode as mongodecode __all__ = ['ThemeTemplateLoader', 'CompiledThemeTemplateLoader'] logger = logging.getLogger('supe...
templates using as
prefix the parent theme name Example: {% extends 'parent_theme_name/template_name.html' %} {% include 'parent_theme_name/template_name.html' %} Args: name (`str`): Parent theme name Returns: PrefixLoader instance with parent_name as prefix ...
# Copyright 2016 Nicolas Bessi, Camptocamp SA # Copyright 2018 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from lxml import etree from odoo import _, api, fields, models from odoo.exceptions import ValidationError class ResPartner(models.Model): _inherit = "res.par...
ot rec.zip_id: continue if rec.zip_id.city_id.country_id != rec.country_id:
raise ValidationError( _("The country of the partner %s differs from that in location %s") % (rec.name, rec.zip_id.name) ) if rec.zip_id.city_id.state_id != rec.state_id: raise ValidationError( _("The state ...
from django.conf import settings from django.contrib.auth.models import User from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank from django.core.urlresolvers import reverse from django.db import models from github import UnknownObjectException from social.apps.django_app.default.models imp...
process_wiki from interface.utils import get_github from interface.path_processor import PathProcessor class UserProxy(User): class Meta:
proxy = True def get_auth(self): try: data = UserSocialAuth.objects.filter(user=self).values_list('extra_data')[0][0] except: return None username = data['login'] password = data['access_token'] return (username, password) class Repo(models...
# Copyright 2021 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
opt_state: optax.OptState) -> ModelUpdates: grad_fn = jax.grad(loss_fn, has_aux=True) grad, (state, scalars) = grad_fn(params, state, rng, minibatch) grad = jax.lax.pmean(grad, axi
s_name='i') scalars = jax.lax.pmean(scalars, axis_name='i') updates, opt_state = optimizer.update(grad, opt_state, params) params = optax.apply_updates(params, updates) return ModelUpdates(params, state, opt_state, scalars) return update_fn def get_batch_dims(global_batch_size: int, device_count: ...
__author__ = 'matjaz'
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-12-07 22:51 from __future__ import unicode_literals import c3nav.mapdata.fields from django.db import migrations, models cla
ss Migration(migrations.Migration): initial = True dependencies = [ ] opera
tions = [ migrations.CreateModel( name='Announcement', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True, verbose_name='created')), ...
# Copyright 2017, Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import import sys from google.cloud.proto.vision.v1 import geometry_pb2 from google.cloud.proto.vision.v1 import image_annotator_pb2...
web_detection_pb2 from google.gax.utils.messages import get_messages names = [] for module in (geometry_pb2, image_annotator_pb2, text_annotation_pb2, web_detection_pb2): for name, message in get_messages(module).items(): message.__module__ = 'google.cloud.vision_v1.types' setattr...
#!/usr/local/bin/python # -*-coding:utf8-*- from scrapy.contrib.downloadermiddleware.useragent import UserAgentMiddleware import random class RotateUserAgentMiddleware(UserAgentMiddleware): def __init__(self, user_agent=''): self.user_agent = user_agent def process_request(self, request, spider): ...
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3", \ "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.
3 (KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3", \ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24", \ "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24" ]
from __future__ import absolute_import from agms.configuration import Configuration from agms.agms import Agms from agms.transaction import Transaction from agms.safe import S
AFE from agms.report import Report from agms.recurring import Recurring from agms.hpp import HPP from agms.v
ersion import Version
#!/usr/bin/env python # coding=utf-8 """303. Multiples with small digits https://p
rojecteuler.net/problem=303 For a positive integer n, define f(n) as the least positive multiple of n that, written in base 10, uses only digits ≤ 2. Thus f(2)=2, f(3)=12, f(7)=21, f(42)=210, f(89)=1121222. Also, $\sum \limits_{n = 1}^{100} {\dfrac{f(n)}{n}} = 11363107$. Find $\sum \limi
ts_{n=1}^{10000} {\dfrac{f(n)}{n}}$. """
import json import os.path from ems.app import Bootstrapper, absolute_path from ems.inspection.util import classes from ems.validation.abstract import Validator, MessageProvider from ems.validation.registry import Registry from ems.validation.rule_validator import RuleValidator, SimpleMessageProvider from ems.validat...
re(PathNormalizer, self.createPathNormalizer) def createRegistry(self): registry = Registry(self.app) self.addValidatorClasses(registry) return registry def createPathNormalizer(self): return AppPathNormalizer() def addValidat
orClasses(self, registry): for module in self.validatorModules: for cls in self.findModuleValidatorClasses(module): registry += cls def createMessageProvider(self): with open(self.messagesFilePath()) as jsonFile: messages = json.load(jsonFile) retur...
_token self.max_items = max_items self.sleep_for_rate = sleep_for_rate self.min_rate_to_sleep = min_rate_to_sleep self.sleep_time = sleep_time self.client = None def fetch(self, category=CATEGORY_TWEET, since_id=None, max_id=None, geocode=None, lang=None, ...
aticmethod def sanitize_for_archive(url, headers, payload): """Sanitize payload of a HTTP request by removing the token information before storing/retrieving archived items :param: url: HTTP url request :param: headers: HTTP headers request :param: payload: HTTP payload requ...
orization') return url, headers, payload def tweets(self, query, since_id=None, max_id=None, geocode=None, lang=None, include_entities=True, result_type=TWEET_TYPE_MIXED): """Fetch tweets for a given query between since_id and max_id. :param query: query to fetch tweets ...
import os import pydoc import sys class DocTree: def __init__(self, src, dest): self.basepath = os.getcwd() sys.path.append(os.path.join(self.basepath,
src)) self.src = src self.dest = dest self._make_dest(dest) self._make_docs(src) self._move_docs(dest) def _make_dest(self, dest): path = os.path.join(self.basepath, dest) if os.path.isdir(path): os.rmdir(path) os.makedirs(path) def ...
print(os.listdir()) def _move_docs(self, dest): for f in os.listdir(): if f.endswith('.html'): _dest = os.path.join(dest, f) os.rename(f, _dest) def main(): dest = 'docs' src = 'vcx/api' src = os.path.join(os.getcwd(), src) DocTree(src, dest) ...
NVALID -j DROP', comment=None), mock.call.add_rule('ofake_dev', '-j $sg-fallback', comment=None), mock.call.add_rule('sg-chain', '-j ACCEPT')] comb = zip(calls, filter_inst.mock_calls) for (l, r) in comb: self.assertEqu...
'direction': 'ingress'}] self.firewall.prepare_port_filter(port) port['security_group_rules'] = [{'ethertype': 'IPv4', 'direction': 'egress'}] self.firewall.updat
e_port_filter(port) self.firewall.update_port_filter({'device': 'no-exist-device'}) self.firewall.remove_port_filter(port) self.firewall.remove_port_filter({'device': 'no-exist-device'}) calls = [mock.call.add_chain('sg-fallback'), mock.call.add_rule( ...
def add_without_op(x, y): while y !=0: carry = x & y
x = x ^ y y = carry << 1 print(x) def main(): x, y = map(int, input().split()) add_without_op(x, y) if
__name__ == "__main__": main()
# get triangles for all i-points on j-line k = get_triangles_j(j, nx, k, t_land, ds_max, lambda_f, phi_f, dep, x, y, z, t) # k is now total no of triangles; chop off unused parts of the arrays & copy ... x, y, z, t = [a[:k,:].copy() for a in (x, y, z, t)] return k, x, y, z, t def wrap_lon(lon): ...
[...] *= self.zscale def globe_proj(self, x, y, z): r_eq, dr_pol_eq = self.rsphere_eq, self.rsphere_pol - self.rsphere_eq rad = np.pi/180. z[...] = z*self.zsc
ale + r_eq y *= rad x *= rad xt = z*np.cos(y) z[...] = (z + dr_pol_eq)*np.sin(y) y[...] = xt*np.sin(x) x[...] = xt*np.cos(x) if __name__ == '__main__': parser = ArgumentParser(description='produce lego-block topography e.g. \n python ~/VC_code/NEMOcode/lego5.py -b ...
self.log.debug( "Collecting done, value %s" % result[col_idx]) if metric_type == GAUGE: self.gauge(metric, float( result[col_idx]), tags=tags) ...
noDB status
but are not otherwise present as part of the STATUS # variables in MySQL. Majority of these metrics are reported though # as a part of STATUS variables in Percona Server and MariaDB. # Requires querying user to have PROCESS privileges. try: with closing(db.cursor()) as curso...
quire a rising rhythm (e.g., iambic, anapestic) # ############################################ ############################################ # REALIZATION PARAMETERS # # All subsequent constraints can be seen as "realization parameters." # See note to "structure parameters" above for more information. # ##############...
ould be a function word: #Cs['footmin-wordbound-neitherfw']=1 # # ...the left-hand syllable should be a function-word: #Cs['footmin-wordbound-leftfw']=1 # # ...the right-hand syllable should be a function word: #Cs['footmin-wordbound-rightfw']=1 # # ...neither word should be a monosyllable: #Cs['footmin-wordbound-nomon...
Miscellaneous constraints relating to disyllabic positions] # # A disyllabic metrical position may contain a strong syllable # of a lexical word only if the syllable is (i) light and # (ii) followed within the same position by an unstressed # syllable normally belonging to the same word. # [written by Sam Bowman] #Cs['...
8191 class ObjectPaginator(Paginator): """ Legacy ObjectPaginator class, for backwards compatibility. Note that each method on this class that takes page_number expects a zero-based page number, whereas the new API (Paginator/Page) uses one-based page numbers. """ def __init__(self, query_s...
'%s.%s IN (%s)' % (\ connection.ops.quote_name('feedjack_post_tags'), \ connection.ops.quote_name('post_id'), \ ', '.join([str(post.id) for post in object_list]))]) for tag
in tags: if tag.post_id not in tagd: tagd[tag.post_id] = [] tagd[tag.post_id].append(tag) if tag_name and tag.name == tag_name: tag_obj = tag subd = {} for sub in sfeeds_obj: subd[sub.feed.id] = sub for post in object_list: if post.id in tagd: ...
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "street_agitation_bot.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ens...
# issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHO...
TH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
niform((batch_size, height, width, 3)) logits, _ = alexnet.alexnet_v2(
eval_inputs, is_training=False) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) predictions = tf.argmax(logits, 1) self.assertListEqual(predictions.get_shape().as_list(), [batch_size]) def testTrainEvalWithReuse(self): train_batch_size = ...
.p.pointer_count def report_finger(self, t): t = t % self.trial_time if 0.3<t<1.0: return [1] else: return [0] def report_compare(self, t): return [0] def memory_clear(self, t): t = t % self.trial_time if 1.0 - self.p.time_clear_mem < t...
=1.2) # create a system to report whether the first # or second number is bigger compare = nengo.Ensemble(p.N_compare,1, label='compare', radius=1) nengo.Connection(memory.ensembles[0],compare[0],transform=p.evidence_scale) nengo.Connection(memory.ensembles[...
o reporting systems report_gate_f = nengo.Ensemble(50,1, encoders=nengo.dists.Choice([[1]]), intercepts=nengo.dists.Uniform(0.1,0.9), label='report gate f') report_gate_c=nengo.Ensemble(50,1, encoders=nengo.dists.Choice([[1]]), ...
from PySide2 import QtGui, QtCore, QtWidgets from design import SidUi, DdUi from ServersData import ServersDownloadThread, servers import sys class SpeedInputDialog(QtWidgets.QDialog, SidUi): def __init__(self): QtWidgets.QDialog.__init__(self) self.setupUi() def get_data(self)...
download_error) self.get_servers_download_thread.start() def update_progress_text(self, text): self.progress_text.append(text) def update_progress_bar(self, value): self.progress_bar.setValue(value) def update_button(self): self.horizontalLayout.removeWidget(...
) self.horizontalLayout.addWidget(self.okButton) self.okButton.clicked.connect(self.ok_function) def cancel_function(self): reply = QtWidgets.QMessageBox.question(self, 'Message', "Are you sure that you want to cancel downloading? This will exit the program.",...
from rpg.plugin import Plugin from rpg.command import Command from rpg.utils import path_to_str from re import compile from subprocess import CalledProcessError import logging class CPlugin(Plugin): EXT_CPP = [r"cc"
, r"cxx", r"cpp", r"c\+\+", r"ii", r"ixx", r"ipp", r"i\+\+", r"hh", r"hxx", r"hpp", r"h\+\+", r"c", r"h"] def patched(self, project_dir, spec, sack): """ Finds dependencies via makedepend - This is not garanteed to be all of them. Makedepend uses
macro preprocessor and if it throws and error makedepend didn't print deps. """ out = Command([ "find " + path_to_str(project_dir) + " -name " + " -o -name ".join( ["'*." + ex + "'" for ex in self.EXT_CPP] ) ]).execute() cc_makedep...
# -*- coding: utf-8 -*- from .env import * from amoco.cas.expressions import regtype from amoco.arch.core import Formatter, Token def mnemo(i): mn = i.mnemonic.lower() return [(Token.Mnemonic, "{: <12}".format(mn))] def deref(opd): return "[%s+%d]" % (opd.a.base, opd.a.disp) def opers(i): s = [] ...
ot None: s.append((Token.Address, "%s" % (i.misc["imm_ref"]))) elif op.sf: s.append((Token.Constant, "%+d" % op.value)) else: s.append((Token.Constant, op.__str__())) elif op._is_reg: s.append((Token.Register, op.__str__())) ...
s[-1] = (Token.Address, ".%+d" % i.operands[-1]) else: imm_ref = i.address + i.length + (i.operands[-1] * 8) s[-1] = (Token.Address, "#%s" % (imm_ref)) return s def opers_adr2(i): s = opers(i) if i.address is None: s[-3] = (Token.Address, ".%+d" % i.operands[-2]) s[-1...
# from http://diydrones.com/forum/topics/mission-planner-python-script?commentId=705844%3AComment%3A2035437&xg_source=msg_com_forum import socket import sys import math from math import sqrt import clr import time import re, string clr.AddReference("MissionPlanner.Utilities") import MissionPlanner #import * clr.AddRe...
t) print(float_lng) print(float_heading) print(float_alt)
"""Writing Waypoints""" item = MissionPlanner.Utilities.Locationwp() # creating waypoint MissionPlanner.Utilities.Locationwp.lat.SetValue(item,float_lat) MissionPlanner.Utilities.Locationwp.lng.SetValue(item,float_lng) #MissionPlanner.Utilities.Locationwp.groundcourse.SetValue(item,flo...
from oscar.test.testcases import WebTestCase from oscar.test.factories import create_product, UserFactory from oscar.core.compat import get_user_model from oscar.apps.catalogue.reviews.signals import review_added from oscar.test.contextmanagers i
mport mock_signal_receiver class TestACustomer(WebTestCase): def setUp(self): self.product = create_product() def test_can_add_a_review_when_anonymous(self): detail_page = self.app.get(self.product.get_absolute_url()) add_review_page = detail_page.click(linkid='write_review') ...
'Loving it, loving it, loving it' form['name'] = 'John Doe' form['email'] = 'john@example.com' form.submit() self.assertEqual(1, self.product.reviews.all().count()) def test_can_add_a_review_when_signed_in(self): user = UserFactory() detail_page = self.app.get(self...
#!/usr/bin/python import cv2 import numpy as np import sys, getopt import
matplotlib matplotlib.use('Agg') # Force matplotlib to not use any Xwindows backend.
from matplotlib import pyplot as plt image_path = None def printHelp(): print 'main.py\n' \ ' -i <Image Path. Ex: /home/myImage.jpg > (Mandatory)\n' \ ' \n Example: python main.py -i myOriginalImage.jpg \n ' try: opts, args = getopt.getopt(sys.argv[1:],"hi:") except getopt.GetoptError: printHelp...
{'image_id': image_id}, default=False)): return SUCCESS client = get_client(options) client.delete_cached_image(image_id) if options.verbose: print("Deleted cached image %(image_id)s" % {'image_id': image_id}) return SUCCESS @catch_error('Delete all cached images...
help="Explicitly allow glance to perform \"insecure\" " "SSL (https) requests. The server's certificate will " "not be verified against any certificate auth
orities. " "This option should be used with caution.") parser.add_option('-f', '--force', dest="force", metavar="FORCE", default=False, action="store_true", help="Prevent select actions from requesting " "user confirmation....
# -*- coding: utf-8 -*- # # mete0r.gpl : Manage GPL'ed source code files # Copyright (C) 2015 mete0r <mete0r@sarangbang.or.kr> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software F
oundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public ...
f not, see <http://www.gnu.org/licenses/>. #
# encoding: UTF-8 import talib as ta import numpy as np from ctaBase import * from ctaTemplate import CtaTemplate import time ######################################################################## class TickBreaker(CtaTemplate): """跳空追击策略(MC版本转化)""" className = 'TickBreaker' author = u'融拓科技' # 策略...
if len(self.tickHistory) > self.max
History: self.tickHistory.pop(0) # 如果小于缓存上限,则说明初始化数据尚未足够,不进行后续计算 else: return # # 将缓存的收盘价数转化为numpy数组后,传入talib的函数SMA中计算 # closeArray = np.array(self.closeHistory) # sma = ta.SMA(closeArray, self.maPeriod) # # >=5个上涨tick # condition1 = self...
"""sandbox URL Configuration The `urlpatterns` list routes URLs to views. For more information plea
se see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from oth
er_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, includ...
from datetime import timedelta from django.db.models import Sum from django.utils.duration import duration_string from rest_framework_json_api.serializers import ( CharField, ModelSerializer, SerializerMethodField, ) from timed.projects.models import Project from timed.tracking.models import Report from ...
izerMethodField(source="get_spent_time") def get_purchased_time(self, obj): """ Calculate purchased time for given project. Only acknowledged hours are included. """ orders = Order.objects.filter(project=obj, acknowledged=True) data = orders.aggregate(purchased_time...
get_spent_time(self, obj): """ Calculate spent time for given project. Reports which are not billable or are in review are excluded. """ reports = Report.objects.filter( task__project=obj, not_billable=False, review=False ) data = reports.aggregate(sp...
'id': 1, 'size': TOO_BIG_VOLUME_SIZE}) def test_initialize_connection(self): """Test that inititialize connection attaches volume to host.""" self.driver.do_setup(None) self.driver.create_volume(VOLUME) self.driver.initialize_c...
ME['name']}
self.driver.manage_existing(VOLUME, existing_ref) self.assertEqual(VOLUME['size'], MANAGED_VOLUME['size']) # cover both case, whether driver renames the volume or not self.driver.delete_volume(VOLUME) self.driver.delete_volume(MANAGED_VOLUME) def test_manage_existing_should_...
""" Pseudo code Breadth-First-Search(Graph, root): create empty set S create empty queue Q root.parent = NIL Q.enqueue(root) while Q is not empty: current = Q.dequeue() if current is the goal: return current for each node n that is adjacent to current: ...
h) return visited if __name__ == "__main__": g = { "a": {"d": 4}, "b": {"c": 2}, "c": {"b": 2, "c": 5, "d": 1, "e": 7}, "d": {"a": 4, "c": 1}, "e": {"c": 7} } graph = Graph(g) print(
"Vertices of graph:") print(graph.list_vertices()) print("\nEdges of graph:") print(graph.list_edges()) print("\nAdding a vertice") graph.add_vertex("g") print (graph.list_vertices()) graph.add_edge(("g", "a")) graph.add_edge(("a", "c")) graph.add_edge(("g", "c")) print("\nEdge...
from util.arguments import Arguments from discord.ext import commands from shlex import split import rando
m class Choices: def __init__(self, bot): self.bot = bot @commands.command(aliases=['choose'], description='Randomly picks a 1 of the given choices.') async def choices(self, *, msg): parser = Arguments(allow_abbrev=False, prog='choices') parser.add_argument('choices', nargs='+',...
await self.bot.say('```%s```' % parser.format_help()) return except Exception as e: await self.bot.say('```%s```' % str(e)) return choice = args.choices[random.SystemRandom().randint(0, len(args.choices) - 1)] await self.bot.say('**%s** has randomly been...
import logging import socket from . import arcade logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) class Switch: remote_ip = None remote_port = 9999 state = None commands = {'info': '{"system":{"get_sysinfo":{}}}', 'on': u'{"system...
lf.switch_requester(self.commands.get('info')) def switch_requester(self, content=None): if content is None: print("Fail") return False else: try: sock_tcp = socket.socket(socket
.AF_INET, socket.SOCK_STREAM) sock_tcp.connect((self.remote_ip, self.remote_port)) print("Sending: ", content) # sock_tcp.send(bytes(self.encrypt(content), 'utf8')) sock_tcp.send(self.encrypt(content).encode('utf8')) data = sock_tcp.recv...
import ctypes class _DpxGenericHeaderBigEndian(ctypes.BigEndianStructure): _fields_ = [ ('Magic', ctypes.c_char * 4), ('ImageOffset', ctypes.c_uint32), ('Version', ctypes.c_char * 8), ('FileSize', ctypes.c_uint32), ('DittoKey', ctypes.c_uint32), ('GenericSize', ctyp...
esPerElement', ctypes.c_uint32), ('ImageElement', _DpxGenericImageElementBigEndian * 8), ('Reserved', ctypes.c_char * 52) ] class _DpxGenericOrientationHeaderBigEndian(ctypes.BigEndianStructure): _fields_ = [ ('XOffset', ctypes.c_uint32), ('YOffset', ctypes.c_uin
t32), ('XCenter', ctypes.c_float), ('YCenter', ctypes.c_float), ('XOriginalSize', ctypes.c_uint32), ('YOriginalSize', ctypes.c_uint32), ('FileName', ctypes.c_char * 100), ('TimeDate', ctypes.c_char * 24), ('InputName', ctypes.c_char * 32), ('InputSN', ctyp...
import random from gatesym import core, ga
tes, test_utils from gatesym.blocks import latches def test_gated_d_latch(): network = core.Network() clock = gates.Switch(network) data = gates.Switch(network) latch = latches.gated_d_latch(data, clock) network.drain() assert not lat
ch.read() data.write(True) network.drain() assert not latch.read() clock.write(True) network.drain() assert latch.read() data.write(False) network.drain() assert not latch.read() def test_ms_d_flop_basic(): network = core.Network() clock = gates.Switch(network) data ...
# Copyright 2019 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, ...
, name): setattr(obj, name, []) while len(getattr(obj, name)) < len(self.entries): new_model = self.model() db.session.add(new_model)
getattr(obj, name).append(new_model) while len(getattr(obj, name)) > len(self.entries): db.session.delete(getattr(obj, name).pop()) super().populate_obj(obj, name) class CommitLinksForm(FlaskForm): repo_url = StringField( "Git Repo URL", validators=[validators.Opti...
import socket,sys,os,hashlib,codecs,time # Import socket module #filecodec = 'cp037' filecodec = None buffersize = 1024 failed = False def filehash(filepath): openedFile = codecs.open(filepath,'rb',filecodec) # readFile = openedFile.read().encode() readFile = openedFile.read() openedFile.cl...
if (l): f.write(l)
flenc = flenc + 1 f.close() print("Done Receiving") ofhash = filehash(fname + ".tmp") tries = tries + 1 if ofhash == fhash: print("File Valid") c.send("Y".encode()) ...
r.truediv), ('*', operator.mul), ] self._ASSIGN_OPERATORS = [(op + '=', opfunc) for op, opfunc in self._OPERATORS] self._ASSIGN_OPERATORS.append(('=', lambda cur, right: right)) self._VARNAME_PATTERN = r'[a-zA-Z_$][a-zA-Z_$0-9]*' if ...
cur = lvar[idx] val = opfunc(cur, right_val) lvar[idx] = val return val else: cur = local_vars.get(m.group('out')) val = opfunc(cur, right_val) local_vars[m.group('out')] = val return val ...
'(?!if|return|true|false)(?P<name>%s)$' % self._VARNAME_PATTERN, expr) if var_m: return local_vars[var_m.group('name')] try: return json.loads(expr) except ValueError: pass m = re.match(r'(?P<var>%s)\.(?P<member>[^(]+)(?:\(+(?P<args>[^()]*)\))?$' % s...
import math # According to Law of cosines, p^2 + p*r + r^2 = c^2. # Let c = r+k, => r = (p^2-k^2)/(2*k-p) and p > k > p/2 (k is even). # Suppose p <= q <= r. max_sum = 120000 d = {} # p => set(r) for p in range(1, ma
x_sum/2+1): if p%10000 == 0: print p d[p] = set() mink = int(
p/2)+1 maxk = int((math.sqrt(3)-1)*p) # so that r >= p for k in range(mink, maxk+1): if (p**2-k**2)%(2*k-p) == 0: q = (p**2-k**2)/(2*k-p) d[p].add(q) ans = set() for p in d.keys(): for q in d[p]: if q in d and len(d[q]) > 0: for r in d[p].intersection(d[...
he # GNU AFFERO GENERAL PUBLIC LICENSE for more details. # # You should have received a copy of the GNU Affero General Public # License along with this program. If not, see <http://www.gnu.org/licenses/>. # __doc__ = """The realm endpoints are used to define realms. A realm groups together many users. Administrators c...
.. sourcecode:: http GET / HTTP/1.1 Host: example.com Accept: application/json **Example response**: .. sourcec
ode:: http HTTP/1.1 200 OK Content-Type: application/json { "id": 1, "jsonrpc": "2.0", "result": { "status": true, "value": { "realm1_with_resolver": { "default": true, "resolver": [ ...
"""Tests for distutils.command.build_py.""" import os import sys import StringIO import unittest from distutils.command.build_py import build_py from distutils.core import Distribution from distutils.errors import DistutilsFileError from distutils.tests import support class BuildPyTestCase(support.Te...
kdtemp() f = open(os.path.join(sources, "__init__.py"), "w") f.write("# Pretend this is a package.") f.close() f = open(os.path.join(sources, "README.txt"), "w") f.write("
Info about this package") f.close() destination = self.mkdtemp() dist = Distribution({"packages": ["pkg"], "package_dir": {"pkg": sources}}) # script_name need not exist, it just need to be initialized dist.script_name = os.path.join(sources...
# ------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: Stefan # # Created: 11.07.2017 # Copyright: (c) Stefan 2017 # Licence: <your licence> # ------------------------------------------------------------------------...
entity " + str(_ENTITY)) _process_main(sp, "http://www.primarie3.ro/consiliu-local/hotarari-de-consiliu/", False) _process_main(sp, "http://www.primarie3.ro/consiliu-local/procese-verbale-de-sedinta/", True) print("End processing entity " + str(_ENTITY)) # main processing - take a
ll years and process until no more pages def _process_main(sp, configaddress, ispvpage): html = ScrapeProcessor.download_page(configaddress) _process_year(sp, html, ispvpage) if sp.get_processmode() in (ScrapeProcessor.ProcessMode.DELTA, ScrapeProcessor.ProcessMode.DELTA_DOWNLOAD): return ...
ed_msg.Subscribe(self.OnUpdateDoc, ed_msg.EDMSG_FILE_SAVED) ed_msg.Subscribe(self.OnUpdateDoc, ed_msg.EDMSG_FILE_OPENED) ed_msg.Subscribe(self.OnUpdateDoc, ed_msg.EDMSG_UI_STC_LEXER) def OnDestroy(self, evt): """Unsubscribe from messages""" if self._lexmenu: self._le
xmenu.Destroy() if self._eolmenu: self._eolmenu.Destroy() if evt.GetId() == self.GetId(): ed_msg.Unsubscribe(self.OnProgress) ed_msg.Unsubscribe(self.OnUpdateText) ed_msg.Unsubscribe(self.OnUpdateDoc) evt.Skip() def __SetStatusText(self, txt, ...
d): """Safe method to use for setting status text with CallAfter. @param txt: string @param field: int """ try: super(EdStatBar, self).SetStatusText(txt, field) self.AdjustFieldWidths() if field == ed_glob.SB_INFO and txt != u'': ...
from datetime import datetime, date import pytest from pytz import UTC from uber.config import c from uber.models import Attendee, Session from uber.site_sections import summary @pytest.fixture def birthdays(): dates = [ date(1964, 12, 30), date(1964, 12, 31), date(1964, 1, 1), d...
017, 12, 31), datetime(2018, 1, 1), 2), # Crossing the year (datetime(2018, 1, 31), datetime(2018, 2, 1), 2), # Crossing the month (datetime(2018, 2, 28), datetime(2018, 3, 1), 3), # Leap day (datetime(2018, 1, 1), datetime(2018, 3, 4), 15), # Multi-month (datetime(2017, 12, 28), dat...
self, admin_attendee, epoch, eschaton, expected, birthdays, monkeypatch): monkeypatch.setattr(c, 'EPOCH', epoch) monkeypatch.setattr(c, 'ESCHATON', eschaton) response = summary.Root().event_birthday_calendar() ...
# -*- coding: utf-8 -*- from
__future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('structure', '0039_remove_permission_groups'), ] operations = [ migrations.AlterField( model_name='customerpermission', name='is_a...
model_name='projectpermission', name='is_active', field=models.NullBooleanField(default=True, db_index=True), ), ]
import glob import matplotlib.pyplot as plt import numpy as np import os import pickle import scipy.signal import shutil import display_pyutils def apply_averaging_filter(x, filter_size=5): return np.convolve(x, np.ones(filter_size,) / float(filter_size), mode='valid') def apply_median_filter(x, filter_size=5):...
return scipy.signal.medfilt(x, f
ilter_size) def postprocess_signal(anomaly_ratings): signal = anomaly_ratings / (1 - anomaly_ratings) bottom_ninetyfive_percent = sorted(signal)[:int(np.floor(len(signal) * 0.95))] smoothed_signal = apply_averaging_filter(signal, 100) threshold = (np.median(signal) + 2 * np.std(bottom_ninetyfive_perce...
for key in ['is_public', 'protected', 'deleted']: if key in meta: meta[key] = meta[key].strip().lower() in ('t', 'true', 'yes', '1') for key in ['size', 'min_ram', 'min_disk']: if key in meta: ...
0, resp.status) body = json.loads(body) return resp, body['image'] def delete_image(self, image_id): url = 'v1/images/%s' % image_id resp, body = self.delete(url) self.expected_success(200, resp.status) return resp, body def image_list(self, **kwargs): u...
url += '?%s' % urllib.urlencode(kwargs) resp, body = self.get(url) self.expected_success(200, resp.status) body = json.loads(body) return resp, body['images'] def image_list_detail(self, properties=dict(), changes_since=None, **kwargs): ...
""" Functional Data Analysis Routines """ from __future__ import division import numpy as np def _curve_area(A, B): r1 = np.mean(A-B) r2 = np.mean(B-A) if r1 > r2: return r1 else: return r2 def curve_test(Y, cnd_1, cnd_2, n_perm=1000): """ Assess whether two curv
es are statistically significant based on permutation test over conditions and replicates. Parameters ---------- Y: 2d array, shape: (
time x var) Observations matrix for each variable over time. cnd_1: list, shape: (n_reps_1) List of replicate indices in columns of Y for condition 1 cnd_2: list, shape: (n_reps_2) List of replicate indices in columns of Y for condition 2 n_perm: int Number of permut...
""" pyva
lence """ __version__ = '0.
0.1.3'
#!/usr/bin/python def conversionMap(): """ returns conversionmap """ return { 'a': [1, -2, -1], 'b': [1, 2, 1], 'c': [1, 2, -1], 'd': [1, -2, 1], 'e': [-1, 1, 1], 'f': [1, -2, 2], 'g': [-2, 1, 2], 'h': [-2, -1, 2], 'i': [-1, -1, 1], 'j': [2, 1, 2], 'k': [2, -1, 2], '...
ap """ o = [] e = [] for c in s: if c == ' ': c = 'char_empty' elif c == '.': c = 'char_eol' if c in m: o += m[c] else: e.append(c) if len(e) > 0: return {'e': True, 'l': e} else: return {'e': False, 'l': o} def addBaseLines(a): """ a = array to add baseline...
f ((p - 1) == int(c) or (p) == int(c) or (p + 1) == int(c)) and (p != 0) and (c != 0): o.append(0) p = int(c) o.append(int(c)) return o def main(prefix = False, string = '', suffix = False): print 'Input:' print 'var_prefix: ' + str(prefix) print 'var_string: ' + str(string) print 'var_suffix...
from tgbot import plugintest from plugin_examples.guess import GuessPlugin class GuessPluginTest(plugintest.PluginTestCase): def setUp(self): self.plugin = GuessPlugin() self.bot = self.fake_bot('', plugins=[self.plugin]) def test_play(self): self.receive_message('/guess_start') ...
at = { 'id': -1, 'type': 'group', 'title': 'Test' } self.receive_message('/guess_start', chat=chat) self.assertReplied("I'm going to think of a number between 0 and 9 and you have to guess it! What's your guess?") self.assertIsNotNone(self.plugin.read_...
self.assertIsNone(self.plugin.read_data(-1))
""" Compatibility module. This module contains duplicated code from Python itself or 3rd party extensions, which may
be included for the following reasons: * compatibility * we may only need a small
subset of the copied library/module """ import _inspect import py3k from _inspect import getargspec, formatargspec from py3k import * __all__ = [] __all__.extend(_inspect.__all__) __all__.extend(py3k.__all__)
# -*- coding: utf-8 -*- import hook import bnetprotocol from misc import * from config import config #settings = config[__name__.split('.')[-1]] def message_received(bn, d): if d.event == bnetprotocol.EID_TALK: msg_list = str(d.message).split(' ', 1) try: command, payload = msg_list except ValueError: ...
'''if str(d.message).split(' ')[0] == settings['trigger'] + 'join':''' bn.send_packet(bnetprotocol.SEND_SID_CHATCOMMAND('/join %s' % (payload))) def install(): hook.register('after-hand
le_sid_chatevent', message_received) def uninstall(): hook.unregister('after-handle_sid_chatevent', message_received)
#!/usr/bin/python # -*- coding: utf-8 -*- # thumbor imaging service # https://github.com/thumbor/thumbor/wiki # L
icensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2011 globo.com thumbor@googlegroups.com from preggy import expect from tornado.testing import gen_test from tests.base import TestCase from thumbor.config import Config from thumbor.importer import Importer class BaseMax...
t_fixture_path(self, name): return "./tests/fixtures/%s" % name def get_config(self): return Config.load(self.get_fixture_path("max_age_conf.py")) def get_importer(self): importer = Importer(self.config) importer.import_modules() return importer class MaxAgeFilterTest...
# -*- coding: utf-8 -*- # # Copyright 2014-2021 BigML # # 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 ...
ither express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Predicates structure for the BigML local AnomalyTree This module defines an auxiliary Predicates structure that is used in the AnomalyTree
to save the node's predicates info. """ from bigml.predicate import Predicate class Predicates(): """A list of predicates to be evaluated in an anomaly tree's node. """ def __init__(self, predicates_list): self.predicates = [] for predicate in predicates_list: if predicate is ...
se queryset used only in admin. Return all the users who have completed their profile registration. """ if not self.request.user.is_staff: return UserProfile.objects.none() qs = UserProfile.objects.complete() self.q_base_filter = (Q(full_name__icontains=self.q) ...
ership.MEMBER).distinct() .values_list('userprofile__pk', flat=True) ) query = Q(pk__in=staff_ids) | Q(pk__in=nda_members_ids) qs = UserProfile.objects.filter(query).distinct() if self.q: qs = qs.filter(Q(full
_name__icontains=self.q) | Q(user__email__icontains=self.q) | Q(user__username__icontains=self.q)) return qs class NDAGroupInvitationAutocomplete(StaffProfilesAutocomplete): def get_queryset(self): staff_qs = super(NDAGroupInvitationAutocomple...
# Daniel Fernandez Rodriguez <danielfr@cern.ch> from argparse import ArgumentParser from collections import defaultdict from requests_kerberos import HTTPKerberosAuth import json import requests import subprocess import logging import sys class PuppetDBNodes(object): def __init__(self, args): for k, v ...
file.write(" "*4 + "username: root" + '\n') for fact in factlist:
if data[node].has_key(fact): file.write(" "*4 + fact + ": " + data[node][fact] + '\n') logging.info("Node list saved successfully") else: logging.error("Fact list empty. Check PuppetDB connection params") def run(self): self.negociate_krb_ticke...
from django.contrib import admin from core.models import Language # Register your models here. cl
ass LanguageAdmin(admin.ModelAdmin): model = Language fieldsets = [ ('', {'fields': ['name', 'locale']}) ] list_display = ['name', 'locale'] search_fields = ['name', 'locale'] orderin
g = ('name',) admin.site.register(Language, LanguageAdmin)
from csacompendium.research.models import ExperimentUnit from csacompendium.utils.pagination import APILimitOffsetPagination from csacompendium.utils.permissions import IsOwnerOrReadOnly from csacompendium.utils.viewsutils import DetailViewUpdateDelete, CreateAPIViewHook from rest_framework.filters import DjangoFilter...
type: Object """ experiment_unit_serializer = experiment_unit_serializers() class ExperimentUnitCreateAPIView(CreateAPIViewHook): """ Creates a single record.
""" queryset = ExperimentUnit.objects.all() serializer_class = experiment_unit_serializer['ExperimentUnitDetailSerializer'] permission_classes = [IsAuthenticated] class ExperimentUnitListAPIView(ListAPIView): """ API list view. Gets all records API. """ ...
#!/usr/bin
/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "game_server.settings") from django.core.management import execute_from_command_line execute_fro
m_command_line(sys.argv)
#! /usr/bin/env python from P
yFoam.Applications.ChangePython import changePython change
Python("pvpython","PVSnapshot",options=["--mesa"])
# Licensed to the StackStorm, Inc ('StackStorm') 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 th...
iting, 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 unde
r the License. import bson import mock from st2common.models.db.rule_enforcement import RuleEnforcementDB from st2common.persistence.rule_enforcement import RuleEnforcement from st2common.transport.publishers import PoolPublisher from st2common.exceptions.db import StackStormDBObjectNotFoundError from st2tests import...
ee the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Authors: Jan Safranek <jsafrane@red...
ing['NoSinglePointOfFailure']) self.assertEqual( lv['NoSingl
ePointOfFailure'], vg_setting['NoSinglePointOfFailure']) self.assertEqual( lv['DataRedundancy'], lv_setting['DataRedundancyGoal']) self.assertEqual( lv['DataRedundancy'], vg_setting['DataRedundancyGoal']) self.assert...
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding: utf-8 -*- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8 # # Convolve MTSS rotamers with MD trajectory. # Copyright (c) 2011-2017 Philip Fowler and AUTHORS # Published under the GNU Public Licence, version 2 (or higher) # # Includ...
:
*name* name of the library (must exist in the registry of libraries, :data:`LIBRARIES`) """ self.name = name self.lib = {} try: self.lib.update(LIBRARIES[name]) # make a copy except KeyError: raise ValueError("No rotamer library wit...
#! /usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of cpe package. This module of is an implementation of name matching algorithm in accordance with version 2.2 of CPE (Common Platform Enumeration) specification. Copyright (C) 2013 Alejandro Galindo García, Roberto Abdelkader Martínez Pérez This ...
############ #: Version of CPE set VERSION = "2.2" #################### # OBJECT METHODS # ###################
# def append(self, cpe): """ Adds a CPE Name to the set if not already. :param CPE cpe: CPE Name to store in set :returns: None :exception: ValueError - invalid version of CPE Name TEST: >>> from .cpeset2_2 import CPESet2_2 >>> from .cpe2_2 import...
## begin license ## # # "Meresco Components" are components to build searchengines, repositories # and archives, based on "Meresco Core". # # Copyright (C) 2007-2009 SURF Foundation. http://www.surf.nl # Copyright (C) 2007 SURFnet. http://www.surfnet.nl # Copyright (C) 2007-2010 Seek You Too (CQ2) http://www.cq2.nl # C...
iginalPath = kwargs.pop('originalPath', path) yield self.all.handleRequest(path=self._rename(path), originalPath=originalPath, *args, **kwargs)
#coding=utf8 import thread, time, sys, os, platform try: import termios, tty termios.tcgetattr, termios.tcsetattr import threading OS = 'Linux' except (ImportError, AttributeError): try: import msvcrt OS = 'Windows' except ImportError: raise Exception('Mac i...
Buff:
sys.stdout.write(i) sys.stdout.flush() def getch(self): c = getch() return c if c != '\r' else '\n' def get_history_command(self, direction): if direction == 'UP': if self.historyCmd < CMD_HISTORY - 1 and self.historyCmd < len(self.cmdBuff) - 1: self.historyCm...
# -*- coding: utf-8 -*- ############################################################################## # # Daniel Reis, 2013 # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, eith...
cker is als
o installed. Please refer to the ``project_baseuser`` module for more details. """, 'author': "Daniel Reis,Odoo Community Association (OCA)", 'license': 'AGPL-3', 'depends': [ 'project_issue', 'project_baseuser', ], 'data': [ 'security/ir.model.access.csv', 'security/...
from argparse import ArgumentParser from typing import Any from zerver.lib.actions import create_stream_if_needed from zerver.lib.management import ZulipBaseCommand class Command(ZulipBaseCommand): help = """Create a stream, and subscribe all active users (excluding bots). This should be used for
TESTING only, unless you understand the limitations of the command.""" def add_arguments(self, parser: ArgumentParser) -> None: self.add_realm_args(parser, True, "realm in which to create the stream") parser.add_argument('stream_name', metavar='<stream name>', type=str, ...
te') def handle(self, *args: Any, **options: str) -> None: realm = self.get_realm(options) assert realm is not None # Should be ensured by parser stream_name = options['stream_name'] create_stream_if_needed(realm, stream_name)
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IM
PROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Building() result.template = "object/building/poi/shared_lok_nymshenchman_medium.iff" result.attribute_template_id = -1 result
.stfName("poi_n","base_poi_building") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result