prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
[0, 0.3, 0.6]}) cut = {'front': 3, 'back': 4} ts_pvrow = TsPVRow.from_raw_inputs( xy_center, width, df_inputs.rotation_vec, cut, df_inputs.shaded_length_front, df_inputs.shaded_length_back) # Plot it at ts 0 f, ax = plt.subplots() ts_pvrow.p...
pvground.list_segme
nts[0].shaded_collection.length == 5 np.testing.assert_allclose(pvground.shaded_length, 5) # Run some checks for index 1 pvground = ts_ground.at(1, with_cut_points=False) assert pvground.n_surfaces == 5 assert pvground.list_segments[0].illum_collection.n_surfaces == 3 assert pvground.list_segme...
# # (c) 2020 Red Hat Inc. # # This file is part of Ansible # # Ansible 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. # # Ansible is distributed in the hope that it will be useful, #
but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make ...
#!/usr/bin/python # _*_ coding: utf-8 _*_ import zlib s = b'witch which has which witches wrist
watch' print len(s) t = zlib.compress(s) print len(t) print t print zlib.decompress(t) print zlib.crc32(s)
# UrbanFootprint v1.5 # Copyright (C) 2017 Calthorpe Analytics # # This file is part of UrbanFootprint version 1.5 # # UrbanFootprint is distributed under the terms of the GNU General # Public License version 3, as published by the Free Software Foundation. This # code is distributed WITHOUT ANY WARRANTY, without impl...
{output_file_name}'.format( pg_conn_string=build_postgres_conn_string(settings.DATABASES['default']), output_file_name=pg_output_file_name) output = self.exec_cmd(pg_dump) self.stdout.write(output)
self.stdout.write('Wrote ' + pg_output_file_name + '\n') def exec_cmd(self, cmd): p = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, err = p.communicate() if p.returncode != 0: raise CommandError('Error Executing "{cmd}\n{output}\...
# Copyright 2011 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...
sion_request \ import MAX_PROXY_API_SUPPORT_VERSION from nova.api.openstack.api_version_request \ import MIN_WITHOUT_IMAGE_META_PROXY_API_VERSION from nova.api.openstack.api_version_request \ import MIN_WITHOUT_PROXY_API_SUPPORT_VERSION from nova.api.openstack.compute.schemas import limits from nova.api.ope...
s limits_policies from nova import quota QUOTAS = quota.QUOTAS # This is a list of limits which needs to filter out from the API response. # This is due to the deprecation of network related proxy APIs, the related # limit should be removed from the API also. FILTERED_LIMITS_2_36 = ['floating_ips', 'security_groups'...
"""Config flow for OpenWeatherMap.""" from pyowm import OWM from pyowm.exceptions.api_call_error import APICallError from pyowm.exceptions.api_response_error import UnauthorizedError import voluptuous as vol from homeassistant import config_entries from homeassistant.const import ( CONF_API_KEY, CONF_LATITUDE,...
} ) async def _is_owm_api_online(hass, api_key): owm = OWM(api
_key) return await hass.async_add_executor_job(owm.is_API_online)
twork interface. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param network_interface_name: The name of the network interface. :type network_interface_name: str :param expand: Expands referenced resources. :type expand: str ...
ialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs
= {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'NetworkInterface') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run...
# SPDX-License-Identifier: GPL-2.0+ # Copyright (c) 2016 Google, Inc # Written by Simon Glass <sjg@chromium.org> # # Entry-type module for the 16-bit x86 reset code for U-Boot # from binman.entry import Entry from binman.etype.blob import Entry_blob class Entry_x86_reset16(Entry_blob): """x86 16-bit reset code fo...
ode
is responsible for jumping to the x86-start16 code, which continues execution. For 64-bit U-Boot, the 'x86_reset16_spl' entry type is used instead. """ def __init__(self, section, etype, node): super().__init__(section, etype, node) def GetDefaultFilename(self): return 'u-boot-x86-...
name_plural = '视频地区' def __str__(self): return self.name class VideoCategory(models.Model): name = models.CharField(max_length=128, verbose_name='分类名称') type = models.CharField(max_length=128, choices=TYPES, default='common', verbose_name='类型') isSecret = models.BooleanField(default=False, ve...
.video.name is not in the LOCAL_FOLDER if not self.video.name.startswith(settings.LOCAL_FOLDER_NAME) and \ not self.video.name.startswith(setting
s.RECORD_MEDIA_FOLDER): self.video.name = str(rel_name) logging.debug('save_path:', self.save_path) logging.debug('video.name:', self.video.name) logging.debug('size:', self.video.file.size) self.file_size = humanfriendly.format_size(se...
# coding=utf-8 """Request handler for authentication.""" from __future__ import unicode_literals import logging import random import string import time from builtins import range import jwt from medusa import app, helpers, notifiers from medusa.logger.adapters.style import BraceAdapter from medusa.server.api.v2.base...
vided') if self.request.headers['content-type'] != 'application/json': return self._failed_login(error='Incorrect content-type') request_body = json_decode(self.request.body) submitted_username = request_bod
y.get('username') submitted_password = request_body.get('password') submitted_exp = request_body.get('exp', 86400) if username != submitted_username or password != submitted_password: return self._failed_login(error='Invalid credentials') return self._login(submitted_exp) ...
_modules(modules, options, sender, tags): """Reloads any changed modules from the 'etc' directory. Args: cdir: The path to the 'collectors' directory. modules: A dict of path -> (module, timestamp). Returns: whether or not anything has changed. """ etcdir = os.path.join(options.cdir, '...
TY_TIME): # It's too old, kill it LOG.warning('Terminating collector %s after %d seconds of inactivity', col.name, now - col.last_datapoint) col.shutdown() register_collector(Collector(col.na
me, col.interval, col.filename, col.mtime, col.lastspawn)) def set_nonblocking(fd): """Sets the given file descriptor to non-blocking mode.""" fl = fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK fcntl.fcntl(fd, fcntl.F_SETFL, fl) def spawn_collector(col): """...
#!/usr/bin/env python import numpy as np import os import shutil import mss import matplotlib matplotlib.use('TkAgg') from datetime import datetime from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg as FigCanvas from PIL import ImageTk, Image import sys PY3_OR_LATER...
UI self.create_main_panel() # Timer
self.rate = IDLE_SAMPLE_RATE self.sample_rate = SAMPLE_RATE self.idle_rate = IDLE_SAMPLE_RATE self.recording = False self.t = 0 self.pause_timer = False self.on_timer() self.root.mainloop() def create_main_panel(self): # Panels top_ha...
# This file is part of Buildbot. Buildbot 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, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
OSE. See the GNU Gen
eral Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from __future__ import absolute...
from hypothesis import given from ppb_v
ector import Vector from utils import floats, vectors @given(x=floats(), y=floats()) def test_class_member_access(x: float, y: float): v = Vector(x, y) assert v.x == x assert v.y == y @given(v=vectors()) def test_index_access(v: Vector): assert v[0] == v.x assert v[1] ==
v.y @given(v=vectors()) def test_key_access(v: Vector): assert v["x"] == v.x assert v["y"] == v.y
atol and btol. = 2 means x approximately solves the least-squares problem according to atol. = 3 means COND(A) seems to be greater than CONLIM. = 4 is the same as 1 with atol = btol = eps (machine precision) ...
iables for estimation of ||r||.
betadd = beta betad = 0 rhodold = 1 tautildeold = 0 thetatilde = 0 zeta = 0 d = 0 # Initialize variables for estimation of ||A|| and cond(A) normA2 = alpha * alpha maxrbar = 0 minrbar = 1e+100 normA = sqrt(normA2) condA = 1 normx = 0 # Items for use in stopp...
from datetime import datetime from django.core.files import storage from django.contrib.staticfiles.storage import CachedStaticFilesStorage class DummyStorage(storage.Storage): """ A storage class that does implement modified_time() but raises NotImplementedError when calling """ def _save(self, n...
pass def modified_time(self, name): return datetime.date(1970, 1, 1) class SimpleCachedStaticFilesStorage(CachedStaticFilesStorage): def file_hash(self, name, content=N
one): return 'deploy12345'
for agent in stmt['authority']['member']: if 'account' in agent: if not 'oauth' in agent['account']['homePage'].lower(): err_msg = "Statements cannot have a non-Oauth group as the authority" ...
", "activity", "registration", "related_activities", "related_agents", "since", "until", "limit", "format", "attachments", "ascending"]) if rogueparams:
raise ParamError("The get statements request contained unexpected parameters: %s" % ", ".join(rogueparams)) formats = ['exact', 'canonical', 'ids'] if 'params' in req_dict and 'format' in req_dict['params']: if req_dict['params']['format'] not in formats: raise ParamError("The format filter...
#============================================================================ # This library is free software; you can redistribute it and/or # modify it under the terms of version 2.1 of the GNU Lesser General Public # License as published by the Free Software Foundation. # # This library is distributed in the hope th...
=============================
============================================ from xen.xend.XendAPIConstants import * from xen.util import auxbin # # Shutdown codes and reasons. # DOMAIN_POWEROFF = 0 DOMAIN_REBOOT = 1 DOMAIN_SUSPEND = 2 DOMAIN_CRASH = 3 DOMAIN_HALT = 4 DOMAIN_SHUTDOWN_REASONS = { DOMAIN_POWEROFF: "poweroff", DOM...
# Copyright 2013 Ken Pepple <ken@pepple.info> # # 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 # # U...
T # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License.
import alfred_utils as utils import requests PROWL_URL = "https://api.prowlapp.com/publicapi/" DEFAULT_PRIORITY = 0 VALID_PRIORITIES = [-2, -1, 0, 1, 2] def get_api_key(): return utils.get_config('apikey') def get_priority_key(): try: p = utils.get_config('priority') if p not in VALID_PRIORI...
# Copyright(c)2015 NTT corp. 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 app...
implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.api.object_storage import test_container_sync from tempest import config from tempest import test CONF = config.CONF # This test can be quite long to run due to its # dependency on cont...
e # container-server configuration. class ContainerSyncMiddlewareTest(test_container_sync.ContainerSyncTest): @classmethod def resource_setup(cls): super(ContainerSyncMiddlewareTest, cls).resource_setup() # Set container-sync-realms.conf info cls.realm_name = CONF.object_storage.real...
from __future__ import absolute_import #
Copyright (c) 2010-2015 openpyxl from .formatting import ConditionalFormatting fro
m .rule import Rule
import json import time import pytest from anchore_engine.auth.common import ( get_creds_by_registry, get_docker_registry_userpw, registry_record_matches, ) _test_username = "tonystark" _test_password = "potts" _test_registry_meta = { "authorizationToken": "{}:{}".format(_test_username, _test_passwor...
registry_record_matches_wildcard(registry_record_str, registry, repository): assert registry_record_matches(registry_record_str, registry, repository) @pytest.mark.parametrize( "registry_record_str,registry,repository"
, [ ("docker.io", "gcr.io", "myproject/myuser"), ("docker.io/*", "gcr.io", "myproject/myuser"), ("docker.io/library/*", "docker.io", "myuser/myrepo"), ("docker.io/myuser/myrepo", "docker.io", "myuser/myrepo2"), ], ) def test_registry_record_matches_non(registry_record_str, regist...
#!/usr/bin/env python3 """ sumton.py : compute the sum of 0 through N Copyright (C) Simon D. Levy 2016 This file is part of ISCPP. ISCPP is free software: you can re
distribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your optio
n) any later version. This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Publi...
#!/usr/bin/env python2 # This file is part of Archivematica. # # Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com> # # Archivematica is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, ...
rc, dst) try: SIP.objects.get(uuid=originalSIPUUID) except SIP.DoesNotExist: # otherwise doesn't appear in dashboard createSI
P(unitPath, UUID=originalSIPUUID) Job.objects.create(jobtype="Hack to make DIP Jobs appear", directory=unitPath, sip_id=originalSIPUUID, currentstep="Completed successfully", unittype="unitSIP", ...
rent_exp_end_date = frappe.db.get_value("Task", self.parent_task, "exp_end_date") if parent_exp_end_date and getdate(self.get("exp_end_date")) > getdate(parent_exp_end_date): frappe.throw(_("Expected End Date should be less than or equal to parent task's Expected End Date {0}.").format(getdate(parent_exp_end_dat...
pe.whitelist() def check_if_child_exists(name): child_tasks = frappe.get_all("Task", filters={"parent_task": name}) child_tasks = [get_link_to_form("Task", task.name) for task in child_tasks] return child_tasks @frappe.whitelist() @frappe.validate_and_sanitize_search_inputs def get_project(doctype, txt, searchfiel...
search_fields() search_columns = ", " + ", ".join(searchfields) if searchfields else '' search_cond = " or " + " or ".join([field + " like %(txt)s" for field in searchfields]) return frappe.db.sql(""" select name {search_columns} from `tabProject` where %(key)s like %(txt)s %(mcond)s {search_condition} or...
#!/usr/bin/env python # encoding: utf-8 """ Show how to use `dur` and `delay` parameters of play() and out() methods to sequence events over time. """ from pyo import * import random s = Server(duplex=0).boot() num = 70 freqs = [random.uniform(100, 1000) for i in range(num)] start1 = [i * 0.5 for i in range(num)] fa...
delay=start2) b = Beat(time=0.125, w1=[90, 30, 30, 20], w2=[30, 90, 50, 40], w3=[0, 30, 30, 40], poly=1).play(dur=dur2, delay=start2) out = TrigEnv(b, tabs, b["dur"], mu
l=b["amp"] * fade2).out(dur=dur2, delay=start2) start3 = 45 dur3 = 30 fade3 = Fader(15, 15, dur3, mul=0.02).play(dur=dur3, delay=start3) fm = FM(carrier=[149, 100, 151, 50] * 3, ratio=[0.2499, 0.501, 0.75003], index=10, mul=fade3).out( dur=dur3, delay=start3 ) s.gui(locals())
# -*- coding: utf-8 -*- from Headset import Heads
et import logging import time puerto = 'COM3' headset = Headset(logging.INFO) try: headset.connect(puerto, 115200) except Exception, e: raise e print "Is conected? " + str(headset.isConnected()) print "-
----------------------------------------" headset.startReading(persist_data=True) time.sleep(5) headset.stopReading() headset.closePort() print "-----------------------------------------" print "Is conected? " + str(headset.isConnected()) print headset.getStatus()
import sublime import sublime_plugin import re import os import datetime TMLP_DIR = 'templates' KEY_SYNTAX = 'syntax' KEY_FILE_EXT = 'extension' IS_GTE_ST3 = int(sublime.version()) >= 3000 PACKAGE_NAME = 'new-file-pro' PACKAGES_PATH = sublime.packages_path() BASE_PATH = os.path.abspath(os.path.dirname(__file__)) cla...
'js': 'js', 'json': 'json', 'php': 'php', 'php-class': 'php', 'php-interface': 'php', 'xml':'xml', 'python': 'python', 'ruby': 'ruby'} try: t_ext = exts[t] if (s_ext == t_ext and length == 1) or s_ext != t_ext: return
name + '.' + t_ext except KeyError: pass return name; def appendPHPExtension(self, name): t = name.split('.') length = len(t) ext = t[length - 1] if ext != "php": return name + '.php' return name; def get_code(self, type='text' ): code = '' file_name = "%s.tmpl" % type isIOError = False ...
Move SCU application. For sending Query/Retrieve (QR) C-MOVE requests to a QR Move SCP. """ import argparse import sys from pynetdicom import ( AE, evt, QueryRetrievePresentationContexts, AllStoragePresentationContexts, ) from pynetdicom.apps.common import setup_logging, create_dataset, handle_store...
mentParser( description=( "The movescu application implements a Service Class User (SCU) " "for the Query/Retrieve (QR) Service Class and (optionally) a " "Storage SCP for the Storage Service Class. movescu supports " "retrieve functionality using the C-MOVE messa...
purpose of receiving images sent as a " "result of the C-MOVE request. movescu can initiate the transfer " "of images to a third party or can retrieve images to itself " "(note: the use of the term 'move' is a misnomer, the C-MOVE " "operation performs a SOP Instance cop...
from sys import exit from random import randint def death(): quips = ["You died. You kinda suck at this.", "Your mom would be proud. If she were smarter.", "Such a luser.", "I have a small puppy that's better at this."] print quips[randint(0,len(quips)-1)] exit(1) def princess_lives_here(): print "Y...
munching on your torso. Yum!" return 'death' elif eat_it == "make her eat it": print "The Princess screams as you cram the cake in her mouth." print "Then she smiles and cries and thanks you for saving her." print "She points to a tiny door and says, 'The Koi needs cake too.'" print "She gives you the very ...
ss_lives_here' def gold_koi_pond(): print "There is a garden with a koi pond in the center." print "You walk close and see a massive fin pole out." print "You peek in and a creepy looking huge Koi stares at you." print "It opens its mouth waiting for food." feed_it = raw_input("> ") if feed_it == "feed it": ...
quota_project_id=client_options.quota_project_id, client_info=client_info, always_use_jwt_access=( Transport == type(self).get_transport_class("grpc") or Transport == type(self).get_transport_class("grpc_asyncio") ), ...
ing jobs on Cloud, managers and labelers work with the jobs using CrowdCompute console. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments
that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) # Minor opti...
# -*- coding: utf-8 -*- { 'name': 'Import OFX Bank Statement', 'category': 'Banking addons', 'version': '8.0.1.0.1', 'license': 'AGPL-3', 'author': 'OpenERP SA,' 'Odoo Community Association (OCA)', 'website': 'https://github.com/OCA/bank-statement-import', 'depends': [ ...
_bank_statement_import' ], 'demo': [ 'demo/demo_data.xml', ], 'external_dependencies': { 'python': ['ofxparse'], }, 'auto_install': False,
'installable': True, }
r[int(Singleton.state.spinner_frame/20)]) self.mw.widget.update() else: self.mw.progress_label.set_text("No task running") self.mw.widget.update() def update_settings(self, args): dbgfname() debug(" settings update: "+str(args)) setting = args[0]...
ingleton.state.scale[0])) elif self.ctrl_pressed: offset = Singleton.state.get_base_offset() Singleton.mw.widget_hscroll.set_value(-(offset[0]+10*Singleton.state.scale[0])) else: osx, osy = Singleton.state.scale if Singleton.state.scale[0]<=0.01: ...
[0]*1.5, Singleton.state.scale[1]*1.5) tx, ty = Singleton.state.get_offset() sx, sy = Singleton.state.get_screen_size() px, py = self.pointer_position nsx, nsy = Singleton.state.scale debug(" Old px, py: %f, %f"%(px, py)) debug(" Screen size: %s"...
from zope.
interface import Interface, Attribute from zope import schema from uwosh.emergency.client.config import mf as _ class IUWOshEmergencyClientLayer(Interface): """Marker interface that defines a browser layer "
""
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
per_time = [] for time_sec in xrange(start_time_sec, end_time_sec + 1): # assume that value is 0 if it is not read by jmx tool at the given time. This is appropriate for metrics such as bandwidth values_per_node = [time_to_stats.get(time_sec, {}).get(name, 0) for time_to_stat...
propriate for metrics such as bandwidth aggregates_per_time.append(sum(values_per_node)) self.average_jmx_value[name] = sum(aggregates_per_time) / len(aggregates_per_time) self.maximum_jmx_value[name] = max(aggregates_per_time) def read_jmx_output_all_nodes(self): fo...
ding: utf-8 -*- # # textract documentation build configuration file, created by # sphinx-quickstart on Fri Jul 4 11:09:09 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All conf...
al information about the project. project = u'textract' copyright = u'2014, Dean Malmgren' # The version info for the project you're documenting,
acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = textract.VERSION # The full version, including alpha/beta/rc tags. release = textract.VERSION # The language for content autogenerated by Sphinx. Refer to document...
import random class ImageQueryParser: def __init__(self): pass def parse(self, query_string): tab = query_string.split(" ") last = tab[-1].lower() is_random = False index = 0
if last.startswith("-"): if last == "-r": is_random = True tab.pop() else: try: i
ndex = int(last[1:]) tab.pop() except ValueError: pass query_string = " ".join(tab) return ImageQuery(query_string, is_random, index) class ImageQuery: def __init__(self, query, is_random, index): self.__query = query self.__i...
class Parameter(object): def __init__(self, name): self.name = name class Vehicle(object): def __init__(self, name, path): self.name = name self.path = path self.params = [] class Library(object): def __init__(self, name): self.name = name self.params = [...
s 'cdeg/s' : 'centidegrees per second', # Not SI, but is some situations more user-friendly than radians 'cdeg/s/s': 'centidegrees per square second' , # Not SI, but is some situations more user-friendly than radians 'rad' : 'radians' , 'rad/s' ...
, 'V' : 'volt' , 'W' : 'watt' , # magnetism 'Gauss' : 'gauss' , # Gauss is not an SI unit, but 1 tesla = 10000 gauss so a simple replacement is not possible here 'Gauss/s' : 'gauss per second' ,...
# c
oding=utf-8 HOSTNAME = 'localhost' DATABASE = 'r' USERNAME = 'web' PASSWORD = 'web' DB_URI = 'mysql://{}:{}@{}/{}'.format(
USERNAME, PASSWORD, HOSTNAME, DATABASE)
# Copyright (c) 2008 Joost Cassee # Licensed under the terms of the MIT License (see LICENSE.txt) import logging from django.core import urlresolvers from django.http import HttpResponse from django.shortcuts import render_to_response from django.template import RequestContext, loader from django.utils import simplejs...
result, 'error': None, } except Exception: logging.exception("Erro
r running spellchecker") return HttpResponse(_("Error running spellchecker")) return HttpResponse(simplejson.dumps(output), content_type='application/json') def preview(request, name): """ Returns a HttpResponse whose content is an HTML file that is used by the TinyMCE preview plug...
''' mode
| desc r 또는 rt | 텍스트 모드로 읽기 w 또는 wt | 텍스트 모드로 쓰기 a 또는 at | 텍스트 모드로 파일 마지막에 추가하기 rb | 바이너리 모드로 읽기 wb | 바이너리 모드로 쓰기 ab | 바이너리 모드로 파일 마지막에 추가하기 ''' f = open("./py200_sample.txt", "w") f.write("abcd") f.close() r = open("./py200_sample.txt", "r") print("-" * 60) print(r
.readline()) r.close()
# 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...
es {{.*}} tf_saved_model.exported_names = ["f0006_multiple_return_statements"] @tf.function(input_signature=[tf.TensorSpec([], tf.float32)]) def f0006_multiple_return_statements(self, x): if x > 3.: return
{'x': tf.constant(1.0, shape=[1])} else: return {'x': tf.constant(1.0, shape=[1])} if __name__ == '__main__': common.do_test(TestModule)
import unittest from series import slices # Tests adapted from `problem-specifications//canonical-data.json` @ v1.0.0 class SeriesTest(unittest.TestCase): def test_slices_of_one_from_one(self): self.assertEqual(slices("1", 1), ["1"]) def test_slices_of_one_from_two(self): self.assertEqual(s...
2345", 0) def test_slice_length_cannot_be_negative(self): with self.assertRaisesWithMessage(ValueError): slices("123", -1) def test_empty_series_is_invalid(self): with self.assertRaisesWithMessage(ValueError): slices("", 1) # Utility functions def setUp(self): ...
ithMessage(self, exception): return self.assertRaisesRegex(exception, r".+") if __name__ == "__main__": unittest.main()
r https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type import time from datetime import datetime, timedelta from ansible.errors import AnsibleError from ansible.plugins.action import ActionBase from ansible.module_utils._text import to_nat...
t -ClassName Win32_OperatingSystem).LastBootUpTime" (rc, stdout, stderr) = self._connection.exec_command(uptime_command) if rc != 0: raise Exception("win_reboot: failed to get host uptime info, rc: %d, stdout: %s, stderr: %s" % (rc, stdout, stderr)) retu...
sleep=1): max_end_time = datetime.utcnow() + timedelta(seconds=timeout) exc = "" while datetime.utcnow() < max_end_time: try: what() if what_desc: display.debug("win_reboot: %s success" % what_desc) return ...
LD_ORDER,) = range(3) JOB_REFRESH_RATE = 100 def getwords(s): # We decompose the string so that ascii letters with accents can be part of the word. s = normalize("NFD", s) s = multi_replace(s, "-_&+():;\\[]{}.,<>/?~!@#$*", " ").lower() s = "".join( c for c in s if c in string.ascii_letters + ...
the match. int from 1 to 100. For exact scan methods, such as Contents scans, this will always be 100. """ __slots__ = () def get_match(first, second, flags=()): # it is assumed here that first and second both have a "words" attribute percentage = compare(first.words, second.words, flags) ...
_words=False, no_field_order=False, j=job.nulljob, ): """Returns a list of :class:`Match` within ``objects`` after fuzzily matching their words. :param objects: List of :class:`~core.fs.File` to match. :param int min_match_percentage: minimum % of words that have to match. :param bool match_sim...
#!/usr/bin/env python # encoding: utf-8 """ Copyright (c) 2010 The Echo Nest. All rights reserved. Created by Tyler Williams on 2010-09-01 # 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; eithe...
ils. """ # ======================== # = try_new_things.py = # ======================== # # enter a few of your favorite artists and create a playlist of new music that # you might like. # import sys, os, logging import xml.sax.saxu
tils as saxutils from optparse import OptionParser from pyechonest import artist, playlist # set your api key here if it's not set in the environment # config.ECHO_NEST_API_KEY = "XXXXXXXXXXXXXXXXX" logger = logging.getLogger(__name__) class XmlWriter(object): """ code from: http://users.musicbrainz.org/~matt/xsp...
# -*- coding: utf-8 -*- def main(): startApplication("sasview") clickTab(waitForObject(":FittingWidgetUI.tabFitting_QTabWidget_2"), "Resolution") test.compare(waitForObjectExists(":groupBox_4.cbSmearing_QComboBox").currentIndex, 0) test.compare(str(waitForObjectExists(":groupBox_4.cbSmearing_QComboBox"...
ing_QComboBo
x").count, 1) clickTab(waitForObject(":FittingWidgetUI.tabFitting_QTabWidget_2"), "Model") clickButton(waitForObject(":groupBox.cmdLoad_QPushButton")) waitForObjectItem(":stackedWidget.listView_QListView", "test") doubleClickItem(":stackedWidget.listView_QListView", "test", 36, 4, 0, Qt.LeftButton) ...
from __future__ import absolute_import, division import time import os try: unicode except NameError: unicode = str from . import LockBase, NotLocked, NotMyLock, LockTimeout, AlreadyLocked class SQLiteLockFile(LockBase): "Demonstrate SQL-based locking." testdb = None def __init__(self, path, t...
if len(rows) > 1: # Nope. Someone else got there. Remove our lock. cursor.execute("delete from locks" " where unique_name = ?", (self.unique_name,)) self.connection.commit() ...
up. We're done, so go home. return else: # Check to see if we are the only lock holder. cursor.execute("select * from locks" " where unique_name = ?", (self.unique_name,)) rows...
#!/usr/bin/python import json import sys import data_processing as dp from mython import NumpyToListEncoder from subprocess import check_output from imp import reloa
d reload(dp) # Neat way of calling: # find . -name '*_metadata.json' > rootlist # python gen_json.py $(< rootlist) &> gen_json.out files = sys.argv[1:] roots = [f.replace('_metadata.json','') for f in files] for
root in roots: data = dp.read_dir_autogen(root,gosling='/home/busemey2/bin/gosling') loc = '/'.join(root.split('/')[:-1]) outfn = loc+"/record.json" print("Outputting to %s..."%outfn) with open(outfn,'w') as outf: json.dump(data,outf,cls=NumpyToListEncoder)
import numpy as np class lemketableau: def __init__(self,M,q,maxIter = 100): n = len(q) self.T = np.hstack((np.eye(n),-M,-np.ones((n,1)),q.reshape((n,1)))) self.n = n self.wPos = np.arange(n) self.zPos = np.arange(n,2*n) self.W = 0 self.Z = 1 self.Y =...
lf,ind): a = self.T[ind,-2] self.T[ind] /= a for i in range(self.n): if i != ind:
b = self.T[i,-2] self.T[i] -= b * self.T[ind] def ind2str(self,indvec): v,pos = indvec if v == self.W: s = 'w%d' % pos elif v == self.Z: s = 'z%d' % pos elif v == self.Y: s = 'y' else:...
import logging #Config MYSQL_HOST = '127.0.0.1' MYSQL_PORT = 3306 MYSQL_USER = 'root' MYSQL_PASS = 'oppzk' MYSQL_DB = 'SSMM' MANAGE_PASS = 'passwd' #if you want manage in other server you should set this value to global ip MANAGE_BIND_IP = '127.0.0.1' #make sure this port is idle MANAGE_PORT = 10001 PANEL_VERSION = ...
want bind all of if only '4.4.4.4' SS_BIND_IP = '0.0.0.0' SS_METHOD = 'rc4-md5' #LOG CON
FIG LOG_ENABLE = False LOG_LEVEL = logging.DEBUG LOG_FILE = '/var/log/shadowsocks.log'
#!/usr/bin/env python import sys # import particle restart sys.path.append('../../src/utils') import particle_restart as pr # read in particle restart file if len(sys.argv) > 1: p = pr.Particle(sys.argv[1]) else: p = pr.Particle('par
ticle_12_842.binary') # set up output string outstr = ''
# write out properties outstr += 'current batch:\n' outstr += "{0:12.6E}\n".format(p.current_batch) outstr += 'current gen:\n' outstr += "{0:12.6E}\n".format(p.current_gen) outstr += 'particle id:\n' outstr += "{0:12.6E}\n".format(p.id) outstr += 'run mode:\n' outstr += "{0:12.6E}\n".format(p.run_mode) outstr += 'part...
__version__ = '$Id$' from Acquisition import aq_inner from Products.Five.browser import BrowserView from Products.CMFCore.utils import getToolByName from DateTime import DateTime class LastZorionagurrak(BrowserView): def getLastZorionagurrak(self, num=5): context = aq_inner(self.context) today ...
nd,), 'range':'mi
n'}, sort_on='getDate', sort_limit=tomorrowbrainnumber) return todaybrains + tomorrowbrains
import unittest import os import hiframe import hipubiface_test_basic_plugin._hiframe MY_ABSOLUTE_PATH = os.path.abspath(__file__) MY_ABSOLUTE_PARENT = os.path.dirname(MY_ABSOLUTE_PATH) HIPUBIFACE_PATH = os.path.dirname(os.path.dirname(os.path.dirname(MY_ABSOLUTE_PARENT))) HIPUBIFACE_SRC_PATH = HIPUBIFACE_PATH+"/src"...
) # self.assertEqual(r["type"],"value") # self.assertEqual(r["value"],c[0].lower()) # # def test_guest_ping_fail(self): # cv = ["asdf", # "0000", # "1234", # "dddd", # "1234567890", # "-9999999", # "-99999999",...
ng", {"txt_value":c}) # self.assertTrue(r != None) # self.assertTrue(isinstance(r,dict)) # self.assertEqual(r[hipubiface.RESULT_KEY], hipubiface.RESULT_VALUE_FAIL_TXT) # self.assertEqual(r["fail_reason"],"bad value") # def test_list_cmd(self): # ret = hipubiface._h...
#!/usr/bin/env python import os import sys import argparse import traceback sys.path.insert(1, os.path.join(os.path.dirname(__file__), os.pardir)) from toollib.group import Group,UnsortedInputGrouper import scipy.stats as ss class KSGroup(Group): def __init__(self, tup): super(KSGroup, self).__init__(tup)...
tion to fit') parser.add_argument('-i', '--dist', default='paretoLomax') parser.add_argument('-p', '--params', default='', help='initial parameters') parser.add_argument('-c', '--column', type=int, default=0) parser.add_argument('-g', '--group', nargs='+', type=int, default=[]) parser.add_argument('...
tats': args.source = ss else: args.source = None if args.source: mod = args.source for c in args.dist.split('.'): mod = getattr(mod, c) args.distf = mod else: args.distf = eval(args.dist) grouper = UnsortedInputGrouper(args.infile, KS...
from django.db import models from django.template.defaultfilters import slugify from datetime import datetime from redactor.fields import RedactorField from management.post_tweet import post_tweet ### News #################################################################################################### cla...
ted to News piece' verbose_name_plural = u'People related to News pieces' ### EventRelatedToNews #################################################################################################### class EventRelatedToNews(models.Model): event = models.ForeignKey('events.Event') news = models.F...
ews piece' verbose_name_plural = u'Events related to News pieces'
from PIL import Image import stripe import datetime from django.shortcuts import render, redirect from django.views.generic import TemplateView, View, FormView from django.core.urlresolvers import reverse_lazy, reverse from django.views.decorators.csrf import csrf_exempt from
django.utils.decorators import method_decorator from django.conf import settings from paypal.standard.forms import PayPalPaymentsForm from picture.models import Picture, Settings, Pixel, PaymentNote from picture.forms import PaymentNoteForm from paypal.standard.models import ST_PP_COMPLETED from paypal.standard.ipn...
plate_name = 'picture/index.html' form_class = PaymentNoteForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['picture'] = Settings.objects.first().picture context['random'] = datetime.datetime.now() context['payment_notes'] = [{ 'name': note.name, 'url': no...
import startbot, stats, os, re, random, sys import utils MARKOV_LENGTH = 2 #majority of the code taken from https://github.com/hrs/markov-sentence-generator #changes made: allowed it to hook up from the text gotten directly from messages #changed it to be encompassed in a class structure. Made minor changes to make ...
def genSentence2(self,
message, markovLength): #attempts to use input sentence material to construct a sentence # Start with a random "starting word" from the input message splitmessage = message.lower().split() splitmessage.remove('{0},'.format(self.m_botName.lower())) if len(splitmessage) == 0: ...
# -*- coding: utf-8 -*- # Generated by Django 1.9.12 on 2018-12-04 15:13 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('anagrafica', '0049_auto_20181028_1639')...
('question', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='survey.Question')), ('survey', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='survey.Survey')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='an...
ente", 'verbose_name_plural': 'Risposte degli utenti', }, ), migrations.AddField( model_name='question', name='survey', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='survey.Survey'), ), ]
#-*- coding: utf-8 -*- import unittest from top.WordTableModel import WordTableModel class WordTableModelTestsTestCase(unittest.TestCase): def setUp(self): self.model = WordTableModel() self.model.load("dotestow.pkl") def testLo
ading(self): assert len(self.model.words) == 5, "incorrect number of loaded words " + \ "got: " + len(self.model.words) + ", but: 5 was expected" list = [] for word in self.model.words: list.append(word.word) msg = "failed while loading the words with number: " ...
== "aberration", msg + '1' assert list[2] == "acrid", msg + '2' assert list[3] == "adjourn", msg + '3' assert list[4] == "ambience", msg + '4' def testSorting(self): self.model.sortByWord() assert self.model.words[0].word == "aberration", "incorrect sorting by word " + \ ...
#!/usr/bin/env python2 # Print out the 2^n possibilities of a word with the length n import unittest from itertools import product, permutations def word_variations(s): try: if not len(s): return lower, upper = s.lower(), s.upper() except: return # Since number strings won't produ...
roduct(*zip(lower, upper)) result = {''.join(pair) for pair in pairs} # Using set literal notation. print result, "\n", len(result) return result word_variations("abc") class WordTest(unittest.TestCase): def _test(self, s, expected): result = word_variations(s) self.assertEqual(len(re...
est_basecase(self): self._test("hello", 32) def test_int(self): self._test("123", 6) def test_empty(self): self.assertEqual(word_variations(""), None)
self.assertEqual(F2.is_before(O3), None) class TestMigrationDependencies(Monkeypatcher): installed_apps = ['deps_a', 'deps_b', 'deps_c'] def setUp(self): super(TestMigrationDependencies, self).setUp() self.deps_a = Migrations('deps_a') self.deps_b = Migrations('deps_b') s...
s_b['0001_b'], self.deps_a['0001_a'], self.deps_a['0002_a'], self.deps_b['0002_b'], self.deps_a['0003_a'], self.deps_b['0003_b'], self.deps_b['0004_b']], ...
self.deps_a['0002_a'], self.deps_b['0002_b'], self.deps_a['0003_a'], self.deps_b['0003_b'], self.deps_b['0004_b'], self.deps_b['0005_b']]], [m....
from __future__ import unicode_literals from django.contrib.syndication import views from django.utils import feedgenerator from django.utils.timezone import get_fixed_timezone from .models import Article, Entry class TestRss2Feed(views.Feed): title = 'My blog' description = 'A more thorough desc...
with multiple enclosures. """ def item_enclosu
res(self, item): return [ feedgenerator.Enclosure('http://example.com/hello.png', '0', 'image/png'), feedgenerator.Enclosure('http://example.com/goodbye.png', '0', 'image/png'), ]
def safe_add(fn): """A wrapper for adding commands in a safe manner.""" def checked_add(*args): # Wrappers aren't bound methods so they can't reference 'self' # directly. However, 'self' will be provided as the first parameter # when the wrapped method is called...
afe_add def add_ui_draw_clean(self): """Fills the screen with LCDColor.BACKGROUND.""" self._msg.append(Opcode.UI_DRAW
) self._msg.append(UIDrawSubcode.CLEAN) @safe_add def add_ui_draw_fillwindow(self, lcd_color, start_y, count): """Fills the window with count rows of the given LCDColor starting at row start_y. NOTE: Starting at 0 with a size of 0 will clear the window. This seems ...
from vectore
s_oo import Vector x = input('vector U componente X= ') y = input('vector U componente X= ') U = Vector(x,y) m = input('vector V magnitud= ') a = input('vector V angulo= ') V = Vector(m=m, a=a) E = input('Escalar= ') print "U=%s" % U print "V=%s" % V print 'UxE=%s' % U.x_escalar(E) print 'VxE=%s' % V.x_escal...
# -*- coding: utf-8 -*- import os import pygame from pygame.locals import * class Sprite(pygame.sprite.Sprite): def __init__(self,SpriteName): pygame.sprite.Sprite.__init__(self) self.Name = SpriteName self.rect = 0 self.image = 0 def getRect(self): return self.rect ...
orkey = image.get_at((0,0)) image.set_colorkey(colorkey, pygame.RLEACCEL) return image, rect # Load a whole bunch of images and return them as a list def images_at(self, rects): "Loads multiple images, supply a list of coordinates" return [self.image_at(rect) fo
r rect in rects], rect # Load a whole strip of images def load_strip(self, rect, image_count, colorkey = None): "Loads a strip of images and returns them as a list" tups = [(rect[0]+rect[2]*x, rect[1], rect[2], rect[3]) for x in range(image_count)] return self.images_at(t...
from validx import Dict, List from .protos import DataObject from .palette import Palette from .utils.parser import BinaryParser from .utils.validator import UInt8 from .utils.types import Remappings, Remapping class PaletteMapping(DataObject): __slots__ = ( "colors", "remaps", ) schema ...
self.remaps.append(remap) return self def write(self, parser): self.colors.write(parser) for k in range(0, 19): for m in range(0, 256): parser.put_uint8(self.
remaps[k][m]) def serialize(self) -> dict: return {"colors": self.colors.serialize(), "remaps": self.remaps} def unserialize(self, data: dict): self.colors = Palette().unserialize(data["colors"]) self.remaps = data["remaps"] return self
from pyroute2.netlink import nlmsg class errmsg(nlmsg): ''' Custom message type
Error ersat
z-message ''' fields = (('code', 'i'), )
import src class Chemical(src.items.Item): type = "Chemical" def __init__(self): super().__init__(display=src.canvas.displayChars.fireCrystals) self.name = "chemical" self.composition = b"cccccggggg" def apply(self, character): import hashlib results = [] ...
self.mix(character) elif tmp == "shift": self.shift() test = hashlib.sha256(self.composition[0:9]) character.addMessage(counter) result = int(test.digest()[-1]) result2 = int(test.digest()[-2]) if result < 15: char...
e(test.digest()) character.addMessage(result) character.addMessage(result2) break counter += 1 # character.addMessage(results) def shift(self): self.composition = self.composition[1:] + self.composition[0:1] def mix(self, character)...
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """ ZMQ example using python3's asyncio Bitcoin should be started with the command line argument...
t message asyncio.ensure_future(self.handle()) def start(self): self.loop.add_signal_handler(signal.SIGINT, self.stop
) self.loop.create_task(self.handle()) self.loop.run_forever() def stop(self): self.loop.stop() self.zmqContext.destroy() daemon = ZMQHandler() daemon.start()
# Copyright 2014,
Doug Wiegley, A10 Networks. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
ITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from __future__ import absolute_import from __future__ import unicode_literals from acos_client import errors as acos_errors from acos_client.v21 import base cla...
# tsuserver3, an Attorney Online server # # Copyright (C) 2016 argoneus <argoneuscze@gmail.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 o...
nty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import ipaddress import json import yaml from server.excep...
t ServerError class BanManager: def __init__(self): self.bans = {} self.load_banlist() self.hdid_exempt = {} self.load_hdidexceptions() def load_banlist(self): try: with open('storage/banlist.json', 'r') as banlist_file: self.bans = json.loa...
""" mbed SDK Copyright (c) 2011-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 law or agreed to in wr...
ue} else: report = {'success': False} if ide not in EXPORTERS: report['errormsg'] = "Unsupported toolchain" else: Exporter = EXPORTERS[ide] target = EXPORT_MAP.get(target, target) if target not in Exporter.TARGETS: report['erro...
_url_resolver, extra_symbols=extra_symbols) exporter.scan_and_copy_resources(project_path, tempdir) exporter.generate() report['success'] = True except OldLibrariesException, e: report['errormsg'] = ERROR_MESSAGE_NOT_EXPORT_...
# -*- coding: UTF-8 -*- # Copyright 2015-2021 Rumma & Ko Ltd # License: GNU Affero General Public License v3 (see file COPYING for details) """ Defines a set of user roles and fills :class:`lino.modlib.users.choicelists.UserTypes`. This is used as the :attr:`user_types_module <lino.core.site.Site.user_types_module>` ...
ly=True, authenticated=False) add('100', _("Customer"), Customer, 'customer user') add('200', _("Contributor"), Contributor, 'contributor') add('400', _("Developer"), Developer, 'developer') add('900', _("Administrator"), SiteAdmin, 'admin') # UserTypes.user = UserTypes.customer # from lino.core.merge import MergeAct...
fine_action(merge_row=MergeAction( # m, required_roles=set([ContactsStaff])))
## # Copyright 2009-2015 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en), # the Hercules foundation (htt...
# along with EasyBuild. If not, see <http://www.gnu.org/licenses/>. ## """ EasyBuild support for SuiteSparse, implemented as an easyblock @author: Stijn De Weirdt (Ghent University) @author: Dries Verdegem (Ghent University) @author: Kenneth Hoste (Ghent University) @author: Pieter De Baets (Ghent University) @autho...
immerman (Ghent University) """ import fileinput import re import os import shutil import sys from distutils.version import LooseVersion from easybuild.easyblocks.generic.configuremake import ConfigureMake from easybuild.tools.build_log import EasyBuildError from easybuild.tools.filetools import mkdir from easybuild.t...
from dja
ngo.urls import path from . import views urlpatterns = [ path('start-ga', views.St
artGA.as_view()), path('stop-ga', views.StopGA.as_view()), path('check-ga', views.CheckGA.as_view()), ]
#!/usr/bin/env python # Copyright 2014 The Swarming Authors. All rights reserved. # Use of this source code is governed by the Apache v2.0 license that can be # found in the LICENSE file. import datetime import sys import unittest import test_env test_env.setup_test_env() # From components/third_party/ import webtes...
es': 0, 'failures': 0, 'key': datetime.datetime(2010, 1, 2, 3, 4), 'other_requests': 0, 'requests': 1, 'uploads': 0, 'uploads_bytes': 0, }, ] expected[0].update(added_data) self.assertEqual(expected, act
ual) def test_store(self): expected = { 'uploads': 1, 'uploads_bytes': 2048, } self._test_handler('/store', expected) def test_return(self): expected = { 'downloads': 1, 'downloads_bytes': 4096, } self._test_handler('/return', expected) def test_lookup(self): ...
""" Updated on 19.12.2009 @author: alen, pinda """ from django.conf import settings from django.conf.urls.defaults import * from socialregistration.utils import OpenID, OAuthClient, OAuthTwitter, OAuthLinkedin urlpatterns = patterns('', url('^setup/$', 'socialregistration.views.setup', name='socialregi...
l('^logout/$', 'socialregistration.views.logout', name='social_logout'), ) # Setup Facebook URLs if there's an API key specified if getattr(settings, 'FACEBOOK_API_KEY', None) is not None:
urlpatterns = urlpatterns + patterns('', url('^facebook/login/$', 'socialregistration.views.facebook_login', name='facebook_login'), url('^facebook/connect/$', 'socialregistration.views.facebook_connect', name='facebook_connect'), url('^xd_receiver.htm', 'django.views...
# -*- coding: utf-8 -*- """ 兼容Python版本 """ import sys is_py2 = (sys.version_info[0] == 2) is_py3 = (sys.version_info[0] == 3) is_py33 = (sys.version_info[0] == 3 and sys.version_info[1] == 3) try: import simplejson as json except (ImportError, SyntaxError): import json if is_py2: from urllib import q...
""若输入为str(即unicode),则转为utf-8编码的bytes;其他则原样返回""" if isinstance(data, str): return data.encode(encoding='utf-8') else: return data def to_string(data): """若输入为bytes,则认为是utf-8编码,并返回str""" if isinstance(data, bytes): return data.decode('utf-8') ...
turn to_string(data) def stringify(input): return input builtin_str = str bytes = bytes str = str
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import re # Todo this mapping REALLY needs a non-hardcoded home _slave_type = { "bld-linux64-ec2": [ re.com...
lass = slave_to_slavetype(slave) if sla
veclass in _gpo_needed: return True return False def slave_filter(slave_class): def _inner_slave_filter(item): for i in _slave_type[slave_class]: if i.match(item["name"]): return True return False # If we got here, no match return _inner_slave_filter ...
# Time: O(n) # Space: O(1) # Suppose you have a long flowerbed in which some of the plots are planted and some are not. # However, flowers cannot be planted in adjacent plots - they would compete for water # and both would die. # # Given a flowerbed (represented as an array containing 0 and 1, # where 0 means empty a...
nge of [1, 20000]. # n is a non-negative integer which won't exceed the input array size. class Solution(object): def canPlaceFlowers(self, flowerbed, n): """ :type flowerbed: List[int] :type n: int :rtype: bool
""" for i in xrange(len(flowerbed)): if flowerbed[i] == 0 and (i == 0 or flowerbed[i-1] == 0) and \ (i == len(flowerbed)-1 or flowerbed[i+1] == 0): flowerbed[i] = 1 n -= 1 if n <= 0: return True return False
ective """ import webnotes from webnotes.utils import cstr class DocType: def __init__(self, doc, doclist=[]): self.doc, self.doclist = doc, doclist self.doctype_properties = [ 'search_fields', 'default_print_format', 'read_only_onload', 'allow_print', 'allow_email', 'allow_copy', 'allow_atta...
self): """ * Gets doclist of type self.doc.doc_type * Applies property setter properties on the doclist * returns the modified doclist """ from webnotes.model.doctype import get ref_doclist = get(self.doc.doc_type) ref_doclist = webnotes.doclist([ref_doclist[0]] + ref_doclist.get({"parent": se...
f): """ Clear fields in the doc """ # Clear table before adding new doctype's fields self.doclist = self.doc.clear_table(self.doclist, 'fields') self.set({ 'list': self.doctype_properties, 'value': None }) def set(self, args): """ Set a list of attributes of a doc to a value or to attribute v...
he 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 https://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 ...
ean( adversarial_sentences_embedded, axi
s=1) else: original_sentences_reduced = tf.math.reduce_sum( original_sentences_embedded, axis=1) adversarial_sentences_reduced = tf.math.reduce_sum( adversarial_sentences_embedded, axis=1) difference_vector = tf.math.subtract(original_sentences_reduced, ...
# Copyright 2015 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
import app from solar.system_log.operations import set_error, move_to_commited __all__ = ['error_logitem', 'commit_logitem'] @app.task(name='error_logitem') def error_logitem(task_uuid
): return set_error(task_uuid.rsplit(':', 1)[-1]) @app.task(name='commit_logitem') def commit_logitem(task_uuid): return move_to_commited(task_uuid.rsplit(':', 1)[-1])
import numpy import data_generator class Generator: def __init__(self): self.combinations = data_generator.generateAllByteToAx25DataCombinations() self.frameSeparatorOne = data_generator.calculateNewAx25DataFromOldImpl(1, 0, 0x7E, False) self.frameSeparatorZero = data_generator.calculateNew...
an see ax25-utils Python project, // code_generation_v2.py file // extern const AX25EncodedData byte2ax25EncodedData[]; #define FRAME_SEPAR
ATOR_GIVEN_THAT_PREVIOUS_BIT_WAS_ZERO ''' + str(self.frameSeparatorZero[0]) + ''' #define FRAME_SEPARATOR_GIVEN_THAT_PREVIOUS_BIT_WAS_ONE ''' + str(self.frameSeparatorOne[0]) + ''' #define GET_VALUE_IF_LAST_BIT_IS_ONE(pAx25EncodedData) \\ ((~(pAx25EncodedData)->dataGivenThatPreviousBitWasZero) & ((1 << ((pAx25Enco...
from documents.models import Document from categories.models import Category import os def move_doc(doc_id, cat_
id): doc = Document.objects.get(pk=int(doc_id)) old_cat = doc.refer_category new_cat = Category.objects.get(pk=int(cat_id)) for p in doc.pages.all(): cmd = "mv " + p.get_absolute_path() + " " + new_cat.get_absolute_path() + "/" os.system(cmd) doc.refer_category = new_cat doc.save...
ts.remove(doc) new_cat.documents.add(doc)
from hypothesis import given from hypothesis.strategies import binary from msgpack import packb from mitmproxy.contentviews import msgpack from . import full_eval def msgpack_encode(content): return packb(con
tent, use_bin_type=True) def test_parse_msgpack(): assert msgpack.parse_msgpack(msgpack_encode({"foo": 1})) assert msgpack.parse_msgpack(b"aoesuteoahu") is msgpack.PARSE_ERROR assert msgpack.parse_msgpack(msgpack_encode({"foo": "\xe4\xb8\x96\xe7\x95\x8c"})) def t
est_format_msgpack(): assert list(msgpack.format_msgpack({ "data": [ "str", 42, True, False, None, {}, [] ] })) def test_view_msgpack(): v = full_eval(msgpack.ViewMsgPack()) assert v(msgpack_encode({}))...
# vim: set ts=2 expandtab: ''' Module: read.py Desc: unpack data from binary files Author: John O'Neil Email: oneil.john@gmail.com DATE: Thursday, March 13th 2014 ''' import struct DEBUG = False class EOFError(Exception): """ Custom exception raised when we read to EOF """ pass def split_buffer(length, buf): ...
ger) from binary file ''' if isinstance(f, list): n, f = split_buffer(8, f)
return struct.unpack('>Q', ''.join(n))[0] else: _f = f.read(8) if len(_f) < 8: raise EOFError() return struct.unpack('>Q', _f)[0] def buffer(f, size): '''Read N bytes from either a file or list ''' if isinstance(f, list): n, f = split_buffer(size, f) return ''.join(n) else: _f ...
# Copyright 2013 NEC Corporation # 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 ...
'end': self.end, 'detailed': int(bool(True))} self.assertRaises(exceptions.Unauthorized,
self.client.list_tenant_usages, params) class TenantUsagesNegativeTestXML(TenantUsagesNegativeTestJSON): _interface = 'xml'
"""Tests the surveytools.footprint module.""" import numpy as np from surveytools.footprint import VphasFootprint, VphasOffset def test_vphas_offset_coordinates(): """Test the offset pattern, which is expected to equal ra -0, dec +0 arcsec for the "a" pointing; ra -588, dec +660 arcsec for the "b" pointin...
"""Ensure the right filename is returned for a given band/offset.""" assert VphasOffset('1122a').image_filenames['ha'] == 'o20120330_00032.fit' assert VphasOffset('1122b').image_filenames['ha'] == 'o20120330_00034.fit' assert VphasOffset('1122c').image_filenames['ha'] == 'o20120330_00033.fit' assert Vph...
130314_00061.fit' assert VphasOffset('1842b').image_filenames['r'] == 'o20130314_00062.fit' assert VphasOffset('0765a').image_filenames['g'] == 'o20130413_00024.fit' assert VphasOffset('0765b').image_filenames['g'] == 'o20130413_00026.fit' assert VphasOffset('0765c').image_filenames['g'] == 'o20130413_0...
ata) def get_def(dictionary, key, default_value): if key not in dictionary or len(dictionary[key]) == 0: return default_value return dictionary[key] start_date = datetime.strptime("10/10/2015 10:10", "%d/%m/%Y %H:%M") if len(election["Start date time"]) > 0: try: ...
args.input_path) exit(2) if os.path.isdir(args.output_path) and not os.access(args.output_path, os.W_OK): print("can't write to %s" % args.output_path)
exit(2) if not os.access(args.config_path, os.R_OK): print("can't read %s" % args.config_path) exit(2) config = None with open(args.config_path, mode='r', encoding="utf-8", errors='strict') as f: config = json.loads(f.read()) try: if args.format == "csv-blocks" or args.for...
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
', 'normalized_oo2rml.xsl'),'rb') if file_type=='odt': fp = open(get_module_resource('base_report_designer','openerp_sxw2rml', 'normalized_odt2rml.xsl'),'rb') return {'report_rml_content': str(sxw2rml(sxwval, xsl=fp.read()))} def upload_report(se
lf, cr, uid, report_id, file_sxw, file_type, context=None): ''' Untested function ''' sxwval = StringIO(base64.decodestring(file_sxw)) if file_type=='sxw': fp = open(get_module_resource('base_report_designer','openerp_sxw2rml', 'normalized_oo2rml.xsl'),'rb') i...
ort slugify, domain, markdown from newsmeme.permissions import auth, moderator from newsmeme.models.types import DenormalizedText from newsmeme.models.users import User class PostQuery(BaseQuery): def jsonify(self): for post in self.all(): yield post.json def as_list(self): """ ...
rator @cached_property def view(self): if self.obj.access == Post.PUBLIC: return Permission() if self.obj.access == Post.FRIENDS: needs = [UserNeed(user_id) for user_id in self.obj.author.friends] return ...
def delete(self): return self.default @cached_property def vote(self): needs = [UserNeed(user_id) for user_id in self.obj.votes] needs.append(UserNeed(self.obj.author_id)) return auth & Denial(*needs) @cached_property def comment...
# coding=utf-8 # Copyright 2020 The TF-Agents Authors. # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
_spec( o
bservation_spec=array_spec.ArraySpec((1,), np.int32)) policy = random_py_policy.RandomPyPolicy( time_step_spec=time_step_spec, action_spec=action_spec) action_step = policy.action( time_step.restart(np.array([[1], [2], [3]], dtype=np.int32))) tf.nest.assert_same_structure(action_spec, actio...
.assertEqual( exception.annotation, ( u"+\n" u"^" ) ) def test_group(self): self.assertEqual( parse(u"(a)"), Group(Character(u"a")) ) def test_group_missing_begin(self): with self.assert...
_missing_end(self): with self.assertRaises(ParserError) as context: parse(u"(a") exception = context.exception self.assertEqual( exception.reason, u"unexpected end of string, expected ) corresponding to (" ) self.assertEqual( except...
-^" ) ) def test_either(self): self.assertEqual( parse(u"[ab]"), Either(frozenset(map(Character, u"ab"))) ) def test_either_missing_begin(self): with self.assertRaises(ParserError) as context: parse(u"ab]") exception = con...
namely, the type of request, the package and os required (if applies). :param: msg (string) the content of the email to be parsed. :return: (list) 3-tuple with the type of request, os and pt info. """ # by default we asume the request is asking for help req = {} ...
mail.message_from_string(raw_msg) content = self._get_content(parsed_msg) from_addr = parsed_msg['From'] to_addr = parsed_msg['To'] bogus_request = False
status = '' req = None try: # two ways for a request to be bogus: address malformed or # blacklisted try: self.log.debug("Normalizing address...") norm_from_addr = self._get_normalized_address(from_addr) except Addre...
ad it and override the default options. Most tools in $ROOT/tools take a --cfg option to specify an override file. - See tools/{train,test}_net.py for example code that uses cfg_from_file() - See experiments/cfgs/*.yml for example YAML config override files """ import os import os.path as osp import numpy as ...
>= thresh: positive example __C.TRAIN.RPN_POSITIVE_OVERLAP = 0.7 # IOU < thresh: negative example __C.TRAIN.RPN_NEGATIVE_OVERLAP = 0.3 # If an anchor statisfied by positive and negative conditions set to negative __C.TRAIN.RPN_CLOBBER_POSITIVES = False # Max number of foreground examples __C.TRAIN.RPN_FG_FRACTION = 0....
ESH = 0.7 # Number of top scoring boxes to keep before apply NMS to RPN proposals __C.TRAIN.RPN_PRE_NMS_TOP_N = 12000 # Number of top scoring boxes to keep after applying NMS to RPN proposals __C.TRAIN.RPN_POST_NMS_TOP_N = 2000 # Proposal height and width both need to be greater than RPN_MIN_SIZE (at orig image scale) ...
""" Parse spotify URLs """ from __future__ import unicode_literals import re import logging log = logging.getLogger('spotify') def handle_privmsg(bot, user, channel, args): """Grab Spotify URLs from the messages and handle them""" m = re.match(".*(http:\/\/open.spotify.com\/|spotify:)(?P<item>album|artist|...
url) if r.status_code != 200: if r.status_code not in [401, 403]: log.warning('Spotify API returned %s while trying to fetch %s' % r.status_code, apiurl) return data = r.json() title = '[Spotify] ' if item[0] in ['albums', 'tracks']: artists = [] for artist...
se_date']) if item[0] == 'artists': title += data['name'] genres_n = len(data['genres']) if genres_n > 0: genitive = 's' if genres_n > 1 else '' genres = data['genres'][0:4] more = ' +%s more' % genres_n - 5 if genres_n > 4 else '' title += '...
if tokens[3] != 'as': raise template.TemplateSyntaxError("Third argument in %r must be 'as'" % tokens[0]) return cls( object_expr = parser.compile_filter(tokens[2]), as_varname = tokens[4], ) # {% get_whatever for app.model pk a...
VED', True) and 'is_removed' in field_names: qs = qs.filter(is_removed=False) return qs def get_target_ctype_pk(self, context): if self.object_expr: try: obj = self.object_expr.resolve(context) except template.VariableDoesNotExist: ...
return None, None return ContentType.objects.get_for_model(obj), obj.pk else: return self.ctype, self.object_pk_expr.resolve(context, ignore_failures=True) def get_context_value_from_queryset(self, context, qs): """Subclasses should override this.""" raise No...
#!/usr/bin/env python # -*- coding: utf-8 -*- from novel import serial, utils BASE_URL = 'http://www.quanben5.com/n/{}/xiaoshuo.html' class Quanben5(serial.SerialNovel): def __init__(self, tid): super().__init__(utils.base_to_url(BASE_URL, tid), '#content', intro_sel='.descript...
li', ti
d=tid) def get_title_and_author(self): name = self.doc('h1').text() author = self.doc('.author').text() return name, author