prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
#!/usr/bin/env p
ython ################################################################################ # # qooxdoo - the new era of web development # # http://qooxdoo.org # # Copyright: # 2007 1&1 Internet AG, Germany, http://www.1and1.org # # License: # LGPL: http://www.gnu.org/licenses/lgpl.html # EPL: http://www.eclips...
* Sebastian Werner (wpbasti) # ################################################################################ import os import sys import shutil import optparse def rmgeneric(path, __func__): try: __func__(path) except OSError, (errno, strerror): print ERROR_STR % {'path' : path, 'error': strerror }...
: today = Canvas(root,width = 1100, height = 50) today.create_rectangle(1100, 50, 0, 0, fill = "red") today.create_text(100, 25,text = "Today on Movie-Net", fill = "white", font = ("broadway", 12)) today.place(x = 10, y = 150) def filmsOphalen(): ''' Dit was de code om de buttons met een loop te...
ambda:laatBeschrijvingZien(5))) Button6.place(x = 20, y = 405, width=350) Button7 = Button(root, text=FilmsOphalen.titelFilms[6], bg = "red", fg = "white", font = ("broadway", 12), command=(lambda:laatBeschrijving
Zien(6))) Button7.place(x = 20, y = 440, width=350) Button8 = Button(root, text=FilmsOphalen.titelFilms[7], bg = "red", fg = "white", font = ("broadway", 12), command=(lambda:laatBeschrijvingZien(7))) Button8.place(x = 20, y = 475, width=350) Button9 = Button(root, text=FilmsOphalen.tite...
MonochromaticWaves(period=period, waveHeight=height, mwl=mwl, depth=depth, g=np.array([0., -9.81, 0.]), waveDir=direction, wavelength=opts.wave_wavelength, waveType=opts.wave_type, Ycoeff=...
es=sloped_shore) # ----- GENERATION / ABSORPTION LAYERS ----- # tank.setSponge(x_n=tank_sp
onge[0], x_p=tank_sponge[1]) dragAlpha = 10.*omega/1e-6 if opts.generation: tank.setGenerationZones(x_n=True, waves=waves, dragAlpha=dragAlpha, smoothing = smoothing) if opts.absorption: tank.setAbsorptionZones(x_p=True, dragAlpha = dragAlpha) # ----- BOUNDARY CONDITIONS ----- # # Waves tank.BC['x-'].setUnst...
#!/usr/bin/python # Copyright 2011 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 appli...
OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Fix sys.path so it can find our libraries. This file is named google3.py because gpylint specifically ignores it when complaining about the order of import statements - goo...
me before other non-python-standard imports. """ __author__ = 'apenwarr@google.com (Avery Pennarun)' import tr.google3 #pylint: disable-msg=C6204,W0611
# This file is part of Indico. # Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN). # # Indico 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 (a...
will be useful, but # WITHOUT ANY WAR
RANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Indico; if not, see <http://www.gnu.org/licenses/>. from __future__ import unicod...
progs_12.asp result = [] needquote = False for arg in seq: bs_buf = [] # Add a space to separate this argument from the others if result: result.append(' ') needquote = (" " in arg) or ("\t" in arg) if needquote: result.append('"') f...
ESS)
def _find_w9xpopen(self): """Find and return absolut path to w9xpopen.exe""" w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)), "w9xpopen.exe") if not os.path.exists(w9xpopen): # Eeek - file-not-found - possibly an embe...
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) import pytest from .. import Backend from . import AVAILABLE_BACKENDS @pytest.mark.parametrize('key', AVAILABLE_BACKENDS) def test_Dummy(key): be = Backend
(key) d0 = be.Dummy() d1 = be
.Dummy() assert d0 == d0 assert d0 != d1
""" This module is responsible for doing all the authentication. Adapted from the Google API Documentation. """ from __future__ import print_function import os import httplib2 import apiclient import oauth2client try: import argparse flags = argparse.ArgumentParser( parents=[oauth2client.tools.argpar...
client.flow_from_clientsecrets( CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials = oauth2client.tools.run_flow(flow, store, flags) else: # Needed only for compatibility with Python 2.6 credentials = oauth2client.tools.run(f...
ls.authorize(httplib2.Http()) file_service = apiclient.discovery.build('drive', 'v3', http=http).files()
------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundErro...
ctly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group
. :type models: ~test_base.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serial...
#Example numpy2.py from numpy import * a = arange(1.0, 2.0, 0.1) # start, stop & s
tep print a b = linspace(1,2,11) print b c = ones(5) print c d
= zeros(5) print d e = random.rand(5) print e
# Author: Mike 'Fuzzy' Partin # Copyright: (c) 2016-2018 # Email: fuzzy@fumanchu.org # License: See LICENSE.md for details # Stdlib imports import math import datetime def red(txt): return '\033[1;31m%s\033[0m' % txt def green(txt): return '\033[1;32m%s\033[0m' % txt def yellow(txt): return '\033[1;33m%...
print('%s: %s' % (red('ERROR'), txt)) def fatal(txt): error(txt) def OutputWord(word): return '%s%s' % (cyan(word[0].upper()), white(word[1:].lower())) def humanTime(amount): secs = float(datetime.timedelta(seconds=amount).total_seconds()
) units = [("d", 86400), ("h", 3600), ("m", 60), ("s", 1)] parts = [] for unit, mul in units: if secs / mul >= 1 or mul == 1: if mul > 1: n = int(math.floor(secs / mul)) secs -= n * mul else: n = secs if secs != int(secs) else i...
def get_word_pattern(word: str) -> str: """ >>> get_word_pattern("pattern") '0.1.2.2.3.4.5' >>> get_word_pattern("word pattern") '0.1.2.3.4.5.6.7.7.8.2.9' >>> get_word_pattern("get word pattern") '0.1.2.3.4.5.6.7.3.8.9.2.2.1.6.10' """ word = word.upper() next_num = 0 letter_n...
return ".".join(word_pattern) if __name__ == "__main__": import pprint import time start_time = time.time() with open("dictionary.t
xt") as in_file: wordList = in_file.read().splitlines() all_patterns: dict = {} for word in wordList: pattern = get_word_pattern(word) if pattern in all_patterns: all_patterns[pattern].append(word) else: all_patterns[pattern] = [word] with open("word...
import dataset_creator # TODO(rchao): Investigate why there cannot be single worker and multi worker # PS strategies running in the same shard. @test_utils.run_v2_only @tf.__internal__.distribute.combinations.generate( tf.__internal__.test.combinations.combine( strategy=strategy_combinations.all_strategi...
EvaluateWithNoStepsPerEpoch(self, strategy): with self.assertRaisesRegex( ValueError, "When using a `tf.keras.utils.experimental.DatasetCreator`, " "`steps_per_epoch`, `validation_steps` or `steps` argument must be " "provided in `Model.fit`, `Model.evaluate`, or `Model.predict`."): ...
fourth (3rd index) and the last predictions # because the first, fourth and the last input are the same in # `model.predict` so there predictions should match. self.assertTrue(all(predictions[0] == predictions[i] for i in [0, 3, 5])) self.assertFalse( all(predictions[0] == predictions[i] for i ...
#!/usr/bin/env python # encoding=utf-8 # Copyright 2014 Cloudera 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 app...
port signal from impala_shell_results import get_shell_cmd_result, cancellation_helper from subprocess import P
open, PIPE from time import sleep SHELL_CMD = "%s/bin/impala-shell.sh" % os.environ['IMPALA_HOME'] class TestImpalaShellInteractive(object): """Test the impala shell interactively""" # TODO: Add cancellation tests @pytest.mark.execute_serially def test_escaped_quotes(self): """Test escaping quotes""" ...
#!/usr/bin/env python3 # sequence = [] defence = 0.4 for x in range(1): print(x) for x in range(10): if
x == 0: defence = defence
else: defence = defence + (1 - defence) * (1 / 2) print(defence) # print(defence) # print(sequence) # print(sum(sequence)) # x = input() # print(x)
__author__ = 'thorwhalen' import requests from serialize.khan_logger import KhanLogger import logging class SimpleRequest(object): def __init__(self, log_file_name=None, log_level=logging.INFO): full_log_path_
and_name = KhanLogger.default_log_path_with_unique_name(log_file_name) self.logger = KhanLogger(file_path_and_name=full_log_path_and_name, level=log_level) def slurp(self, u
rl): r = requests.get(url, timeout=30.0) if not r.ok: self.logger.log(level=logging.WARN, simple_request="HTTP Error: {} for url {}".format(r.status_code, url)) else: self.logger.log(level=logging.INFO, simple_request="Slurped url {}".format(url)) return r.t...
from .
modules.buckle_embedding import * from .modules
.gather import *
# Generated by Django 3.1.2 on 2021-05-19 20:24 from django.db import migrations, models class Migration(migrations
.Migration): dependencies = [ ('eventkit_cloud_auth', '0002_auto_20191127_1425'), ] operations = [ migrati
ons.AlterField( model_name='oauth', name='user_info', field=models.JSONField(default=dict), ), ]
# ##### BEGIN GPL LICENSE BLOCK ##### # # 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 distrib...
imported_mods[bl_id] = mod return mod print("Cannot find {} among old nodes".format(bl_id)) retu
rn None def unregister_old(bl_id): global imported_mods mod = imported_mods.get(bl_id) if mod: #print("Unloaded old node type {}".format(bl_id)) mod.unregister() del imported_mods[bl_id] def unregister(): global imported_mods print(imported_mods) for mod in im...
""" This signature containts test to see if the site is running on ExpressionEngine. """ __author__ = "Seth Gottlieb" __copyright__ = "CM Fieldguide" __credits__ = ["Seth Gottlieb",] __license__ = "Unlicense" __version__ = "0.1" __maintainer__ = "Seth Gottlieb" __email__ = "sgottlieb@alumni.duke.edu" __status__ = "Expe...
://expressionengine.com'): return 1 else: return 0 def test_has_css_loader_script(self, site): """ ExpressionEngi
ne loads CSS files with a query string off the root of the site like ?css=something.css """ if site.home_page.has_matching_tag('link', {'rel':'stylesheet','href': '/\?css=\w+[\.|/]'}): return 1 else: return 0
#!/usr/bin/env python # 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 "Licen...
# noqa F405 parser = ArgumentParser() parser.add_argument("-s", "--dll", dest="dll_file", help="DLL filename", metavar="FILE") parser.add_argument("-n", "--nifi", dest="nifi_instance", help="NiFi Instance") parser.add_argument("-i", "--input", dest="input_port", ...
etFile Dir to monitor", metavar="FILE") args = parser.parse_args() """ dll_file is the path to the shared object """ minifi = MiNiFi(dll_file=args.dll_file, url=args.nifi_instance.encode('utf-8'), port=args.input_port.encode('utf-8')) # noqa F405 minifi.set_property("nifi.remote.input.http.enabled", "true") proces...
# -*- coding: utf-8 -*- """Cluster Robust Standard Errors with Two Clusters Created on Sat Dec 17 08:39:16 2011 Author: Josef Perktold """ from statsmodels.compat.python import urlretrieve import numpy as np from numpy.testing import assert_almost_equal import statsmodels.api as sm import statsmodels.stats.sandwich...
pete
rsen/htm/papers/se/test_data.txt try: pet = np.genfromtxt("test_data.txt") print('using local file') except IOError: urlretrieve('http://www.kellogg.northwestern.edu/faculty/petersen/htm/papers/se/test_data.txt', 'test_data.txt') print('downloading file') pet = np.genfromtxt("...
# coding: utf-8 """ Cloudbreak API Cloudbreak is a powerful left surf that breaks over a coral reef, a mile off southwest the island of Tavarua, Fiji. Cloudbreak is a cloud agnostic Hadoop as a Service API. Abstracts the provisioning and ease management and monitoring of on-demand clusters. SequenceIQ's Cloud...
None self._recipe_type = None self._content = None if name is not None: self.name = name if description is not None: self.description = description self.recipe_type = recipe_type if content i
s not None: self.content = content @property def name(self): """ Gets the name of this RecipeRequest. name of the resource :return: The name of this RecipeRequest. :rtype: str """ return self._name @name.setter def name(self, name): ...
#!/usr/bin/env python # -*- coding: utf-8 -
*- # # https://github.com/michielkauwatjoe/Meta class CubicBezier: def __init__(self, bezierId=None, points=None, parent=None, isClosed=False): u""" Stores points of the cubic Bézier curve. """ self.bezierId = bezierId sel
f.points = points self.parent = parent self.isClosed = isClosed
urn True if position in ("first-child", "last-child"): return page.has_add_permission(request) elif position in ("left", "right"): if page.parent_id: return has_generic_permission(page.parent_id, request.user, "add", page.site) else: from cms.utils.plu...
page__level__gte=user_level)) | (Q(pageusergroup__created_by=user) & Q(page
permission__page=None)) ) return qs def has_global_change_permissions_permission(request): opts = GlobalPagePermission._meta user = request.user if user.is_superuser or ( user.has_perm(opts.app_label + '.' + opts.get_change_permission()) and has_global_page_permission(request, can_c...
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
tant_op.constant(np.random.randn(3, 1), dtype=dtype) r8 = a - x a = constant_op.constant(np.random.randn(3, 1, 1), dtype=dtype) r9 = gen_math_ops.maximum(x, a) a = constant_op.constant(np.random.randn(3, 1), dtype=dtype) r10 = gen_math_ops.minimum(a, x) a = constant_op.constant(np.ra...
* a a = constant_op.constant(np.random.randn(1), dtype=dtype) r12 = a * x concat1 = array_ops.concat([r1, r2, r3, r4, r5, r6], axis=-1) concat2 = array_ops.concat([r7, r8, r9, r10, r11, r12], axis=3) x = array_ops.concat([concat1, concat2], axis=-1) gen_array_ops.reshape(x, [2, -1], ...
import os import requests from flask import Flask, request, abort, redirect, jsonify from requests.exceptions import RequestException import quicklatex application = Flask(__name__) slack_client_id = os.environ['SLACK_CLIENT_ID'] slack_client_secret = os.environ['SLACK_CLIENT_SECRET'] slack_verification_token = os....
'response_type': 'in_chann
el', 'attachments': [ err_attachment, { 'fallback': 'LaTeX', 'text': 'LaTeX', 'image_url': image, }, ], }) if __name__ == "__main__": application.run()
import platform import shlex from coalib.bearlib import deprecate_settings from coalib.bearlib.abstractions.Linter import linter from coalib.bearlib.spacing.SpacingHelper import SpacingHelper from dependency_management.requirements.DistributionRequirement import ( DistributionRequirement) @linter(executable='ind...
ine, is the blank line following a declaration when ``blank_line_after_declaration=True``. :param declaration_indent: Forces variables names to be aligned in column ``n`` with ``n = declaration_indent`` in declaration. Example: If ``declaration_indent = 8`` the...
float b; :param brace_indent: Specifies the number of spaces by which braces are indented. Its default value is 2. :param gnu_style: Uses GNU coding style. :param k_and_r_style: Uses Kernighan & Ritchie coding style. :param ...
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
96, 3), } _VERSION = 0 _SUBVERSION = 1 def check_file_existence(x): if not os.path.isfile(x): # Argparse uses the ArgumentTypeError to g
ive a rejection message like: # error: argument input: x does not exist raise argparse.ArgumentTypeError('{0} does not exist'.format(x)) return x def show_and_save_bitmaps(input_file, bitmap_list, channels): """Display and save a list of bitmaps. Args: input_file: input file name bitmap_list: l...
self._last_timestamp = state_config.get(self._TIME_KEY) self._context = state_config.get(self._CONTEXT_KEY, {}) self._event = event self.function_name = func_name self.function_version = func_version self.start_last_timestamp = None def set_starting_timestamp(self, date_for...
rty def successive_event(self): """Retu
rn formatted json for event representing a successive invocation""" event = {'invocation_type': self.Events.SUCCESSIVE_INVOKE} event.update(self._event) return json.dumps(event) @property def _app_type(self): """The app type for this config""" return self._event['app_typ...
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2017-11-09 18:13 from __future__ import unicode_literals import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('bot', '0013_auto_20171109_1759'), ] operations = [ migratio...
AlterField( model_name='alertausuario', name='chat_id', field=models.IntegerField(blank=True), ), migrations.AlterField( model_name='alertausuario', name='ultima_actualizacion', field=models.DateTimeField(default=datetime.datetime(2...
3, 50, 254179)), ), ]
import numpy as np import tvm from tvm.contrib import graph_runtime import topi.testing import nnvm.symbol as sym import nnvm.compiler from nnvm.testing.config import ctx_list from nnvm.testing.check_computation import check_function def check_map(symfunc, np_func, np_backward=None, dtype="float32", rnd_min=-1, rnd_ma...
check_map(sym.round, np.round) def test_abs(): check_map(sym.abs, np.abs) check_map(sym.abs, np.abs, dtype = "int32") check_map(sym.abs, np.abs, dtype = "int8") def test_shift(): n = 3 for dtype in ["int32", "int8"]: check_map(lambda x : x >> n, lambda x: x >> n, dtype=dtype, rnd_min=...
st_shift() test_floor() test_ceil() test_round() test_abs() test_trunc()
# -*- coding: utf-8 -*- # Copyright (c) 2020, Frappe Technologies and contributors
# For license information, pl
ease see license.txt from __future__ import unicode_literals # import frappe from frappe.model.document import Document class WebPageBlock(Document): pass
from alembic.config import Config from alembic.environment import EnvironmentContext from alembic.migration import MigrationContext from alembic.script import ScriptDirectory from difflib import unified_diff from pytest import fixture from re import split from sqlalchemy import engine_from_config from subprocess import...
# then we create a clean DB from the metadata createdb(db_name) metadata = models.metadata engine = engine_from_config(settings) metada
ta.bind = engine metadata.create_all(engine, tables=[table for name, table in metadata.tables.items() if not name.startswith('test_')]) # and store the results create_all_result = dumpdb(db_name) engine.dispose() # now we do it again, but this time using migrations dropdb(db_name) cr...
"""Base class for IKEA TRADFRI.""" from __future__ import annotations from collections.abc import Callable from functools import wraps import logging from typing import Any from pytradfri.command import Command from pytradfri.device import Device from pytradfri.device.air_purifier import AirPurifier from pytradfri.de...
TradfriBaseDevice(TradfriBaseClass): """Base class for a TRADFRI device. All devices shoul
d inherit from this class. """ @property def device_info(self) -> DeviceInfo: """Return the device info.""" info = self._device.device_info return DeviceInfo( identifiers={(DOMAIN, self._device.id)}, manufacturer=info.manufacturer, model=info.mode...
napshotted directly since the API expects a `vm_ref`. To work around this, we need to create a temporary VM and then map the VDI to the VM using a temporary VBD. """ name_label = "dummy" vm_ref = create_vm(session, instance, name_label, None, None) try: vbd_ref = create_vbd(session, vm_r...
if vbd_rec['userdevice'] == '0': vdi_rec = session.call_xenapi("VDI.get_record", vbd_rec['VDI']) return vbd_rec['VDI'], vdi_rec raise exception.NovaException(_("No primary VDI found for %(vm_ref)s") % locals()) @contextlib.contextmanager def snapshot_a...
) == 1: update_task_state = args[0] """Snapshot the root disk only. Return a list of uuids for the vhds in the chain. """ LOG.debug(_("Starting snapshot for VM"), instance=instance) # Memorize the original_parent_uuid so we can poll for coalesce vm_vdi_ref, vm_vdi_rec = get_vdi_for_vm...
: """A datacenter that can contain racks""" def __init__(self, name, tenant_id=0): self.name = name self.racks = [] self.rack_max = None self.tenant_id= tenant_id """Set maximum number of racks in DC""" def set_rack_max(self, rack_max): self.rack_max = rack_max def add_rack(self, rack): ...
ests: for vm in server.guests["vms"]: if vm.get_host_capability(kind) and vm.has_enough_ressources(guest_capacity):
suitable_objects.append(vm) return random.choice(suitable_objects) def get_dc_free_capacity(self, kind): dc_free_capacity = {"vcpu": 0, "ram": 0} for rack in self.racks: rack_free_capacity = rack.get_rack_free_capacity(kind) dc_free_capacity["vcpu"] += rack_free_capacity["vcpu"] dc...
put in tests.iteritems(): result = functor(test_input) msg = ('Expected %s to translate %r to %r, but got %r.' % (functor.__name__, test_input, test_output, result)) self.assertEquals(test_output, result, msg) def testNormalizeRef(self): """Test git.NormalizeRef function.""" te...
apture_output=True) self.assertCommandContains(['%s:refs/drafts/%s' % (self.PUSH_LOCAL, self.PUSH_BRANCH)], capture_output=True) class ProjectCheckoutTest(cros_test_lib.TestCase): """Tests for git.ProjectCheckout""" def set...
revision='remotes/for/master')) self.fake_unversioned_unpatchable = git.ProjectCheckout( dict(name='chromite', path='src/platform/somethingsomething/chromite', # Pinned to a SHA1. revision='1deadbeeaf1deadbeeaf1deadbeeaf1deadbeeaf')) self.fake_versioned_patc...
from django.contrib.sites.models import Site import factory from factory.f
uzzy import FuzzyText from oscar.core.loading import get_model from oscar.test.factories import ProductFactory, StockRecordFactory as OscarStockRecordFactory from ecommerce.core.models import SiteConfiguration class PartnerFactory(factory.DjangoModelFactory): class Meta(object):
model = get_model('partner', 'Partner') django_get_or_create = ('name',) name = FuzzyText(prefix='test-partner-') short_code = factory.SelfAttribute('name') class SiteFactory(factory.DjangoModelFactory): class Meta(object): model = Site class SiteConfigurationFactory(factory.Djang...
from threading import Thread, Lock import bluetooth as bt import socket class SerialPortService(Thread): def __init__(self, port): super(SerialPortService, self).__init__() self.port = port self.sen
d_lock = Lock() self.setDaemon(True) def run(self): self.running = True self.port.settimeout(0.1) while self.running: try: data = self.port.recv(2048) print 'IN:', data except :
pass self.port.close() def end(self): self.running = False def send(self, msg): self.send_lock.acquire() self.port.send(msg) self.send_lock.release()
# Copyright (c) 2013 Rackspace, Inc. # Copyright (c) 2013 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 b...
ent=
data) self.assertIsInstance(req.deserialized_content, dict)
from django.test import TestCase from versiontools.models import AssemblyInfo from django.utils.timesince import timesince from django.utils.datetime_safe import datetime # Create your tests here. class AssembyInfoTest(TestCase): def test_create(self): data = {'fullpath' : r'C:\Users\lberrocal\Doc...
.2.6'} ai = AssemblyInfo.objects.create(**data)
self.assertEqual(ai.fullpath, data['fullpath']) self.assertEqual(ai.title, data['title']) self.assertEqual(ai.description, data['description']) self.assertEqual(ai.version, data['version']) print ai.updated_on print datetime.now() print ai.project
# Generated by Django 2.0.13 on 2020-10-09 14:56 from django.db import migrations, models class Migration(migrations.Migration): dependenci
es = [ ('currency_convert', '0001_initial'), ] operations = [ migrations.AddField( model_name='monthlyaverage', name='imf_url', field=models.URLField(max_lengt
h=2000, null=True), ), ]
faculty_view.html", {'form': form, 'table': table, }) #View for TA ########################################################################## from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy @login_required @user_passes_test(lambda u: hasattr(u, 'staff')) def ta_view(request): repor...
############## @login_required @user_passes_test(lambda u: hasattr(u, 'student')) def student_logged_in_view(request): """Homepage for logged in users""" return render(request, 'loggedin.html', {'username': request.user.username, 'is_TA': hasattr(request.user, "staff"), 'is_Student': hasattr(request.user, 'stude...
): """Page for users who have not successfully logged in""" return render(request, 'invalid_login.html') @login_required @user_passes_test(lambda u: u.is_superuser) def admin_home_view(request): """Homepage for logged in admin""" return render(request, 'admin_loggedin.html', {'username': request.user.username})...
# BS mark.1-55 # /* coding: utf-8
*/ # BlackSmith plugin # servres_plugin.py # Coded by: WitcherGeralt (WitcherGeralt@jabber.ru) # http://witcher-team.ucoz.ru/ SERVSTAT = {} RESSTAT = {} def handler_servres_stat(conf, nick, afl, role, status, text): instance =
GROUPCHATS[conf][nick] if instance.has_key('full_jid'): jid = instance['full_jid'] if jid.count('/'): list = jid.split('/') stripped_jid = list[0] server = stripped_jid.split('@')[1] resourse = list[1] if server not in SERVSTAT: SERVSTAT[server] = [] if stripped_jid not in SERVSTAT[server]: ...
#!/usr/bin/env python import json import sys import web from coloredcoinlib import BlockchainState, ColorDefinition blockchainstate = BlockchainState.from_url(None, True) urls = ( '/tx', 'Tx', '/prefetch', 'Prefetch', ) class ErrorThrowingRequestProcessor: def require(self, data, key, message): ...
self.require(data, 'txhash', "TX requires txhash") txhash = data.get('txhash') return blockchainstate.get_raw(txhash) class Prefetch(ErrorThrowingRequestProcessor): def POST(self): # data is sent in as json data = json.
loads(web.input().keys()[0]) self.require(data, 'txhash', "Prefetch requires txhash") self.require(data, 'output_set', "Prefetch requires output_set") self.require(data, 'color_desc', "Prefetch requires color_desc") txhash = data.get('txhash') output_set = data.get('output_set') ...
Forked processes are a traditional way to structure parallel tasks, and they are a fun- damental part of the Unix tool set. Forking is based on the notion of copying programs: when a program calls the fork routine, the operating system makes a new copy of that program and its process in memory and starts running that...
of that, global objects like files start out with the same values in a child process, so all the proce
sses here are tied to the same single stream. But it’s important to remember that global memory is copied, not shared; if a child process changes a global object, it changes only its own copy. (As we’ll see, this works differently in threads,
import pyodbc import config def main(): # formatで`{`を使うため、`{`を重ねることでエスケープ con_str = 'Driver={{Microsoft Access Driver (*.mdb, *.accdb)}};Dbq={0}
;'.format(config.PATH_ACCDB) conn = pyodbc.connect(con_str) cur = conn.cursor() cur.execute("select item_name from item") for c in cur.fetchall(): print(c[0]) #=> `ringo`, `みかん cur.close() conn.cl
ose() if __name__ == '__main__': main()
#!/usr/bin/env python import glob import cv2 import cv_bridge import rospy from sensor_msgs.msg import Image from std_msgs.msg import Int32, Float32 import rospkg import sys class Animation: def __init__(self, directory): self.fnames = [fname for fname in glob.glob("%s/*" % directory)] self.fnames...
ent_value = 0 else:
raise ValueError("No target: " + `self.target`) def main(): rospy.init_node('animator_server', anonymous=True) rate = rospy.Rate(30) rospack = rospkg.RosPack() path = sys.argv[1] Animation(path) while not rospy.is_shutdown(): rate.sleep() if __name__ == "__main__":...
#coding:utf8 from baseclass.DeepRecommender import DeepRecommender import numpy as np from random import choice,random,randint,shuffle from tool import config import tensorflow as tf #According to the paper, we only class DMF(DeepRecommender): def __init__(self,conf,trainingSet=None,testSet=None,fold='[1]'): ...
f.regLoss = tf.add(self.regLoss, tf.nn.l2_loss(item_W1)) for i in range(1, len(self.n_hidden_i)): W = tf.Variable(initializer([self.n_hidden_i[i-1], self.n_hidden_i[i]],stddev=0.01)) b = tf.Variable(initializer([self.n_hidden_i[i]],stddev=0.01)) self.regLos
s = tf.add(self.regLoss, tf.nn.l2_loss(W)) self.regLoss = tf.add(self.regLoss, tf.nn.l2_loss(b)) self.item_out = tf.nn.relu(tf.add(tf.matmul(self.item_out, W), b)) norm_user_output = tf.sqrt(tf.reduce_sum(tf.square(self.user_out), axis=1)) norm_item_output = tf.sqrt(tf.reduce_su...
# Top Rollover Lanes __author__="jim" __date__ ="$Jan 18, 2011 1:36:37 PM$" import procgame import locale from procgame import * base_path = config.value_for_key_path('base_path') game_path = base_path+"games/whirlwind/" speech_path = game_path +"speech/" sound_path = game_path +"sound/" music_path = game_path +"mu...
: # self.game.coils.ballLaunch.pulse(50) def warning(self): self.times_warned += 1 #update display time=2 self.text_layer.set_text("WARNING",blink_frames=5,seconds=time) self.layer = self.text_layer self.delay(name='clear_delay', event...
f clear(self): self.layer = None def sw_plumbBobTilt_active(self, sw): if self.times_warned == self.game.user_settings['Standard']['Tilt Warnings']: self.tilt() else: self.warning()
# # Copyright 2015-2019, Institute for Systems Biology # # Licensed under the Apache License, Version 2.0 (the "Lice
nse"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARR...
ense for the specific language governing permissions and # limitations under the License. # from django.contrib import admin # Register your models here.
import inspect from biicode.client.shell.biistream import Color class ToolCatalog(dict): def __init__(self, main_class, tools): dict.__init__(self) self.main_class = main_class # dict from tool group name to set of classes for c in tools: self[c.group] = c self....
out.writeln(' $ bii COMMAND --help') out.write('To change verbosity, use options ', Color.YELLOW) out.writeln('--quiet --verbose\n') if not argv or 'all' in argv: out.writeln('--------- Global Commands ----------', Color.YELLOW) for m in inspect.getmembers(self.main_...
('_'): method = m[1] if not method.__doc__.startswith(' ADVANCED'): doc = method.__doc__ out.write(' %-10s' % method_name, Color.GREEN) out.writeln(self._get_doc_short(doc)) elif self.sho...
""" Module containing classes for HTTP client/server interactions """ # Python 2.x/3.x compatibility imports try: from urllib.error import HTTPError, URLError from urllib.parse import urlencode except ImportError: from urllib2 import HTTPError, URLError from urllib import urlencode import socket from ...
URL :type API_endpoint_URL: str :param params_dict: a dictionary containing the query parameters to be used in the HTTP request (given as key-value couples in the dict) :type params_dict: dict :param API_key: th
e OWM web API key :type API_key: str :returns: a full string HTTP request URL """ url =self._API_root_URL + API_endpoint_URL params = params_dict.copy() if self._API_key is not None: params['APPID'] = self._API_key return self._build_query_parameters(...
#!/usr/bin/python import fetch import sys from pymongo import MongoClient db = MongoClient().ppa.ticket for loc in db.distinct('location'): print loc sys.exit(1) ''' Getting the count for each date for date in sorted(db.distinct('issueDate')): print "%s: %s" % (date, db.find({'issueDate':date}).count()) ''...
k_end}}).count() try : start_date = db.find({'_id':{'$gte':block_start,'$lte':block_end},'issueTime':{'$exists':True}}).sort([('_id', 1)]).limit(1)[0]['issueTime'] except : start_date = "???" try : end_date = db.find({'_id':{'$gte':block_start,'$lte':block_end},'issueTime':{'$exists'...
nresolved = db.find({'_id':{'$gte':block_start,'$lte':block_end},'resolved':False}).count() missing = db.find({'_id':{'$gte':block_start,'$lte':block_end},'missing':True}).count() if True: print "%s: %d-%d" % ("Range", block_start, block_end) print "\t%s:\t\t%s" % ("Start", start_date) p...
import mimetypes from typing import Optional, Sequence import cgi from requests import Response from requests.structures import CaseInsensitiveDict from requests_toolbelt.multipart.decoder import MultipartDecoder from rets.errors import RetsApiError, RetsResponseError from rets.http.data import Object from rets.http....
headers. if not content_id or not object_id: raise RetsResponseError(part.content, part.headers) # Respond with `Location` header redirect. if location: return Object( mime_type=_guess_mime_type(location) or mime_type, content_id=content_id, description=d...
ed=preferred, data=None, ) # Check the `Content-Type` header exists for object responses. if mime_type is None or mime_type == 'text/html': raise RetsResponseError(part.content, part.headers) return Object( mime_type=mime_type, content_id=content_id, des...
#!/usr/bi
n/env python import sys import csv import json if len(sys.argv) != 3: print 'Incorrect number of arguments.' print 'Usage: csv_to_json.py path_to_csv path_to_json' exit() print 'Argument List:', str(sys.argv) csvFileName = sys.argv[1] jsonFileName = sys.ar
gv[2] csvFile = open (csvFileName, 'rU') myReader = csv.reader(csvFile) header = myReader.next() print "Header fields:", header myReader = csv.DictReader( csvFile, fieldnames = header) parsedJson = json.dumps( [ row for row in myReader ] ) print "JSON parsed." jsonFile = open( jsonFileName, 'w') jsonFile.wri...
# 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 a...
to Datastore. datastore_client.put(entity) # Redirect to the home page. return redirect('/') @app.errorhandler(500) def server_error(e): logging.exception('An error occurred during a request.') return """ An internal error occurred: <pre>{}</pre> See logs for full stacktrace. """.form...
d to run the # application on Google App Engine. See entrypoint in app.yaml. app.run(host='127.0.0.1', port=8080, debug=True) # [END app]
from main import * from django.utils import simplejson class CsvView(CachedPage): cacheName = "CsvView" mimeType = "text/csv" selfurl = "database.csv" def generatePage(self): output = [] output.append( """title, homepage, person, category, posts_url, comments_url, priority, fav...
achedPage): mimeType = "application/javascript" def post_process_content(self, content): callback = self.request.get("callback") logging.info("Add JSONP padding: " + callback) return "%s(%s);" % (callback, content) class WeeklyPicksJSONPHandler(JSONPHandler): cacheName = "We...
.wordpress.com/2011/12/03/the-meaning-of-omega/", "caption": "If you haven't followed the debate on TCS breakthrough in matrix multiplication, you can read up on it at Godel's Lost Letter and P=NP (and you might also check out a short comment at Yet Another Math Programmer)." } ] output = picks ...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '/home/colin/dev/QCrash/forms/dlg_github_login.ui' # # Created by: PyQt5 UI code generator 5.5.1 # # WARNING! All changes made in this file will be lost! from qcrash.qt import QtCore, QtGui, QtWidgets class Ui_Dialog(object): def setupU...
rname) self.label_3 = QtWidgets.QLabel(Dialog) self.label_3.setObjectName("label_3") self.formLayout.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.label_3) self.le_password = QtWidgets.QLineEdit(Dialog) self.le_password.setEchoMode(QtWidgets.QLineEdit.Password) self....
.formLayout.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.le_password) self.verticalLayout.addLayout(self.formLayout) self.cb_remember = QtWidgets.QCheckBox(Dialog) self.cb_remember.setObjectName("cb_remember") self.verticalLayout.addWidget(self.cb_remember) self.cb_remember...
#!/usr/bin/env python # # Python-bindings support functions test script # # Copyright (C) 2010-2022, Joachim Metz <joachim.metz@gmail.com> # # Refer to AUTHORS for acknowledgements. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as ...
mport pyfsntfs class SupportFunctionsTests(unittest.TestCase): """Tests the support functions.""" def test_get_version(self): """Tests the get_version function.""" version = pyfsntfs.get_version() self.assertIsNotNone(version) if __name__ == "__main__": argument_parser = argparse.ArgumentParser()...
path of the source file.") options, unknown_options = argument_parser.parse_known_args() unknown_options.insert(0, sys.argv[0]) setattr(unittest, "source", options.source) unittest.main(argv=unknown_options, verbosity=2)
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import django from django.db import models class MessageBase(models.Model): text = models.CharField(max_length=140) # TODO save connection title rather than wacky object string? identity = models.CharField(max_length=150) backend = models.CharField(max_...
icode__(self): return "%s (%s) %s:" % (self.identity, self.backend, self.text) class Meta: abstract = True class IncomingMessage(MessageBase): received = models.DateTimeField(auto_now_add=True) class OutgoingMessage(MessageBase): sent =
models.DateTimeField(auto_now_add=True)
# I was just curious how well I coul
d approximate the rl5 starting values # with an interpolative scheme from quadracheer.rl5 import * import numpy as np import matplotlib.pyplot as plt fnc = lambda ay, by: mu_5_4(ay, by, k1(ay, by), k2(ay, by)) ay = np.linspace(-2, 2, 100) by = np.linspace(-2.0, 2.0, 100) Ay, By = np.meshgrid(ay, by) f = np.log(np.ab...
abel(r'$b_y$') plt.colorbar() plt.show()
import time import math import cv2 from pymavlink import mavutil from droneapi.lib import VehicleMode, Location import sc_config from sc_video import sc_video from sc_webcam import SmartCameraWebCam from sc_SonyQX1 import SmartCamera_SonyQX """ sc_main.py - runs top level smart camera function To run this module: * R...
e_alt) self.home_initialised = True else: sel
f.mission_cmds = None # To-Do: if we wish to have the same home position as the flight controller # we must download the home waypoint again whenever the vehicle is armed # return whether home has been initialised or not return self.home_initialised # checks if video outpu...
#!/usr/bin/python2.6 # -*- coding: utf8 -*-
""" settings.py: Config des utilitaires pul_* permettant la consultation et l'edition des jobs en batch """ __author__ = "Jerome Samson" __copyright__ = "Copyright 2013, Mikros Image" class Settings(object): # Global tools attributes verbose = False # Initial server/port config hostname = "puliserve...
time_format = '%H:%M:%S'
code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import os import re import signal import subprocess import sys import tempfile from telemetry.core import platform from telemetry.core import util from telemetry.core.platform import profiler from telemetry.core.platform....
ymfs_root = os.path.dirname(self._output_file) kallsyms = android_profiling_helper.CreateSymFs(device, symfs_root, required_libs, use_symlinks=True) ...
allsyms %s' % (symfs_root, kallsyms) for lib in required_libs: lib = os.path.join(symfs_root, lib[1:]) if not os.path.exists(lib): continue objdump_path = android_profiling_helper.GetToolchainBinaryPath( lib, 'objdump') if objdump_path: cmd += ' --ob...
self.f = open(state_fn,'w') self.f_contact = None if contact_fn != None: print "SimLogger: Saving contacts to",contact_fn self.f_contact = open(contact_fn,'w') self.colliding = [] if colliding=='all': self.sim.enableContactFeedbackAll() ...
xrange(world.robot(i).numDrivers()): elements.append(n+'_t['+str(j)+']') if self.saveSensors: j = 0 while True: s = self.sim.controller(i).sensor(j) if len(s.name())==0: break ...
(len(names)): elements.append(n+'_'+s.name()+'['+names[sn]+']') j += 1 for i in xrange(world.numRigidObjects()): n = world.rigidObject(i).getName() elements += [n+'_'+suffix for suffix in ['comx','comy','comz','x','y','z','rx','ry','rz','dx','d...
# Copyright (C) 2016 William Langhoff WildBill567@users.noreply.github.com # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your optio...
n a feed-forward network. Adapted fro
m: https://github.com/CodeReclaimers/neat-python, accessed May 2016 :param inputs: list of the network input nodes :param connections: list of (input, output) connections in the network. Returns a list of layers, with each layer consisting of a set of node identifiers. """ # TODO: Detect and omit...
import pygtk import gtk import dill pygtk.require('2.0') class TreeStoreFunctions(): def get_
children(self, root_iter): children = [] for i in range(0, self.treestore.iter_n_children(ro
ot_iter)): children.append(self.treestore.iter_nth_child(root_iter, i)) return children
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of SickRage. # # SickRage is free software: you c
an 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. # # SickRage is distributed in the hope that i
t will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with SickRage. If not, see <http://www.gnu.org...
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2018-04-30 14:47 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('parliament', '0029_auto_20180323_1039'), ] operations = [
migrations.AlterField( model_name='interjection', name='type', field=models.IntegerFiel
d(choices=[(1, 'Applause'), (2, 'Speech'), (3, 'Objection'), (4, 'Amusement'), (5, 'Laughter'), (6, 'Outcry')]), ), ]
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2019 The FATE 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 # # ht
tp://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permis...
#################################################################### # # AUTO GENERATED TRANSFER VARIABLE CLASS. DO NOT MODIFY # ################################################################################ from federatedml.transfer_variable.base_transfer_variable import BaseTransferVariables # noinspection PyAtt...
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright © Spyder Project Contributors # # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) # ----------------------------------------------------------------------------- ...
_set_relative_pythonpath) # --- Python Path def is_in_pythonpath(self, dirname): """Return True if dirname is in project's PYTHONPATH""" return fixpath(dirname) in [fixpath(_p) for _p in self.pythonpath] def get_python
path(self): """Return a copy of pythonpath attribute""" return self.pythonpath[:] def set_pythonpath(self, pythonpath): """Set project's PYTHONPATH""" self.pythonpath = pythonpath self.save() def remove_from_pythonpath(self, path): """Remove path from ...
class Video(object): def __init__(self, json): se
lf.id = json['id'] self.slug = json['slug'] self.title = json['title'] self.presenters = json['presenters'] self.host = json['host'] self.embed_code = json['embed_code'] def presenter_names(self): return ', '.join(map(lambda p: p['first_name'] + ' ' + p['last_name'], self.presenters)) def ...
return 'plugin://plugin.video.%s/?action=play_video&videoid=%s' % (self.host, self.embed_code) def is_available(self): return True if self.embed_code else False
# -*- coding: utf-8 -*- # P
art of Odoo. See LICENSE file for full copyright and licensing details. from . import account_bank_statement from . import account_
journal from . import barcode_rule from . import pos_category from . import pos_config from . import pos_order from . import pos_session from . import product from . import res_partner from . import res_users
# -*- coding: utf-8 -*- # Copyright 2019 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """build_target_lib tests.""" from __future__ import print_function import os from chromite.lib.build_target_lib import BuildTa...
lf.sysroot_denormalized = os.path.join(self.tempdir, 'dne', '..',
'sysroot') osutils.SafeMakedirs(self.sysroot) def testEqual(self): """Sanity check for __eq__ method.""" bt1 = BuildTarget('board', profile='base') bt2 = BuildTarget('board', profile='base') bt3 = BuildTarget('different', profile='base') self.assertEqual(bt1, bt2) self.assertNotEqual...
#!/usr/bin/python # Copyright (C) 2015 Patrick Happel <patrick.happel@rub.de> # # This file is part of pySICM. # # pySICM 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 (a...
sys.path.append(os.path.abspath('./pySICM/'))
sys.path.append(os.path.abspath('./pySICMgui/')) from pySICM.pysicmcore import PySicmCore PySicmCore(PySicmCore.CLIENT) else: usage(allargs[0]) sys.exit(2) if __name__ == "__main__": main(sys.argv)
f.start_html=start_html self.end_html=end_html self.embed_css=embed_css self.css=css self.link_generator=link_generator if imagedir and imagedir[-1] != os.path.sep: imagedir += os.path.sep #make sure we end w/ slash if not imagedir: imagedir = "" #make sure it's a string ...
elif attr == 'instructions': it
emprop = 'recipeInstructions' if itemprop: self.out.write('<p class="%s"><span class="label">%s:</span> <span itemprop="%s">%s</span></p>\n' % (attr, label.capitalize(), itemprop, xml.sax.saxutils.escape(text))) else: self.out.write("<p class='%s'><span class='lab...
# -*- coding: utf-8 -*- from collections import Counter from copy import deepcopy from math import sqrt from random import sample as random_sample from string import ascii_uppercase class SudokuBoard(object): """Create a Sudoku Board of variable size The method will create the random sudoku Board of vari...
initial_matrix = [board_list] for i in range(1, self.size): rhs = board_list[i:] lhs = board_list[:i] new_list = rhs + lhs initial_matrix.append(new_list) return initial_matrix def get_full_board(self): """Get the full random board ...
mns in the matrix. For this, we switch rows and columns that are within the base groups. ex. if the base is 3, we switch the following groups with each other: - 1, 2, 3 - 4, 5, 6 - 7, 8, 9 """ self.board = self.get_initial_...
from django.contrib import admin from django import forms from django.contrib.auth.models import User from sa
mple.mod
els import (Doctor, Worker, Patient, SpecialtyType, TimeSlot, Case, Comment, CommentGroup, Scan) class searchDoctor(admin.ModelAdmin): list_display = ['user_first_name', 'user_last_name', 'get_some_value'] search_fields = ['user__first_name', 'user__last_name', 'specialties__name'...
# coding: utf-8 #Created on 05.06.2012 #Copyright (C) 2013 Fabian Hachenberg #This file is part of EcstaticaLib. #EcstaticaLib 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...
#run-length times the following pixel value lastcolor = ((bytedata[pos] + (bytedata[pos+1] << 8)) << 2) & 0xffff for i in range(runlength): out.append(lastcolor) pos += 2 return out import unittest import struct import
itertools class TestView(unittest.TestCase): def test_decodepixels(self): #we have to load data for testing viewfileobj = open("test/views/0002.raw", "rb") typemark = viewfileobj.read(2) len_a = struct.unpack("<i", viewfileobj.read(4))[0] len_b = struct.unp...
import json from pimlico.datatypes.corpora.json import JsonDocumentType from pimlico.cli.brow
ser.tools.formatter import DocumentBrowserFormatter class JsonFormatter(DocumentBrowserFormatter): DATATYPE = JsonDocumentType() def format_document(self, doc):
return json.dumps(doc.data, indent=4)
#!/usr/bin/env python # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that ...
etwork.hosts import LocalHost class Bridging(Test): ''' Test bridge interface ''' def check_failure(self, cmd): if process.system(cmd, sudo=True, shell=True, ignore_status=True): self.fail("Command %s failed" % cmd) def setUp(self): self.host_interfaces = self.params....
ot self.host_interfaces: self.cancel("User should specify host interface/s") if self.host_interfaces[0:2] == 'ib': self.cancel("Network Bridge is not supported for IB") interfaces = netifaces.interfaces() for host_interface in self.host_interfaces: if host_i...
# -*- coding: utf-8 -*- import rapidsms import datetime from rapidsms.apps.base import AppBase from .models import Poll from django.db.models import Q from rapidsms_httprouter.models import Message,MessageBatch class App(AppBase): def respond_to_message(self,message,response_msg,poll): if response_msg ==...
se else: response_obj, response_msg = poll.process_response(message) if hasattr(message, 'db_message'): # if no other app handles this message, we want # the handled_by field set appropriately, ...
db_message = message.db_message db_message.handled_by = 'poll' db_message.save() if response_msg and response_msg.strip(): self.respond_to_message(message,response_msg,poll) elif poll.default_re...
ou can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even th...
() page_title = topic.title page_description = u'大家正在讨论:{}'.format(topic.title) return render('topic_detail.html',locals(),context_instance=RequestContext(request)) def list_by_tag(request,tag_name): current_page = 'topic' """ 按标签列出话题 """ try: tag_name = tag_name ...
.get('page',20)) except ValueError: page = 1 topic_all = Topic.objects.filter(tag=tag,deleted=False) paginator = Paginator(topic_all,1) title = u'标签:%s' %tag.name try: entrys = paginator.page(page) except (EmptyPage,InvalidPage): entrys = paginator.page(paginator...
#coding=utf-8 from functools
import wraps from flask import abort from flask_login import current_user from app.models import Permission
def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if not current_user.can(permission): abort(403) return f(*args, **kwargs) return decorated_function return decorator def admin_required(f): ...
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-01-19 15:28 from __future__ import unicode_literals import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('races', '0001_initial'), ] opera...
reated_at', field=models.DateTimeField(auto_now_add=True, default=datetime.datetime(2016, 1, 19, 15, 28, 29, 178154, tzinfo=utc)), preserve_default=False, ),
migrations.AddField( model_name='race', name='updated_at', field=models.DateTimeField(auto_now=True, default=datetime.datetime(2016, 1, 19, 15, 28, 36, 816957, tzinfo=utc)), preserve_default=False, ), ]
import functools as ft import math from collections import OrderedDict import numba import numpy as np from sde import SDE # from simulation.strong.explicit.predictorcorrector import Order_10 as pc_e from simulation.strong.explicit.rk import Order_10 as rk_e from simulation.strong.explicit.taylor import Order_05 as E...
for i in resolutions] differentials = [np.random.standard_normal(max(stepsizes)) * math.sqrt(end_
point / max(stepsizes)) for i in range(num_samples)] analytical_values = np.full([num_samples, len(stepsizes)], np.nan) scheme_values = [np.full([num_samples, len(stepsizes)], np.nan) for s in list_of_schemes] list_scheme_instances = [list_of_schemes for i in range(num_samples...
# -*- coding: utf-8 -*- import re import urlparse from module.plugins.captcha.ReCaptcha import ReCaptcha from module.plugins.internal.SimpleHoster import SimpleHoster, create_getInfo class Keep2ShareCc(SimpleHoster): __name__ = "Keep2ShareCc" __type__ = "hoster" __version__ = "0.25" __status__...
ee download link not found")) self.link = m.group(1) def handle_captcha
(self): post_data = {'free' : 1, 'freeDownloadRequest': 1, 'uniqueId' : self.fid, 'yt0' : ''} m = re.search(r'id="(captcha\-form)"', self.html) self.log_debug("captcha-form found %s" % m) ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 待匹配的数据 (tofill)及匹配数据池(pool),存储于csv文件中,两个csv都要包含主键列, 及数据列。脚本将对tofill的每一条数据字段,在pool文件的数据列中做匹配,如果pool 数据列包含tofile列数据,则将各自主键列建立一条关系记录,存储在结果文件csv中 以上提到的csv文件,格式要求: 使用逗号分隔,字段可以使用双引号括起。 不支持字段内换行 必须包含主键列,主键列不得重复 主键列在数据列后 ---- 事实上,两表主键列可以重复,只不过对应关系也是重复的;恰好需此...
src=p[1] break if ok: print "toofill[%s]:%s found in pool[%s]:%s ...... %s"%(f[0],f[1],p[0],p[1],ok) else: pass print "\n%s records matched, written to file output.csv."%(len(match)) #raw_input(' pr
ess any key to exit')
import datetime from django.db import models from django.core.exceptions import ValidationError def validate_year(year): if year is None: return # Years can be null if year < 1800 or year > datetime.datetime.now().year: raise ValidationError("Not a valid year.") def validate_day_of_month(d...
_length=10, default="") accession
= models.CharField(max_length=20, default="") year_collected = models.PositiveSmallIntegerField(null=True, validators=[validate_year]) month_collected = models.PositiveSmallIntegerField(null=True, choices=MONTH_CHOICES) day_collected = models.PositiveSmallIntegerField(null=True, validators=[validate_day_of...
# Copyright (c) 2012 Patrick Dunnigan # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in the # Software without restriction, inc
luding without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell copies of # the Software, and to permit persons to whom the Software is furn
ished to do so, # subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, # INCLUDING BUT NOT LIMITED TO THE WARRANTI...
# -*- coding: utf-8 -*- ############################################################################## # # jasper_server module for OpenERP # Copyright (c) 2008-2009 EVERLIBRE (http://everlibre.fr) Eric VERNICHON # Copyright (C) 2009-2011 SYLEAM ([http://www.syleam.fr]) Christophe CHAUVET # # This file is a...
should have received a copy of the GNU General Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. # ############################################################################## { 'name': 'JasperReport Server Interface', 'version': '6.3', 'category': 'Reporting', ...
ment source must be in CSV, XML - Save document as attachment on object - Retrieve attachment if present - Launch multiple reports and merge in one printing action - Add additionnals parameters (ex from fields function) - Affect group on report - Use context to display or not the print button (eg: in stock.picking ...
im = open('006993_phot
oA.tif', 'rb') ord(im.read(1)) c
hr(ord(im.read(1)))
"schedule_at": None, "started_at": None, "finished_at": None, "duration": None, "is_independent": False, "cloning_kind": V1CloningKind.COPY, "original_uuid": "uuid-copy", "store_path": "/claim...
ICE, "ports": [1212, 1234], "container": {"image": "test", "command": "{{ ports[0] }}"},
}, } ) spec = resolve_contexts( namespace="test", owner_name="user", project_name="project", project_uuid="uuid", run_uuid="uuid", run_name="run", run_path="test", compiled_operation=compiled...
"""Order a block storage replica volume.""" # :license: MIT, see LICENSE for more details. import click import SoftLayer from SoftLayer.CLI import environment from SoftLayer.CLI import exceptions
CONTEXT_SETTINGS = {'token_normalize_func': lambda x: x.upper()} @click.command(context_settings=CONTEXT_SETTINGS) @click.argument('volume_id') @click.option('--snapshot-schedule', '-s', help='Snapshot schedule to us
e for replication, ' '(HOURLY | DAILY | WEEKLY)', required=True, type=click.Choice(['HOURLY', 'DAILY', 'WEEKLY'])) @click.option('--location', '-l', help='Short name of the data center for the replicant ' '(e.g.: dal09)', required=True)...
import os.pat
h from gi.repository import Gst, GstPbutils DEFAULT_IMAGE_PATH = './openmedia/gui/res/img/no_image.png' class Track(object): """ This holds data about media files. The information about the media file
associated with this includes the name, file path, duration and metadata. """ def __init__(self, file_path): """ Create a track using data from the specified file. Parameters ---------- :param file_path: the path of the file out of which to create a track :...
import numpy from srxraylib.plot.gol import plot_image, plot import sys from comsyl.scripts.CompactAFReader import CompactAFReader def plot_stack(mystack,what="intensity",title0="X",title1="Y",title2="Z"): from silx.gui.plot.StackView import StackViewMainWindow from silx.gui import qt app = qt.QAppl...
sers/srio/OASYS_VE/comsyl_srio/calculations/new_u18_2m_1h_s2.5") plot_stack(mystack,what="intensity", title0="Mode index", title1="V from %3.2f to %3.2f um"%(1e3*v.min(),1e3*v.max()),
title2="H from %3.2f to %3.2f um"%(1e3*h.min(),1e3*h.max())) plot(numpy.arange(occupation.size),occupation)
""" [2017-04-14] Challenge #310 [Hard] The Guards and the Mansion https://www.reddit.com/r/dailyprogrammer/comments/65fkwh/20170414_challenge_310_hard_the_guards_and_the/ # Description I recently came into some money and built myself a mansion. And I'm afraid of robbers who now want to come and steal the rest of my m...
input* tell me how many triangles I can make that fully enclose my mansion at (0,0) with a unit radius of 1. Example: 0 0 1 2 # Challenge Input 10 2 -7 2 2 4 -9 -4 -6 9 3 -8
-7 6 0 -5 -6 -1 -1 -7 10 """ def main(): pass if __name__ == "__main__": main()
# -*- coding: utf-8 -*- from operator import attrgetter from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType from pyangbind.lib.yangtypes import RestrictedClassType from pyangbind.lib.yangtypes import TypedListType from pyangbind.lib.yangtypes import YANGBool from pyangbind.lib.yangtypes import YANGListTy...
N parameters associated with interfaces """ _pyangbind_elements = {} class openconfig_vlan(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-vlan - based on the path /openconfig-vlan. Each member element of the container is represented as a c...
ers associated with interfaces """ _pyangbind_elements = {}