prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
import argparse import sys import traceback as tb from datetime import datetime from cfme.utils.path import log_path from cfme.utils.providers import list_provider_keys, get_mgmt def parse_cmd_line(): parser = argparse.ArgumentParser(argument_default=None) parser.add_argument('--nic-template', ...
Removing Nics with the name \'{}\':\n".format(nic_template)) report.write("\n".join(str(k) for k in nic_list)) report.write("\n") provider_mgmt.remove_nics_by_search(nic_template) else: report.write("No \'{}\' NICs were foun...
pip(pip_template) if pip_list: report.write("Removing Public IPs with the name \'{}\':\n". format(pip_template)) report.write("\n".join(str(k) for k in pip_list)) report.write("\n") provider_...
# Generated by
Django 3.2.4 on 2021-07-05 13:56 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("bibliography", "0002_move_json_data"), ] operations = [ migrations.AlterModelOptions( name="entry", options={"verbose_name_plural": "Entrie...
), ]
#Parsing program to sort through Investopedia import urllib2 import re #This is the code to parse the List of Terms def get_glossary(res_num): html_lowered = res_num.lower(); begin = html_lowered.find('<!-- .alphabet -->') end = html_lowered.find('<!-- .idx-1 -->') if begin == -1 or end == -1: return None else:...
('<title>'):end].strip() #We start with the numbers section of Investopedia url = "http://www.investopedia.com/terms/1/" res_num="" for line in urllib2.urlopen(url): res_num+=line title_num = get_title(res_num) glossary_num = get_glossary(res_num) ##Find all hyperlinks in list then eliminate duplicates glossary_pa...
' Definition | Investopedia' short_tail = ' | Investopedia' print title_num gp_list = [] for x in glossary_parsed_num: gpn = parent_url + x res_num="" for line in urllib2.urlopen(gpn): res_num+=line gpn_title = get_title(res_num) gpn_penult = gpn_title.replace(tail,'') gpn_final = gpn_penult.replace(short_tail...
# -*- coding: utf-8 -*- from django.utils.encoding import smart_str class Menu(object): namespace = None def __init__(self, renderer): self.renderer = renderer if not self.namespace: self.namespace = self.__class__.__name__ def get_nodes(self, request): """ s...
espace, root_id, post_cut, breadcrumb): pass class NavigationNode(object): def __init__(self, title, url, id, parent_id=None, parent_namespace=None, at
tr=None, visible=True): self.children = [] # do not touch self.parent = None # do not touch, code depends on this self.namespace = None # TODO: Assert why we need this and above self.title = title self.url = url self.id = id self.parent_id = parent_id s...
# # Copyright (c) 2014 Piston Cloud Computing, 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 # # ...
implied. See the # License for the specific language governing permissions and limitations # under the License. # import unittest class TestSequenceFunctions(unittest.TestCase): def setUp(self): pass def test_nothing(self): # make sure the shuffled sequence does not lose any elements ...
'__main__': unittest.main()
""" This contains all the constants needed
for the daemons to run """ LOGGING_CONSTANTS = { 'LOGFILE' : 'summer.log', 'MAX_LOG_SIZE' : 1048576, # 1 MEG 'BACKUP_COUNT' : 5 } def getLoggingConstants(constant): """ Returns various constants needing by the logging module """ return LOGGING_CONSTANTS.get(constant, False)
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
clone/archive/1.5.1.tar.gz" giturl = "https://github.com/stfc/PSy
clone.git" version('1.5.1', git=giturl, commit='eba7a097175b02f75dec70616cf267b7b3170d78') version('develop', git=giturl, branch='master') depends_on('py-setuptools', type='build') depends_on('py-pyparsing', type=('build', 'run')) # Test cases fail without compatible versions of py-fp...
import praw import requests from env import env from twitch import twitch class reddit: def __init__(self): self.r = praw.R
eddit(user_agent='Heroes of the Storm Sidebar by /u/Hermes13') self.env = env() self.access_information = None def setup(self): # self.r.set_oauth_app_info( client_id=self.env.redditClientID, # client_secret=self.env.redditSecretID, # redirect_uri=self.env.redditRedirectURI) # url = self...
ad', True) # import webbrowser # webbrowser.open(url) pass def connect(self): self.r.set_oauth_app_info( client_id=self.env.redditClientID, client_secret=self.env.redditSecretID, redirect_uri=self.env.redditRedirectURI) # self.access_information = self.r.get_access_information(sel...
# -*- coding: utf-8 -*- """ Created on Mon Jun 22 15:32:58 2015 @author: hanbre """ from __future__ import print_function import sys import numpy as np import pandas as pd import xray import datetime import netCDF4 from mpl_toolkits.basemap import Basemap import matplotlib from matplotlib.pylab import * import matplo...
if typ == 'm': print('here') mvar1 = l[5]; mvar2 = l[6] if size(v.dims)==4: mvar
s = [mvar1,mvar2] else: mvars = [mvar1] vm=meaner(v,mvars) savestring = '{0}{1}{2}{3}{4}{5}{6}.png'.format(id_in,typ,var,xvar,yvar,mvar1,mvar2) print(savestring) elif typ == 'p': print('there') ...
_epoch - the total number of epochs for training - keep_prob - the probability of keeping weights in the dropout layer - lr_decay - the decay of the learning rate for each epoch after "max_epoch" - batch_size - the batch size The data required for this example is in the data/ dir of the PTB dataset from Tomas Mikolov'...
fig() eval_config.batch_size = 1 eval_config.num_steps = 1 with tf.Graph().as_default(), tf.Session() as session: initializer = tf.random_uniform_initializer(-config.init_scale, conf
ig.init_scale) with tf.variable_scope("model", reuse=None, initializer=initializer): m = PTBModel(is_training=True, config=config) with tf.variable_scope("model", reuse=True, initializer=initializer): mvalid = PTBModel(is_training=False, config=config) mtest = PTBModel(is_training=False, confi...
import logging import logging.config import sys import threading import os from amberclient.collision_avoidance.collision_avoidance_proxy import CollisionAvoidanceProxy from amberclient.common.amber_client import AmberClient from amberclient.location.location import LocationProxy from amberclient.roboclaw.roboclaw imp...
visited_targets_and_location() targets = response_message.Extensions[drive_to_point_pb2.targets] targets.longitudes.extend(map(lambda target: target[0], visited_targets)) targets.latitudes.extend(map(lambda target: target[1], visited_targets)) targets.radiuses.extend(map(lambda target: ...
n.timeStamp = current_location response_message.Extensions[drive_to_point_pb2.getVisitedTargets] = True return response_header, response_message @MessageHandler.handle_and_response def __handle_get_configuration(self, received_header, received_message, response_header, response_message): ...
"""Models for Zeroconf.""" import asyncio from typing import Any from zeroconf import DNSPointer, DNSRecord, ServiceBrowser, Zeroconf from zeroconf.asyncio import AsyncZeroconf class HaZeroconf(Zeroconf): """Zeroconf that cannot be closed.""" def close(self) -> None: """Fake method to avoid integra...
"""Pre-Filter update_record to DNSPointers for the configured type.""" # # Each ServerBrowser currently runs in its own thread which # processes every A or AAAA record update per instance. # # As the list of zeroconf names we watch for grows, each additional # Service...
e-filter here and only process # DNSPointers for the configured record name (type) # if record.name not in self.types or not isinstance(record, DNSPointer): return super().update_record(zc, now, record)
issues=[ dict(name='Habit',number=5,season='Winter 2012', description='commit to a change, experience it, and rec
ord'), dict(name='Interview', number=4, season='Autumn 2011', description="this is your opportunity to inhabit another's mind"), dict(name= 'Digital Presence', number= 3, season= 'Summer 2011', description='what does your digital self look like?'), dict(name= 'Adventure', number=2, season= '...
rd to leaving?') ] siteroot='/Users/adam/open review quarterly/source/' infodir='/Users/adam/open review quarterly/info' skip_issues_before=5 illustration_tag='=== Illustration ===' illustration_tag_sized="=== Illustration width: 50% ==="
"""Spyse OODA behaviour module""" import time # http://www.mindsim.com/MindSim/Corporate/OODA.html # http://www.d-n-i.net/second_level/boyd_military.htm # http://www.
belisarius.com/modern_business_s
trategy/boyd/essence/eowl_frameset.htm # http://www.valuebasedmanagement.net/methods_boyd_ooda_loop.html # http://www.fastcompany.com/magazine/59/pilot.html # # The OODA loop (Observe, Orient, Decide, and Act) is an # information strategy concept for information warfare # developed by Colonel John Boyd (1927-1997...
# -*- coding: utf-8 -*- from odoo import fields, models class CustomSurvey(models.Model):
_inherit = 'survey.survey' auth_required = fields.Boolean('Login required', help="Users with a public link will be requested to login before taking part to the survey", oldname="authenticate", default=True) users_can_go_back = fields.Boolean('Users can go back', help="If checked, users can go...
k to previous pages.", default=True)
# containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os import sphinx_bootstrap_theme # If extensions (or modules to document with autodo...
for La
TeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into La...
import unittest class ATest(unittest.TestCase): def setUp(self): print("setup") pass def test_a(self): self.assertTrue(True)
def tearDown(self): print("tear down") if __name__ == "__main__": print("masher_test.py")
unittest.main()
# Copyright (c) 2010, 2011 Timothy Lovorn # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation
files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: #...
right notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEM...
oader self.target_accounts = [ a for a in self.document.accounts if a.is_balance_sheet_account()] self.target_accounts.sort(key=lambda a: a.name.lower()) accounts = [] for account in self.loader.accounts: if account.is_balance_sheet_account(): entr...
e tests fail. to investigate. self._refresh_target_selection() self.view.update_selected_pane() self._refresh_swap_list_items() self.import_table.refresh() # --- Public def can_perform_swap(self): index = self.swap_type_list.selected_index
if index == SwapType.DayMonth: return self._can_swap_date_fields(DAY, MONTH) elif index == SwapType.MonthYear: return self._can_swap_date_fields(MONTH, YEAR) elif index == SwapType.DayYear: return self._can_swap_date_fields(DAY, YEAR) else: return ...
from .base import configure_app, create_app import re find_urls = re.compile('http[s]?://(?:[a-zA
-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+') class MailTemplatesAuthControllerTests(object): def setup(self): self.app = create_app(self.app_config, True) class TestMailTemplatesAuthControllerSQLA(MailTemplatesAuthControllerTests): @classmethod def setupClass(cls): cls.ap...
= configure_app('ming')
** - _vals_ should be sorted! """ nVals = len(cuts)+1 varTable = numpy.zeros((nVals,nPossibleRes),'i') idx = 0 for i in range(nVals-1): cut = cuts[i] while idx < starts[cut]: varTable[i,results[idx]] += 1 idx += 1 while idx < len(vals): varTable[-1,results[idx]] += 1 ...
,1), (2.3,0)] varValues = list(map(lambda x:x[0],d)) resCodes = list(map(lambda x:x[1],d)) nPossibleRes = 2 res = FindVarMu
ltQuantBounds(varValues,2,resCodes,nPossibleRes) print('RES:',res) target = ([1.3, 2.05],.34707 ) else: d = [(1.,0), (1.1,0), (1.2,0), (1.4,1), (1.4,0), (1.6,1), (2.,1), (2.1,0), (2.1,0), (2.1,0), (2.2,1), (...
import errno import signal import os import socket import time SERVER_ADDRESS = (HOST, PORT) = '', 8888 REQUEST_QUEUE_SIZE = 1024 def grim_
reaper(signum, frame): while True: try: pid, status = os.waitpid(
-1, os.WNOHANG, ) except OSError: return if pid == 0: return def handle_request(client_connection): request = client_connection.recv(1024) print 'Child PID: {pid}. Parent PID: {ppid}'.format(pid=os.getpid(), ppid=os.getppid()) print requ...
#!/usr/bin/env python #::::::::::::::::::::::::::::::::::::::::::::::::::::: #Author: Damiano Barboni <damianobarboni@gmail.com> #Version: 0.1 #Description: Script used to test bandsharing.py #Changelog: Wed Jun 11 12:07:33 CEST 2014 # First test version # #::::::::...
import sys import shutil import unittest current_path = os.path.realpath( __file__ ).split( os.path.basename(__fi
le__) )[0] bandsharing_path = os.path.abspath(os.path.join( current_path, os.pardir)) sys.path.insert(1, bandsharing_path) class TestBandSharing( unittest.TestCase ): def setUp(self): pass def test_bs( self ): pass def test_csv( self ): pass def...
import scrapy import re from research.items import ResearchItem import sys reload(sys) sys.setdefa
ultencoding('utf-8') class CaltechSpider(scrapy.Spider): name = "WISC" allowed_domains = ["cs.wisc.edu"] start_urls = ["https://www.cs.wisc.edu/research/groups"] def parse(self, response): item = ResearchItem() for sel in response.xpath('//table[@class="views-table cols-2"]'): item['groupname'] = sel.xpath...
ct() print str(tmpname) item['proflist'].append(tmpname) yield item
#!/usr/bin/python # -*- coding: utf-8 -*- from flask import Flask, jsonify, request app = Flask(__name__) from charge.chargeManager import ChargeManager from data.dataProvider import DataProvider @app.route('/') def hello_world(): return jsonify(testPreMa(['棉花'],20)) @app.route('/result') def get_result(): na...
----%s--%d周期-------------------' % (name, period) dp = DataProvider(name=name) p_list = dp.getData(['date', 'close']) cm = ChargeMan
ager(p_list, period, nodeStat=False) cm.startCharge('preMa') return cm.resultJson() if __name__ == '__main__': app.run(host='localhost')
return obj def get_context_data(self, **kwargs): context = super(ProjectDetail, self).get_context_data(*
*kwargs) context['user_project_rating'] = \ get_object_or_None(ProjectRating, project=self.kwargs['pk'], user=self.request.user) \ if self.request.user.is_authenticated() else None context['user_project_role'] = \ ...
archProject(ListView): """ Display project search. If an user input a project's title, it shows the project. Else if, it shows No Results """ model = Project context_object_name = 'projects' template_name = 'projects/list.html' def get_queryset(self): filter = self.kwargs['title...
import numpy as np from scipy import sparse import statistics def metrics(data_file): output_str = '' dsms = [] # the first thing we do is load the csv file (file #,from,to) # into a DSM; we do this by converting the triples to a sparse matrix # dsm is the first-order DSM of dependencies dsm_initial = loa...
tr + str(vfo_median) + ',' output_str = output_str + str(vfi_median) + ',' output_str = output_str + str(fo_median) + ',' output_str = output_str + st
r(fi_median) return output_str def raiseAllPowers(initial_matrix, max_paths): initial_matrix = sparse.csr_matrix(initial_matrix) initial_matrix.data.fill(1) done = 0 current_path_length = 0 matrices = [] if max_paths == -1: max_paths = 1000 matrices.append(initial_matrix) while done == 0 an...
import os DEBUG = True SITE_ID = 1 APP_ROOT = os.path.a
bspath(os.path.join(os.path.dirname(__file__), '')) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } STATIC_URL = '/static/' # STATIC_ROOT = os.path.join(APP_ROOT, '../app_static') STATICFILES_DIRS = ( os.path.join(APP_ROOT, 'static'), ) INSTAL...
= [ 'django.contrib.admin', 'django.contrib.admindocs', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.staticfiles', 'django.contrib.sitemaps', 'django.contrib.sites', 'bower', 'bower.tests.test_ap...
""" Python script to create a new article in a given section id. """ import os import sys from zdesk import Zendesk from scripts import file_constants from colorama import init from colorama import Fore init() def _create_shell(section_id): # Get subdomain. try: subdomain = os.environ["ZENDESK_SU...
'article']['id'] _empty_article(str(article_id)) def _empty_article(article_id): article = "posts/" + article_id + "/index.html" tit
le = "posts/" + article_id + "/title.html" if article_id.isdigit() and not os.path.isfile(article): # Makes the folder for the article and pictures to be placed in. os.makedirs('posts/' + article_id) # Create the article and title shell. open(article, 'a').close() open(titl...
import sys import matplotlib.pyplot as plt import numpy as np import sklearn.gaussian_process import sklearn.kernel_approximation import splitter from appx_gaussian_processes import appx_gp TRAINING_NUM
= 1500 TESTING_NUM = 50000 ALPHA = .003 LENGTH_SCALE = 1 GAMMA = .5 / (LENGTH_SCALE ** 2) COMPONENTS = 100 def interval_in_box_from_line(box, line): x_min, x_max, y_min, y_max = box m, b = line x_min_y
= m * x_min + b x_max_y = m * x_max + b y_min_x = (y_min - b) / m y_max_x = (y_max - b) / m endpoints = set() if y_min <= x_min_y <= y_max: endpoints.add((x_min, x_min_y)) if y_min <= x_max_y <= y_max: endpoints.add((x_max, x_max_y)) if x_min <= y_min_x <= x_max: end...
raise_not_implemented def teardown(): for attr, value in _widget_attrs.items(): setattr(Widget, attr, value) def f(**kwargs): pass def clear_display(): global displayed displayed = [] def record_display(*args): displayed.extend(args) #---------------------------------------------------...
x]) nt.assert_equal(len(c.children), 2) d = dict( cls=widgets.FloatSliderWidget, min=min, max=max,
step=.1, readout=True, ) check_widgets(c, tup=d, lis=d) def test_list_tuple_3_float(): with nt.assert_raises(ValueError): c = interactive(f, tup=(1,2,0.0)) with nt.assert_raises(ValueError): c = interactive(f, tup=(-1,-2,1.)) with nt.assert_raises(ValueError): ...
: after 1/2 num train steps, we start halving the learning rate for 5 times before finishing.\ luong10: after 1/2 num train steps, we start halving the learning rate for 10 times before finishing.\ """) parser.add_argument( "--num_train_steps", type=int, default=100000, help="...
help="Forget bias for BasicLSTMCell.") parser.add_argument("--dropout", type=float, default=0.2, help="Dropout rate (not keep_prob)") parser.add_argument("--max_gradient_norm", type=float, default=5.0, help="
Clip gradients to this norm.") parser.add_argument("--batch_size", type=int, default=128, help="Batch size.") parser.add_argument("--steps_per_stats", type=int, default=5, help=("How many training steps to do per stats logging." "Save checkpoint every 10x steps_per...
# -*- coding: utf-8 -*- # Copyright(C) 2010 Romain Bignon # # 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, version 3 of the License. # # This program is distributed in the hope that it will b...
s if content.content != data: content.content = data else: contents.remove(content) if len(contents) == 0: print 'No changes. Abort.' return print 'Contents changed:\n%s' % ('\n'.join([' * %s' % content.id for content in c...
return errors = CallErrors([]) for content in contents: path = [path for path, c in paths.iteritems() if c == content][0] sys.stdout.write('Pushing %s...' % content.id) sys.stdout.flush() try: self.do('push_content', content, messag...
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from s
outh.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): pass def backwards(sel
f, orm): pass models = { } complete_apps = ['quest']
import os from django.conf.urls import url, i
nclude urlpatterns = [ url(r'^misc/', include('misc.urls')), url(r'^qualification/', include('qualification.urls')), ] if os.environ.get('DJANGO_SETTINGS_MODULE') == 'etrack.settings.dev': import debug_toolbar urlpatterns += [ url(r'^__debug__/', include(
debug_toolbar.urls)), ]
# run
with https://codepen.io/sjdv1982/pen/MzNvJv # copy-paste seamless-client.js from seamless.highlevel import Context ctx = Context() ctx.cell1 = "test!" ctx.cell1.share() ctx.translate() ctx.compute() from seamless import shareserver print(shareserver.namespaces["ctx"].shares) print(shareserver.namespaces["ctx"].shares...
erver.namespaces["ctx"].shares) print(shareserver.namespaces["ctx"].shares["cell1"].bound) print(shareserver.namespaces["ctx"].shares["cell1"].bound.cell)
''' forms, mostly used for simpl
e tastypie validation ''' from django.contrib.gis import forms class MeetingForm(forms.Form): ''' form for meetings ''' day_of_week = forms.IntegerField(min_value=1, max_value=7) start_time = forms.TimeField() end_time = forms.TimeField() name = forms.CharField(max_length=100) description = fo...
ngth=300)
pyright (c) 2015, imageio contributors # imageio is distributed under the terms of the (new) BSD License. """ .. note:: imageio is under construction, some details with regard to the Reader and Writer classes may change. These are the main classes of imageio. They expose an interface for advanced users an...
t line needs special attention. return '%s - %s\n\n %s\n' % (self.name, self.description, self.__doc__.strip()) @property def name(self): """ The name of this format. """ return self._name @property def description(sel...
): """ A list of file extensions supported by this plugin. These are all lowercase without a leading dot. """ return self._extensions @property def modes(self): """ A string specifying the modes that this format can handle. """ return self._modes ...
"""Serialization of geometries for use in pyIEM.plot mapping We use a pickled protocol=2, which is compat binary. """ from pandas import read_sql from pyiem.util import
get_dbconnstr PATH = "../src/pyiem/data/ramps/" # Be annoying print("Be sure to run this against Mesonet database and not laptop!") def do(ramp): """states.""" df = read_sql( "SELECT l.coloridx, l.value, l.r,
l.g, l.b from iemrasters_lookup l " "JOIN iemrasters r ON (l.iemraster_id = r.id) WHERE r.name = %s and " "value is not null " "ORDER by coloridx ASC", get_dbconnstr("mesosite"), params=(ramp,), index_col="coloridx", ) df.to_csv(f"{PATH}{ramp}.txt") def main(): ...
"""Tests for the RunTaskCommand class""" from cumulusci.cli.runtime import CliRuntime from cumulusci.cli.cci import RunTaskCommand import click import pytest from unittest.mock import Mock, patch from cumulusci.cli import cci from cumulusci.core.exceptions import CumulusCIUsageError from cumulusci.cli.tests.utils imp...
s(): new_options = {"debug-before": None} old_options = (("color", "green"),) opts = RunTaskCommand()._collect_task_options( new_options, old_options, "dummy-task", color_opts["options"] ) assert opts == {"color": "green"} def test_collect_task_options__duplicate(): new_options = {"co...
geError): RunTaskCommand()._collect_task_options( new_options, old_options, "dummy-task", color_opts["options"] ) def test_collect_task_options__not_in_task(): new_options = {} old_options = (("color", "green"),) with pytest.raises(CumulusCIUsageError): RunTaskCommand(...
import base64 import httplib import json import os import re import ssl import urllib from urlparse import urlunsplit from exceptions import CloudPassageAuthentication class HaloSession(object): """All Halo API session management happens in this object. Args: key(str): Halo API key secret(str...
str): Hostname for Halo API. Defaults to ``api.cloudpassage.com`` cert_file(str): Full path to CA file. integration_string(str): This identifies a specific integration to the Halo API. """ def __init__(self, halo_key, halo_secret, **kwargs): self.key = halo_key ...
k_version() self.sdk_version_string = "Halo-Python-SDK-slim/%s" % self.sdk_version self.integration_string = '' self.cert_file = None if "api_host" in kwargs: self.api_host = kwargs["api_host"] if "cert_file" in kwargs: self.cert_file = kwargs["cert_file"]...
# This module is for compatibility only. All functions are defined elsewhere. __all__ = ['rand', 'tril', 'trapz', 'hanning', 'rot90', 'triu', 'diff', 'angle', 'roots', 'ptp', 'kaiser', 'randn', 'cumprod', 'diag', 'msort', 'LinearAlgebra', 'RandomArray', 'prod', 'std', 'hamming', 'flipud', ...
ode=None, dtype=None): """ eye returns a N-by-M 2-d array where the k-th diagonal is all ones, and everything else is zeros. """ dtype = convtypecode
(typecode, dtype) if M is None: M = N m = np.equal(np.subtract.outer(np.arange(N), np.arange(M)),-k) if m.dtype != dtype: return m.astype(dtype) def tri(N, M=None, k=0, typecode=None, dtype=None): """ returns a N-by-M array where all the diagonals starting from lower left corner...
#TSTOP # #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. # #This program is distributed in the hope that it will be useful, ...
l0 prev_line = line label_set = set([d[self.config.label_index] for d in full_data]) if self.config.window_size == -1 : self.config.window_size = self.config.segment_size self.segments = [] for segment_start in range(0, len(full_data) - self.config.segment_size +...
# if the data_index has more than one entry, interleave the results. # e.g. if data_index is [1,2] it's [(x_0, label), (y_0, label), (x_1, label), (y_1, label)...] for window_start in range(segment_start, segment_end - self.config.window_size + 1, self.config.window_stride): ...
from django.conf.urls.defaults import * from dj
ango.contrib import admin from django.conf import settings admin.autodiscover() urlpatterns = patterns('', (r'^kipa/', include('tupa.urls')), (r'^admin/', include(admin.site.urls)), ) if settings.DEBUG : urlpatterns += patterns('', (r'^kipamedia/(?P<path>.*)$', 'django.views....
T}),) handler500 = 'tupa.views.raportti_500'
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from __future__ import unicode_literals """ This package provi
des the modules to perfo
rm FEFF IO. FEFF: http://feffproject.org/feffproject-feff.html """ from .inputs import * from .outputs import *
from django.contrib import admin from django.core.urlresolvers import NoReverseMatch from . import models class WPSiteAdmin(admin.ModelAdmin): list_display = ('name', 'url', 'hook') readonly_fields = ('name', 'description') def save_model(self, request, obj, form, change): # TODO do this sync as...
in) class WPLogAdmin(admin.ModelAdmin): list_display = ('timestamp', 'wp', 'action', ) list_filter = ('wp', 'action', ) readonly_fields = ('wp', 'timestamp', 'action', 'body', ) admin.site.
register(models.WPLog, WPLogAdmin)
#-*- coding: utf-8 -*- ''' Created on 24 дек. 20%0 @author: ivan ''' import random all_agents = """ Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.3) Gecko/20090913 Firefox/3.5.3 Mozilla/5.0 (Windows; U; Windows NT 6.1; en; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 3.5.30729) Mozilla/5.0 (Windows; U; Win...
ecko) Chrome/4.0.219.6 Safari/532.1 Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.
0; SLCC2; .NET CLR 2.0.50727; InfoPath.2) Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 1.1.4322; .NET CLR 3.5.30729; .NET CLR 3.0.30729) Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Win64; x64; Trident/4.0) Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; T...
#!/usr/bin/evn python # Start a network import time import os import re import sys import commands import libvirt from libvirt import libvirtError from src import sharedmod required_params = ('networkname',) optional_params = {} def start(params): """activate a defined network""" global logger logger ...
I error message: %s, error code is %s" \ % (e.message, e.get_error_code())) logger.error("fail to destroy domain") return 1 net_activated_list = conn.listNetworks() if networkname not in net_activated_list: logger.error("virtual
network %s failed to be activated." % networkname) return 1 else: shell_cmd = "virsh net-list --all" (status, text) = commands.getstatusoutput(shell_cmd) logger.debug("the output of 'virsh net-list --all' is %s" % text) logger.info("activate the virtual network successfully.") ...
#!/usr/bin/python import os, sys from termcolor import colored try: import requests except: print "[!]Requests module not found. Try to (re)install it.\n[!]pip install requests" oks = [] print("EASY DIRBUSTER!") def parser(): #URL flag = False while ( flag == False ): url = raw_input("Ins...
") if (url.startswith("http://")): flag = True elif (url.startswith("https://")): flag = True else: pass #PATH flag = False while ( flag ==
False ): path = raw_input("Insert path to File (ex: /root/wordlists/list.txt)\n\tPATH: ") if (os.path.isfile(path)): flag = True else: pass return url, path def requester(url, fpath): if (requests.get(url).status_code != 200): return 0 else: w...
''' Created on 10/mar/2014 @author: sectumsempra ''' import sys ''' from variab_conc import errbox from PyQt4 import QtGui, QtCore, Qt from PyQt4.QtCore import pyqtSignal, SLOT from PyQt4.QtCore import pyqtSlot, SIGNAL from PyQt4.QtGui import QPushButton, QTextEdit, QTableWidgetItem ''' from PyQt4 import QtGui, QtCor...
for b in range(
rw_num): aleph = QtGui.QTableWidgetItem(0) aleph.setText(str("0")) self.tabellone.setItem(b, a, aleph) """ self.tabellone.setHorizontalHeaderLabels(col_names) self.tabellone.setVerticalHeaderLabels(rw_names) self.tabellone.horizontalHeader...
from __future__ import with_statement import os from alembic import context from sqlalchemy import engine_from_config, pool from logging.config import fileConfig # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # Interpret the config file ...
on with the context. """ dbcfg = config.get_section(config.config_ini_section) if 'DATABASE_URL' in os.environ: dbcfg['sqlalchemy.url'] = os.environ['DATABASE_URL'] engine = engine_from_config(
dbcfg, prefix='sqlalchemy.', poolclass=pool.NullPool) connection = engine.connect() context.configure( connection=connection, target_metadata=target_metadata ) try: with context.begin_transaction(): ...
#@ { #@ "targets": #@ [{ #@ "name":"versioninfo.txt" #@ ,"status_check":"dynamic" #@ ,"dependencies":[{"ref":"maike","rel":"tool"}] #@ }] #@ } import sys import subprocess import shutil import os def modified_time(filename): try: return (os.path.getmtime(filename),True) except (KeyboardInterrupt, Sys...
]==False: raise OSError('Error: None of the files %s, and %s are accessible.'%(file_a,file_b)) if not mod_a[1]: return False if not mod_b[1]: return True return mod_a[0] > mod_b[0] def newer_than_all(file_a, files): for file in files: if newer(file,file_a): return False return True def git_changes(...
( k[3:].split(' ')[0] ) return result def get_revision(): if shutil.which('git')==None: with open('versioninfo-in.txt') as versionfile: return versionfile.read().strip() else: with subprocess.Popen(('git', 'describe','--tags','--dirty','--always') \ ,stdout=subprocess.PIPE) as git: result=git.stdout.r...
from django.conf.urls impor
t patterns, url from manoseimas.lobbyists import views urlpatterns = patterns( '', url(r'^lobbyists/?$', views.lobbyists_json,
name='lobbyists_json'), url(r'^law_projects/(?P<lobbyist_slug>[^/]+)/?$', views.law_projects_json, name='law_projects_json'), )
setup newlistener=HiveClientListener(self,newsock,self.master,self.clientid) newlistener.run() class customPyServer(SocketServer.ThreadingMixIn,SocketServer.TCPServer,qtcore.QObject): def __init__(self,hostport,master,parentthread): qtcore.QObject.__init__(self) SocketServer.TCPServer.__init__(self,hostport,...
elf.socket.write(data) self.socket.flush() if self.socket.state()!=qtnet.QTcpSocket.UnconnectedState: self.socket.waitForBytesWritten(-1) elif self.type==BeeSocketTypes.python: try: self.socket.sendall(data) except socket.error, errmsg: print_debug("exception while trying to send data: %s" % ...
lse) # thread to setup connection, authenticate and then # listen to a socket and add incomming client commands to queue class HiveClientListener(qtcore.QThread): def __init__(self,parent,socket,master,id): qtcore.QThread.__init__(self,parent) self.socket=socket self.master=master self.id=id self.authenti...
#!/usr/bin/python # encoding: utf-8 import subprocess from config import Config applescript_name_tem = "osascript/open_%s.scpt" arg_tem = { "calendar": "%s %s %s", "fantastical": "%s-%s-%s", "busycal": "%s-%s-%s", "google": "%s%s%s" } SOFTWARE = 'software' def open_cal(arg): arg = arg.strip() ...
default_software = Config('').load_default(SOFTWARE) software_name = wf.settings.get(SOFTWARE, default_software) file_name = applescript_name_tem % (software_name)
year, month, day = arg.split() script_arg = arg_tem[software_name] % (year, month.zfill(2), day.zfill(2)) execute_osascript(file_name, script_arg) def execute_osascript(file, arg): subprocess.call(['osascript', file, arg]) def open_file(file): subprocess.call(['open', file]) if _...
# -*- coding: utf-8 -*- from behave import given, then from nose.tools import assert_true, assert_regexp_matches import pexpect import re @then(u'I should see how many entries were found') def see_number_of_entries_found(context): expected_text = 'Found total number of \d+ entries.' context.trove.expect(expec...
compile(expected_text) assert_regexp_matches(output, regexp) # vim: expandtab
shiftwidth=4 softtabstop=4
# Django settings for imageuploads project. import os PROJECT_DIR = os.path.dirname(__file__) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql...
ppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = 'qomeppi59pg-(^lh7o@seb!-9d(yr@5n^=*y9w&(=!yd2p7&e^' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.te...
loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMidd...
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- # pylint: ...
if not overwrite: # if customers didn't specify access conditions, they cannot
flush data to existing file if not _any_conditions(modified_access_conditions): modified_access_conditions.if_none_match = '*' if properties or umask or permissions: raise ValueError("metadata, umask and permissions can be set only when overwrite is enabled") ...
# Lior Hirschfeld # JargonBot # -- Imports -- import re import pickle import random import praw from custombot import RedditBot from time import sleep from define import getDefinition from collections import Counter from nltk.stem import * from sklearn import linear_model # -- Setup Variables -- jargonBot = RedditBo...
# Som
etimes, randomly reply to train the model. if random.random() < jargonBot.models[sub][1]: reply(com, word, ml, info=info) elif jargonBot.models[sub][0].predict([[info["popularity"], info["wLength"...
batch_size = y_shape[y_ndim - 1] new_shape = K.concatenate( [K.expand_dims(batch_size), y_shape[:y_ndim - 1]]) y = K.reshape(y, (-1, batch_size)) y = K.permute_dimensions(y, (1, 0)) y = K.reshape(y, new_shape) elif y_ndim > 1: dims =...
output *= inputs[i] return output class Average(_Merge): """Layer that averages a list of inputs. It takes as input a list of tensors, all of the same shape, and returns a single tensor (also of the sam
e shape). """ def _merge_function(self, inputs): output = inputs[0] for i in range(1, len(inputs)): output += inputs[i] return output / len(inputs) class Maximum(_Merge): """Layer that computes the maximum (element-wise) a list of inputs. It takes as input a list of tensors, all of the s...
#!/usr/bin/env python # Copyright 2021 - Gustavo Montamat # # Licensed u
nder the Apache License, Version 2.0 (the "License"); # you may not use th
is 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 A...
#!/usr/bin/env python # # Released under the BSD license. See LICENSE file for details. """ This program basically does face detection an blurs the face out. """ print __doc__ from SimpleCV import Camer
a, Display, HaarCascade # Initialize the camera cam = Camera() # Create the display to show the image display = Display() # Haar
Cascade face detection, only faces haarcascade = HaarCascade("face") # Loop forever while display.isNotDone(): # Get image, flip it so it looks mirrored, scale to speed things up img = cam.getImage().flipHorizontal().scale(0.5) # Load in trained face file faces = img.findHaarFeatures(haarcascade) ...
"""SCons.Tool.gcc Tool-specific initialization for gcc. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001 - 2017 The SCons Foundation # # Permission is hereby granted, free of charge, to...
pipe = SCons.Action._subproc(env, SCons.Util.CLVar(cc) + ['--version'], stdin = 'devnull', stderr = 'devnull', stdout
= subprocess.PIPE) # -dumpversion was added in GCC 3.0. As long as we're supporting # GCC versions older than that, we should use --version and a # regular expression. #line = pipe.stdout.read().strip() #if line: # version = line line = SCons.Util.to_str(pipe.stdout.readline()) matc...
# -*- coding: utf-8 -*- ############################################################################### # # InitializeOAuth # Generates an authorization URL that an application can use to complete the first step in the OAuth process. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under ...
tializeOAuthInputSet, self)._set_input('CustomCallbackID', value) def set_ForwardingURL(self, value): """ Set the value of the ForwardingURL input for this Choreo. ((optional, string) The URL that Temboo will redirect your users to after they grant access to your application. This should include the...
/" or "http://" prefix and be a fully qualified URL.) """ super(InitializeOAuthInputSet, self)._set_input('ForwardingURL', value) class InitializeOAuthResultSet(ResultSet): """ A ResultSet with methods tailored to the values returned by the InitializeOAuth Choreo. The ResultSet object is us...
#!/usr/bin/env python3 # Copyright (c) 2017 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 RPC calls related to net. Tests correspond to code in rpc/net.cpp. """ import time from test_framewo...
the other assert_equal(self.nodes[0].getconnectioncount(), 2) def _test_getnettotals(self): # check that getnettotals totalbytesrecv and totalbytessent # are consistent with getpeerinfo peer_info = self.nodes[0].getpeerinfo() assert_equal(len(peer_info), 2) ne
t_totals = self.nodes[0].getnettotals() assert_equal(sum([peer['bytesrecv'] for peer in peer_info]), net_totals['totalbytesrecv']) assert_equal(sum([peer['bytessent'] for peer in peer_info]), net_totals['totalbytessent']) # test getnettotals and getpeeri...
def trypr
int(): retur
n ('it will be oke')
# Copyright 2013: Mirantis 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 b...
e): msg_fmt = _("Resouce %(resource)s has %(status)s status: %(fault)s") class SSHError(RallyException): msg_fmt = _("Remote command failed.") class TaskInvalidStatus(RallyException): msg_fmt = _("Task `%(uuid)s` in `%(actual)s` status but `%(require)s` is " "required.") class Checksum...
sn't have 'admin' role") class InvalidEndpointsException(InvalidArgumentsException): msg_fmt = _("wrong keystone credentials specified in your endpoint" " properties. (HTTP 401)") class HostUnreachableException(InvalidArgumentsException): msg_fmt = _("unable to establish connection to the re...
._x_scores) assert_matrix_orthogonal(pls._y_scores) def test_convergence_fail(): # Make sure ConvergenceWarning is raised if max_iter is too small d = load_linnerud() X = d.data Y = d.target pls_nipals = PLSCanonical(n_components=X.shape[1], max_iter=2) with pytest.warns(ConvergenceWarning...
stability(Est, X, Y): """scal
e=True is equivalent to scale=False on centered/scaled data This allows to check numerical stability over platforms as well""" X_s, Y_s, *_ = _center_scale_xy(X, Y) X_score, Y_score = Est(scale=True).fit_transform(X, Y) X_s_score, Y_s_score = Est(scale=False).fit_transform(X_s, Y_s) assert_allclo...
est2@example.com', password='test', ) @override_settings(AUTH_USER_MODEL='auth.ExtensionUser') class ExtensionUserModelBackendTest(BaseModelBackendTest, TestCase): """ Tests for the ModelBackend using the custom ExtensionUser model. This isn't a perfect test, because both the User and...
) @override_settings(AUTH_USER_MODEL='auth.CustomPermissionsUser') class CustomPermissionsUserModelBackendTest(BaseModelBackendTest, TestCase): """ Tests for the ModelBackend using the CustomPermissionsUser model. As with the ExtensionUser test, this isn't a perfect test, because both the User and Cu...
sionsUser def create_users(self): self.user = CustomPermissionsUser._default_manager.create_user( email='test@example.com', password='test', date_of_birth=date(2006, 4, 25) ) self.superuser = CustomPermissionsUser._default_manager.create_superuser( ...
# Download the Python helper library from twilio.com/docs/python/install from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/user/account account_sid = "ACCOUNT_SID" auth_token = "your_auth_token" client = Client(account_sid, auth_token) number = client.lookups.phone_numbers("+165
02530000").fetch( type="caller-name", ) print(number.carrier['type']) print(number.carrier['name'])
from chainer.iter
ators import multiprocess_iterator from chainer.iterators import serial_iterator MultiprocessIterator = multiprocess_iterator.MultiprocessIterator SerialIterator = serial_ite
rator.SerialIterator
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2017-01-03 10:30 from __future__ import unicode_literals from django.db import migrations
, models class Migration(migrations.Migration): dependencies = [ ('main', '0026_auto_20161215_2204'), ] operations = [ migrations.AddField( model_name='lan', name='show_calendar', field=models.BooleanField(default=False, help_
text='Hvorvidt en kalender skal vises på forsiden. Slå kun dette til hvis turneringer og andre events efterhånden er ved at være klar.', verbose_name='Vis kalender'), ), migrations.AddField( model_name='tournament', name='end', field=models.DateTimeField(null=True, ve...
# Copyright (C) 2016 Deloitte Argentina. # This file is part of CodexGigas - https://github.com/codexgigassys/ # See the file 'LICENSE' for copying permission. from PlugIns.PlugIn import PlugIn class CypherPlug(PlugIn): def __init__(self, sample=None): PlugIn.__init__(sel
f, sample) def getPath(self): return "particular_header.cypher" def getName(self): return "cypher" def getVersion(self):
return 1 def process(self): return "Not_implemented"
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Windows constants for IOCP """ # this stuff should really be gotten from Windows headers via pyrex, but it # probably is not going to change ERROR_PORT_UNREACHABLE = 1234 ERROR_NETWORK_UNREACHABLE = 1231 ERROR_CONNECTION_REFU...
NFINITE = -1
SO_UPDATE_CONNECT_CONTEXT = 0x7010 SO_UPDATE_ACCEPT_CONTEXT = 0x700B
f
rom sklearn2sql_heroku.tests.regression import generi
c as reg_gen reg_gen.test_model("LGBMRegressor" , "boston" , "postgresql")
# run scripts/jobslave-nodatabase.py import os os.environ["SEAMLESS_COMMUNION_ID"] = "simple-remote" os.environ["SEAMLESS_COMMUNION_INCOMING"] = "localhost:8602" import seamless seamless.set_ncores(0) from seamless import communion_server communion_server.configure_master( buffer=True, transformation_job=Tru...
"output" }) ctx.cell1_unilink = unilink(ctx.cell1) ctx.cell1_unilink.connect(ctx.tf.a) ctx.cell2.connect(ctx.tf.b) ctx.code = cell("transformer").set("c = a + b") ctx.code.connect(ctx.tf.code) ctx.result_
unilink = unilink(ctx.result) ctx.tf.c.connect(ctx.result_unilink) ctx.result_copy = cell() ctx.result.connect(ctx.result_copy) ctx.compute(0.1) print(ctx.cell1.value) print(ctx.code.value) ctx.compute() print(ctx.result.value, ctx.status) print(ctx.tf.exception) ctx.cell1.set(10) ctx.compute() print(ctx.result.value,...
import pkg_resources from string import Template mod
el_template = Template(pkg_resources.resource_string(__name__, "model_template.C")) lorentz_calc_template = Template(pkg_resources.resource_string(__name__, "lorentz_calc_template.C")) sconstruct_template = Template(pkg_resources.resource_string(__name__, "sconstruct_template")
) run_card_template = Template(pkg_resources.resource_string(__name__, "run_card_template"))
c requirements for chromosome order, run group information and other BAM formatting. This provides a pipeline to prepare and resort an input. """ import os import sys import pysam from bcbio import bam, broad, utils from bcbio.bam import ref from bcbio.distributed.transaction import file_transaction, tx_tmpdir from b...
rder", in_bam, ref_file, reorder_bam) rg_bam = runner.run_fn("picard_fix_rgs", reorder_bam, names) return _filter_bad_reads(rg_bam, ref_file, data) def _filter_bad_reads(in_bam, ref_file, data): """Use GATK filter to remove problem reads which choke GATK and Picard. """ bam.index(in_bam, data["conf...
tmp_dir: with file_transaction(data, out_file) as tx_out_file: params = [("FixMisencodedBaseQualityReads" if dd.get_quality_format(data, "").lower() == "illumina" else "PrintReads"), "-R", ref_file, ...
# -*- coding: utf-8 -*- """ pgp_import command Import keys and signatures from a given GPG keyring. Usage: ./manage.py pgp_import <keyring_path> """ from collections import namedtuple, OrderedDict from datetime import datetime import logging from pytz import utc import subprocess import sys from django.core.managem...
n other.items(): if getattr(dkey, k) != v: setattr(dkey, k, v) needs_save = True if dkey.owner_id is None: owner = find_key_owner(data, keydata, finder) if owner is not None: dkey.owner = ...
y.save() updated_ct += 1 key_ct = DeveloperKey.objects.all().count() logger.info("%d total keys in database", key_ct) logger.info("created %d, updated %d keys", created_ct, updated_ct) class SignatureData(object): def __init__(self, signer, signee, created): self.signer = sign...
""" Qxf2 Services: A plug-n-play class for logging. This class wraps around Python's loguru module. """ import os, inspect import pytest,logging from loguru import logger from pytest_reportportal import RPLogger, RPLogHandler class Base_Logging(): "A plug-n-play class for logging" def __init__(self,log_file_na...
ions.append("Error when setting up the reportportal logger") def write(self,msg,level='info'): "Write out a message" #fname = inspect.stack()[2][3] #May be use
a entry-exit decorator instead all_stack_frames = inspect.stack() for stack_frame in all_stack_frames[1:]: if 'Base_Page' not in stack_frame[1]: break fname = stack_frame[3] d = {'caller_func': fname} if self.rp_logger: if level.lower()== '...
"""mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') C...
ort:
from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls impo...
# Generated by Django 2.1.3 on 2018-11-09 18:28 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('proposals', '0016_auto_20180405_2116'), ] operations = [ migrations.AlterField( model_name='timeallocation', name='i...
-FLOYDS-SCICAM'), ('2M0-SCICAM-SPECTRAL', '2M0-SCICAM-SPECTRAL'), ('2M0-SCICAM-SBIG', '2M0-SCICAM-SBIG')], max_length=200), ), migrations.AlterField( model_name='timeallocation', name='telescope_class',
field=models.CharField(choices=[('0m4', '0m4'), ('0m8', '0m8'), ('1m0', '1m0'), ('2m0', '2m0')], max_length=20), ), ]
"""Support for Transport NSW (AU) to query next leave event.""" from datetime import timedelta from TransportNSW import TransportNSW import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ( ATTR_ATTRIBUTION, ATTR_MODE, CONF_API_KE...
ATTRIBUTION: ATTRIBUTION, } @property def native_unit_of_measurement(self): """Return the unit this state is expressed in.""" return TIME_MINUTES @property def icon(self): """Icon to use in the frontend, if any.""" return self._icon def update(self): ...
lf.data.info self._state = self._times[ATTR_DUE_IN] self._icon = ICONS[self._times[ATTR_MODE]] class PublicTransportData: """The Class for handling the data retrieval.""" def __init__(self, stop_id, route, destination, api_key): """Initialize the data object.""" self._stop_id ...
# Copyright (c) 2019 Guangwang Huang # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, dis...
ES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES O
R OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import pytest import libqtile.config from libqtile import layout from libqtile.confreader import Config from test.layouts.layout_utils imp...
"""Tests for vumi.middleware.tagger.""" import re from vumi.middleware.tagger import TaggingMiddleware from vumi.message import TransportUserMessage from vumi.tests.helpers import VumiTestCase class TestTaggingMiddleware(VumiTestCase): DEFAULT_CONFIG = { 'incoming': { 'addr_pattern': r'^\d+...
= new TaggingM
iddleware._deepupdate(re.match(".*", "foo"), orig, new) self.assertEqual(orig, {'a': {'b': "baz"}, 'c': "bar"}) def test_map_msg_to_tag(self): msg = self.mk_msg("123456") self.assertEqual(TaggingMiddleware.map_msg_to_tag(msg), None) msg['helper_metadata']['tag'] = {'tag': ['pool', '...
"""Tests for tools and arithmetics for monomials of distributed polynomials. """ from sympy.polys.monomialtools import ( monomials, monomial_count, monomial_lex_cmp, monomial_grlex_cmp, monomial_grevlex_cmp, monomial_cmp, monomial_mul, monomial_div, monomial_gcd, monomial_lcm, monomial_max, monomial_min, )...
revlex_cmp raises(ValueError, "monomial_cmp('unknown')") def test_monomial_mul(): assert monomial_mul((3,4,1), (1,2,0)) == (4,6,1) def test_monomial_div(): assert monomial_div((3,4,1), (1,2,0)) == (2,2,1) def test_monomial_gcd(): assert monomial_gcd((3,4,1), (1,2,0)) == (1,2,0) def test_monomial_lc...
t monomial_min((3,4,5), (0,5,1), (6,3,9)) == (0,3,1)
# Copyright 2011 OpenStack Foundation # # Licensed under the Apache Licens
e, 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...
"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. """The Extended Status Admin API extension.""" from nova.api.openstack import extensions from nova.api.openstack import...
.edu> # Portions of code by Geoffrey French. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public version 2.1 as # published by the Free Software Foundation. # # See COPYING.lib file that comes with this distribution for full text # o...
iter = self.buffer.get_iter_at_mark(self.buffer.get_insert()) if ps: self.freeze_undo() self.buff
er.insert(iter, self.ps) self.thaw_undo() self.__move_cursor_to(iter) self.scroll_to_mark(self.cursor, 0.2) self.in_raw_input = True if self.run_on_raw_input: run_now = self.run_on_raw_input self.run_on_raw_input = None self.buffer.inser...
ing individual files for each function and class, we shard the files across several directories to avoid hitting the limit for files per directory. This function determines the subdirectory for a member based on a stable hash of its name. Args: name: string. The name of a function or class. ...
We should do something better. if argspec.varargs == "args" and argspec.keywords == "kwds": original_func = func.__closure__[0].cell_contents return self._generate_signature_for_function(original_func) if argspec.defaults: for arg, defa
ult in zip( argspec.args[first_arg_with_default:], argspec.defaults): if callable(default): args_list.append("%s=%s" % (arg, default.__name__)) else: args_list.append("%s=%r" % (arg, default)) if argspec.varargs: args_list.append("*" + argspec.varargs) if args...
#!/bin/false # This file is part of Espruino, a JavaScript interpreter for Microcontrollers # # Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk> # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at h...
'D34', 'pin_do': 'D33', 'pin_clk': 'D32'}} # left-right, or top-bottom order board = { 'top': ['D14', 'GND', 'D13', 'D12', 'D11', 'D10', 'D9', 'D8', '', 'D7', 'D6', 'D5', 'D4', 'D3', 'D2', 'D1', 'D0'], 'bottom': ['RST', '3.3', '3.3A', 'GNDA', 'GND', 'VIN', '', 'A0', 'A1', 'A2', 'A3', 'A4', 'A5'], 'r...
'left2': ['GND', 'D8', 'D20', 'D11', 'D4'], '_pinmap': {'A0': 'D15', 'A1': 'D16', 'A2': 'D17', 'A3': 'D18', 'A4': 'D19', 'A5': 'D20'} } board['left'].reverse() board['left2'].reverse() board['right'].reverse() board['right2'].reverse() board["_css"] = """ #board { width: 540px; height: 418px; top: 300px; lef...
from urllib.parse import urljoin import pytest from adhocracy4.comments import models as comments_models from adhocracy4.ratings import models as rating_models @pytest.mark.django_db def test_delete_comment(comment_factory, rating_factory): comment = comment_factory() for i in range(5): comment_fac...
n 200 ' 'characters. Yes yes yes. That long! Really that long. How long is ' 'that. Yes yes yes. That long! Really that long. How long is that. ' 'Yes yes yes. That long! Really that long. How long is that.' )
assert str(short_comment) == short_comment.comment assert str(long_comment) == "{} ...".format(long_comment.comment[:200]) @pytest.mark.django_db def test_get_absolute_url(comment, child_comment): # comment from factory has Question as content_object, which does not # define get_absolte_url, so url ...
SampleAttribute module. """ import unittest import json from cutlass import SampleAttribute from CutlassTestConfig import CutlassTestConfig from CutlassTestUtil import CutlassTestUtil # pylint: disable=W0703, C1801 class SampleAttributeTest(unittest.TestCase): """ A unit test class for the SampleAttribute modu...
sc' in JSON had expected value." ) self.assertEqual(attrib_d
ata['meta']['sample_type'], sample_type, "'sample_type' in JSON had expected value." ) self.assertEqual(attrib_data['meta']['subproject'], subproject, "'subproject' in JSON had expected v...
livora.Package'].objects.all(): package.normalized_name = normalize_name(package.name) package.save() def backwards(self, orm): "Write your backwards methods here." models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.mo...
[], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['aut
h.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_nam...
__author__ = "Steffen Vogel" __copyright__ = "Copyright 2015, Steffen Vogel" __license__ = "GPLv3" __maintainer__ = "Steffen Vogel" __email__ = "post@steffenvogel.de" """ This file is part of transWhat transWhat is free software: you can redistribute it and/or modify it under the terms of the GNU General Public Li...
except KeyError: return None def requestVCard(self, buddy, ID=None): if buddy == self.user or buddy == self.user.split('@')[0]: buddy = self.session.legacyName # Get profile picture self.logger.debug('Requesting profile picture of %s', buddy) response = deferred.Deferred() sel
f.session.requestProfilePicture(buddy, onSuccess = response.run) response = response.arg(0) pictureData = response.pictureData() # Send VCard if ID != None: call(self.logger.debug, 'Sending VCard (%s) with image id %s: %s', ID, response.pictureId(), pictureData.then(base64.b64encode)) call(self.back...
import _plotly_utils.basevalidators cla
ss ColorValidator(_plotly_utils.basevalidators.ColorValidator): def __init__( self, plotly_name="color", parent_name="histogram2dcontour.textfont", **kwargs ): supe
r(ColorValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "style"), **kwargs )
#!/usr/bin/pyt
hon # -*- coding: utf-8 -*- from gobspy import main
main()
# -*- coding: utf-8 -*- import time class Timer(object): ''' Simple timer control ''' def __init__(self, delay): self.current_time = 0 self.set_delay(delay) def pause(self, pause): if pause >= self.delay: self.current_time = time.clock() ...
self.next_time = self.current_time else: self.current_time = time.clock() self.next_tim
e = self.current_time + self.delay def idle(self): ''' Verify if the timer is idle ''' self.current_time = time.clock() ## if next frame occurs in the future, now it's idle time if self.next_time > self.current_time: return True ...
import rando
m def say_thing(): return random.choi
ce([ "dude", "sup", "yo mama" ])
'Phillips', '20149' : 'Pottawatomie', '20151' : 'Pratt', '20153' : 'Rawlins', '20155' : 'Reno', '20157' : 'Republic', '20159' : 'Rice', '20161' : 'Riley', '20163' : 'Rooks', '20165' : 'Rush', '20167' : 'Russell', '20169' : 'Saline', '20171' : 'Scott', '20173' : 'Sedgw...
'26067' : 'Ionia', '26069' : 'Iosco', '26071' : 'Iron', '26073' : 'Isabella', '26075' : 'Jackson', '26077' : 'Kalamazoo', '26079' : 'Kalkaska', '26081' : 'Kent', '26083' : 'Keweenaw', '26085' : 'Lake', '26087' : 'Lapeer',
'26089' : 'Leelanau', '26091' : 'Lenawee', '26093' : 'Livingston', '26095' : 'Luce', '26097' : 'Mackinac', '26099' : 'Macomb', '26101' : 'Manistee', '26103'
# ============================================================================== # Copyright (C) 2011 Diego Duclos # Copyright (C) 2011-2018 Anton Vorobyov # # This file is part of Eos. # # Eos is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as publi...
Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Eos. If not, see <http://www.gnu.org/licenses/>. # ============================================================================== from abc import ABCMeta from abc import abstractme...
ion import RestrictionValidationError from .base import BaseRestriction ResourceErrorData = namedtuple( 'ResourceErrorData', ('total_use', 'output', 'item_use')) class ResourceRestriction(BaseRestriction, metaclass=ABCMeta): """Base class for all resource restrictions. Resources in this context is some...