prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
#!/usr/bin/python # # 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 distribut...
": "platform", "host_name": "hostname", "rr_reason": "rr" } mapped_show_version_facts = apply_key_map(key_map, body) return map
ped_show_version_facts def get_interface_facts(module): command = 'show interface status' body = execute_show_command(command, module)[0] interface_list = [] interface_table = body['TABLE_interface']['ROW_interface'] if isinstance(interface_table, dict): interface_table = [interface_tabl...
#!/usr/bin/env python # -*- coding: utf-8 -*- import pymongo from pymongo import MongoClient from pymongo import errors import re class Database(object): '''Database creation''' def __init__(self, database_name): self.client = MongoClient('mongodb://localhost,localhost:27017') self.db_name = database_name sel...
o is not None: # print n['url']+";"+o # else: # print n["url"]+";None" # return # def export_backlinks(self): #
print "source;target" # for n in self.db.results.find(): # if n != []: # for u in n["backlinks"]: # print n["url"]+";"+u["url"] # # for o in n["backlinks"]: # # if o is not None: # # print n['url']+";"+o # # else: # # print n["url"]+";None" # return if __name__ == "__main__": ...
__contains__(self, point): return self.low <= point <= self.high @property def transformed_bounds(self): if self.transform_ == "normalize": return 0.0, 1.0 else: if self.prior == "uniform": return self.low, self.high else: ...
self.prior = prior if prior is None: self.prior_ = np.tile(1. / len(self.categories), len(self.categories)) else: self.prior_ = prior # XXX check that sum(prior) == 1 self._rvs = rv_discrete( values=(range(len(self...
type(other) and self.categories == other.categories and np.allclose(self.prior_, other.prior_)) def __repr__(self): if len(self.categories) > 7: cats = self.categories[:3] + [_Ellipsis()] + self.categories[-3:] else: cats = self.categories ...
""" SALTS XBMC Addon Copyright (C) 2014 tknorris 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 option) any later version. T...
def provides(cls): return frozenset([VIDEO_TYPES.MOVIE]) @classmethod def get_name(cls): return 'filmikz.
ch' def resolve_link(self, link): return link def format_source_label(self, item): return '[%s] %s' % (item['quality'], item['host']) def get_sources(self, video): source_url = self.get_url(video) hosters = [] if source_url and source_url != FORCE_NO_MATCH: ...
if not match: raise ValueError("Uri '%s' does not start with a RFC 3986 compliant" " scheme" % (uri)) return netutils.urlsplit(uri) def look_for(haystack, needles, extractor=None): """Find items in haystack and returns matches found (in haystack order). Given a list of it...
: on_clamped() return value def fix_newlines(text, replacement=os.linesep): """Fi
xes text that *may* end with wrong nl by replacing with right nl.""" return replacement.join(text.splitlines()) def binary_encode(text, encoding='utf-8', errors='strict'): """Encodes a text string into a binary string using given encoding. Does nothing if data is already a binary string (raises on unknow...
me_type_id :param volumeInstance: the volume instance :param targetPoolName: the target poolName :param targetFastPolicyName: the target FAST policy name, can be None :param sourceFastPolicyName: the source FAST policy name, can be None :param new_type: None :returns: bo...
to " "original storage pool. Please contact your system " "administrator to return it to the correct location ") % {'volumeName': volumeName}) LOG.error(ex
ceptionMessage) if sourceFastPolicyName is not None: self.add_to_default_SG( conn, volumeInstance, storageSystemName, sourceFastPolicyName, volumeName) def _migrate_cleanup(self, conn, volumeInstance, storageSystemName, sourceFastPolicyN...
_23 geometry"]=s s= marker_sets["particle_23 geometry"] mark=s.place_marker((6281.96, 7073.27, 9116.57), (0.7, 0.7, 0.7), 627.901) if "particle_24 geometry" not in marker_sets: s=new_marker_set('particle_24 geometry') marker_sets["particle_24 geometry"]=s s= marker_sets["particle_24 geometry"] mark=s.place_marker((...
icle_39 geometry') marker_sets["particle_39 geometry"]=s s= marker_sets["particle_39 geometry"] mark=s.place_marker((5843.67, 6803.03, 9425.01), (0.7, 0.7, 0.7), 750.656)
if "particle_40 geometry" not in marker_sets: s=new_marker_set('particle_40 geometry') marker_sets["particle_40 geometry"]=s s= marker_sets["particle_40 geometry"] mark=s.place_marker((5746.46, 5614.48, 8373.18), (0.7, 0.7, 0.7), 709.625) if "particle_41 geometry" not in marker_sets: s=new_marker_set('particle_4...
import pytest from dvc.env import DVC_PAGER from dvc.ui.pager import ( DEFAULT_PAGER, LESS, PAGER_ENV, find_pager, make_pager, pager, ) @pytest.fixture(autouse=True) def clear_envs(monkeypatch): monkeypatch.delenv(DVC_PAGER, raising=False) monkeypatch.delenv(PAGER_ENV, raising=False) ...
assert find_pager() is None def test_find_pager_uses_custom_pager_when_dvc_pager_env_var_is_defined( mocker, monkeypatch ): monkeypatch.
setenv(DVC_PAGER, "my-pager") mocker.patch("sys.stdout.isatty", return_value=True) assert find_pager() == "my-pager" def test_find_pager_uses_custom_pager_when_pager_env_is_defined( mocker, monkeypatch ): monkeypatch.setenv(PAGER_ENV, "my-pager") mocker.patch("sys.stdout.isatty", return_value=Tru...
# 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 Licen
se. 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. import glob import io import json imp...
#!/usr/bin/python # -*- coding: utf-8 -*- """Tests for the EWF image path specification implementation.""" import unittest from dfvfs.path import ewf_path_spec from tests.path import test_lib class EwfPathSpecTest(test_lib.PathSpecTestCase): """Tests for the EWF image path specification implementation.""" def...
or): _ = ewf_path_spec.EwfPathSpec(parent=None) with self.assertRaises(ValueError): _ = ewf_path_spec.EwfPathSpec(parent=self._path_spec, bogus=u'BOGUS') def testComparable(self): """Tests the path specification comparable property.""" path_spec = ewf_path_spec.EwfPathSpec(parent=self._path_...
u'']) self.assertEqual(path_spec.comparable, expected_comparable) if __name__ == '__main__': unittest.main()
"""VASP POSCAR format.""" import numpy as np __all__ = ["write_poscar"] def write_poscar( compound, filename, lattice_constant, bravais=[[1, 0, 0], [0, 1, 0], [0, 0, 1]], sel_dev=False, coord="cartesian", ): """Write a VASP POSCAR file from a Compound. See //https://www.vasp.at formo...
atom.xy = atom.xy / lattice_constant atom.xz = atom.xz
/ lattice_constant for atom_name in atom_names: atom_count = np.array( [atom.name for atom in structure.atoms].count(atom_name) ) count_list.append(atom_count) xyz = np.array( [ [atom.xx, atom.xy, atom.xz] for atom in structure...
# -*- coding: utf-8 -*- from __future__ import print_function import os import sys import time import subprocess # Import parameters from the setup file. sys.path.append('.') from setup import ( setup_dict, get_project_files, print_success_message, print_failure_message, _lint, _test, _test_all, CODE_DIR...
"i.e., `pip install watchdog'.") raise SystemExit(1) class RebuildDocsEventHandler(Fi
leSystemEventHandler): def __init__(self, base_paths): self.base_paths = base_paths def dispatch(self, event): """Dispatches events to the appropriate methods. :param event: The event object representing the file system event. :type event: :class:`watchdo...
# -*- coding: utf-8 -*- """ Created on Mon Aug 1 17:14:20 2016 @author: stephaniekwan Plot prominent emission lines of IC 10 X-2 from TripleSpec chop-subtracted data. He I and Pa-Gamma lines fit on one plot, Pa-Beta line goes in a separate plot (comment/uncomment blocks to plot each set). """ import numpy as np im...
fontsize = 12, color = 'red') # Plot the peak emission line in green ax2.axvli
ne(x = 1.28103- 0.0005, color = 'green', ls = 'dashed') ax2.text(1.278- 0.0005, 1.5, 'Pa $\\beta$ (1.2805)', rotation = 90, fontsize = 12, color = 'green') ax2.invert_xaxis() ax2.set_xlim([1.270, 1.2939]) ax2.set_ylim([0, 2.0]) # Set common labels f.text(0.5, 0.04, 'Wavelength ($\mu$m)', ha = 'center', va = ...
# Copyright 2018 Open Source Robotics Foundation, 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...
nch Documentation', 'Open Source Robotics Foundation, Inc.', 'manual'), ] # -- Options for manual page output ------------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'la
unch', 'launch Documentation', [author], 1) ] # -- Options for Texinfo output ---------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (mast...
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2012,2013 Contributor # # 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...
here is no knc in use here, it just returns None. """ def getPrincipal(self): """For any anonymous channel, always returns None.""" return None class AnonSite(server.Site): """ Overrides the basic HTTPChannel protocol with AnonHTTPChannel to provide a getPrincipal method. Sho...
# This is exactly the default server.Site.log() method for now. def log(self, request): if hasattr(self, "logFile"): line = '%s - %s %s "%s" %d %s "%s" "%s"\n' % ( request.getClientIP(), # request.getUser() or "-", # the remote user is almost never important ...
# Copyright 2013 Virgil Dupras (http://www.hardcoded.net) # # This software is licensed under the "BSD" License as d
escribed in the "LICENSE" file, # which should be included with this package. import os.path as op from urllib.request import urlope
n import subprocess import json from bs4 import BeautifulSoup HERE = op.dirname(__file__) AUR_FOLDER = op.join(HERE, 'aur') BASE_URL = 'https://aur.archlinux.org' def get_pkg_list(): result = [] # (name, version) URL = BASE_URL + '/packages/?SB=a&SO=d&O=0&PP=250' with urlopen(URL) as fp: contents...
class Solution: # @param nums: a list of integers # @return: an integer def findMissing(self, n
ums): # write your code here n = len(nums)
return n * (n + 1) / 2 - sum(nums)
standards, changed for WidgetasticTaggable.get_tags()""" entities = View.nested(DetailsEntitiesAnsibleCatalogItemView) @property def is_displayed(self): return ( self.in_explorer and self.entities.title.text == 'Service Catalog Item "{}"'.format( self.context...
: updates["retirement"]["repository"] }) wait_for(lambda: view.retirement.playbook.is_displayed, delay=0.5, num_sec=2) view.retirement.fill({
"playbook": updates["retirement"]["playbook"], "machine_credential": updates["retirement"]["machine_credential"], "cloud_type": updates["retirement"].get("cloud_type"), "hosts": updates["retirement"].get("hosts"), "escalate_privilege": updates["retirement...
clusive with I(template) required: false default: None aliases: [] author: - "Daniel Tschan <tschan@puzzle.ch>" extends_documentation_fragment: [] ''' EXAMPLES = ''' # TODO ''' class ResourceModule: def __init__(self, module): self.module = module self.changed = False self.msg = [] self...
, v in object.items(): self.remove_omitted_keys(v, object, k) elif isinstance(object, list): for i, v in enumerate(object[:]): self.remove_omitted_keys(v, object, i) elif isinstance(object, basestring): if isinstance(object, basestring) and object.startswith('__omit_place_holder__'):...
f re.match('\.status\..*', path): return True elif kind == 'DeploymentConfig' and re.match('.spec.template.spec.containers\[[0-9]+\].image', path): return "@" in current return False def patch_applied(self, kind, name, current, patch, path = ""): self.trace("patch_applied %s", path) if...
'dnf.rpm.detect_releasever', return_value=69): super(Base, self).__init__(*args, **kwargs) # mock objects def mock_comps(history, seed_persistor): comps = dnf.comps.Comps() comps._add_from_xml_filename(COMPS_PATH) persistor = history.group if seed_persistor: name = 'Peppers' ...
class _BaseStubMixin(object):
"""A reusable class for creating `dnf.Base` stubs. See also: hawkey/test/python/__init__.py. Note that currently the used TestSack has always architecture set to "x86_64". This is to get the same behavior when running unit tests on different arches. """ def __init__(self, *extra_repos): ...
from __future__ imp
ort unicode_literals __version__ =
'2016.01.09'
# -*- coding: utf-8 -*- # Copyright (c) 2010 - 2015 Detlev Offenbach <detlev@die-offenbachs.de> # """ Module implementing a dialog to enter the data for a copy or rename operation. ""
" from __future__ import unicode_literals import os.path from PyQt5.QtCore import pyqtSlot from PyQt5.QtWidgets import QDialog, QDialogButtonBox from E5Gui.E5PathPicker import E5PathPickerModes from .Ui_HgCopyDialog import Ui_HgCopyDialog class HgCopyDialog(QDialog, Ui_HgCopyDialog): """ Class impl
ementing a dialog to enter the data for a copy or rename operation. """ def __init__(self, source, parent=None, move=False): """ Constructor @param source name of the source file/directory (string) @param parent parent widget (QWidget) @param move flag indica...
import numpy as np import theano import theano.tensor as T import pickle import timeit import os.path import sys class MultiNomialLR(object): def __init__(self, in_dim, out_dim): self.W = theano.shared( np.zeros((out_dim, in_dim), dtype=np.float64), name="W", borrow=True...
osses) print( 'epoch %i, minibatch %i/%i, validation error %f %% (%f)' % ( epoch, minibatch_index + 1, n_train_batches, this_validation_los...
if this_validation_loss < best_validation_loss: #improve patience if loss improvement is good enough if this_validation_loss < best_validation_loss * \ improvement_threshold: patience = max(patience, iter * pati...
# type command prin
ts file contents from lib.utils import *
def _help(): usage = ''' Usage: cat (file) Print content of (file) Use '%' in front of global vars to use value as file name. ''' print(usage) def main(argv): if len(argv) < 1 or '-h' in argv: _help() return # The shell doesnt send the # command name in the arg list # so the...
####################################################################################################################### # Copyright (C) 2016 Regents of the University of California # # This is free software: you can redistribute it and/or modify it under the terms of the # GNU General Public License (GNU GPL) as publi...
######################### """GUI
Python code auto-generated from Qt Creator *.ui files by PyQt pyuic utility.""" # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'analysis_progress_window.ui' # # Created by: PyQt5 UI code generator 5.6 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtG...
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
pesClient() # Initialize request argument(s) request = dialogflowcx_v3.ListEntityTypesRequest( parent="parent_value", ) # Make the request page_result = client.list_entity_types(request=request) # Handle the response for response in page_result:
print(response) # [END dialogflow_v3_generated_EntityTypes_ListEntityTypes_sync]
self._readtab) else: self.resumption_complete() return False else: return True def resumption_complete(self): self.get_maximum_offset_possible() self._maximum_offset_calculated = True s...
f self.find_first_text_and_return_status(text) is False: self._main_instance.set_ui_sensitive(False) self.__load_next_f
ile_and_highlight_first_word(text) def find_text_prev(self, text): self._metadata = self._main_instance.get_current_state(False) if self.find_previous_text_and_return_status(text) is False: self._main_instance.set_ui_sensitive(False) self.__load_previous_file_and_highlight_...
free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FI...
self.__config__['max_speed'] print "max_speed=", max_speed if parm2 == max_speed: print "parm2 ok" else: print "parm2 with parm_change" parm_change.append('parm2') print "*****************************" #check
parm3 parm3 = self.read_parm("00.03") print "parm3=",parm3 acc_rate = self.__config__['acc_rate'] print "acc_rate=", acc_rate if parm3 == acc_rate: print "parm3 ok" else: print "parm3 with parm_change" parm_change.append('parm3') ...
# Copyright (c) 2016 PaddlePaddle 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 applic...
sum += 1 return sum, label def test_train(self): instances, max_label_value = self.check_reader( paddle.dataset.flowers.train()) self.assertEqua
l(instances, 6149) self.assertEqual(max_label_value, 102) def test_test(self): instances, max_label_value = self.check_reader( paddle.dataset.flowers.test()) self.assertEqual(instances, 1020) self.assertEqual(max_label_value, 102) def test_valid(self): insta...
#!/usr/bin/python import sys import lib.ssh_helper as ssh host = sys.argv[1] blade = sys.argv[2] pw = ssh.prompt_password(host) c
han, sess = ssh.get_channel(host, pw) # Eat the initial welcome text ssh.get_output(chan) ssh.run(chan, 'tcpcmdmode -t 3600 -T system:mm[0]') ssh.run(chan, 'env -T system:blade[' + blade + ']') ssh.run(chan, 'bootseq c
d usb hd0 nw') chan.close() sess.close()
from unittest import TestCase from melta.transactions.transactional import Transaction class TransactionTestClass(Transaction): def __init__(self): self.plant_type = 'Pointisera' self.plant_age = 3 self.plant_pot = 'plastic' self.combination = 'one\ntwo\nthree' class Transactiona...
plant_pot = clay self.test_plant.rollback() self.assertNotEqual(self.test_plant.plant_pot, clay) self.assertEqual(self.test_plant.plant_pot,'plastic') def test_multiline_string_transaction(self)
: another_combination = 'one\nnine\nfive' new_combination = 'one\nnine\nthree' self.test_plant.combination = new_combination self.test_plant.commit() self.assertEqual(self.test_plant.combination, new_combination) self.test_plant.start() self.test_plant.combinatio...
=True)), ('description', self.gf('django.db.models.fields.CharField')(max_length=512, blank=True)), ('slider_item', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['hero_slider.SliderItem'])), ('language', self.gf('django.db.models.fields.CharField')(max_length=2)), ...
t': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}...
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, ...
from SimpleCV import Image import time # Get the template and image goBoard = Image('go.png') black = Image('go-black.png') black.show() time.sleep(3) goBoard.show() time.sleep(3) # Find the matches and
draw them matc
hes = goBoard.findTemplate(black) matches.draw() # Show the board with matches print the number goBoard.show() print str(len(matches)) + " matches found." # Should output: 9 matches found. time.sleep(3)
# $Id: tns.py 23 2006-11-08 15:45:33Z dugsong $ # -*- coding: utf-8 -*- """Transparent Network Substrate.""" import dpkt class TNS(dpkt.Packet): __hdr__ = ( ('length', 'H', 0), ('pktsum', 'H', 0), ('type', 'B', 0), ('rsvd', 'B', 0), ('hdrsum', 'H', 0), ('msg', '0s'...
runcated packet try: t = TNS(s[:-10]) except dpkt.NeedData: pass if __name__ == '__main__': test_tn
s() print 'Tests Successful...'
#! /usr/bin/env python import utility_function as uf import sys import cv2 import numpy as np def read_file_list(file_name): # assume the first argument is the image name and the second one is the label name_list = list() label_list = list() with open(file_name, "r") as f: s = f.read() ...
file_name.txt label_file.txt") exit(1) res_file_name = sys.argv[1] label_file_name = sys.argv[2] res_name, res_list = read_file_list(res_file_name) label_name, label_list = read_file_list(label_file_name) diff_count = 0 for i in range(len(res_name)): if (res_name[i] != label_...
on(label_list, res_list, 12) con_mat = uf.cal_confusion_matrix(label_list, res_list, 12) np.save("ave_precision_v3.npy", ave_precision) np.save("con_mat_v3.npy", con_mat) print(uf.cal_ave_precision(label_list, res_list, 12)) print(uf.cal_confusion_matrix(label_list, res_list, 12))
# clean sequences after alignment, criteria based on sequences # make inline with canonical ordering (no extra gaps) import os, datetime, time, re from itertools import izip from Bio.Align import MultipleSeqAlignment from Bio.Seq import Seq from scipy import stats import numpy as np class virus_clean(object): """doc...
oup_seq = self.sequence_lookup[self.outgroup['strain']].seq return np.array([hamming_distance(x.seq, outgroup_seq) for x in self.viruses if x.strain]) def clean_distances(self): """Remove viruses that don't follow a loose clock """ times = self.times_from_outgroup(
) distances = self.distance_from_outgroup() slope, intercept, r_value, p_value, std_err = stats.linregress(times, distances) residuals = slope*times + intercept - distances r_iqd = stats.scoreatpercentile(residuals,75) - stats.scoreatpercentile(residuals,25) if self.verbose: print "\tslope: " + str(slope) ...
import unittest, os from mock import Mock, patch, call, sentinel from tests.ditest import DependencyInjectionTestBase class AddTests(DependencyInjectionTestBase): def setUp(self): super(AddTests, self).setUp() self.config.dryrun = False self.repo.byLocati
on.return_value = None self.query.
copiesOf.return_value = [] self.img = Mock() self.lastProvenance = None def locAt(loc, provenance): self.lastProvenance = provenance self.lastPath = loc return self.img self.fileFactory.locatedAt.side_effect = locAt patcher = patch('niprov.addi...
#!/usr/bin/env python #coding:utf-8 ## # @file argv-test.py # @brief # 最底层的命令行解析,其他模块应该都是对其的封装 # @author unlessbamboo # @version 1.0 # @date 2016-03-03 import sys def testSys(): """testSys""" for arg in sys.argv[1:]: print (arg) if __name__ == '__main__': test
Sys()
"""The AEMET OpenData component.""" import asyncio import logging from aemet_opendata.interface import AEMET from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME from homeassistant.core import HomeAssistant from .const import COMP...
itude =
config_entry.data[CONF_LONGITUDE] aemet = AEMET(api_key) weather_coordinator = WeatherUpdateCoordinator(hass, aemet, latitude, longitude) await weather_coordinator.async_refresh() hass.data[DOMAIN][config_entry.entry_id] = { ENTRY_NAME: name, ENTRY_WEATHER_COORDINATOR: weather_coordi...
# This file is part of FreePC. # # FreePC 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. # # FreePC is distributed in the hope that ...
l: # other_connection_today = True # diff = wua.connection_end - wua.connection_start
# total_connection += diff if time_end == None: return None diff_time = time - time_end #print "avant other_connection_today" #if other_connection_today: # max_hours = timedelta(hours=w.max_hours_connection) # if total_connection < max_hours: # return True timedelta_interval = timedelta(minutes=w.interval_t...
# Copyright 2016 Bridgewater Associates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
og_items = self.get_watcher_support_items( FlowLog.index, vpc_item.account) vpc_id = vpc_item.config.get("id") tag = "Flow Logs not enabled for VPC" severity = 5 flow_logs_enabled = False for flow_log in flow_log_items: if vpc_id == flow_log.config.get("...
flow_logs_enabled = True break if not flow_logs_enabled: self.add_issue(severity, tag, vpc_item)
(b'Z', b'Zombies only'), (b'A', b'All players')])), ], ), migrations.CreateModel( name='Game', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_len...
('notes', models.TextField(blank=True)), ('lat', mode
ls.FloatField(null=True, verbose_name=b'latitude', blank=True)), ('lng', models.FloatField(null=True, verbose_name=b'longitude', blank=True)), ('lft', models.PositiveIntegerField(editable=False, db_index=True)), ('rght', models.PositiveIntegerField(editable=False, db_inde...
class C: def fo
o(self): x = 1 y = 2
x = 1 def foo(): pass
#! /usr/bin/python3 # -*- coding:utf-8 -*- """ Define the "status" sub-command. """ from lib.transaction import * from lib.color import color import sys import yaml def status(conf, args): """Print staging transactions. """ if not conf: # The account book is not inited print("There is n...
stage] # Print those transactions print()
printTransactions(transactions) else: print("Nothing to commit.") sys.exit()
import os import sys import nose from subprocess import CalledProcessError, check_output as run from functools import partial GJSLINT_COMMAND = 'gjslint' GJSLINT_OPTIONS = ['--strict'] JS_BASE_FOLDER = os.path.join('skylines', 'public', 'js') JS_FILES = [ 'baro.js', 'fix-table.js', 'flight.js', 'gen...
filename) yield f def run_gjslint(filename): path = os.path.join(JS_BASE_FOLDER, filename) args = [GJSLINT_COMMAND] args.extend(GJSLINT_OPTIONS) args.append(path) tr
y: run(args) except CalledProcessError, e: print e.output raise AssertionError('gjslint has found errors.') except OSError: raise OSError('Failed to run gjslint. Please check that you have ' 'installed it properly.') if __name__ == "__main__": sys.argv...
dependencies = [ ('events', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('leaflets', '0001_initial'), ('schools', '0001_initial'), ('competitions', '0001_initial'), ] operations = [ migrations.CreateModel( name='OrgS...
ution', base.models.ContentTypeRestrictedFileField(storage=base.storage.OverwriteFileSystemStorage(base_url=b'/protected/', location=b'/home/tbabej/Projects/roots-env/roots/protected/'), upload_to=problems.models.get_solution_path_global, null=True, verbose_name='solution')), ('corrected_soluti
on', base.models.ContentTypeRestrictedFileField(storage=base.storage.OverwriteFileSystemStorage(base_url=b'/protected/', location=b'/home/tbabej/Projects/roots-env/roots/protected/'), upload_to=problems.models.get_corrected_so
#%% Libraries: Built-In from copy import deepcopy as copy import pandas as pd import numpy as np from datetime import datetime as dt from datetime import timedelta as td #% Libraries: Custom from Clusters.Data import DataCluster from Clusters.ClusterGroup import ClusterGroup #%% class NetworkController(object): def...
to_cluster.clusters[to_cluster.grouped_cluster_name(to_back_cluster)] from_clust.connect_add('output', to_clust, *args) to_clust.connect_add('input', from_clust, *args) def
connect_clusters_many(self, connect_items): for connect_item in connect_items: self.connect_clusters(*connect_item) def add_with_connects(self, cluster_name, cluster_class, connect_items, *args, **kwargs): def gen_new_connects(connect_items): connect_lis...
import speech_recognition as sr # Obtain audio from the microphone r = sr.Recognizer() with sr.Microphone() as source: print("Say something!") audio = r.listen(source, phrase_time_limit=5) # Recognize using wit.ai WIT_AI_KEY = "GP3LO2LIQ2Y4OSKOXZN6OAOONB55ZLN5" try: print("wit.ai think
s you said " + r.recognize_wit(audio, key=WIT_AI_KEY)) except sr.UnknownValueError: print("w
it.ai could not understand audio") except sr.RequestError as e: print("Could not request results from wit.ai servicel {0}".format(e))
#!/us
r/bin/env python import sys, os sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import messagebird ACCESS_KEY = 'test_gshuPaZoeEG6ovbc8M79w0QyM' try: # Create a MessageBird client with the specified ACCESS_KEY. client = messagebird.Client(ACCESS_KEY) # Send a new voice message. vmsg = client...
_message_create('31612345678', 'Hello World', { 'reference' : 'Foobar' }) # Print the object information. print('\nThe following information was returned as a VoiceMessage object:\n') print(' id : %s' % vmsg.id) print(' href : %s' % vmsg.href) print(' originator : %s' % ...
na_mode", # "cancel_pseudo_ascii_mode_key", "circle_typing_method", "circle_dict_method", "insert_space", "insert_alternate_space", "insert_half_space", "insert_wide_space", "backspace", "delete", "commit", "convert", "predict", "cancel", "cancel_all", "reconv...
"sha" : "しゃ", "shi" : "し", "shu" : "しゅ", "she" : "しぇ", "sho" : "しょ", "zya" : "じゃ", "zyi" : "じぃ", "zyu" : "じゅ", "zye" : "じぇ", "zyo" : "じょ", "ja" : "じゃ", "jya" : "じゃ", "ji" : "じ", "jyi" : "じぃ", "ju" : "じゅ", ...
, ##2 "ta" : "た", "ti" : "ち", "tu" : "つ", "tsu" : "つ", "te" : "て", "to" : "と", "da" : "だ", "di" : "ぢ", "du" : "づ", "de" : "で", "do" : "ど", "xtu" : "っ", "xtsu" : "っ", "ltu" : "っ", "ltsu" : "っ", ...
ength': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'contenttype...
dels.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'row': ('django.db.models.fields.CharField', [], {'max_length': '6'}) }, 'questionnaire.comment': { 'Meta': {'object_name': 'Comment'}, 'answer_group': ('django.db.models.fields.re...
, 'to': "orm['questionnaire.AnswerGroup']"}), 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified': ('django.db.models.fields.DateTimeFiel...
#!/usr/bin/env python3 import argparse import requests import time import datetime import random # import pymysql from connections import hostname, username, password, portnumber, database class MarketKuCoin(object): # Set variables for API String. domain = "https://api.kucoin.com" url = "" uri = "" ...
dbstr + "(ask,bid,lastsale,recorded_time) " \ # "VALUES(%s,%s,%s,FROM_UNIXTIME(%s))" % (ask, bid, last, tstamp)
# print (query) # cur.execute(query) # cur.close() # db.close()
identifier Parameters ---------- replacement_character: string, default '' The character to replace invalid characters with. allow_unicode: boolean, default False If True, then allow Python 3-style unicode identifiers. Examples -------- >>> get_valid_identifier('my-var') ...
ttr): try: return self[attr] except KeyError: return super(SchemaProperties,
self).__getattr__(attr) def __getitem__(self, attr): dct = self._properties[attr] if 'definitions' in self._schema and 'definitions' not in dct: dct = dict(definitions=self._schema['definitions'], **dct) return SchemaInfo(dct, self._rootschema) def __iter__(self): r...
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/wearables/pants/shared_pants_s14.iff" result.attribute_template_id =...
x_condition = 1000 #### END MODIFICATIONS #### ret
urn result
# Copyright 2019 Microsoft Corporation # # 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/LIC
ENSE-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 Li...
sts.tools import AgentTestCase from .test_default import osutil_get_dhcp_pid_should_return_a_list_of_pids class TestClearLinuxUtil(AgentTestCase): def setUp(self): AgentTestCase.setUp(self) def tearDown(self): AgentTestCase.tearDown(self) def test_get_dhcp_pid_should_return_a_list_of_pid...
import pytest import sys sys.path.append("../src/") import cryspy from cryspy.fromstr import fromstr as fs import numpy as np def test_Karussell(): metric = cryspy.geo.Cellparameters(1, 1, 1, 90, 90, 90).to_Metric() k = cryspy.utils.Karussell(metric, fs("d 1 0 0"), fs("d 0 1 0")) d1 = k.direction(0) a...
e-9 d2 = k.direction(np.pi / 4) assert float(metric.length(d2 - fs("d 0 1 0"))) < 1e-9 def test_fill(): atomset = cryspy.crystal.Atomset({cryspy.crystal.Atom("Fe1", "Fe", fs("p 1/2 1/2 1/2"))}) atomset = cryspy.utils.fill(atomset, [0.6, 0.6, 0.6]) assert len(atomset.menge) == 27 atomset = ...
yspy.crystal.Atomset({cryspy.crystal.Atom("Fe1", "Fe", fs("p 0 0 0"))}) atomset = cryspy.utils.fill(atomset, [0.1, 0.1, 0.1]) assert len(atomset.menge) == 8
from actstream.models import Action from django.test import TestCase from cyidentity.cyfullcontact.tests.util import create_sam
ple_contact_info class FullContactActivityStreamTestCase(TestCase): def test_contact_create(self): contact_info = create_sample_contact_info()
action = Action.objects.actor(contact_info).latest('timestamp') self.assertEqual(action.verb, 'FullContact information was created')
# coding:utf-8 """ Author : qbeenslee Created : 2014/12/12 """ import re # 客户端ID号 CLIENT_ID = "TR5kVmYeMEh9M" ''' 传输令牌格式 加密方式$迭代次数$盐$结果串 举个栗子: ====start==== md5$23$YUXQ_-2GfwhzVpt5IQWp$3ebb6e78bf7d0c1938578855982e2b1c ====end==== ''' MATCH_PWD = r"md5\$(\d\d)\$([a-zA-Z0-9_\-]{20})\$([a-f0-9]{32}...
'h': 480, 'thumb': 'n'} THUMB_SIZE_LARGE = {'w': 3000, 'h': 3000, 'thumb': 'l'} THUMB_SIZE_ORIGIN = {'w': 0, 'h': 0, 'thumb': 'r'} MAX_SHARE_DESCRIPTION_SIZE = 140 NOW_ANDROID_VERSION_CODE = 7 NOW_VERSION_DOWNLOAD_URL = "/static/download/nepenthes-beta0.9.3.apk" MAX_RAND_EMAIL_CODE = 99999 MIN_RAND_EMAIL_...
E_SIZE = 10
#!/usr/bin/python import argparse from board_manager import BoardManager from constants import * def main(): parser = argparse.ArgumentParser(description='Board client settings') parser.add_argument('-sp', '--PORT', help='server port', type=int, default=80, required=False) parser....
', required=False) parser.add_argument('-pt', '--TO', help='phone to', type=str, default='', required=False) parser.add_argument('-pf', '--FROM', help='phone from', type=str, default='', required=False) parser.add_argument('-tk', '--TWKEY', help='twilio key', ...
gs() bm = BoardManager(args) bm.activate() if __name__ == "__main__": main()
################################################################################ # 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...
or implied. # See the License for the specific language governing permissions and # limitations under the License. ################################################################################ import unittest from pyflink.dataset import ExecutionEnvironment from pyflink.testing.test_case_utils import PythonAPICom...
class ExecutionEnvironmentCompletenessTests(PythonAPICompletenessTestCase, unittest.TestCase): @classmethod def python_class(cls): return ExecutionEnvironment @classmethod def java_class(cls): return "org.apache.flink.api.java.ExecutionEnv...
#!/usr/bin/env python3 from pathlib import Path import pprint pp = pprint.PrettyPrinter() import logging log = logging.getLogger(__name__) def main(): p = Path('particles.txt') if p.exists() and p.is_file(): parse(str(p)) def parse(filepath): raw = '' try: with open(filepath) as f: ...
() if parts[0] == '*': category = ' '.join(parts[1:]) if category not in
data: data[category] = {} else: log.warn('Category "{}" already defined!'.format(category)) elif parts[0] == '**': if category: if parts[1] not in data[category]: particle = parts[1] data[category][pa...
import abc from sqlalchemy.orm import exc from watson.auth import crypto from watson.auth.providers import exceptions from watson.common import imports from watson.common.decorators import cached_property class Base(object): config = None session = None def __init__(self, config, session): self....
r_field ==
username).one() except exc.NoResultFound: return None def get_user_by_email_address(self, email_address): email_column = getattr( self.user_model, self.config['model']['email_address']) try: return self.user_query.filter(email_column == email_address).on...
_info) mock_enable = self._vmops._metricsutils.enable_vm_metrics_collection if enable_instance_metrics: mock_enable.assert_called_once_with(mock_instance.name) mock_set_qos_specs.assert_called_once_with(mock_instance) mock_requires_secure_boot.assert_called_once_with( ...
nstance = fake_instance.fake_instance_obj(self.context) root_device_info = {'type': constants.DISK, 'boot_index': 0, 'disk_bus': constants.CTRL_TYPE_IDE, 'path': 'fake_path', 'drive_addr': 0, ...
o) mock_attach_drive.assert_called_once_with( mock_instance.name, root_device_info['path'], root_device_info['drive_addr'], root_device_info['ctrl_disk_addr'], root_device_info['disk_bus'], root_device_info['type']) @mock.patch.object(vmops.VMOps, '_attach_drive') d...
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from broadcasts.models import BroadcastMessage from broadcasts.forms import BroadcastMessageForm class BroadcastAdmin(admin.ModelAdmin): """Admin class for the broadcast messages""" form = BroadcastMessageForm list_d...
title', 'user_target', 'show_frequency', 'start_time', 'end_time', 'is_published') list_filter = ('is_published', 'show_frequency', 'user_target') search_fields = ['message', 'title'] fieldsets = ( (None, { 'fields': ('title', 'message', 'message_type',) }), (_('M...
arget', 'url_target') }), (_("Message Display"), { 'description': _( "Messages will display only if they are published, " "it is between the start and end times, and the show " "frequency has not been exceeded."), 'fields': ('show_f...
self.digits2 += char return None else: self.state = 0 return None elif len(self.digits2) < 5: if char >= '0' and char <= '9': self.digits2 += char if len(s...
name) xmlDoc.documentElement.setAttributeNode(att) if value != None: att.nodeValue = value de
f PDFiD(file, allNames=False, extraData=False, disarm=False, force=False): """Example of XML output: <PDFiD ErrorOccured="False" ErrorMessage="" Filename="test.pdf" Header="%PDF-1.1" IsPDF="True" Version="0.0.4" Entropy="4.28"> <Keywords> <Keyword Count="7" HexcodeCount="0" Name=...
from math import isclose import numpy as np from pytest import fixture from hoomd.box import Box @fixture def box_dict(): return dict(Lx=1, Ly=2, Lz=3, xy=1, xz=2, yz=3) def test_base_constructor(box_dict): box = Box(**box_dict) for key in box_dict: assert getattr(box, key) == box_dict[key] @...
: assert isclose(base_box.volume, np.product(base_box.L)) for L in np.linspace(1, 10, 10): box = Box.cube(L) assert isclose(box.volume, L**3) box = Box(L, L + 1, L + 2) assert isclose(box.volume, L * (L + 1) * (L + 2)) def test_volume_setting(base
_box): aspect = get_aspect(base_box.L) for v in np.linspace(1, 100, 10): base_box.volume = v assert np.allclose(aspect, get_aspect(base_box.L)) assert isclose(base_box.volume, v) def test_periodic(base_box): assert all(base_box.periodic) @fixture def expected_matrix(box_dict): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import argparse from configparser import SafeConfigParser class Configurable(object): """ Configuration processing for the network """ def __i...
operty def save_dir(self): return self._config.get('OS', 'save_dir') argparser.add_argument('--save_dir') @property def word_file(self): return self._config.get('OS', 'word_file') argparser.add_argument('--word_file') @property def target_file(self): return se
lf._config.get('OS', 'target_file') argparser.add_argument('--target_file') @property def train_file(self): return self._config.get('OS', 'train_file') argparser.add_argument('--train_file') @property def valid_file(self): return self._config.get('OS', 'valid_file') argparser.add_argument('--valid...
import socket import threading bind_ip = "" bind_port = 60007 s
erver = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((bind_ip, bind_port)) server.listen(5) print("[*] Listening on %s:%d" % (bind_ip, bind_port)) def handle_client(client_socket): request = client_socket.recv(1024)
.decode() print("[*] Received: %s" % request) send_data = "ACK!" client_socket.send(send_data.encode()) print(client_socket.getpeername()) client_socket.close() while True: client, addr = server.accept() print("[*] Accepted connect from: %s:%d" % (addr[0], addr[1])) client_handler =...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import sys def get_color(color): if 'default'==color: return '\x1b[39;01m' elif 'black'==color: return '\x1b[30;01m' elif 'red'==color: r
eturn '\x1b[31;01m' elif 'green'=
=color: return '\x1b[32;01m' elif 'yellow'==color: return '\x1b[33;01m' elif 'blue'==color: return '\x1b[34;01m' elif 'magenta'==color: return '\x1b[35;01m' elif 'cyan'==color: return '\x1b[36;01m' return '\x1b[34;01m' def main(): if 4==len(sys.argv): ...
rt iteritems from flye.six.moves import range POLISH_BIN = "flye-modules" logger = logging.getLogger() class PolishException(Exception): pass def check_binaries(): if not which(POLISH_BIN): raise PolishException("polishing binary was not found. " "Did you run 'make'?...
"Separating alignment into bubbles") contigs_info = get_contigs_info(chunks_file) bubbles_file = os.path.join(work_dir, "bubbles_{0}.fasta".format(i + 1)) coverage_stats, mean_aln_error = \ make_bubbles(alignment_file, contigs_info, chunks_file, ...
("Alignment error rate: %f", mean_aln_error) consensus_out = os.path.join(work_dir, "consensus_{0}.fasta".format(i + 1)) polished_file = os.path.join(work_dir, "polished_{0}.fasta".format(i + 1)) if os.path.getsize(bubbles_file) == 0: logger.info("No reads were aligned during polishi...
"].isSame( s["n"]["in"][3] ) ) self.assertTrue( s["n"]["in"]["e1"].getInput(), s["a"]["sum"] ) self.assertTrue( s["n"]["in"]["e2"].getInput() is None ) self.assertTrue( s["n"]["in"]["e3"].getInput(), s["a"]["sum"] ) self.assertTrue( s["n"]["in"]["e4"].getInput() is None ) s2 = Gaffer.ScriptNode() s2.execu...
Gaffer.Plug.__init__( self, name, direction, flags ) def createCounterpart( self, name, direction ) : return PythonElement( name, direction, self.getFlags() ) n = Gaffer.Node() n["a"] = Gaffer.ArrayPlug( element = PythonElement
() ) self.assertEqual( len( n["a"] ), 1 ) self.assertTrue( isinstance( n["a"][0], PythonElement ) ) p = PythonElement() n["a"][0].setInput( p ) self.assertEqual( len( n["a"] ), 2 ) self.assertTrue( isinstance( n["a"][1], PythonElement ) ) def testTopLevelConnection( self ) : n = Gaffer.Node() n["...
import simplejson as json, os from sklearn.decomposition import PCA from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from kettle.utils import get_beers import numpy as np class BeerMLData(list): def __init__(self): self.proj = None self.arr = None self.beer_map...
self.beer_mapping = {} for beer in self: #beer = x['beer'] beer_id = beer['id'] self.beer_mapping[beer_id] = self.map_beer(beer) def get_beer_by_id(self,beer_id): beers = [beer for beer in self if beer['id'] == beer_id] return
beers[0] def map_beer(self,x): if isinstance(x,str): beer = self.get_beer_by_id(x) else: beer = x record = np.zeros(self.fs_dim) idx = 0 for key,dtype in self.important_keys: beer_vals = beer[key] fsk = self.feature_space_key...
oup7.id, filtered_group_ids) def test_greater_than_3(self): filtered_queryset = self.__filter_examiners(filter_value='gt-3') self.assertEqual(filtered_queryset.count(), 4) filtered_group_ids = [group.id for group in filtered_queryset] self.assertNotIn(self.testgroup0.id, filtered_gr...
ueryset] self.assertNotIn(self.testgroup0.id, filtered_group_ids) self.ass
ertNotIn(self.testgroup1.id, filtered_group_ids) self.assertNotIn(self.testgroup2.id, filtered_group_ids) self.assertNotIn(self.testgroup3.id, filtered_group_ids) self.assertNotIn(self.testgroup4.id, filtered_group_ids) self.assertNotIn(self.testgroup5.id, filtered_group_ids) sel...
''' http://jsfiddle.net/nvYZ8/1/ ''' from functionChecker import functionChecker functionChecke
r("schedulePrioritizer.
py", "getAllPossibleSchedules") "function name: getNonOverlappingRanges" "requires functions: containsOverlappingRanges, overlapsWithOthers(theArr,theIndex)" "is defined: True" "description: Return all ranges in the array that do not overlap with any of the other ranges." "function name: removeNonOverlappingRanges" "...
from django.template import TemplateDoesNotExist from django.test import ( Client, RequestFactory, SimpleTestCase, override_settings, ) from django.utils.translation import override from django.views.csrf import CSRF_FAILURE_TEMPLATE_NAME, csrf_failure @override_settings(ROOT_URLCONF='view_tests.urls') class Csrf...
Referer header is strictly checked for POST over HTTPS. Trigger the exception by sending an incorrect referer. """ response = s
elf.client.post('/', HTTP_X_FORWARDED_PROTO='https') self.assertContains(response, "You are seeing this message because this HTTPS " "site requires a &#39;Referer header&#39; to be " "sent by your Web browser, but none was sent....
#!/usr/bin/env python # Based on previous work by # Charles Menguy (see: http://stackoverflow.com/questions/10217067/implementing-a-full-python-unix-style-daemon-process) # and Sander Marechal (see: http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/) # Adapted by M.Hendrix [2015] (deprecated)...
tDate = commands.getoutput("date '+%F %H:%M:%S, %s'") res
ult = ', '.join(map(str, result)) lock(flock) with open(fdata, 'a') as f: f.write('{0}, {1}\n'.format(outDate, result) ) unlock(flock) def lock(fname): open(fname, 'a').close() def unlock(fname): if os.path.isfile(fname): os.remove(fname) def syslog_trace(trace): # Log a python stack trace to sys...
# encoding: utf-8 # Copyright 2011 Tree.io Limited # This file is part of Treeio. # License www.tree.io/license #!/usr/bin/python OBJECTS_NUM = 100 # setup environment import sys, os sys.path.append('../') os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' from django.core.management import setup_environ from treeio...
Object, User from treeio.projects.models import Project setup_environ(settings) user = User.objects.all()[0] for i in range(0, OBJECTS_NUM): project = Project(name='test'+unicode(i)) project.set_user(user) project.save() objects = Object
.filter_permitted(user, Project.objects) allowed = 0 for obj in objects: if user.has_permission(obj): allowed += 1 print len(list(objects)), ':', allowed
import unittest import numpy as np from chainer import testing from chai
nercv.utils import generate_random_bbox from chainercv.visualizations import vis_bbox try: import matplotlib # NOQA _available = True except ImportError: _avai
lable = False @testing.parameterize( *testing.product_dict([ { 'n_bbox': 3, 'label': (0, 1, 2), 'score': (0, 0.5, 1), 'label_names': ('c0', 'c1', 'c2')}, { 'n_bbox': 3, 'label': (0, 1, 2), 'score': None, 'label_names': ('c0', 'c1', 'c2')}, { ...
"""Kernel K-means""" # Author: Mathieu Blondel <mathieu@mblondel.org> # License: BSD 3 clause import logging import numpy as np from sklearn.base import BaseEstimator, ClusterMixin from sklearn.metrics.pairwise import pairwise_kernels from sklearn.utils import check_random_state logger = logging.getLogger(__name__)...
_get_kernel_approx(self, X, Y=None): n = Nystroem(kernel=self.kernel, n_components=self.nystroem, kernel_params=self.kernel_params).fit(X) z_transformed = n.transform(X) return np.dot(z_transformed, z_transformed.T) def _get_kernel(self, X, Y=None): if callable(self.kernel): ...
e: params = {"gamma": self.gamma, "degree": self.degree, "coef0": self.coef0} return pairwise_kernels(X, Y, metric=self.kernel, filter_params=True, **params) def fit(self, X, y=None, sample_weight=None): n_sampl...
import collections import io import itertools from ..mkExceptions import BadProQuestRecord, RecordsNotCompatible from ..mkRecord import ExtendedRecord from .tagProcessing.specialFunctions import proQuestSpecialTagToFunc from .tagProcessing.tagFunctions import proQuestTagToFunc class ProQuestRecord(ExtendedRecord): ...
tools.chain): #Already enumerated #itertools.chain is for the parser upstream to inse
rt stuff into the stream fieldDict = proQuestRecordParser(inRecord, recNum) elif isinstance(inRecord, io.IOBase): fieldDict = proQuestRecordParser(enumerate(inRecord), recNum) elif isinstance(inRecord, str): #Probaly a better way to do this but it ...
er(TestNavBase, cls).setup_class( config=settings(file_path="qacode/configs/"), skip_force=SKIP_NAVS) def setup_method(self, test_method, close=True): """Configure self.attribute""" super(TestNavBase, self).setup_method( test_method, config=settings(f...
element_wait( self.dd_menu_data.get("selector"))) self.bot.navigation.ele_click(
self.bot.navigation.find_element_wait( self.dd_menu_data_lists.get("selector"))) # end setup_login @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_navbase_instance(self): """Testcase: test_navbase_instance""" ASSERT.is_instance(self.bot.navigation, NavBase) ...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui_fiscal_icnfefetuarpagamento.ui' # # Created: Mon Nov 24 22:25:57 2014 # by: pyside-uic 0.2.15 running on PySide 1.2.2 # # WARNING! All changes made in this file will be lost! from PySide import QtCore, QtGui from pydaruma.pydaruma i...
StrValor = self.lineEditValor.text() StrInfo = self.lineEditInfo.text() tratarRetornoFiscal(iCNFEfetuarPagamento_ECF_Daruma(StrFormaPGTO,StrValor,StrInfo), self) def on_pushButtonCancelar_clicked(self): self.close() def setupUi(self, ui_FISC
AL_iCNFEfetuarPagamento): ui_FISCAL_iCNFEfetuarPagamento.setObjectName("ui_FISCAL_iCNFEfetuarPagamento") ui_FISCAL_iCNFEfetuarPagamento.resize(531, 123) self.verticalLayout = QtGui.QVBoxLayout(ui_FISCAL_iCNFEfetuarPagamento) self.verticalLayout.setObjectName("verticalLayout") sel...
zation) before `PollError` with non-empty ``waiting`` is raised. :returns: ``(cert, updated_authzrs)`` `tuple` where ``cert`` is the issued certificate (`.messages.CertificateResource`), and ``updated_authzrs`` is a `tuple` consisting of updated Authorization Res...
response, default=mintime), authzr)) else: exhausted.add(authzr) if exhausted or any(authzr.body.status == messages.STATUS_INVALID for authzr in six.itervalues(updated)): raise errors.PollError(exhausted, updated) ...
lf, uri): """Returns certificate from URI. :param str uri: URI of certificate :returns: tuple of the form (response, :class:`acme.jose.ComparableX509`) :rtype: tuple """ content_type = self.DER_CONTENT_TYPE # TODO: make it a param response = self.n...
f register_URL_echo(self, _object=None, _attributes={}, **_arguments): """register URL echo: Registers the \xd2echo\xd3 application. Each download from now on will be echoed to this application. Required argument: Application signature Keyword argument _attributes: AppleEvent attribute dictionar...
) _arguments['----'] = _object _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.get('errn', 0): raise aetools.Error, aetools.deco
deerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----'] _argmap_unregister_window_close = { 'for_window' : 'WIND', } def unregister_window_close(self, _object=None, _attributes={}, **_arguments): """unregister...
#!/usr/bin/python -u # # Application Monitoring (version 1.5) # Alejandro Calderon @ ARCOS.INF.UC3M.ES # GPL 3.0 # import math import time import psutil import threading import multiprocessing import subprocess import os import sys import getopt import json def print_record ( format, data ): try: ...
rocess with
pid '" + str(p_id) + "' has ended."
""" Tests for functionality in the utils module """ import platform import unittest import mock import queries from queries import utils class GetCurrentUserTests(unittest.TestCase): @mock.patch('pwd.getpwuid') def test_get_current_user(self, getpwuid): """get_current_user returns value from pwd.g...
lid(self): """invalid query argument should not be in kwargs""" self.assertNotIn('invaid', utils.uri_to_kwargs(self.URI)) def test_unix_socket_path_format_one(self): sock
et_path = 'postgresql://%2Fvar%2Flib%2Fpostgresql/dbname' result = utils.uri_to_kwargs(socket_path) self.assertEqual(result['host'], '/var/lib/postgresql') def test_unix_socket_path_format2(self): socket_path = 'postgresql:///postgres?host=/tmp/' result = utils.uri_to_kwargs(socket_...
from __future__ import print_functi
on from ed2d.cmdargs import CmdArgs debugEnabled = CmdArgs.add_arg('debug', bool, 'Enable debug output.') def d
ebug(*args): if debugEnabled: print(*args)
file = open('input.txt') instructions = [] for line in file.readlines(): instructions.append(line.replace(',', '').s
trip().split(' ')) regs = { 'a': 0, 'b': 0 } ptr = 0 while True: if ptr not in range(len(instructions)): break instr = instructions[ptr] inst, r = instr[0], instr[1] di = 1 if inst == 'inc': regs[r] += 1 elif inst == 'tpl': regs[r] *= 3 elif inst == '...
regs[r] //= 2 elif inst == 'jie': offset = instr[2] if regs[r] % 2 == 0: di = int(offset) elif inst == 'jio': offset = instr[2] if regs[r] == 1: di = int(offset) elif inst == 'jmp': di = int(r) ptr += di print regs
#!/usr/bin/python3 import random import copy import enum import jsonpickle import pickle import argparse from sharedlib import Attr, Card, Config import json class Die: def __init__(self, attack, defense, magic, mundane, numSides=12): self.attack = attack self.defense = defense self.magic = magic self.mundane...
ender defender = initialAttacker winner, distance = takeTurn(attacker, defender, distance) if winner != None: break if Attr.theroll in attacker.attrs or (Attr.rampage in attacker.attrs and is_rampage()): winner, distance = takeTurn(attacker, defender, distance) if winner != None: break if win...
if winner.name == initialAttacker.name: return Winner.attacker, i else: return Winner.defender, i if __name__ == '__main__': diceTypes = None with open("dice.json") as f: diceTypes = jsonpickle.decode(f.read()) parser = argparse.ArgumentParser(description='Fight two cards to the death') parser.add_argumen...
#!/usr/bin/env python import unittest from day04 import find_integer class Test(unittest.TestCase): cases = ( ('abcdef', 609043), ('pqrstuv', 1048970), ) def test_gets_integer(self): f
or (key, expected) in self.cases: result = find_integer(key, zeroes=5) self.assertEqual(result, expected, "Expected {key} to yield {expected}, but got {result}".\
format(**locals())) if __name__ == '__main__': unittest.main()
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Lic
ense. # You may obtain a copy of the License at # # http://w
ww.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 ...
# coding: utf-8 from smarthumb import SMARTHUMB from gluon.contrib.imageutils import RESIZE # Noticias db.noticias.titulo.requires = [ IS_NOT_EMPTY(error_message=T('Este campo não pode ficar vazio!')), IS_NOT_IN_DB(db, db.noticias.titulo, error_message=T('Título deve ser único.')), IS_LENG...
o grande!' 'Tamanho máximo permitido é 100kb')), IS_EMPTY_OR(RESIZE(200, 200)) ] db.membros.email.requires = IS_EMAIL(error_message=T("Entre um email válido")) # Eventos db.eventos.nome.requires = [ IS_NOT_EMPTY(error_message=T('Este campo não pode ficar vazio!'
)), IS_LENGTH(128, error_message=T('Tamanho máximo de 128 caracteres.')) ] db.eventos.endereco.requires = [ IS_NOT_EMPTY(error_message=T('Este campo não pode ficar vazio!')), IS_LENGTH(128, error_message=T('Tamanho máximo de 128 caracteres.')) ] db.eventos.descricao.requires = [ IS_NOT_EMPTY(error_messa...
in [0, 1]. Usually one uses the dynamic shape of the image or conv-layer tensor: boxlist = box_list_ops.to_normalized_coordinates(boxlist, tf.shape(images)[1], tf.shape(images)[2]), This function raises ...
height, width) def refine_boxes_multi_class(pool_boxes, num_classes, nms_iou_thresh, nms_max_detections, voting_iou_thresh
=0.5): """Refines a pool of boxes using non max suppression and box voting. Box refinement is done independently for each class. Args: pool_boxes: (BoxList) A collection of boxes to be refined. pool_boxes must have a rank 1 'scores' field and a rank 1 'classes' field. num_classes: (int scalar) Num...
"""Tests for Gosper's algorithm for hypergeometric summation. """ from sympy import binomial, factorial, gamma, Poly, S, simplify, sqrt, exp, log, Symbol from sympy.abc import a, b, j, k, m, n, r, x from sympy.concrete.gosper import gosper_normal, gosper_sum, gosper_term def test_gosper_normal(): assert gosper_n...
1/x**2) + factorial(m)**2/(x**2*factorial(m - x)*factorial(m + x)) g = gosper_sum(f2a, (n, 0, m)) assert g is not None and simplify(g - g2a) == 0
g = gosper_sum(f2b, (n, 0, m)) assert g is not None and simplify(g - g2b) == 0 g = gosper_sum(f2c, (n, 1, m)) assert g is not None and simplify(g - g2c) == 0 def test_gosper_nan(): a = Symbol('a', positive=True) b = Symbol('b', positive=True) n = Symbol('n', integer=True) m = Symbol('m'...
e, 50.0) self.assertEqual(product_cable_management_box.value_svl, 500.0, 'Wrong stock value') # I create a draft Purchase Order for second shipment for 30 kg at 80 euro purchase_order_2 = self.env['purchase.order'].create({ 'partner_id': res_partner_3.id, 'order_line': [...
(product_cable_management_box.qty_available, 19.5, 'Should still have 19.5 in stock') # We will temporarily change the currency rate on the sixth of June to have the same results all year NewUSD = self.env['res.currency'].create({ 'name': 'new_usd', 'symbol': '$²', '...
150$/kg purchase_order_usd = self.env['purchase.order'].create({ 'partner_id': res_partner_3.id, 'currency_id': NewUSD.id, 'order_line': [(0, 0, { 'name': 'FIFO Ice Cream', 'product_id': product_cable_management_box.id, ...
wintypes.DWORD, wintypes.LPCVOID, wintypes.DWORD, wintypes.DWORD, wintypes.LPWSTR, wintypes.DWORD, wintypes.LPVOID ] kernel32.FormatMessageW.restype = wintypes.DWORD kernel32.LocalFree.argtypes = [wintypes.HLOCAL] kernel32.LocalFree.restype = wintypes.HLOCAL kernel32.SetConsoleTextAttribute.argt...
retval = kernel32.GetConsoleScreenBufferInfo( handle, ctypes.byref(csbi), ) win_handle = None if retval == 0: errno = ctypes.get_last_error() if errno == ERROR_INVALID_HANDLE: # Return a special non-console handle win_handle = WinHandle.get_nonconso...
else: win_handle = WinHandle(handle) # Set defaults color values # TODO: Do these need to be reread when colors are redefined? win_handle.default_fg = csbi.wAttributes & 0xf win_handle.default_bg = (csbi.wAttributes >> 4) & 0xf # Set the color for the handle win_handl...
import asyncio import uvloop from aioactor.transports import NatsTransport from aioactor.service import Service from aioactor.broker import ServiceBroker asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) # TODO ADD possible actions list! # TODO ADD abstractions to Message Handler! # MessageHandler must be able t...
services = [UsersService] register_services(broker, services) print(broke
r.available_services()) await broker.start() if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.run_forever() loop.close()
#!/usr/bin/env python3 # Copyright (c) 2016-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test Hierarchical Deterministic wallet function.""" import os imp
ort shutil from test_framework.test_framework import BitcoinTestFramework from test_framework.util import ( assert_equal, connect_nodes, assert_raises_rpc_er
ror ) from test_framework.qtumconfig import COINBASE_MATURITY from test_framework.qtum import generatesynchronized class WalletHDTest(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 2 self.extra_args = [[], ['-keypool=0']] self.suppor...
factories.BookFactory.create() self.contact = factories.ContactFactory.create( name="Philip James", book=self.book, ) def test_contact_name(self): """String repr of contact s
hould be name.""" self.assertEqual(self.contact.name, str(self.contact)) def test_contact_url(self): expected_url = reverse('contac
ts-view', kwargs={ 'pk': self.contact.id, 'book': self.book.id, }) self.assertEqual(self.contact.get_absolute_url(), expected_url) def test_contact_last_contacted(self): log = factories.LogFactory.create(contact=self.contact) self.contact.update_last_contact_...
"climate.bla" entity_id2 = "climate.blu" hass.states.async_set(entity_id, STATE_ON) hass.states.async_set(entity_id, STATE_OFF) hass.bus.async_fire(EVENT_HOMEASSISTANT_START) hass.states.async_set(entity_id2, STATE_ON) hass.states.async_set(entity_id2, STATE_OFF) hass.states.async_remove...
STATE_ON, {ATTR_FRIENDLY_NAME: "Alarm Automation"}, context=context, ) entity_id_test = "alarm_control_panel.area_001" hass.states.async_set(entity_id_test, STATE_OFF, context=context) await hass.async_block_till_done() hass.states.async_set(entity_id_test, STATE_ON, context=c...
await hass.async_block_till_done() entity_id_second = "alarm_control_panel.area_002" hass.states.async_set(entity_id_second, STATE_OFF, context=context) await hass.async_block_till_done() hass.states.async_set(entity_id_second, STATE_ON, context=context) await hass.async_block_till_done() hass....