prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
from django.conf import settings # these 3 should be provided by your app FACEBOOK_APP_ID = getattr(settings, 'FACEBOOK_APP_ID', None) FACEBOOK_APP_SECRET = getattr(settings, 'FACEBOOK_APP_SECRET', None) FACEBOOK_DEFAULT_SCOPE = getattr(settings, 'FACEBOOK_DEFAULT_SCOPE', [ 'email', 'user_about_me', 'user_...
tings, 'FACEBOOK_TRACK_RAW_DATA', False) # if we should store friends and likes FACEBOOK_STORE_LIKES = getattr(settings, 'FACEBOOK_STORE_LIKES', False) FACEBOOK_STORE_FRIENDS = getattr(settings, 'FACEBOOK_STORE_FRIENDS', False) # i
f we should be using celery to do the above two, # recommended if you want to store friends or likes FACEBOOK_CELERY_STORE = getattr(settings, 'FACEBOOK_CELERY_STORE', False) # use celery for updating tokens, recommended since it's quite slow FACEBOOK_CELERY_TOKEN_EXTEND = getattr( settings, 'FACEBOOK_CELERY_T...
from clint import resources import json resources.init('thomasballinger', 'trello-card-updater') #being used as though they have in-memory caches class LocalStorage(object): def __init__(self, name): object.__setattr__(self, 'res', getattr(
resources, name)) def __getattr__(self, att): s = self.res.read(att) if s is None: return None data = json.loads(s) return data def __setattr__(self, att, data): s = json.dumps(data) self.re
s.write(att, s) def __getitem__(self, key): return getattr(self, key) def __setitem__(self, key, value): setattr(self, key, value) class LocalObfuscatedStorage(LocalStorage): """Of questionable use, but should avoid card names being indexed""" def __getattr__(self, att): s = sel...
[{"url": "https://raw.
githubusercontent.com/ikesuncat/listas/master/Addon.xml", "fanart": ".\\fanart.jpg", "title": "I
ke"}]
"""iching. See: https://packaging.python.org/en/latest/distributing.html https://github.com/chengjun/iching """ # Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) ...
dditional-files # noqa # In this case, 'data_file' will be installed into '<sys
.prefix>/my_data' # data_files=[('my_data', ['data/data_file'])], # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # pip to create the appropriate form of executable for the target platform. entry_point...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migrati
on(migrations.Migration): dependencies = [ ('core', '0016_remove_user_is_census_admin'), ] operations = [ migrations.AddField( model_name='group', name='affiliation', field=models.CharField(default='', max_length=255, blank=True), preserve_de...
), ]
#!/usr/bin/env python '''relay handling module''' import time from pymavlink import mavutil from MAVProxy.modules.lib import mp_module class RelayModule(mp_mod
ule.MPModule): def __init__(self, mpstate): super(RelayModule, self).__init__(mpstate, "relay") self.add_command('relay', self.cmd_relay, "relay commands") self.add_command('servo', self.cmd_servo, "servo commands") self.add_command('motortest', self.cm
d_motortest, "motortest commands") def cmd_relay(self, args): '''set relays''' if len(args) == 0 or args[0] not in ['set', 'repeat']: print("Usage: relay <set|repeat>") return if args[0] == "set": if len(args) < 3: print("Usage: relay set ...
ort User from django.test import TestCase from django.urls.base import reverse class TestAccountRegistration(TestCase): def setUp(self): # create one user for convenience response = self.client.post( reverse('account:register'), { 'username': 'Alice', ...
reverse('account:login'), {'username': 'Bob', 'password': 'supasecret'}, follow=True ) self.assertEqual(response.redirect_chain[0][1], 302) self.assertEqual(response.redirect_chain[0][0], reverse('account:login')) self.assertEqual(response.status_code, 200) ...
# -*- coding: utf-8 -*- r""" # .---. .----------- # / \ __ / ------ # / / \( )/ ----- (`-') _ _(`-') <-. (`-')_ # ////// '\/ ` --- ( OO).-/( (OO ).-> .-> \( OO) ) .-> # //// / // : : --- (,------. \ .'_ (`-')----. ,...
line2 = f2.readline() line1_num_counter += 1 line2_num_counter += 1
if line1 == line2: continue else: if line1 == '': line1 = line1 + '\n' if line2 == '': line2 = line2 + '\n' line1 = str(line1_num_counter) + '-' + line1 ...
__all__ = ['LEAGUE_PROPERTIES'] LEAGUE_PROPERTIES = { "PL": { "rl": [18, 20], "cl": [1, 4], "el": [5, 5], }, "EL1": { "rl": [21, 24], "cl": [1, 2], "el": [3, 6] }, "EL2": { "rl": [21, 24], "cl": [1, 2], "el": [3, 6] }, ...
], "el": [4, 5] }, "DED": { "rl": [17, 18], "cl": [1, 3], "el": [4, 5] }, "FL1": { "rl": [19, 20], "cl": [1, 3], "el": [4, 4] }, "FL2": { "rl": [18, 20], "cl": [1, 3], "el": [0, 0] }, "SB": {
"rl": [19, 22], "cl": [1, 2], "el": [3, 6] }, "ENL": { "rl": [22, 24], "cl": [1,2], "el": [3,6] }, }
#from interface.services.icontainer_agent import ContainerAgentClient #from pyon.ion.endpoint import ProcessRPCClient from pyon.public import Container, log, IonObject from pyon.util.containers import DotDict from pyon.util.int_test import IonIntegrationTestCase from interface.services.coi.iresource_registry_service i...
ry.observatory_management_service import ObservatoryManagementService from interface.services.sa.iobservatory_management_service import IObservatoryManagementService, ObservatoryManagementServiceClient from interface.services.sa.iinstrument_management_service import InstrumentManagementServiceClient from pyon.util.con...
ixin from pyon.core.exception import BadRequest, NotFound, Conflict, Inconsistent from pyon.public import RT, PRED #from mock import Mock, patch from pyon.util.unit_test import PyonTestCase from nose.plugins.attrib import attr import unittest from ooi.logging import log from ion.services.sa.test.helpers import any_old...
# coding=utf-8 import time import datetime __author__ = 'JIE' #! /usr/bin/env python #coding=utf-8 from tornado.tcpserver import TCPServer from tornado.ioloop import IOLoop class Connection(object): clients = set() def __init__(self, stream, address): Connection.clients.add(self) self._stream...
se) self.read_message() print "A new user has entered the chat room.", address def read_message(self): self._stream.read_until('\n', self.broadcast_messages) def broadcast_messages(self, data): print "User said:", data[:-1], self._addr
ess for conn in Connection.clients: conn.send_message(data) self.read_message() def send_message(self, data): self._stream.write(data) def on_close(self): print "A user has left the chat room.", self._address Connection.clients.remove(self) class ChatServer...
# -*- coding: utf-8 -*- # BankCSVtoQif - Smart conversion of csv files from a bank to qif # Copyright (C) 2015-2016 Nikolai Nowaczyk # # 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 v...
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, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA...
description='Smart conversion of csv files from a bank to qif', author='Nikolai Nowaczyk', author_email='mail@nikno.de', license='GNU GPLv2', url='https://github.com/niknow/BankCSVtoQif/tree/master/bankcsvtoqif', packages=find_packages(), test_suite='bankcsvtoqif.tests', tests_require=['py...
import datetime import unittest2 from google.appengine.ext import testbed from consts.event_type import EventType from datafeeds.usfirst_matches_parser import UsfirstMatchesParser from helpers.match_helper import MatchHelper from models.event import Event from models.match import Match class TestAddMatchTimes(unitt...
1, 0, 0), year=2014, timezone_id="America/New_York", ) self.event_dst = Event( id="2014casj", event_short="casj", event_type_enum=EventType.REGIONAL, name="Silicon Valley Regional", start_date=datetime.datetime(2014, 3...
to span DST change year=2014, timezone_id="America/Los_Angeles", ) def match_dict_to_matches(self, match_dicts): return [Match( id=Match.renderKeyName( self.event.key.id(), match_dict.get("comp_level", None), match_...
from pymacy.db import get_db from bson.json_util import dumps db = get_db() results = [] count = 0 for i in db.benchmark.find({"element": "Ni"}): count += 1 if
count > 100: break results.append(i) print(results[
0]) with open("Ni.json", 'w') as f: file = dumps(results) f.write(file)
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2017 Joshua Charles Campbell # 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 o...
ug class Config(object): def __init__(self, file_path): self._config = run_path(file_path) de
f __getattr__(self, attr): return self._config[attr] def restify_class(self, o): if isclass(o): d = {} for k, v in getmembers(o): if '__' not in k: d[k] = self.restify_class(v) return d else: assert (isi...
from sys import argv script, filename = argv print "We're going to erase %r." % filename print "If you don't want that, hit CTRL-C (^C)." print "If you do want that, hit RETURN." raw_input("?") print "Opening the file..." target = open(filename,'w') print "Truncating the file. Goodbye!" target.truncate() print "N...
ing to write these to the file." content = "%s\n
%s\n%s\n" % (line1, line2, line3) target.write(content) print "And finally, we close it." target.close()
""" Testing hrf module """ from __future__ import absolute_import from os.path import dirname, join as pjoin import numpy as np from scipy.stats import gamma import scipy.io as sio from ..hrf import ( gamma_params, gamma_expr, lambdify_t, spm_hrf_compat, spmt, dspmt, ddspmt, ) from ...
under_delay=upk, under_disp=udsp, p_u_ratio=rat) # Normalize integral to match SPM assert_almost_equal(our_hrf, hrfs[i]) # Test basis functions # mat file resulting from get_td_dd.m bases_path...
) dt = bases_mat['dt'] t_vec = np.arange(0, 32 + dt, dt) # SPM function divides by sum of values - revert with dt assert_almost_equal(spmt(t_vec), bases_mat['hrf'] / dt, 4) assert_almost_equal(dspmt(t_vec), bases_mat['dhrf'] / dt, 4) assert_almost_equal(ddspmt(t_vec), bases_mat['ddhrf'] / dt, 4)...
#!/usr/bin/env python """Plot information needed file""" ######################################################################## # File: plot_raw_read_alignment.py # executable: plot_raw_read_alignment.py # # Author: Andrew Bailey # History: Created 12/01/17 ###########################################################...
(raw=True, scale=True) resegment_events = fast5_handle.get_resegment_basecall() if fast5_handle.is_read_rna(): plot_raw_reads(signal, events, resegment=resegment_events, window_size=window_size) else: start_time = fast5_handle.raw_attributes["start_time"] sampling_freq = fast5_handle...
True, sampling_freq=sampling_freq, start_time=start_time, window_size=window_size) def main(): """Main docstring""" start = timer() minknow_params = dict(window_lengths=(5, 10), thresholds=(2.0, 1.1), peak_height=1.2) speedy_params = dict(min_width=5, max_width=30, min_gain_per_...
f.identifier, self.datatype.subtype.__name__ )) # value is mutated into a new array value = self.datatype(value) # if it's an array, make sure it's valid regarding arrayIndex provided elif issubclass(self.datatype, Lis...
if is_monitored: old_value = obj._values.get
(self.identifier, None) # seems to be OK obj._values[self.identifier] = value # check for monitors, call each one with the old and new value if is_monitored: for fn in obj._property_monitors[self.identifier]: if _debug: Property._debu...
eng Liang. Date: 2012.09.24 Email: oriental-cds@163.com ############################################################################## """ # Core Library modules import string # Third party modules from rdkit import Chem # First party modules from PyBioMed.PyGetMol import Getmol as getmol from PyBioMed.PyMolecule...
tput: res is a molecule object. ################################################################# """ from openbabel import pybel temp = pybel.readstring("inchi", inchi) smi = temp.write("smi") self.mol = Chem.MolFromSmiles(smi.strip()) return self.mol def ...
res=ReadMolFromMol(filename) Input: filename is a file name. Output: res is a molecule object. ################################################################# """ self.mol = Chem.MolFromMolFile(filename) return self.mol def GetMolFromNCBI(se...
# -*- coding: utf-8 -*- # # pymdstat documentation build configuration file, created by # sphinx-quickstart on Sat Dec 20 16:43:07 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. # # ...
# documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General c
onfiguration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ ...
# Copyright 2020 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Flags:
-expose-wasm --wasm-gdb-remote --wasm-pause-waiting-for-debugger test/debugging/wasm/gdb-server/test_files/test_memory.js import struct import sys import unittest import gdb_rsp import test_files.test_memory as test_memory # These are set up by Main(). COMMAND = None class Tests(unittest.TestCase): # Test that r...
dr = 0xffffffff result = connection.RspRequest('m%x,%x' % (mem_addr, 1)) self.assertEquals(result, 'E02') def RunToWasm(self, connection, breakpoint_addr): # Set a breakpoint. reply = connection.RspRequest('Z0,%x,1' % breakpoint_addr) self.assertEqual(reply, 'OK') # When we run the program, ...
from django.db import models from guardian.shortcuts import get_objects_for_user from readthedocs.builds.constants import LATEST from readthedocs.builds.constants import LATEST_VERBOSE_NAME from readthedocs.builds.constants import STABLE from readthedocs.builds.constants import STABLE_VERBOSE_NAME from readthedocs.p...
et = queryset.filter(users__in=[user])
return queryset def for_admin_user(self, user=None, *args, **kwargs): if user.is_authenticated(): return self.filter(users__in=[user]) else: return self.none() def public(self, user=None, *args, **kwargs): queryset = self.filter(privacy_level=constants.PUBLIC) ...
#!/usr/bin/env python # -*- coding: Latin-1 -*- """ @file ParamEffectsOLD.py @author Sascha Krieg @author Daniel Krajzewicz @author Michael Behrisch @date 2008-07-26 @version $Id: ParamEffectsOLD.py 22608 2017-01-17 06:28:54Z behrisch $ Creates files with a comparison of speeds for each edge between the taxis...
is True the builder function is called anyway. """ # check if pickle file exists if not os.path.exists(source): buildNew = True # check date # if source is newer if not buildNew and os.path.getmtime(source) > os.path.getmtime(dependentOn): print("load source: ", os.path.bas...
h.basename(source), "...") target = builder(*builderParams) # pickle the target dump(target, open(source, 'wb'), 1) print("Done!") return target def chooseTaxis(vehList): """ Chooses from the vehicle list random vehicles with should act as taxis.""" # calc absolute amount of ta...
# # This file is part of pyasn1 software. # # Copyright (c) 2005-2019, Ilya Etingof <etingof@gmail.com> # License: http://snmplabs.com/pyasn1/license.html # from sys import version_info if version_in
fo[0:2] < (2, 6): def bin(value): bitstring = [] if value > 0: prefix = '0b' elif value < 0: prefix = '-0b' value = abs(value) else: prefix = '0b0' while value: if value & 1 == 1: bitstring.append('...
ring.reverse() return prefix + ''.join(bitstring) else: bin = bin
_url=None): self.site_url = site_url def query(self, *args, **kwargs): self.query = MockSolrQuery() return self.query class MockSolrQuery: def __init__(self): self.query_call_count = 0 self.query_args = [] self.field_list = None self.sort_field = None ...
f.solr_q(), 'brazil\\ and\\ health\\ and\\ ozone') def test_free_text_query_ignores_disconnected_and(self): self.sw.add_free_text_query('brazil and health ozone and') self.assertEqual(self.solr_q(), 'brazil\\ and\\ health\\ ozone\\ and') def test_free_text_query_ignores_and_at_start_of_string(...
h ozone') self.assertEqual(self.solr_q(), 'and\\ brazil\\ and\\ health\\ ozone') def test_f
# # 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 # # http://www.apache.org/licenses/LICENSE-2.0 #
# Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License....
# Copyright (C) 2012,2013 # Max Planck Institute for Polymer Research # Copyright (C) 2008,2009,2010,2011 # Max-Planck-Institute for Polymer Research & Fraunhofer SCAI # # This file is part of ESPResSo++. # # ESPResSo++ is free software: you can redistribute it and/or modify # it under the terms of the G...
can also be used to forcecap only a group of particles: >>> particle_group = [45, 67, 89, 103] >>> capforce = espressopp.integrator.CapForce(system, 1000.0, particle_group) >>> integrator.addExtension(capForce) .. function:: espressopp.integrator.CapForce(system, capForce, particleGroup) :param...
:param particleGroup: (default: None) :type system: :type capForce: :type particleGroup: """ from espressopp.esutil import cxxinit from espressopp import pmi from espressopp.integrator.Extension import * from _espressopp import integrator_CapForce class CapForceL...
# Copyright 2020 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...
if not 'username' in data_dict: raise TypeError('Username is not set.') if not 'pass
word' in data_dict: raise TypeError('Password is not set.') self._credential = data_dict def to_bytes(self): """Convert the credential object into bytes for storage.""" if not self._credential: return b'' data_string = json.dumps(self._credential) re...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
visioning_state: str=None, name: str=None, etag: str=None, **kwargs) -> None: super(IPConfiguration, self).__init__(id=id, **kwargs) self.private_ip_address = private_ip_address self.private_ip_allocation_method = private_ip_allocation_method self.subnet = subnet self.public_ip_a...
f.etag = etag
'''Autogenerated by xml_generate script, do not edit!''' from OpenGL import platform as _p, arrays # Code generation uses this from OpenGL.raw.GL import _types as _cs # End users want this... from OpenGL.raw.GL._types import * from OpenGL.raw.GL import _errors from OpenGL.constant import Constant as _C import ctypes _...
,_cs.GLenum,_cs.GLenum,_cs.GLenum,_cs.GLenum,_cs.GLenum) def glCombinerInputNV(stage,portion,variable,input,mapping,componentUsage):pass @_f @_p.types(None,_cs.GLenum,_cs.GLenum,_cs.GLenum,_
cs.GLenum,_cs.GLenum,_cs.GLenum,_cs.GLenum,_cs.GLboolean,_cs.GLboolean,_cs.GLboolean) def glCombinerOutputNV(stage,portion,abOutput,cdOutput,sumOutput,scale,bias,abDotProduct,cdDotProduct,muxSum):pass @_f @_p.types(None,_cs.GLenum,_cs.GLfloat) def glCombinerParameterfNV(pname,param):pass @_f @_p.types(None,_cs.GLenum,a...
#!/usr/bin/env python # # Copyright 2007 Google 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 o...
.remove(thread_id) while self._threads: self._condition.wait() def inject_exception(self, exception): """Injects an exception to all threads running as part of this request.""" with self._condition: thread_ids = list(self._threads)
for thread_id in thread_ids: ctypes.pythonapi.PyThreadState_SetAsyncExc( ctypes.c_long(thread_id), ctypes.py_object(exception)) _request_states = {} _request_states_lock = threading.RLock() def start_request(request_id): """Starts a request with the provided request id.""" with _request_states_l...
fig, docker=Docker, assets=Assets, composer=DockerComposer, container_builder=ContainerBuilder) def __init__(self, config, docker, assets, composer, container_builder): self._config = config self._assets = assets self._docker = docker self._composer = composer sel...
service = definition['extends']['service'] image = self._get_base_component_image(extended, service) if ':' not in image: image = '{}:master'.format(image) if image: components.append(image) return Count...
If it's a relative path, search for it in the extra flavours directory if not os.path.isabs(yml): extra_flavours = self._config.get_sandbox_value('extra_flavours') if extra_flavours: yml = os.path.join(extra_flavours, yml) with open(yml, 'rb') as _f_yml: ...
""" Consider this game: Write 8 blanks on a sheet of paper. Randomly pick a digit 0-9. After seeing the digit, choose one of the 8 blanks to place that digit in. Randomly choose another digit (with replacement) and then choose one of the 7 remaining blanks to place it in. Repeat until you've filled all 8 blanks. You wi...
e in order from smallest to largest. Write a program that plays this game by itself and determines whether it won or not. Run it 1 million times and post your probability of winning. Assigning d
igits to blanks randomly lets you win about 0.02% of the time. Here's a python script that wins about 10.3% of the time. Can you do better? import random def trial(): indices = range(8) # remaining unassigned indices s = [None] * 8 # the digits in their assigned places while indices: d = ran...
from spotdl.version import __version__
from spotdl.command_line
.core import Spotdl
f.check_permissions(request, "unstar", project) votes_service.remove_vote(project, user=request.user) return response.Ok() @detail_route(methods=["GET"]) def fans(self, request, pk=None): project = self.get_object() self.check_permissions(request, "fans", project) voter...
) signals.post_delete.disconnect(sender=Task, dispatch_uid="tasks_us_close_handler_on_delete") signals.post_delete.disconnect(sender=Task,
dispatch_uid="task_update_project_colors_on_delete") signals.post_delete.disconnect(dispatch_uid="refprojdel") signals.post_delete.disconnect(dispatch_uid='update_watchers_on_membership_post_delete') obj.tasks.all().delete() obj.user_stories.all().delete() obj.issue...
###################################################### # # MouseLook.py Blender 2.55 # # Tutorial for using MouseLook.py can be found at # # www.tutorialsforblender3d.com # # Released under the Creative Commons Attribution 3.0 Unported License. # # If you use this code, please include this information ...
bj['Cap'] > 180: obj['Cap'] = 180 if
obj['Cap'] < 0: obj['Cap'] = 0 # get the orientation of the camera to parent camOrient = obj.localOrientation # get camera Z axis vector camZ = [camOrient[0][2], camOrient[1][2], camOrient[2][2]] # create a mathutils vector vec1 = mathutils.Vector(camZ) # get camera parent camParent = ob...
or): def __init__(self, plotly_name="colorbar", parent_name="bar.marker", **kwargs): super(ColorbarValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "ColorBar"), data_docs=kwargs.pop( ...
to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically. tickcolor Sets the tick color. tickfont Sets the color bar's tick label font tickformat Sets the tick label formatting rule usi...
r to those in Python. For numbers, see: h ttps://github.com/d3/d3-format/tree/v1.4.5#d3-f ormat. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of ...
ead. :param dict experiment_dict: the ``dict`` to update.""" if pdb_dict.get("EXPDTA"): if pdb_dict["EXPDTA"][0].strip(): experiment_dict["technique"] = pdb_dict["EXPDTA"][0][6:].strip() def extract_source(pdb_dict, experiment_dict): """Takes a ``dict`` and adds source information to ...
on information to it by parsing REMARK 3 lines. :param dict pdb_dict: the ``dict`` to read. :param dict quality_dict: the ``dict`` to update.""" if pdb_dict.get("REMARK") and pdb_dict["REMARK"].get("3"): patterns = {
"rvalue": r"R VALUE.+WORKING.+?: (.+)", "rfree": r"FREE R VALUE[ ]{2,}: (.+)", } for attribute, pattern in patterns.items(): for remark in pdb_dict["REMARK"]["3"]: matches = re.findall(pattern, remark.strip()) if matches: try: ...
# # Copyright (C) 2001 Andrew T. Csillag <drew_csillag@geocities.com> # # You may distribute under the terms of either the GNU General # Public License or the SkunkWeb License, as specified in the # README file. # import os import DT import sys import time import marshal import stat def phf...
(cform)[stat.ST_MTIME] comp_form=marshal.load(open(cform)) except: comp_form=None cmtime=-1 d=DT.DT(open(fname).read(), fname, comp_form, mtime, cmtime, lambda x, y=cform: phfunc(y, x)) class dumb: pass ns=dumb() text = d(ns) et = time.time() print
text print 'elapsed time:', et - bt
import pytest from pnc_cli import projects from pnc_cli.swagger_client.apis.projects_api import ProjectsApi from test import testutils import pnc_cli.user_config as uc @pytest.fixture(scope='function', autouse=True) def get_projects_api(): global projects_api projects_api = ProjectsApi(uc.user.get_api_client...
id=new_project.id, body=updated_project) retrieved_project = projects_api.get_specific(new
_project.id).content assert retrieved_project.name == newname and retrieved_project.description == 'pnc-cli test updated description' def test_delete_specific_no_id(): testutils.assert_raises_valueerror(projects_api, 'delete_specific', id=None) def test_delete_specific_invalid_param(): testutils.assert_...
''' Non-original introduction script, added solely for the sake of familiarizing myself with Tensorflow. I, Evan Kirsch, do not claim credit whatsoever for this code. It is taken directly from https://www.tensorflow.org/ ''' import tensorflow as tf import numpy as np
# Create 100 phony x, y data points in NumPy, y = x * 0.1 + 0.3 x_data = np.random.rand(100).astype("float32") y_data = x_data * 0.1 + 0.3 # Try to find values for W and b that compute y_data = W * x_data + b # (We know that W should be 0.1 and b 0.3, but Tensorflow will # figure that out for us.) W = tf.Variable
(tf.random_uniform([1], -1.0, 1.0)) b = tf.Variable(tf.zeros([1])) y = W * x_data + b # Minimize the mean squared errors. loss = tf.reduce_mean(tf.square(y - y_data)) optimizer = tf.train.GradientDescentOptimizer(0.5) train = optimizer.minimize(loss) # Before starting, initialize the variables. We will 'run' this fi...
fro
m view import CView from template_view import CTemplateView from form_view import
CFormView
ticalLayout.addLayout(self.horizontalLayout) self.verticalLayout.addWidget(self.plot_layout) self.verticalLayout.addWidget(self.data_info_label)
self.checkBox_useCorrected.stateChanged.connect(self.set_use_corrected) self.comboBox_primarySelector.currentIndexChanged.connect(self.update_plot) self.comboBox_unitsSelector.currentIndexChanged.connect(self.update_plot) self.combo
Box_traceSelector.currentIndexChanged.connect(self.update_plot) self.plot = self.plot_layout.addPlot() # type: pg.PlotItem self._ntwk = None self._ntwk_corrected = None self._corrected_data_enabled = True self._use_corrected = False self.corrected_data_enabled = kwargs...
lass " "to just what you are wearing, but you sequence much faster in a combat turn. You have no natural Armor " "Class (Armor Class is therefore 0 regardless of Agility). You must wear armor to get an Armor Class.Your " "sequence gets a 5 point bonus.", ALL_RACES), Trait("He...
n choose this " "trait.", ["Ghoul"]), Trait("Vat Skin", "Other people find you hideous to behold and disgusting to smell after your “dip” in the FEV vats. " "The good news is that you gain a +10 bonus to your Armor Class thanks to your extra-tough skin. The bad " "n...
an choose this trait.", ["Half Mutant", "Super Mutant"], attr_mod=-1, attr_name="Perception"), Trait("Ham Fisted", "Genetic engineering – or dumb luck – has endowed you with huge hands. You get a “free” tag skill in " "Unarmed, but you suffer a -20% penalty to Small Guns, Fir...
import os from flask import current_app from flask.cli import FlaskGroup, run_command from opsy.db import db from opsy.app import create_app, create_scheduler from opsy.utils import load_plugins DEFAULT_CONFIG = '%s/opsy.ini' % os.path.abspath(os.path.curdir) def create_opsy_app(info): return create_app(config=o...
obals import _app_ctx_stack banner = 'Welcome to Opsy!' app = _app_ctx_stack.top.app shell_ctx = {'create_app': create_app, 'create_scheduler': create_scheduler, 'db': db} for plugin in load_plugins(current_app): plugin.register_shell_context(shell_ctx) shel...
except ImportError: import code code.interact(banner, local=shell_ctx) @cli.command('init-cache') def init_cache(): """Drop everything in cache database and rebuild the schema.""" current_app.logger.info('Creating cache database') db.drop_all(bind='cache') db.create_all(bind='cache...
# -*- coding: UTF-8 -*- from HowOldWebsite.estimators.estimator_sex import EstimatorSex from HowOldWebsite.models import RecordSex __author__ = 'Hao Yu' def sex_estimate(database_face_array, feature_jar): success = False database_record = None try: n_faces = len(database_face_array) re...
es) database_record = \ __do_save_to_database(database_face_array, result_estimated) success = True except Exception as e: # print(e) pass return success, database_record def __do_estimate(feature_jar, n_faces): feature = EstimatorSex.feature_combine(feature_ja...
feature_reduce(feature) result = EstimatorSex.estimate(feature) return result def __do_save_to_database(database_face, sex): database_record = [] for ith in range(len(database_face)): record = RecordSex(original_face=database_face[ith], value_predict=sex[ith]) ...
from .
import cmis_backend from . import ir_model_
fields
__author__ = 'suwelack' from msml.io.mapper.base_mapping import * import msml.model.generated.msmlScene as mod import msml.model.generated.abaqus as ab import msml.model.generated.msmlBase as mbase from jinja2 import Template, Environment, PackageLoader class Abaqus2StringMapping(Ba
seMapping): def __init__(self): self._env = Environment( keep_trailing_newline=False,loader=PackageLoader('msml.io.mapper', 'templates')) @complete_map_pre(ab.InputDeck) def map_InputDeck_pre(self, element,parent_source,parent_target, source,target): template = self._env.get_template('Inp...
rget.append(returnStr) return target, ab.PartContainer @complete_map_post(ab.InputDeck) def map_InputDeck_post(self, element,parent_source,parent_target,source,target): return None,None @complete_map_pre(ab.PartContainer) def map_PartContainer_pre(self, element,parent_source,parent...
import
pw19.__main__ if
__name__ == "__main__": pw19.__main__.main()
from flask import * import os from decorators import validate_account_and_region from aws import connect from sgaudit import get_reports, add_description from app.models import IPWhitelist elastatus = Blueprint('elastatus', __name__) @elastatus.route('/') def index(): default_account = current_app.config['CONFI...
nt_app.config['CONFIG']['default_service'] return redirect(url_for('.'+default_service, account=default_account, region=default_region)) @elastatus.route('/<account>/<region>/ec2') @validate_account_and_region def ec2(account, region): c = connect(account, region, 'ec2') instances = c.get_only_instances()...
egion=region, instances=instances) @elastatus.route('/<account>/<region>/ami') @validate_account_and_region def ami(account, region): c = connect(account,region, 'ec2') amis = c.get_all_images(owners = ['self']) ami_list = {ami: c.get_image(ami.id) for ami in amis} return render_template('ami.html', re...
if len(groups) > 1: if all(x == 1 for x in map(len, groups.values())): # All groups are different, this is an simpler case print(ut.repr2(groups, nl=3)) else: # Need to handle the multi-item groups first ...
""" Goal: Organize media on a computer over multiple drives. Fix duplicate strategy: make graph where each file/directory is a node make a directed edge whenever <path1> -- contains --> <path
2> Find all files with the same contents make an undirected edge whever <file1.uuid> == <file2.uuid> For each pair of the same files we need to assign them both to either directory 1 or directory 2. Maybe do a min-st cut between directory 1 and directory 2. for each pair of directories with...
"""Tests of the builder registry.""" import unittest from bs4 import BeautifulSoup from bs4.builder import ( builder_registry as registry, HTMLParserTreeBuilder, TreeBuilderRegistry, ) try: from bs4.builder import HTML5TreeBuilder HTML5LIB_PRESENT = True except ImportError: HTML5LIB_PRESENT =...
), HTML5TreeBuilder) else: self.assertEqual(registry.lookup('html'), HTMLParserTreeBuilder) def test_named_library(self): if LXML_PRESENT: self.assertEqual(registry.lookup('lxml', 'xml'), LXMLTreeBuilderForXML) self.assertEqua...
'), LXMLTreeBuilder) if HTML5LIB_PRESENT: self.assertEqual(registry.lookup('html5lib'), HTML5TreeBuilder) self.assertEqual(registry.lookup('html.parser'), HTMLParserTreeBuilder) def test_beautifulsoup_...
_backing_to_folder.""" m = self.mox m.StubOutWithMock(api.VMwareAPISession, 'vim') self._session.vim = self._vim m.StubOutWithMock(self._session, 'invoke_api') backing = FakeMor('VirtualMachine', 'my_back') folder = FakeMor('Folder', 'my_fol') task = FakeMor('Task...
older, name=name, spec=mox.IgnoreArg()).AndReturn(task) m.StubOutWithMock(self._session, 'wait_for_task') clone = FakeMor('Vi
rtualMachine', 'my_clone') task_info = FakeTaskInfo('success', clone) self._session.wait_for_task(task).AndReturn(task_info) m.ReplayAll() ret = self._volumeops.clone_backing(name, backing, snapshot, mox.IgnoreArg(), datastore) self.as...
.rocstats( scores, labels ) tpr = numpy.divide( tp, numpy.add( tp, fn ) ) fpr = numpy.divide( fp, numpy.add( fp, tn ) ) auroc = auc( fpr, tpr ) confidence_surfaces = roc_ci.roc_surfaces( tp, fp, fn, tn, n=300 ) plotROC( fpr, tpr, auroc, plot_title, plot, ...
test) in enumerate(cv): classifier.fit(normal_features[train], labels[train]) importances = classifier.feature_importances_ for j in range(numpy.shape(features)[1]): feature_importance[j,i]=importances[j]
probas_ = classifier.predict_proba(normal_features[test]) pool[i,0]=labels[test] pool[i,1]=probas_[0,1] fpr, tpr, thresholds = roc_curve(pool[:,0], pool[:,1]) roc_auc = auc(fpr, tpr) plotROC(fpr, tpr,roc_auc, classifier_name,plot) return feature_importance #Nested CV for Logist...
from distutils.core import setup setup( name='archinfo', version='0.03', packages=['archinfo'], install_requires=
[ 'capstone'
, 'pyelftools', 'pyvex' ] )
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright 2017 Twitter. 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...
e used to submit the topology. - topology (required) name of the requested topology The response JSON is a dictionary with all the static proper
ties of a topology. Runtime information is available from /topologies/runtimestate. Example JSON response: { release_version: "foo/bar", cluster: "local", release_tag: "", environ: "default", submission_user: "foo", release_username: "foo", submission_time: 1489523952,...
#--*-- coding:utf-8 --*-- ''' Created on 2015��5��8�� @author: stm ''' from utils import DebugLog from base.msgcodec import MsgCodec from abc import abstractmethod from base.vdstate import CREATEVIOSL
PAR_STAT, StateBase from base.cmdmsg import CMDMsg class EngineBase(object): ''' The engine would deal with the command from UI or command line. And it would respond the result to UI or command listener. ''' # objs = {} # def __new__(cls, *args, **kv): # if cls in cls.objs:...
n cls.objs[cls] # cls.objs[cls] = super(EngineBase, cls).__new__(cls) # def __init__(self, vd_comm_cnt, vd_config): ''' Constructor ''' DebugLog.info_print("EngineBase is initialized") self.msg_decoder = MsgCodec() self.vd_comm_cnt = vd_com...
reakers with R>G>B. # Max values red_biggest = math_ops.cast((reds >= blues) & \ (reds >= greens), dtypes.float32) green_biggest = math_ops.cast((greens > reds) & \ (greens >= blues), dtypes.float32) blue_biggest = math_ops.cast((blues > reds) & \ (blues > g...
= 60 * (math_ops.cast(reds > 0, dtype
s.float32) * red_biggest * \ green_smallest * (reds - blues) * \ _CustomReciprocal(math_ops.square(reds - greens))) dh_dg_3 = 60 * (math_ops.cast(reds > 0, dtypes.float32) * red_biggest * \ blue_smallest * _CustomReciprocal(reds - blues)) dh_dg_4 = 60 * (math_op...
#!/usr/bin/python # # Request for symbolList. Currently RFA only support refresh messages # for symbolList. Hence, polling is required and symbolListRequest is called # internally by getSymbolList. # # IMAGE/REFRESH: # ({'MTYPE':'REFRESH','RIC':'0#BMD','SERVICE':'NIP'}, # {'ACTION':'ADD','MTYPE':'IMAGE','SERVICE':...
,'SERVICE':'NIP','RIC':'0#BMD','KEY':'FKLL'}, # {'ACTION':'ADD','MTYPE':'IMAGE','SERVICE':'NIP','RIC':'0#BMD','KEY'
:'FKLM'}) # import pyrfa p = pyrfa.Pyrfa() p.createConfigDb("./pyrfa.cfg") p.acquireSession("Session3") p.createOMMConsumer() p.login() p.directoryRequest() p.dictionaryRequest() RIC = "0#BMD" symbolList = p.getSymbolList(RIC) print("\n=======\n" + RIC + "\n=======") print(symbolList.replace(" ","\n"))
><[^<>]*><[^<>]*><a href=\"mailto:") official_name_4_re = re.compile("<[br /p]*>([A-Za-z\. -]+?)<[^<>]*><[^<>]*><[^<>]*><a href=\"/files") official_name_5_re = re.compile(">([A-Za-z\. -]+?), [^<>]*?Director") official_name_6_re = re.compile("Fax .+?<[^<>]*><[^<>]*>([A-Za-z\. -]+?)<") website_re = re.compile("a href=\...
website = website.strip(", ") reg_website = reg_website.strip(", ") print [email] #There are many
forms the official's name can take. This tries all of them. if official_name_1_re.findall(county): official_name = official_name_1_re.findall(county)[0].strip() elif official_name_2_re.findall(county): official_name = official_name_2_re.findall(county)[0].strip() elif official_name_3_re.findall(county): offi...
#!/usr/bin/env python # # Copyright 2015 Martin Cochran # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
return '' d = d.get(division, {}) if not d: return '' return d.get(age_bracket, '') @staticmethod def GetStructuredPropertiesForList(list_id): """Returns the division, age_bracket, and league for the given list id. Defaults to Division.OPEN, AgeBracket.NO_RESTRICTION
, and League.USAU, if the division, age_bracket, or leauge, respectively, does not exist in the map for the given list_id. Args: list_id: ID of list for which to retrieve properties. Returns: (division, age_bracket, league) tuple for the given list ID. """ division = ListIdBiM...
aler.nitro.exception.nitro_exception import nitro_exception from nssrc.com.citrix.netscaler.nitro.util.nitro_util import nitro_util class appfwprofile_contenttype_binding(base_resource) : """ Binding class showing the contenttype that can be bound to appfwprofile. """ def __init__(self) : self._contenttype = "" ...
n self._state except Exception as e: raise e @state.setter def state(self, state) :
"""Enabled.<br/>Possible values = ENABLED, DISABLED """ try : self._state = state except Exception as e: raise e @property def name(self) : """Name of the profile to which to bind an exemption or rule.<br/>Minimum length = 1. """ try : return self._name except Exception as e: raise e @na...
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distribu...
, self.helium_natoms) def test_none(self): none_geometry = geometry_from_pubchem('none') self.assertIsNone(none_geometry) def test_water_2d(self): water_geometry = geometry_from_pubchem('water', structure='2d') self.water_natoms = len(water_geometry) water_natoms = 3 ...
self.assertEqual(water_natoms, self.water_natoms) self.oxygen_z_1 = water_geometry[0][1][2] self.oxygen_z_2 = water_geometry[1][1][2] z = 0 self.assertEqual(z, self.oxygen_z_1) self.assertEqual(z, self.oxygen_z_2) with pytest.raises(ValueError, ...
import binascii import datetime import hashlib import os from pymongo import ReturnDocument from vj4 import db from vj4.util import argmethod TYPE_REGISTRATION = 1 TYPE_SAVED_SESSION = 2 TYPE_UNSAVED_SESSION = 3 TYPE_LOSTPASS = 4 TYPE_CHANGEMAIL = 5 def _get_id(id_binary): return hashlib.sha256(id_binary).digest...
sort=[('create_at', 1)]).to_list() @argmethod.wrap async def update(token_id: str, token_type: int, expire_seconds: int, **kwargs): """Update a token. Args: token_id: token ID. token_type:
type of the token. expire_seconds: expire time, in seconds. **kwargs: extra data. Returns: The token document, or None. """ id_binary = binascii.unhexlify(token_id) coll = db.coll('token') assert 'token_type' not in kwargs now = datetime.datetime.utcnow() doc = await coll.find_one_and_update...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests.common import TransactionCase class TestGetMailChannel(TransactionCase): def setUp(self): super(TestGetMailChannel, self).setUp() self.operators = self.env['res.users'].create([{ ...
: 'Pierre',
'login': 'pierre' }, { 'name': 'Jean', 'login': 'jean' }, { 'name': 'Georges', 'login': 'georges' }]) self.livechat_channel = self.env['im_livechat.channel'].create({ 'name': 'The channel', 'user_ids': ...
h[0,:],path[1,:]) plt.axis([-100, 300, -100, 300]) plt.show() return path def compute_A_star_path(origin,goal,Map): path=A_star(origin,goal,Map) #path_array=np.array(path) #print(path_array.shape) path_rev=np.flip(path, axis=0) return path_rev def robot_control(pos_rob,target, K_x=1,K_y=1,K_an=1): #pos_rob i...
-pos_rob[0],2) + np.power(marker_map[markers[i],1]-pos_rob[1],2) ''' H[i*3,0] = (marker_map[markers[i],1]-pos_rob[1])/distance H[i*3,1] = -(marker_map[markers
[i],0]-pos_rob[0])/distance H[i*3,2] = -1 H[i*3+1,0] = (pos_rob[0]-marker_map[markers[i],0])/np.sqrt(distance) H[i*3+1,1]= (pos_rob[1]-marker_map[markers[i],1])/np.sqrt(distance) H[i*3+1,2] = 0 H[i*3+2,0] = 0 H[i*3+2,1] = 0 H[i*3+2,2] = -1 ''' H[i*2,0] = (marker_map[markers[i],1]-pos_rob[1])/distanc...
# This file is part of the django-environ. # # Copyright (c) 2021, Serghei Iakovlev <egrep@protonmail.ch> # Copyright (c) 2013-2021, Daniele Faraglia <daniele.faraglia@gmail.com> # # For the full copyright and license information, please view # the LICENSE.txt file that was distributed with this source code. from envi...
STRING_LIKE_BOOL='True', BOOL_TRUE_STRING_1='on', B
OOL_TRUE_STRING_2='ok', BOOL_TRUE_STRING_3='yes', BOOL_TRUE_STRING_4='y', BOOL_TRUE_STRING_5='true', BOOL_TRUE_BOOL=True, BOOL_FALSE_STRING_LIKE_INT='0', BOOL_FALSE_INT=0, BOOL_FAL...
try: import cPickle as pickle except ImportError: import pickle as pickle from django.core.management.color import color_style from django.db.models import signals, get_apps, get_app from django_evolution import is_multi_db, models as django_evolution from django_evolution.evolve import get_evolution_sequence...
__name__.split('.')[-2] sequence = get_evolution_sequence(app)
if sequence: if verbosity > 0: print 'Evolutions in %s baseline:' % app_label, \ ', '.join(sequence) for evo_label in sequence: evolution = django_evolution.Evolution(app_label=app_label, label=evo_label, ...
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from django.http.response import HttpResponse, HttpResponseRedirec...
import telemetry class TelemetryView(TemplateView): template_name = "shuup/admin/system/telemetry.jinja" def get_context_data(self, **kwargs): context = super(TelemetryView, self).get_context_data(**kwargs) context.update({ "opt_in": not telemetry.is_opt_out(), "is_gra...
(request=self.request, indent=2), "title": _("Telemetry") }) return context def get(self, request, *args, **kwargs): if "last" in request.GET: return HttpResponse(telemetry.get_last_submission_data(), content_type="text/plain; charset=UTF-8") return super(Tel...
import numpy as np import pylab as pl from astropy.io import fits from scipy.interpolate import interp1d sigma_y = 0 * np.pi / 2.355 / 60. /180. #angle in radian sigmasq = sigma_y * sigma_y #f = fits.open('/media/luna1/flender/projects/gasmod/maps/OuterRim/cl_tsz150_Battaglia_c05_R13.fits')[1].data #l = np.arange(10...
/github/HaloModel/data/cl_yy.dat', unpack=True) Dl = vl*(1.+vl)*vcl1*1e12*6.7354/2./np.pi Dl = vcl1*1e12 Bl = np.exp(-vl*vl*sigmasq) spl = interp1d(vl, Dl*Bl) pl.figure(1) #pl.semilogx(vl, Dl*Bl, label='Vinu') pl.loglog(vl, Dl*Bl, label='Vinu') pl.xlim(500,10000) pl.xlabel(r'$\ell$') pl.ylabel(r'$D_\ell$') pl.legend(lo...
label(r'$\ell$') pl.ylabel('Battaglia/Vinu') pl.show()
"""modify Revision ID: 4cefae1354ee Revises: 51f5ccfba190 Create Date: 2016-07-23 13:16:09.932365 """ # revision identifiers, used by Alembic. revision = '4cefae1354ee' down_revision = '51f5ccfba1
90' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.add_column('posts', sa.Column('title', sa.String(length=128), nullable=True)) op.create_index('ix_posts_title', 'posts', ['title'], unique=False) ###
end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_index('ix_posts_title', 'posts') op.drop_column('posts', 'title') ### end Alembic commands ###
ance = fake_instance.fake_instance_obj(self.context) self._vmops.power_on(mock_instance, mock.sentinel.block_device_info) mock_fix_instance_vol_paths.assert_called_once_with( mock_instance.name, mock.sentinel.block_device_info) mock_set_vm_state.assert_called_once_with( ...
ck.call(mock.sentinel.FAKE_PATH), mock.call(mock.sentinel.FAKE_PATH_ARCHIVED)] self._vmops._pathutils.exists.assert_has_calls(calls) self._vmops._pathutils.copy.assert_called_once_with( mock.sentinel.FAKE_PATH, mock.sentinel.FAKE_REMOTE_PATH) @mock.patch.object(vmops.i...
ls, 'IOThread') def test_log_vm_serial_output(self, fake_iothread): self._vmops._pathutils.get_vm_console_log_paths.return_value = [ mock.sentinel.FAKE_PATH] self._vmops.log_vm_serial_output(mock.sentinel.FAKE_VM_NAME, self.FAKE_UUID) pi...
ck_via_dict(mycfg, rc=RC_NOT_FOUND, policy_dmi="disabled") def test_path_env_gets_set_from_main(self): """PATH environment should always have some tokens when main is run. We explicitly call main as we want to ensure it updates PATH.""" cust = copy.deepcopy(VALID_CFG['NoCloud']) ro...
d_not_active(self): """EC2: bobrightbox.com in product_serial is not brightbox'""" self._test_ds_not_found('Ec2-E24Cloud-negative') class TestIsIBMProvisioning(DsIdentifyBase): """Test the is_ibm_provisioning method in ds-identif
y.""" inst_log = "/root/swinstall.log" prov_cfg = "/root/provisioningConfiguration.cfg" boot_ref = "/proc/1/environ" funcname = "is_ibm_provisioning" def test_no_config(self): """No provisioning config means not provisioning.""" ret = self.call(files={}, func=self.funcname) ...
self.close(handle) return [name for database in result.rows() for name in database] else: return [] def get_database(self, database): return self.client.get_database(database) def get_tables_meta(self, database='default', table_names='*'): identifier = self.to_matching_wildcard(table_nam...
e)s`.`%(table)s`' % {'database': database, 'table': table} else: hql = 'ANALYZE TABLE `%(database)s`.`%(table)s` COMPUTE STATISTICS' % {'database': database, 'table': table} return self.execute_statement(hql) def analyze_tab
le_columns(self, database, table): if self.server_name == 'impala': hql = 'COMPUTE STATS `%(database)s`.`%(table)s`' % {'database': database, 'table': table} else: hql = 'ANALYZE TABLE `%(database)s`.`%(table)s` COMPUTE STATISTICS FOR COLUMNS' % {'database': database, 'table': table} return sel...
import copy class Histogram( object ): '''Histogram + a few things. This class does not inherit from a ROOT class as we could want to use it with a TH1D, TH1F, and even a 2D at some point. Histogram contains the original ROOT histogram, obj, and a weighted version, weigthed, originally set equal...
oundaries should define an integer number
of bins. nbins=%d, xmin=%3.3f, xmax=%3.3f' % (self.obj.GetNbinsX(), self.obj.GetXaxis().GetXmin(), self.obj.GetXaxis().GetXmax()) ) return hist.Integral(bmin, bmax) else: raise ValueError('if specifying one boundary, you must specify the other') def DrawNormalized(self): '...
#!/usr/bin/env python import os import sys sys.path.insert(0, os.pardir) from testing_harnes
s import TestHarness class StatepointTestHarness(TestHarness): def __init__(self): self._sp_name = None self._tallies = False se
lf._opts = None self._args = None def _test_output_created(self): """Make sure statepoint files have been created.""" sps = ('statepoint.03.*', 'statepoint.06.*', 'statepoint.09.*') for sp in sps: self._sp_name = sp TestHarness._test_output_created(self) if...
from pyramid.response import Response from pyramid.view import view_config from sqlalchemy.exc import DBAPIError from .models import ( DBSession, MyModel, ) @view_config(route_name='home', renderer='templates/mytemplate.pt') def my_view(request): try: one = DBSession.query(MyModel).filter(My...
might be caused by one of the following things: 1. You may need to run the "initialize_mypyramid_db" script to initialize your database tables. Check your virtual environment's "bin" direc
tory for this script and try to run it. 2. Your database server may not be running. Check that the database server referred to by the "sqlalchemy.url" setting in your "development.ini" file is running. After you fix the problem, please restart the Pyramid application to try it again. """
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else [] PROJECT_CATKIN_DEPENDS = "".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = ""
.split(';') if "" != "" else [] PROJECT_NAME
= "hector_imu_tools" PROJECT_SPACE_DIR = "/home/trevor/ROS/catkin_ws/devel" PROJECT_VERSION = "0.3.3"
#!/usr/bin/env python # pylint: disable=C0103,W0622 # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015 Leandro Toledo de Souza <leandrotoeldodesouza@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public ...
self.username: return '@%s' % self.username if self.last_name: return '%s %s' % (self.first_name, self.last_name) return self.first_name @staticmethod def de_json(data): """ Args: data (str): Returns: telegram.
User: """ if not data: return None return User(**data)
fos = dict() #this might take quite a long time self.configreg.foreach_language(self._get_language_variants, None) self.configreg.foreach_country(self._get_country_variants, None) #'grp' means that we want layout (group) switching options self.configreg.foreach_option('grp', se...
ants): return self._rec.set_layouts(self._rec.layouts + [layout]) self._rec.set_variants(self._rec.variants + [variant]) if not self._rec.activate(self._engine): raise XklWrapperError("Failed to add layout '%s (%s)'" % (layout, ...
m the current X configuration. See also the documentation for the add_layout method. :param layout: either 'layout' or 'layout (variant)' :raise XklWrapperError: if the given layout cannot be removed """ #we can get 'layout' or 'layout (variant)' (layout, vari...
tyNotImplemented def dark_maze(): return AbilityNotImplemented return dark_maze, dark_maze, @card("Samite Alchemist") def samite_alchemist(card, abilities): def samite_alchemist(): return AbilityNotImplemented return samite_alchemist, @card("Grandmother Sengir") def grandmother_s...
va_constable(): return AbilityNotImplemented return anhavva_constable, @card("Jinx") def jinx(card, abilities): def jinx(): return AbilityNotImplem
ented def jinx(): return AbilityNotImplemented return jinx, jinx, @card("Serra Inquisitors") def serra_inquisitors(card, abilities): def serra_inquisitors(): return AbilityNotImplemented return serra_inquisitors, @card("Roterothopter") def roterothopter(card, abilities): def...
from rezgui.qt import QtGui from rezgui.util import create_pane from rezgui.mixins.ContextViewMixin import ContextViewMixin from rezgui.models.ContextModel import ContextModel from rez.config import config from rez.vendor import yaml from rez.vendor.yaml.error import YAMLError from rez.vendor.schema.schema import Schem...
txt = yaml.dump({key: value}, default_flow_style=False) title = self.titles.get(key) if title: lines.append("# %s" % title) lines.append(txt.rstrip()) txt = '\n'.join(lines) + '\n' txt = txt.lstrip() self.edit.setPlainText(txt) def _se...
Johns. # # This library is free software: you can redistribute 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 option) any later version. # # This library is distributed in the hope that it will...
# encoding: utf-8 # module gio._gio # from /usr/lib/python2.7/dist-packages/gtk-2.0/gio/_gio.so # by generator 1.135 # no doc # imports import gio as __gio import glib as __glib import gobject as __gobject import gobject._gobject as __gobject__gobject class InetSocketAddress(__gio.SocketAddress): """ Object ...
IPv6 flow info scope-id -> guint: Scope ID IPv6 scope ID Properties from GSocketAddress: family -> GSocketFamily: Address family The family of the socket address Signals from GObject: notify (GParam) """ def get_address
(self, *args, **kwargs): # real signature unknown pass def get_port(self, *args, **kwargs): # real signature unknown pass def __init__(self, *args, **kwargs): # real signature unknown pass __gtype__ = None # (!) real value is ''
#!/usr/bin/env python # # MountDirectories.py: this file is part of the GRS suite # Copyright (C) 2015 Anthony G. Basile # # 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 ...
mounted beore 'dev/pts'. self.directories = [ 'dev', 'dev/pts', {'dev/shm' : ('tmpfs', 'shm')}, 'proc', 'sys', [portage,
'usr/portage'], [package, 'usr/portage/packages'] ] # Once initiated, we only work with one portage_configroot self.portage_configroot = portage_configroot self.package = package self.portage = portage self.logfile = logfile # We need to umount in the...
ration file, created by # sphinx-quickstart on Thu Aug 28 15:17:47 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 configuration values have a default; values that are comment...
--------------------------- # If your documentation needs a minimal Sphinx version, state it here. needs_sphinx = '1.2' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphi...
re, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'PySpark' copyright = u'' #...
#-*- coding: utf-8 -*- import sys from abc import ABCMeta, abstractmethod from src.shell.std import Std class ICommand(Std): """ Interface for a scat command """ def __init__(self, verbose=2): self.__verbose = verbose return def stdout(self, msg, crlf=True): if self...
if crlf: sys.stdout.write("\n") def stderr(self, msg):
""" Print message on standard error, with formatting. @param msg message to print """ if self.__verbose > 0: sys.stderr.write("*** " + msg + "\n") @abstractmethod def run(self, *args, **kwargs): raise NotImplemented @abstractmethod def ...
_DIRECTION, SUPPORT_OSCILLATE, SUPPORT_PRESET_MODE, SUPPORT_SET_SPEED, FanEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import ConfigType,...
rn self._oscillating @property def supported_features(self) -> int: """Flag supported features.""" return self._supported_features class DemoPercentageFan(BaseDemoFan, FanEntity): """A demonstration fan component that uses percentages.""" @property def perce
ntage(self) -> int | None: """Return the current speed.""" return self._percentage @property def speed_count(self) -> int: """Return the number of speeds the fan supports.""" return 3 def set_percentage(self, percentage: int) -> None: """Set the speed of the fan, as...
''' Copyright 2013 Sven Reissmann <sven@0x80.io> This file is part of ddserver. ddserver 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, either version 3 of the License, or (at your option) any later
version. ddserver is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License ...
es.index # @UnusedImport: for web application import ddserver.interface.pages.signup # @UnusedImport: for web application import ddserver.interface.pages.lostpasswd # @UnusedImport: for web application import ddserver.interface.pages.login # @UnusedImport: for web application import ddserver.interface.pages.user.ac...
from tests.base import TestCase from vilya.models.project import CodeDoubanProject from vilya.models.project_conf import PROJECT_CONF_FILE from nose.tools import raises class TestProjectConf(TestCase): def test_create_project_without_conf(self): self.clean_up() project = CodeDoubanProject.add( ...
d( 'tp', owner_id="test1", create_trac=False) u = self.addUser() project.git.commit_one_file(PROJECT_CONF_FILE, 'docs: {unexisting_key: a
aa}', 'm', u) assert project.conf['docs']['unexisting_key'] == 'aaa' def clean_up(self): prj = CodeDoubanProject.get_by_name('tp') if prj: prj.delete()
import numpy as np from scipy import stats from statsmodels.regression.linear_model import OLS from statsmodels.tools import tools from statsmodels.sandbox.regression.gmm import IV2SLS, IVGMM, DistQuantilesGMM, spec_hausman from statsmodels.sandbox.regression import gmm if __name__ == '__main__': import stats...
rument = exog elif exampledata == 'iv': endog, exog, instrument = sample_iv(X) elif exampledata == 'ivfake': endog, exog, instrument = sample_ivfake(X) #using GMM and IV2SLS cla
sses #---------------------------- mod = gmm.IVGMM(endog, exog, instrument, nmoms=instrument.shape[1]) res = mod.fit() modgmmols = gmm.IVGMM(endog, exog, exog, nmoms=exog.shape[1]) resgmmols = modgmmols.fit() #the next is the same as IV2SLS, (Z'Z)^{-1} as weighting matri...
#!/usr/bin/python """checks bugle trace log for OpenGL problems""" from __future__ import print_function import sys count = 0 lineNo = 0 inList = False inBlock = False legalLists = {} setLists = {} usedInList = {} usedInBlock = {} usedOutBlock = {} def error(error, lineNo, *args): print("Error:", error.format(*...
d': if not inBlock: print("Error: Not in block.", lineNo) exit(-1) inBlock = False else: blockDict=usedOutBlock if inBlock: blockDict=usedInBl
ock if not function in blockDict: blockDict[function]=lineNo if function == 'glGenLists': legalLists[result] = True if inList: error("Still in list generation.", lineNo) if function == 'glEndList': if not inList: error("Not in list generation...
""" Course info page. """ from .course_page import CoursePage class CourseInfoPage(CoursePage): """ Course info. """ url_path = "info" def is_browser_on_page(self): return self.is_css_present('section.updates') @property def num_upda
tes(self): """ Return the number of updates on the page. """ return self.css_count('section.updates section article') @property def handout_links(self):
""" Return a list of handout assets links. """ return self.css_map('section.handouts ol li a', lambda el: el['href'])
#!/usr/bin/env python # -*- coding: utf-8 -*- from os import path import os from tempfile import NamedTemporaryFile import numpy as np import morfessor from six import PY2 from six.moves import cPickle as pickle from . import polyglot_path from .decorators import memoize from .downloader import downloader from .map...
None): """Return filename that contains specific language resource name. Args: name (string): Name of the resource. lang (string): language code to be loaded. """ task_dir = resource_dir.get(name
, name) package_id = u"{}.{}".format(task_dir, lang) p = path.join(polyglot_path, task_dir, lang) if not path.isdir(p): if downloader.status(package_id) != downloader.INSTALLED: raise ValueError("This resource is available in the index " "but not downloaded, yet. Try to run\n\n" ...
import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from sklearn.datasets import load_sample_image from sklearn.datasets import load_sample_images # Utility functions def plot_image(image): plt.imshow(image, cmap="gray", interpolation="nearest") plt.axis("off") def plot_color_image(image...
mshow(image.astype(np.uint8),interpolation="nearest") plt.axis("off") # Load sample images china = load_sample_image('china.jpg') flower = load_sample_image('flower.jpg') image = china[150:220, 130:250] height, width, channels = image.shape image_grayscale = image.mean(axis=2).astype(np.float32) images = image_gra...
batchsize, height, width, channels = dataset.shape # Create 2 filters fmap = np.zeros(shape=(7, 7, channels, 2), dtype=np.float32) fmap[:, 3, 0, 0] = 1 fmap[3, :, 0, 1] = 1 plot_image(fmap[:,:,0,0]) plt.show() plot_image(fmap[:,:,0,1]) plt.show() X = tf.placeholder(tf.float32, shape=(None, height, width, channels)) c...
""" Provides a set of pluggable permission policies. """ from __future__ import unicode_literals from django.http import Http404 from rest_framework import exceptions from rest_framework.compat import is_authenticated SAFE_METHODS = ('GET', 'HEAD', 'OPTIONS') class BasePermission(object): """ A base class ...
[], 'HEAD': [], 'POST': ['%(app_label)s.add_%(model_name)s'], 'PUT': ['%(app_label)s.change_%(model_name)s'], 'PATCH': ['%(app_label)s.change_%(model_name)s'], 'DELETE': ['%(app_label)s.delete_%(model_na
me)s'], } def get_required_object_permissions(self, method, model_cls): kwargs = { 'app_label': model_cls._meta.app_label, 'model_name': model_cls._meta.model_name } if method not in self.perms_map: raise exceptions.MethodNotAllowed(method) ...
''' The tests in this package are to ensure the proper resultant dtypes of set operations. ''' import itertools as it import numpy as np import pytest from pandas.core.dtypes.common import is_dtype_equal import pandas as pd from pandas import Int64Index, RangeIndex from pandas.tests.indexes.conftest import indices_l...
idx2 = idx_fact2(20) res1 = idx1.union(idx2) res2 = idx2.union(idx1) assert r
es1.dtype in (idx1.dtype, idx2.dtype) assert res2.dtype in (idx1.dtype, idx2.dtype)
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012, Intel, 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 # # ...
allow_reschedule=allow_reschedule, snapshot_id=snapshot_id, image_id=image_id, source_volid=source_volid), topic=rpc.queue_get_for(ctxt, self.topic, ...
f.cast(ctxt, self.make_msg('delete_volume', volume_id=volume['id']), topic=rpc.queue_get_for(ctxt, self.topic, volume['host'])) def create_snapshot(self, ctxt, volume, snapshot): self.cast(ctxt, self.make_msg('create_snapshot', ...
from backend import app if
__name__ == '__main__': app.run('0.0.0.0',port=8080, threa
ded=True, debug=True)
InvalidFrameError, InternalError, ) from collections import deque from .util import take_from_deque __all__ = [ 'Frame', 'PingFrame', 'DataFrame', 'ResetFrame', 'WindowFrame', 'SettingsFrame', 'FrameReader', ] FRAME_HEADER_FMT = struct.Struct('>IIB') assert FRAME_HEADER_FMT.size == 9 ...
FMT = struct.Struct('>I') def __init__(self, stream_id, flags, increment): self.stream_id = stream_id self.flags = flags self.increment = increment def __cmp__(self, other): if other is self: return 0 if isinstance(other, WindowFrame): return c...
(other.stream_id, other.flags, other.increment), ) return cmp(id(self), id(other)) @classmethod def load_frame_data(cls, header, reader): if header.payload_size != 4: raise InvalidFrameError() increment, = cls.FMT.unpack(reader.read(4)) retur...