prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
#!/usr/bin/python #coding=utf-
8 ''' @author: sheng @contact: sinotradition@gmail.com @copyright: License according to the project license. ''' NAME='guimao33' SPELL='guǐmǎo' CN='癸卯' SEQ='40' if
__name__=='__main__': pass
from .Commerce import Comm
erce from .Transaction im
port Transaction
import wpilib import math class SharpIR2Y0A02: ''' Sharp IR sensor GP2Y0A02YK0F Long distance sensor: 20cm to 150cm Output is in centimeters Distance can be calculated using 62.28*x ^ -1.092 ''' def __init__(self,num): self.distance = ...
def __init__(self,num): self.distance = wpilib.AnalogInput(num) def getDistance(self): '''Returns distance in centimeters''' # Don't allow zero/negative values v = max(self.distance.getVoltage(), 0.00001) d = 12.84*math.pow(v, -0.9824) # Constr...
t__(self, longDist, longOff, shortDist, shortOff): self.longDistance = longDist self.shortDistance = shortDist self.longOff = longOff self.shortOff = shortOff def getDistance(self): long = self.longDistance.getDistance() short = self.shortDistance.ge...
"""Detect zmq version""" # # Copyright (C) PyZMQ Developers # # This file is part of pyzmq, copied and adapted from h5py. # h5py source used under the New BSD license # # h5py: <http://code.google.com/p/h5py/> # # Distributed under the terms of the New BSD License. The full license is in # the file COPYING.BSD, ...
""do a test build of libcapnp""" tmp_dir = tempfile.mkdtemp() # line() # info("Configu
re: Autodetecting Cap'n Proto settings...") # info(" Custom Cap'n Proto dir: %s" % prefix) try: detected = detect_version(tmp_dir, None, **compiler_attrs) finally: erase_dir(tmp_dir) # info(" Cap'n Proto version detected: %s" % v_str(detected['vers'])) return detected ...
import torch import torchvision.transforms as transforms import torch.utils.data as data import os import json import pickle import argparse from PIL import Image import numpy as np from utils import Vocabulary class CocoDataset(data.Dataset): def __init__(self, root, anns, vocab, mode='train',transform=None): ...
shuffle=shuffle, num_workers=num_workers, collate_fn=collate_fn) return data_loader if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--root_dir', type=str, default='/h...
o.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), ...
'id': ('django.db.models.fields.AutoField', [], {'p
rimary_key': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'order': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}), 'slug': ('django...
# -*- encoding: utf-8 -*- import mock import os from shutil import rmtree from tempfile import mkdtemp from django.test import TestCase from django.conf import settings from django.core.management import call_command from django.core.management.base import CommandError from django.test.utils import override_settings ...
ntParserTests(TestCase): def setUp(self):
self.filetype = FileType.objects.create(type=u"Photographie") def tearDown(self): rmtree(settings.MEDIA_ROOT) @mock.patch('requests.get') def test_attachment(self, mocked): mocked.return_value.status_code = 200 mocked.return_value.content = '' filename = os.path.join(os.p...
serial.Serial = lambda *arg: Dummy() global Driver Driver = lambda *arg: Dummy() global Sup800fTelemetry Sup800fTelemetry = lambda *arg: Dummy() global switch_to_nmea_mode switch_to_nmea_mode = lambda *arg: Dummy() # Ignore messages drop = lambda message: None drop2 = lambda: consu...
g better than sleeps to work around race # conditions logger.info('Creating threads') sup800f_telemetry = Sup800fTelemetry(serial_) time.sleep(0.5) command = Command(telemetry, DRIVER, waypoint_ge
nerator) time.sleep(0.5) button = Button() port = int(get_configuration('PORT', 8080)) address = get_configuration('ADDRESS', '0.0.0.0') cherry_py_server = CherryPyServer( port, address, telemetry, waypoint_generator ) time.sleep(0.5) global THREADS T...
"Add a movie to Plex." import sys from pathlib import Path from argparse import ArgumentParser from tkinter import filedialog, messagebox, simpledialog, Tk, Frame, Label from tkinter.ttk import Combobox, Button class FeaturettePicker: FEATURETTES = { "Behind the Scenes": "behindthescenes", "Delet...
.askstring("Movie Name", f"Selected: {src}.\n\nName of movie (and year in parens):", initialvalue=src.name, parent=tkr) or sys.exit() dst = root/'media-library'/'movies'/outname ext = simpledialog\ .askstring("Extension", "File extens...
ere by prepending " "it to the extension, e.g. ` - [OldVersion].mp4`):", initialvalue=src.suffix, parent=tkr) out = dst/(outname+ext) files = [] while messagebox.askyesno("Special Features", "Add more files as special features?"): for f i...
#!/usr/bin/env python3 import rainbow import hashlib import string import time import random """SHA-256 hash function Precondition: Input plaintext as string Postcondition: Returns hash as string """ def sha256(plaintext): return hashlib.sha256(bytes(plaintext, 'utf-8')).hexdigest() """Returns a reduction function...
ef result(hash, col): plaintextKey = (int(hash[:9], 16) ^ col) % (26 ** n) plaintext = "" for _ in range(n): plaintext += string.ascii_lowercase[plaintextKey % 26] plaintextKey //= 26 return plaintext return result """Returns a function which generates a random n-di
git lowercase password """ def gen_lower(n): def result(): password = "" for _ in range(n): password += random.choice(string.ascii_lowercase) return password return result """Precondition: Input a function which generates a random password, or input no arguments to generate a random password Postcondition: ...
#!/usr/bin/env python3 # NOTE: this example requires PyAudio because it uses the Microphone class import speech_recognition as sr # this is called from the background thread def callback(recognizer, audio): # received audio data, now we'll recognize it using Google Speech Recognition try: # for testi...
function requests that
the background listener stop listening while True: time.sleep(0.1)
WHERE id = ?", (tenant_uuid, ) ) result = cur.fetchone() except sqlite3.Error as e: logging.error("Error %s when querying from tenants table for tenant_id %s", e, tenant_uuid) return str(e), None, None if resul...
result = cur.fetchall() except sqlite3.Error as e: logging.error("Error %s when checking whether table privileges exists or not", e) return str(e), False if not result: error_info = "table privileges does not exist" logging.error(error_info) return error_info, False ...
hall() except sqlite3.Error as e: logging.error("Error %s when checking whether table volumes exists or not", e) return str(e), False if not result: error_info = "table volumes does not exist" logging.error(error_info) return error_info, False return None, True def...
import unittest from fractions import Fraction as F from abcesac.music import * class KeyTestCase(unittest.TestCase): def test_get_notes(self): got = Key('C').get_notes() want = ['C','D','E','F','G','A','B'] self.assertEquals(got, want) got = Key('D').get_notes() want = [...
(got, want) got = Key('C').mode_scale('minor') want = ['C', 'D', 'Eb', 'F', 'G', 'Ab', 'Bb'] self.assertEquals(got, want) got = Key('E').mode_scale('minor') want = [
'E', 'F#', 'G', 'A', 'B', 'C', 'D'] self.assertEquals(got, want) got = Key('C').mode_scale('dorian') want = ['C', 'D', 'Eb', 'F', 'G', 'A', 'Bb'] self.assertEquals(got, want) got = Key('C').mode_scale('phrygian') want = ['C', 'Db', 'Eb', 'F', 'G', 'Ab', 'Bb'] se...
"Legend creation helper function.""" proxies = [] descriptions = [] for label, color in items: if label == 'column-index': continue if name == 'Data Type': line = mpl.sns.mpl.lines.Line2D([], [], linestyle='none'...
name = name[1:] if name.startswith('_') else name if isinstance(data, Field): # Fields are handled separately fname = 'FIELD{}_'.format(fc) + name + '/' store[fname + 'data'] = pd.DataFrame(data) for i, fi
eld in enumerate(data.field_values): ffname = fname + 'values' + str(i) if isinstance(field, pd.Series): store[ffname] = pd.Series(field) else: store[ffname] = pd.DataFrame(field) ...
ROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._confi...
error_map.update(kwargs.pop('error_map', {})) api_version = "2019-07-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_
name", resource_group_name, 'str'), 'serviceEndpointPolicyName': self._serialize.url("service_endpoint_policy_name", service_endpoint_policy_name, 'str'), 'serviceEndpointPolicyDefinitionName': self._serialize.url("service_endpoint_policy_definition_name", service_endpoint_policy_definition_name...
from contextlib import ContextDecorator from unittest import mock import httpx import pytest from util.working_directory import working_directory from .http import pull_http class MockedHttpxStreamResponse(ContextDecorator): """ VCR does not like recording HTTPX stream requests so mock it. """ def...
sponse) def test_extension_from_mimetype(tempdir): with working_directory(tempdir.pa
th): files = pull_http({"url": "https://httpbin.org/get"}) assert files["get.json"]["mimetype"] == "application/json" files = pull_http({"url": "https://httpbin.org/image/png"}, path="image") assert files["image.png"]["mimetype"] == "image/png" files = pull_http({"url": "https:...
#!/usr/bin/env python3 # https://docs.python.org/3/library/modulefinder.html from modulefinder import ModuleFinder finder = Mo
duleFinder() finder.run_script('graph1.py') print('Loaded modules:') for name, mod in finder.modules.items(): print('%s: '
% name, end='') print(','.join(list(mod.globalnames.keys())[:3])) print('-'*50) print('Modules not imported:') print('\n'.join(finder.badmodules.keys()))
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (c) 2013 Camptocamp SA (http://www.camptocamp.com) # @author Nicolas Bessi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Genera...
no more now ctx['date'] = line.ml_maturity_date amount = currency_obj.compute( cr, uid, lin
e.currency.id, statement.currency.id, line.amount_currency, context=ctx) if not line.move_line_id.id: continue context.update({'move_line_ids': [line.move_line_id.id]}) vals = self._prepare_statement_line_vals( cr, uid, line, -amount, s...
from pygame.sprite import DirtySprite from pygame import draw class BaseWidget(DirtySprite): """clase base para todos los widgets""" focusable = True # si no es focusable, no se le llaman focusin y focusout # (por ejemplo, un contenedor, una etiqueta de texto) hasFocus = False # indi...
self.hasFocus = False def on_mouse_down(self, mousedata): pass def on_mouse_up(self, mousedata): pass
def on_mouse_over(self): pass def on_mouse_in(self): self.hasMouseOver = True def on_mouse_out(self): self.hasMouseOver = False def on_key_down(self, keydata): pass def on_key_up(self, keydata): pass def on_destruction(self): # e...
from dj
ango.conf import settings from django.http import HttpResponse def index(request): return HttpResponse("Hello")
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. import decimal import os import time import pytest from django.cor...
mat_money(order.taxful_total_price))) url = reverse("shuup_admin:order.create-full-refund", kwargs={"pk
": order.pk}) click_element(browser, "a[href='%s']" % url) wait_until_condition(browser, lambda x: x.is_text_present("Refund Amount: %s" % format_money(order.taxful_total_price))) click_element(browser, "#create-full-refund") wait_until_appeared(browser, "#order_details") _check_create_refund_link(b...
"""Source code used for the talk: http://www.slideshare.net/MarcGarcia11/cart-not-only-classification-and-regression-trees """ # data import pandas as pd data = {'age': [38, 49, 27, 19, 54, 29, 19, 42, 34, 64, 19, 62, 27, 77, 55, 41, 56, 32, 59, 35], 'distance': [6169.98, 7598.87, 3276.07, 15...
ft_entropy + right_weight * right_entropy if split_entropy < best_entropy: best_split = (feature, value) best_entropy = split_entropy return best_split # train_decision_tree def train_decision_tree(x, y): feature, value = get_best_split(x, y) x_left, y_left =...
< value], y[x[feature] < value] if len(y_left.unique()) > 1: left_node = train_decision_tree(x_left, y_left) else: left_node = None x_right, y_right = x[x[feature] >= value], y[x[feature] >= value] if len(y_right.unique()) > 1: right_node = train_decision_tree(x_right, y_right)...
# Copyright 1999-2013 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 from __future__ import unicode_literals import formatter import io import sys import time import portage from portage import os from portage import _encodings from portage import _unicode_encode from portage.ou...
et=False, xterm_titles=True): object.__setattr__(self, "quiet", quiet) object.
__setattr__(self, "xterm_titles", xterm_titles) object.__setattr__(self, "maxval", 0) object.__setattr__(self, "merges", 0) object.__setattr__(self, "_changed", False) object.__setattr__(self, "_displayed", False) object.__setattr__(self, "_last_display_time", 0) self.reset() isatty = os.environ.get('TE...
#!/usr/bin/env python3 from mutagen.mp3 import MP3 import sys if len(sys.argv) < 2: print('error: didn\'t pass enough arguments') print('usage: ./bitrate.py
<file name>') print('usage: find the bitrate of an mp3 file') exit(1) f = MP3(sys.argv[1]) print('bitrate: %s' % (f.
info.bitrate / 1000))
# -*- coding: utf-8 -*- from __future__ i
mport unicode_literals from django.db import models, migrations class Migration(migrations.M
igration): dependencies = [ ] operations = [ migrations.CreateModel( name='Item', fields=[ ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')), ], options={ }, base...
it_matrices([(0,8),(8,8),(8,0),(0,0)]) # set up accelometer accel.init(1) # notify of progress print("P60") sys.stdout.flush() # set up buttons A = 4 B = 17 UP = 25 DOWN = 24 LEFT = 23 RIGHT = 18 START = 27 SELECT = 22 # accelometer threshold THRESHOLD = 3 class State(object): PLAYING, IDLE, SCORE, E...
M) def button_handler(channel): global state global field if channel in [START, SELECT]: state = State.EXIT elif state in [State.IDLE,
State.SCORE] and channel in [A, B]: # Reset field and player to start a new game player = Player(accel=(channel == A)) field = None field = Field(player) field.new_apple() # add the first apple state = State.PLAYING # elif state == State.PLAYING and (not field.player...
import sqlite3 as sql from flask.json import jsonify from flask import current_app def total_entries(): with sql.connect("names.db") as con: cur = con.cursor() entries = cur.execute("SELECT count(*) FROM names").fetchone() con.commit() return '{}\n'.format('{}\n'.format(entries)[1:-3]) ...
name,year,gender,count) ) con.commit() new_id = cur.lastrowid return str(new_id) except Exception as e: print e return 'The baby is already present in the DataBase.' def fir
st_and_last(name): with sql.connect("names.db") as con: cur = con.cursor() last = cur.execute("select MAX(year) from names where name='{}';".format(name) ).fetchone() first = cur.execute("select MIN(year) from names where name='{}';".format(name) ).fetchone() con.commit() return ...
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
IS, 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. """ DAG designed to test a PythonOperator that calls a functool.partial """ import functools import logging from datetime import dateti...
import DAG from airflow.operators.python import PythonOperator DEFAULT_DATE = datetime(2016, 1, 1) default_args = dict(start_date=DEFAULT_DATE, owner='airflow') class CallableClass: """ Class that is callable. """ def __call__(self): """A __call__ method """ def a_function(_, __): """...
readout_classifier class single_shot_readout: """ Single shot readout class Args: adc (Instrument): a device that measures a complex vector for each readout trigger (an ADC) prepare_seqs (list of pulses.sequence): a dict of sequences of control pulses. The keys are use for state identification. ro_seq (puls...
[self.adc_measurement_name] for _class in self.readout_classifier.class_list} features = {'feature'+str(_class):self.adc.get_dtype()[self.adc_measurement_name] for _class in self.readout_classifier.class_list} dtypes.update(avg_samples) dtypes.update(features) if self.measure_hists:
dtypes['hists'] = float dtypes['proba_points'] = float if self.measure_feature_w_threshold: dtypes['feature'] = np.complex dtypes['threshold'] = float return dtypes # def dump_samples(self, name): # from .save_pkl import save_pkl # header = {'type':'Readout classification X', 'name':name} # measur...
tce_sort_4kg_4321.c') os.system('ar -r '+lib_name+' tce_sort_4kg_4321.o') for transpose_order in transpose_list: dummy = 0 A = transpose_order[0] B = transpose_order[1] C = transpose_order[2] D = transpose_order[3] driver_name = 'transpose_'+A+B+C+D print driver_name source_name = driv...
source_file.write(' Tstart=0.0\n') source_file.write(' Tfinish=0.0\n') source_file.write('
CALL CPU_TIME(Tstart)\n') source_file.write(' DO '+str(100+dummy)+' i = 1, '+count+'\n') source_file.write(' CALL '+subroutine_name+'(before, after_jeff,\n') source_file.write(' & aSize(1), aSize(2), aSize(3), aSize(4),\n') source_file.write(' ...
import unittest from models import heliosat import numpy as np from netcdf import netcdf as nc from datetime import datetime import os import glob class TestPerformance(unittest.TestCase): def setUp(self): # os.system('rm -rf static.nc temporal_cache products') os.system('rm -rf temporal_cache pr...
) def tearDown(self): os.system('rm -rf mock_data') def test_main(self): begin = datetime.now() heliosat.workwith('mock_data/goes13.2015.*.BAND_01.nc', 32) end = datetime.now() elapsed = (end - begin).total_seconds() first, last = min(self.files), max(self.files...
o_dt = heliosat.to_datetime processed = (to_dt(last) - to_dt(first)).total_seconds() processed_days = processed / 3600. / 24 scale_shapes = (2245. / 86) * (3515. / 180) * (30. / processed_days) estimated = elapsed * scale_shapes / 3600. print "Scaling total time to %.2f hours." %...
import datetime from typing import Optional, TypedDict from backend.commo
n.sitevars.sitevar import Sitevar class WebConfig(TypedDict): travis_job: str tbaClient_endpoints_sha: str cu
rrent_commit: str deploy_time: str endpoints_sha: str commit_time: str class AndroidConfig(TypedDict): min_app_version: int latest_app_version: int class IOSConfig(TypedDict): min_app_version: int latest_app_version: int class ContentType(TypedDict): current_season: int max_sea...
from .max import max from pyramda.priva
te.asserts import assert_equal
def max_test(): assert_equal(max([1, 3, 4, 2]), 4)
""" Script for selecting a good number of basis functions. Too many or too few basis functions will introduce numerical error. True solution must be known. Run the program several times, varying the value of the -N option. There may be a way to improve on this brute force method. """ # To allow __main__ in subdirecto...
lem.R) problem.boundary = boundary # Options to pass to the solver options = { 'problem': problem, 'N': args.N, 'scheme_order': 4, } meta_options = {
'procedure_name': 'optimize_basis', } io_util.print_options(options, meta_options) def my_print(t): print('n_circle={} n_radius={} error={}'.format(*t)) def worker(t): options['n_circle'] = t[0] options['n_radius'] = t[1] my_solver = ps.ps.PizzaSolver(options) result = my_solver.run() ...
from .model import SV
C
pe).get('ping_rta_warning'): rules[device_type+"_rta"].update({"Severity2":["warning",{'name': device_type+"_rta_warning", 'operator': 'greater_than', 'value': float(ping_rule_dict.get(device_type).get('ping_rta_warning')) or ''}]}) rules[device_type+"_rta"].update({"Severity3":["up",{'name': device_type+"_rta_up...
[False,False], "service":service, "arraylocations":0 } print kpi_rule_dict return kpi_rule_dict def generate_service_rules(): service_threshold_query = Variable.get('q_get_thresholds') #creating Severity Rules data = execute_query(service_threshol
d_query) rules_dict = createDict(data) Variable.set("rules",str(rules_dict)) #can only be done if generate_service_rules is completed and there is a rule Variable in Airflow Variables def generate_kpi_rules(): service_rules = eval(Variable.get('rules')) processed_kpi_rules = process_kpi_rules(service_rules) #Var...
#!/Users/abhisheksamdaria/GitHub/pstHealth/venv/bin/python2.7 from __future__ import print_function import base64 import os import sys if __name__ == "__main__": # create font data chunk for
embedding font = "Tests/images/courB08" print(" f._load_pilfont_data(") print(" # %s" % os.path.basename(font)) print(" BytesIO(base64.decodestring(b'''") base64.encode(open(font + ".pil",
"rb"), sys.stdout) print("''')), Image.open(BytesIO(base64.decodestring(b'''") base64.encode(open(font + ".pbm", "rb"), sys.stdout) print("'''))))") # End of file
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Event.photo' db.add_column('events_event', 'photo', self.gf('django.db...
, [], {}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '150
'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'location_set'", 'to': "orm['auth.User']"}) }, 'participant.category': { 'Meta': {'object_name': 'Category'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), ...
import settings import mysql.connector from domain.domain import Article from domain.domain import Project from domain.domain import User from domain.domain import Tag import service.database as db # 文章管理 class ArticleService: # 查询最近发表的文章 def query_most_published_article(self): conn = d...
uthor_id=u.id", " where a.id=%(article_id)s"]) cursor = conn.cursor() cursor.execute(sql, {"article_id": article_id}) article = None for (id, author_id, author_na
me, title, content, create_time, publish_time, last_update_time) in cursor: if (not article): article = Article() article.id = id article.title = title article.content = content article.create_time = create_time article.publi...
.post(URL_CMS_PLUGIN_ADD, plugin_data) plugin_id = int(response.content) self.assertEquals(response.status_code, 200) self.assertEquals(int(response.content), CMSPlugin.objects.all()[0].pk) # there should be only 1 plugin self.assertEquals(CMSPlugin.objects.all().count(), 1) ...
# add a plugin plugin_data = { 'plugin_type': "TextPlugin", 'language': settings.LANGUAGES[0][0], 'placeholder': page.placeholders.get(slot="body").pk, } response = self.client.post(URL_CMS_PLUGIN_ADD, plugin_data) self.assertEquals(response.status...
self.assertEquals(CMSPlugin.objects.all().count(), 1) ph = Placeholder(slot="subplugin") ph.save() plugin_data = { 'plugin_type': "TextPlugin", 'language': settings.LANGUAGES[0][0], 'placeholder': ph.pk, 'parent': int(response.content) } ...
# 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 # d...
es)) def test_numa_topology_filter_fail_cpu(self): self.flags(cpu_allocation_ratio=1) instance_topology = objects.InstanceNUMATopology( cells=[objects.InstanceNUMACell(id=0, cpuset=set([1]), memory=512),
objects.InstanceNUMACell(id=1, cpuset=set([3, 4, 5]), memory=512)]) instance = fake_instance.fake_instance_obj(mock.sentinel.ctx) instance.numa_topology = instance_topology filter_properties = { 'request_spec': { 'instan...
#!/usr/bin/env python from os.path import dirname, join import plyer try: from setuptools import setup except ImportError: from distutils.core import setup curdir = dirname(__file__) packages = [ 'plyer', 'plyer.platforms', 'plyer.platforms.linux', 'plyer.platforms.android', 'plyer.platfo...
'mat@kivy.org', url='https://plyer.readthedocs.org/en/latest/', packages=packages, package_data={'': ['LICENSE', 'README.rst']}, package_dir={'plyer': 'plyer'}, include_package_data=True, license=open(join(curdir, 'LICENSE')).read(),
zip_safe=False, classifiers=( 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming ...
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # Description: File system resilience testing application # Author: Hubert Kario <hubert@kario.pl> # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # Copyright (c) 2015 Hubert Kario. All rights reserved. # # This ...
unpack(self.reques
t_fmt, data) magic, req_type, handle, data_from, data_length = result_tuple if magic != Magic.NBD_REQUEST_MAGIC: raise Error("Request magic invalid: {0}".format(magic)) if req_type != RequestType.NBD_CMD_WRITE: return NBDRequest(req_type, handle, data_from, data_length)...
ites must match the ID patterns" bad_changes.append(BadChange(status, path, content=msg)) continue # At levels above the suites, can only add directories if len(names) < self.LEN_ID: if status[0] != self.ST_ADDED: msg = ( ...
t = self._get_access_info( txn_info_map[sid] ) if self._verify_users( status, path, txn_owner, txn_access_list, bad_changes ): conti
nue reports = DefaultValidators().validate( txn_info_map[sid], load_meta_config( txn_info_map[sid], config_type=metomi.rose.INFO_CONFIG_NAME, ), ) if reports: ...
# encoding: utf-8 # Copyright 2012 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
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. from .Rackspace
import Rackspace as delegate_class
# From: https://gist.github.com/nathan-hoad/8966377 import os import asyncio import sys from asyncio.streams import StreamWriter, FlowControlMixin reader, writer = None, None @asyncio.coroutine def stdio(loop=None): if loop is None: loop = asyncio.get_event_loop() reader = asyncio.StreamReader() ...
) line = yield from
reader.readline() return line.decode('utf8').replace('\r', '').replace('\n', '')
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2016 OSGeo # # 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 ...
name__iexact=self.cleaned_data["title"]).count() > 0: if self.cleaned_data["title"] == self.instance.name: pass # same instance else: raise forms.ValidationError( _("A group already exists with that nam
e.")) return self.cleaned_data["title"] class Meta: model = GroupProfile exclude = ['group'] class GroupMemberForm(forms.Form): role = forms.ChoiceField(choices=[ ("member", "Member"), ("manager", "Manager"), ]) user_identifiers = forms.CharField( widge...
t_address, server): self.user = None self.host = client_address # Client's hostname / ip. self.realname = None # Client's real name self.nick = None # Client's currently registered nickname self.send_queue = [] # Messages to send to client (strings) ...
er for command: %s. ' 'Full line: %s' % (command, line)) raise IRCError.from_name('unknowncommand', '%s
:Unknown command' % command) response = handler(params) except AttributeError as e: log.error(_py2_compat.str(e)) raise except IRCError as e: response = ':%s %s %s' % (self.server.servername, e.code, e.value) log.error(response) except ...
import random import time import datetime from consts import * __all__ = ['gen_valid_id', 'gen_list_page', 'log'] def gen_valid_id(collection): def gen_id(): _id = '' for i in range(4): _id += random.choice('0123456789') return _id id =
gen_id() while collection.find_one({'id': id}): id = gen_id() return id def gen_list_page(collection, status, page=1): page = int(page) left = (page - 1) * 15 right = left + 15 all = collection.find({'status': status}).sort([('id', 1)]) max_page = int((all.count()-1) / 15) + 1 if...
max_page) selected = all[left:right] return header + '\n'.join([ '{id} {title} ({comment})'.format(**i) for i in selected]) def log(m): with open('log', 'a') as f: if m.type == 'text': exp=m.content elif m.type == 'image': exp=m.img elif m.type == 'link': exp=';'.join([m.t...
# --------------------
----------------------
----------------------------------- # # This file is the copyrighted property of Tableau Software and is protected # by registered patents and other applicable U.S. and international laws and # regulations. # # Unlicensed use of the contents of this file is prohibited. Please refer to # the NOTICES.txt file for further...
# Copyright (C) 2011 One Laptop Per Child # # 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 distribu...
g/ticket/1801 if not [i for i in text if i.isalnum()]: return self.make_pipeline('espeak name=espeak ! autoaudiosink') src = self._pipeline.get_by_na
me('espeak') src.props.text = text src.props.pitch = pitch src.props.rate = rate src.props.voice = voice_name src.props.track = 2 # track for marks self.restart_sound_device() def get_all_voices(self): all_voices = {} for voice in Gst.ElementFactor...
""" PyLEMS API module
. :author: Gautham Ganapathy :organization: LEMS (https://github.com/organizations/LEMS) """ from lems.model.fundamental import * from lems.model.structure import * from lems.model.dynamics import * from lems.model.simulation import * from lems.model.component import * from lems.model.model im
port Model
nts except (ConnectionError, HTTPError) as err : sleep_time = 2**(attempt - 1) verbose("Connection attempt " + str(attempt) + " failed. " "Sleeping for " + str(sleep_time) + " second(s).") time.sleep(sleep_time) attempt = attempt + 1 except (AttributeError, TypeError) : return None return Non...
ubmission (job_id, submission_id, subreddit_id, " \ "subreddit, title, author, url, permalink, thumbnail, name, selftext, " \ "over_18, is_self, created_utc, num_comments, ups, downs, score) VALUES " \ "(%s, %s, %s, %s, %s, %s,
%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) " values = [ job_id, submission.id, submission.subreddit_id, submission.subreddit.display_name, submission.title, submission.author.name, submission.url, submission.permalink, submission.thumbnail, submission.name, submission.selftext, submission....
from django.conf.urls import patterns, include, url from django.conf import settings from django.conf.urls.static import static from django.core.urlresolvers import reverse_lazy from django.views.generic import RedirectView from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r''...
/password/done/$', 'django.contrib.auth.views.password_reset_complete'), url(r'^$', 'api.views.home',name='home'), url(r'^signup/(?P<backend>[^/]+)/$', 'api.views.signup
', name='signup'), url(r'^signup/$' , RedirectView.as_view(url='/signup/username/')), url(r'^email-sent/', 'api.views.validation_sent'), url(r'^resumizr-login/(?P<backend>[^/]+)/$', 'api.views.username_login', name='username_login'), url(r'^login/$','api.views.login', name='login'), url(r'^log...
), scoped = False ) self.dragEndSignal().connect( Gaffer.WeakMethod( self.__dragEnd ), scoped = False ) self.keyPressSignal().connect( Gaffer.WeakMethod( self.__keyPress ), scoped = False ) self.__values = [] if isinstance( values, ( six.integer_types, float ) ) : self.__setValuesInternal( [ values ], self....
rnal( self.__values, self.ValueChangedReason.Invalid ) # reclamps the values to the range if necessary self._
qtWidget().update() def getRange( self ) : return self.__min, self.__max, self.__hardMin, self.__hardMax def indexRemovedSignal( self ) : signal = getattr( self, "_indexRemovedSignal", None ) if signal is None : signal = GafferUI.WidgetEventSignal() self._indexRemovedSignal = signal return signal ...
from unittest import TestCase from paramiko import SSHException from pyinfra.api import Config, State from pyinfra.api.connect import connect_all from pyinfra.api.exceptions import NoGroupError, NoHostError, PyinfraError from ..paramiko_util import PatchSSHTestCase from ..util import make_inventory class TestInven...
ata.some_data == 'hello' assert host.data.another_data == 'world' # Che
ck group data assert host.data.tuple_group_data == 'word' def test_host_and_group_errors(self): inventory = make_inventory() with self.assertRaises(NoHostError): inventory.get_host('i-dont-exist') with self.assertRaises(NoGroupError): inventory.get_group('i...
""" Copyright 2016 Rasmus Larsen This software may be modified and distributed under the terms of the MIT license. See the LICENSE.txt file for details. """ import sys import time from sacred import Experiment from core.ALEEmulator import ALEEmulator from dqn.Agent import Agent from dqn.DoubleDQN import DoubleDQN e...
conv_units = [32, 64, 64] filter_sizes = [8, 4, 3] strides = [4, 2, 1] state_frames = 4 fc_layers = 1 fc_units = [512] in_width = 84 in_height = 84 discount = 0.99 device = '/gpu:0' lr = 0.00025 opt_decay = 0.95 momentum = 0.0 opt_eps = 0.01 target_sync = 1e4 ...
_freq = 50 @ex.config def emu_config(): rom_path = '../ale-git/roms/' rom_name = 'breakout' display_screen = True frame_skip = 4 repeat_prob = 0.0 color_avg = True random_seed = 42 random_start = 30 @ex.config def agent_config(): hist_size = 1e5 eps = 1.0 eps_min = 0.1 ...
import gtk from plugin_base.find_extension import FindExtension class SizeFindFiles(FindExtension): """Size extension for find files tool""" def __init__(self, parent): FindExtension.__init__(self, parent) # create container table = gtk.Table(2, 4, False) table.set_border_wi...
.connect('value-changed', self._max_value_changed) self._entry_min.connect('value-changed', self._min_value_changed) self._entry_max.connect('activate', self._parent.find_files) self._entry
_min.connect('activate', lambda entry: self._entry_max.grab_focus()) # pack interface table.attach(label, 0, 3, 0, 1, xoptions=gtk.FILL) table.attach(label_min, 0, 1, 1, 2, xoptions=gtk.FILL) table.attach(self._entry_min, 1, 2, 1, 2, xoptions=gtk.FILL) table.attach(label_min_un...
import yaml from os import makedirs from os.path import join,dirname,realpath,isdir script_dir = dirname(realpath(__file__)) default_yml_filepath = join(script_dir,'defa
ults.yml') defaults = { "output_dir": 'output', "header_img_dir": 'imgs/headers/', "scaled_img_dir": 'imgs/scaled/', "original_img_dir": 'imgs/original/', "header_img_url": 'imgs/headers/', "scaled_img_url": 'imgs/scaled/', "original_img_url": 'imgs/original/', "template_dir": join(s...
se.yml", "static_dir": join(script_dir,'static'), "copyright_msg": None, "extra_links": [], "import_to_discourse": False, "strapline": None, } config = dict() def getConfig(): if not config: raise RuntimeError('config not loaded yet') return config def loadConfig(yml_filepath)...
# -*- encoding: utf-8 -*- ################################################################################ # # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # ...
dicament_template_history(self, medicament_template_id, state, notes): if self.active_history: values = { 'medicam
ent_template_id': medicament_template_id, 'state': state, 'notes': notes, } self.pool.get('clv_medicament.template.history').create(self._cr, self._uid, values) @api.multi def write(self, values): if (not 'state' in values) and (not 'date' in val...
import my
test print '----This is func1----' mytest.world.func1() print '----This is func2----' mytest.simple.func2() print '----This is f
unc3----' mytest.whatever.func3() print '----This is myobj using MyClass----' myobj = mytest.MyClass('nick', 'florida') myobj.hello()
# Copyright 2014 Cirruspath, 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 wri...
import json import os from pom.triggers.poster import Poster from pom.triggers.github import GitHub from pom.triggers.salesforce import Salesforce from pom.clients.oauth2 import OAuth2 import requests from requests.exceptions import ConnectionError import sys from tornado.wsgi import WSGIContainer from tornado.httpserv...
mport IOLoop import urllib from uuid import uuid4 import yaml app = Flask(__name__) # # Read in all the known oauth providers. # CONFIG_DIR = os.path.dirname(os.path.dirname(__file__)) + "/config" providers = {} for f in os.listdir(CONFIG_DIR + "/providers"): n, e = os.path.splitext(f) print "Source: " + n...
import numpy as np import pandas as pd from plotnine import (ggplot, aes, geom_area, geom_ribbon, facet_wrap, scale_x_continuous, theme) n = 4 # No. of ribbions in a vertical stack m = 100 # Points width = 2*np.pi # width of each ribbon x = np.linspace(0, width, m) df = pd....
tor(z)')) + geom_area() +
geom_area(aes('x+width', alpha='z')) + geom_area(aes('x+2*width', linetype='factor(z)'), color='black', fill=None, size=2) + geom_area(aes('x+3*width', color='z'), fill=None, size=2) + geom_area(aes('x+4*width', fill='factor(z)')) + geom_area(a...
import os import amo.search from .models import Reindexing from django.core.management.base import CommandError # shortcut functions is_reindexing_amo = Reindexing.objects.is_reindexing_amo flag_reindexing_amo = Reindexing.objects.flag_reindexing_amo unflag_reindexing_amo = Reindexing.objects.unflag_reindexing_amo g...
cts(ids, model, search, index=None, transforms=None): if index is None: index = model._get_index() indices = Reindexing.objects.get_indices(index) if transform
s is None: transforms = [] qs = model.objects.no_cache().filter(id__in=ids) for t in transforms: qs = qs.transform(t) for ob in qs: data = search.extract(ob) for index in indices: model.index(data, bulk=True, id=ob.id, index=index) amo.search.get_es().flus...
# -*- coding: utf-8 -*- from
__future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('shows', '0001_initial'),
] operations = [ migrations.AlterModelOptions( name='show', options={'verbose_name_plural': 'shows', 'ordering': ['datetime', 'cinema', 'id'], 'verbose_name': 'show'}, ), ]
# This file is part of James CI. # # James CI 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. # # James CI is distributed in the hope t...
LITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License along # with James CI. If not, see <http://www.gnu.org/licenses/>. # # # Copyright (C) # 2017 Alexander Haase <ahaase@alexhaase.de> # ...
:py:class:`~.Pipeline` or :py:class:`~.Job`. Multiple statuses may be compared by their value. .. note:: The minimum of a list of statuses will be the *worst* status of the list. However, if the list has a status of :py:attr:`created`, :py:attr:`pending` or :py:attr:`running`, these will h...
key], as_iterable=as_iterable) if as_iterable: return _as_iterable(preds, output=key) return preds[key] def get_variable_names(self): return self._estimator.get_variable_names() def get_variable_value(self, name): return self._estimator.get_variable_value(name) def export(self, ...
name": weight_column_name, "update_weights_hoo
k": chief_hook, }) else: model_fn = _linear_model_fn params.update({ "gradient_clip_norm": gradient_clip_norm, "num_ps_replicas": config.num_ps_replicas if config else 0, "joint_weights": _joint_weights, }) self._estimator = estimator.Estimator( mod...
################################################################################ # # Copyright 2015-2020 Félix Brezo and Yaiza Rubio # # This program is part of OSRFramework. You can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Softwa...
# Example of fields: #self.fieldsRegExp["phonefy"]["i3visio.location"] = "" # Definition of regular expressions to be searched in usufy mode self.fieldsRegExp["usufy"] = {} # Example of fields:
#self.fieldsRegExp["usufy"]["i3visio.location"] = "" # Definition of regular expressions to be searched in searchfy mode #self.fieldsRegExp["searchfy"] = {} # Example of fields: #self.fieldsRegExp["searchfy"]["i3visio.location"] = "" ################ # Fields fou...
/docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html#DataModelDataTypes """ def __init__(self, type_as_dict): self.type = list(type_as_dict.keys())[0] self.value = list(type_as_dict.values())[0] def __hash__(self): return hash((self.type, self.value)) def _...
f.read_capacity, "WriteCapacityUnits": self.write_capacity }, "TableName": self.name, "TableStatus": "ACTIVE", "ItemCount": len(self), "TableSizeBytes": 0, } } if self.has_range_ke
y: results["Table"]["KeySchema"]["RangeKeyElement"] = { "AttributeName": self.range_key_attr, "AttributeType": self.range_key_type } return results def __len__(self): count = 0 for key, value in self.items.items(): if self....
# -*- coding: utf-8 -*- ############################################################################### # # GetTariff # Returns an individual Tariff object with a given id. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may no...
_id, path) class GetTariffInputSet(InputSet): """ An InputSet with methods appropriate for specifying the inputs to the GetTariff Choreo. The InputSet object is used to specify input parameters when exec
uting this Choreo. """ def set_AppID(self, value): """ Set the value of the AppID input for this Choreo. ((conditional, string) The App ID provided by Genability.) """ super(GetTariffInputSet, self)._set_input('AppID', value) def set_AppKey(self, value): """ S...
# -*- coding: utf-8 -*- # (c) 2016 Alfredo de la Fuente - AvanzOSC # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from openerp import models, fields, api class SaleOrder(models.Model): _inherit = 'sale.order' @api.multi def action_button_confirm(self): procurement_obj = self.env...
d: vals = self._prepare_procurement_group(self) group = procurement_group_obj.create(vals) self.write({'procurement_group_id': group.id}) vals = self
._prepare_order_line_procurement( self, line, group_id=self.procurement_group_id.id) vals['name'] = self.name + ' - ' + line.product_id.name procurement = procurement_obj.create(vals) procurement.run() return res def _validate_service_proj...
je(request.POST.get('csrfmiddlewaretoken'),request.POST.get('fraseB'),request.user.username,False,"<p class='text-success'><span class='fa fa-check fa-fw'></span>Finaliza la recuperacion de unidades academicas</p>",10) cambia_mensaje(request.POST.get('csrfmiddlewaretoken'),request.POST.get('fraseB'...
oyecto.id_proyecto, request.user, articulos, lista_scopus) # messages.success(request, "Se ha creado exitosamente el proyecto") #~ return redirect('crear_proyecto') else: messages.error(request, "Imposible crear el proyecto") else: form = FormularioCrearProyecto()...
Proyecto.html', {'form': form, 'proyectos_user': proyectos_list, 'mproyecto': model_proyecto, 'lista_permisos': permisos}, context_instance=RequestContext(request)) #Visualización de proyectos propios de un usuario. @login_required def ver_mis_proyectos(request): global model_proyecto global p...
# 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 t...
mitations # under the License. import mock from keystone import catalog from keystone.common import manager from keystone.tests import unit class TestCreateLegacyDriver(unit.BaseTestCase): @mock.patch('oslo_log.versionutils.report_deprecated_feature') def test_class_is_properly_deprecated(self, mock_report...
ver(catalog.CatalogDriverV8) # NOTE(dstanek): I want to subvert the requirement for this # class to implement all of the abstract methods. Driver.__abstractmethods__ = set() impl = Driver() details = { 'as_of': 'Liberty', 'what': 'keystone.catalog.core.D...
me': 'foo', 'email': self.user.email}, follow=True ) assert response.status_code == 200 assert self.user.reload().username == 'foo' alog = ActivityLog.objects.latest('pk') assert alog.action == amo.LOG.ADMIN_USER_EDITED.id assert alog.arguments == [self.user] asse...
core.set_user(user) response = self.client.get(self.delete_url, follow=True) assert response.status_code == 200
assert b'Cannot delete user' not in response.content response = self.client.post(self.delete_url, {'post': 'yes'}, follow=True) assert response.status_code == 200 self.user.reload() assert self.user.deleted assert self.user.email alog = ActivityLog.objects.filter(action=a...
from intprim.ba
yesian_interaction_primitives import * import intprim.basis import intprim.constants impor
t intprim.examples import intprim.filter import intprim.filter.align import intprim.filter.spatiotemporal import intprim.util
# coding: utf-8 import random from PIL import Image
from PIL import ImageDraw from PIL import ImageFont import sys import os # how many pictures to generate num = 10 if len(sys.argv) > 1: num = int(sys.argv[1])
def genline(text, font, filename): ''' generate one line ''' w, h = font.getsize(text) image = Image.new('RGB', (w + 15, h + 15), 'white') brush = ImageDraw.Draw(image) brush.text((8, 5), text, font=font, fill=(0, 0, 0)) image.save(filename + '.jpg') with open(filename + '.txt', 'w'...
gs.DEFINE_float("validation_set_percentage",0.1, "the percentage of training examples that will be used for validation set") tf.flags.DEFINE_string("data_postive_path","./data/rt-polaritydata/rt-polarity.pos", "file path for postive data") tf.flags.DEFINE_string("data_negative_path","./...
"Vocabulary Size: %s" % len(vocab_processor.vocabulary_._mapping)) print("Length of train/validation set: %d , %d ." % (len(y_train),len(y_val))) #=================================================
============================= # Training #============================================================================== with tf.Graph().as_default(): session_config = tf.ConfigProto(allow_soft_placement=FLAGS.allow_soft_parameters, log_device_placement=FLAGS.log_device_placemen...
""" CMSIS-DAP Interface Firmware Copyright (c) 2009-2013 ARM 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 la...
he License. Extract and patch the interface without bootloader """ from options import get_options from paths import get_interface_path, TMP_DIR f
rom utils import gen_binary, is_lpc, split_path from os.path import join if __name__ == '__main__': options = get_options() in_path = get_interface_path(options.interface, options.target, bootloader=False) _, name, _ = split_path(in_path) out_path = join(TMP_DIR, name + '.bin') print '\...
#Ensure there is an exceptional edge from the following case def f2(): b, d = Base, Derived try: class MyNewClass(b, d): pass except: e2 def f3(): sequence_of_four = a_global try: a, b, c = sequence_of_four except: e3 #Always treat locals as no...
: seq = a_global try: a = seq except: ea def fb(): a, b, c = a_global try: seq = a, b, c except: eb #Ensure that a.b and c[d] can raise def fc(): a, b = a_global try: return a[b] except:
ec def fd(): a = a_global try: return a.b except: ed def fe(): try: call() except: ee else: ef
# # Copyright (c) 2008-2015 Citrix Systems, 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 l...
stributed 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. # class nspbr6_args : """ Provides additional arguments required for fetching the nspbr6 resource. """ def __init__(self) : self....
import pytest from plumbum.colorlib.styles import ANSIStyle, Color, AttributeNotFound, ColorNotFound from plumbum.colorlib.names import color_html, FindNearest class TestNearestColor: def test_exact(self): assert FindNearest(0,0,0).all_fast() == 0 for n,color in enumerate(color_html): ...
Color.from_simple("yellow").representation) class TestANSIColor: @classmethod def setup_class(cls): ANSIStyle.use_color = True def test_ansi(self): assert str(ANSIStyle(fgcolor=Color('reset'))) == '\033[39m' assert str(ANSIStyle(fgcolor=Color.from_full('gr...
ssert str(ANSIStyle(fgcolor=Color.from_simple('red'))) == '\033[31m' class TestNearestColor: def test_allcolors(self): myrange = (0,1,2,5,17,39,48,73,82,140,193,210,240,244,250,254,255) for r in myrange: for g in myrange: for b in myrange: near = Fin...
#!/usr/bin/env python # vim: tw=80 ts=4 sw=4 noet from os.path import join, basename, dirname, abspath import _import from wwwclient import browse, scrape HTML = scrape.HTML s = browse.Session("http://www.google.com") f = s.form().fill(q="python web scraping") s.submit(f, action="btnG", method="GET") tree = scrape.H...
ept=lambda n:n.name.lower() in ("table","p")) for node in nodes.children: print HTML.text(node) if node.name == "p": link = node.find(withName="a")[0] print "-->", link.attribute("href") print HTML.links(link) else: print "---------" # Google results are not properly closed, so we had to identify patterns w...
rted # close_on = ("td", "a", "img", "br", "a") # scrape.do(scrape.HTML.iterate, session.last().data(), closeOn=close_on, write=sys.stdout) # EOF
#! Tests out the CG solver with CPHF Polarizabilities import time import numpy as np import psi4 psi4.set_output_file("output.dat") # Benzene mol = psi4.geometry(""" 0 1 O 0.000000000000 0.000000000000 -0.075791843589 H 0.000000000000 -0.866811828967 0.601435779270 H ...
s %12.4f %12.4f %12.4f\n" % (p, polar[n][0], polar[n][1], polar[n][2])) psi4.core.print_out("\n") psi4.compare_values(8.01554, polar[0][0], 3, 'Dipole XX Polarizability') # TEST psi4.compare_values(12.50363, polar[1][1], 3, 'Dipole YY Polarizability') # TEST psi4.compare_values(10.04161, polar[2][2], 3, 'D
ipole ZZ Polarizability') # TEST
from bs4 import BeautifulSoup class RunParameter_xml: ''' A class for reading runparameters xml file from Illumina sequencing runs :param xml_file: A runparameters xml file ''' def __init__(self, xml_file):
self.xml_file = xml_file self._read_xml() def _read_xml(self): ''' Internal function for reading the xml file using BS4 ''' try: xml_file = self.xml_file with open(xml_file, 'r') as fp: soup = BeautifulSoup(fp, "html5lib") self._soup = soup except Exception as e:...
to parse xml file {0}, error {1}'.\ format(self.xml_file, e)) def get_nova_workflow_type(self): try: soup = self._soup workflowtype = None if soup.workflowtype: workflowtype = \ soup.workflowtype.contents[0] return workflowtype except Exception as e...
# -*- encoding: utf-8 -*- ############################################################################## # # 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 Licens...
(check.state != 'draft' for check in self): raise ValidationError("Solo se puede cancelar un cheque en estado borrador") self.next_state('draft_canceled') @api.multi def revert_canceled_check(self): """ Lo que deberia pasar con el cheque cuando se revierte una cancelacion """ ...
eck.state != 'canceled' for check in self): raise ValidationError("Funcionalidad unica para cheques cancelados") self.cancel_state('canceled') @api.multi def reject_check(self): """ Lo que deberia pasar con el cheque cuando se rechaza """ if any(check.state != 'handed' for c...
import datetime import tweepy from geopy.geocoders import Nominatim import json from secret import * import boto3 import re import preprocessor as p import time p.set_options(p.OPT.URL, p.OPT.EMOJI) # Get the service resource. dynamodb = boto3.resource('dynamodb', region_name='us-west-2') table = dynamodb.Table('fuck...
rint("No Country code is in the address") else: print("No address") class TwitterStreamListener(tweepy.StreamListener): def on_status(self, status): try: if status.geo != None: fips, zipcode = get_fips(status.geo['coordinates']) if fips is None: ...
raise Exception if zipcode is None: print("Zipcode is None") raise Exception txt = re.sub('[!@#$]', '', status.text) txt = p.clean(txt) try: table.update_item( Key={ ...
self._index = 0 if collection is not None: self.__class__._coll = collection self._coll = collection elif self._coll is None: if self.__class__._coll is None: raise NoCollectionError('Must have a collection in MongoDB!') else: ...
team
_ftm = 0 team_fta = 0 team_orb = 0 team_pts = 0 team_3pm = 0 team_tov = 0 opp_dreb = 0 for game in games_played: player_data = game.player_boxscore(player) team = game.player_team(player) opponent = game.opponent(team) ...
#!/usr/bin/e
nv p
ython3 print('hello hello hello')
#def binh_phuong() try:
a=int(raw_input("Nhap so n>=0 \n")) while a<=0: a=int(raw_input("Nhap lai so n>=0\n ")) print "%d" %(a) b=pow(a,2) c=int(raw_input("Doan so binh
phuong cua ban\n")) while c!=b: if c<b: print"chua dung, cao len 1 chut\n" c=input() else: print"qua rui giam xuong ti\n" c=input() print "Chinh xac ket qua la %d" %(c) except: print "Ban nhap khong dung kieu Integer"
import unittest import logging from domaincrawl.link_aggregator import LinkAggregator from domaincrawl.link_filters import DomainFilter, is_acceptable_url_scheme from domaincrawl.site_graph import SiteGraph from domaincrawl.util import URLNormalizer, extract_domain_port class LinkAggregatorTest(unittest.Tes...
, we also specify a referrer page filtered_links = link_aggregator.filter_update_links(valid_links, normalized_url) self.assertListEqual(expected_links,filtered_links) self.assertSetEqual(set(expected_links),link_aggregator._links) # Second invocation should result in deduplication...
t(expected_links),link_aggregator._links) # None of the invalid links should pass invalid_links = ["mailto://user@mail.com","code.acme.com","code.acme.com/b","https://127.122.9.1"] filtered_links = link_aggregator.filter_update_links(invalid_links, None) self.assertTrue(len(filtere...
from flask import Flask, request, session, g, redirect, url_for, \ abort, flash import db import routes DATABASE = 'test.db' DEBUG = True SECRET_KEY =
'k
ey' USERNAME = 'admin' PASSWORD = 'password' app = Flask(__name__) app.config.from_object(__name__) if __name__ == '__main__': app.run()
-- the von Mises stress in physical units (Pa) It has a number of additional properties (see __readHeader for full details) """ _raw_row = [('id', int), ('position', float, (3,)), ('grid', int, (3,)), ('pressure', float), ('...
s = {'stable': None, 'voxel_size': None, 'origin': np.array([np.nan, np.nan, np.nan]), 'bb_min': None, 'bb_max': None, 'bb_len': None, 'voxel_count': None} # header = len(_attrs) def __new__(cls, filename): """Create a...
noindex = cls._load(filename, headerDict) index = np.recarray(shape=noindex.shape, dtype=cls.row) for el in cls._raw_row[2:]: key = el[0] index.__setattr__(key, noindex.__getattribute__(key)) continue index.id = np.arange(len(noi...
: cb_idx = self.tasks.index(task) if stay_resident: if cb_idx not in self.resident_tasks: self.resident_tasks.append(self.current_task) print "task going resident:", task else: print "task keeps staying resident:", task return if len(res): print ">>> Error:", res self.status = self.FAI...
nt "[Task %s]" % self.name, line[:-1] pass def processFinished(self, returncode): self.returncode = returncode self.finish() def abort(self): if self.container: self.container.kill() self.finish(aborted = T
rue) def finish(self, aborted = False): self.afterRun() not_met = [ ] if aborted: not_met.append(AbortedPostcondition()) else: for postcondition in self.postconditions: if not postcondition.check(self): not_met.append(postcondition) self.cleanup(not_met) self.callback(self, not_met) def a...
nt = try_import('neutronclient.v2_0.client') health_monitor_template = ''' { "AWSTemplateFormatVersion" : "2010-09-09", "Description" : "Template to test load balancer resources", "Parameters" : {}, "Resources" : { "monitor": { "Type": "OS::Neutron::HealthMonitor", "Properties": { "type...
_template = ''' { "AWSTemplateFormatVersion" : "2010-09-09", "Description" : "Template to test load balancer resources", "Parameters" : {}, "Resources" : { "lb": { "Type": "OS::Neutron::LoadBalancer", "Properties": { "protocol_port": 8080, "pool_id": "pool123", "members":...
o test load balancer resources wit", "Parameters" : {}, "Resources" : { "pool": { "Type": "OS::Neutron::Pool", "Properties": { "protocol": "HTTP", "subnet_id": "sub123", "lb_method": "ROUND_ROBIN", "vip": { "protocol_port": 80, "session_persistence...
oken_view calls get_token() indirectly CsrfViewMiddleware().process_view(req, token_view, (), {}) resp = token_view(req) resp2 = CsrfViewMiddleware().process_response(req, resp) csrf_cookie = resp2.cookies.get('myname', False) self.assertNotEqual(csrf_cookie, False) ...
p2.get('Vary','')) def test_process_response_get_token_not_used(self): """ Check that if get_token() is not called, the view middleware doe
s not add a cookie. """ # This is important to make pages cacheable. Pages which do call # get_token(), assuming they use the token, are not cacheable because # the token is specific to the user req = self._get_GET_no_csrf_cookie_request() # non_token_view_using_...
the_count = [1, 2, 3, 4, 5] fruits = ['apple', 'oranges', 'pears', 'apricots',] change = [1, 'pennies', 2,
'dimes', 3, 'quarters',] #this first kind of for-loop goes through a list for number in the_count: print("This is
count %d" % number) # same as above for fruit in fruits: print("A fruit of type: %s" % fruit) # also we can go through mixed lists too # notice we have to use %r since we don't know what's in it for i in change: print("I got %r " % i) # we can alse build lists, first start with an empty one elements = [] #...
from pydub import * class AudioMerger: voice_tags = ["one", "two", "three", "four", "five", "ten
", "RUN", "relax", "completed"] def __init__(self, music): self.music = music
self.additionalGain = 8 self.voices={} for voice in self.voice_tags: sound = AudioSegment.from_file('voices/' + voice + '.wav') sound += self.additionalGain self.voices[voice] = sound def addCountdown(self, startTime, isRun = True): for i in range(1, 6): voice = self.voices[self.voice_tags[i - 1]...
# -*- coding: utf-8 -*- # Generated by Dja
ngo 1.9.7 on 2016-0
7-03 16:13 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('books', '0003_book_owner'), ] operations = [ migrations.RenameModel( old_name='Book', new_name='BookItem', ), ...
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
n.utils import data_utils from testtools import matchers from tempest.api.compute import base from tempest import config from tempest import test CONF = config.CONF class V
olumesGetTestJSON(base.BaseV2ComputeTest): @classmethod def skip_checks(cls): super(VolumesGetTestJSON, cls).skip_checks() if not CONF.service_available.cinder: skip_msg = ("%s skipped as Cinder is not available" % cls.__name__) raise cls.skipException(skip_msg) @cl...
= map(str, line.split("=")) os_username = os_username.rstrip('\n') elif "OS_PASSWORD" in line: trash, os_password = map(str, line.split("=")) os_password = os_password.rstrip('\n') elif "OS_URL" in line: trash, os_url = map(str, lin...
# vim.TaskInfo.State.error]: # logger.info(_("VirtualElephant::VMware::BDE - Waiting for node power off %s") % nod
e.get("name")) # time.sleep(5) # task = instance.PowerOn() # while task.info.state not in [vim.TaskInfo.State.success, # vim.TaskInfo.State.error]: # ...