prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
icenses as well. In some cases we can relicense portions of *
# * Nmap or grant special permissions to use it in other open source *
# * software. Please contact fyodor@nmap.org with any such requests. *
# * Similarly, we don't incorporate incompatible open source software into *
# * Covered Software... | fs = {}
# We should have a default rest pixbuf, set it with set_rest_pixbuf()
self.rest_pixbuf = None
# This is a list of pixbufs to be used on the animation
# For now, we're only implementing a single animation. Inconsistent!
self.animated_pixbufs = []
def add_static_pixb... | pixbuf the new default on rest, by setting
default_on_rest to True.
"""
dprint('HIGSpinnerImages::add_static_pixbuf')
self.static_pixbufs[name] = pixbuf
if (len(self.static_pixbufs) == 1) or default_on_rest:
self.set_rest_pixbuf(name)
def add_animated_pixbuf(se... |
from __future__ import absolute_import
# Copyright (c) 2010-2017 openpyxl
"""Write the workbook global settings to the archive."""
from copy import copy
from openpyxl.utils import absolute_coordinate, quote_sheetname
from openpyxl.xml.constants import (
ARC_APP,
ARC_CORE,
ARC_WORKBOOK,
PKG_REL_NS,
... | m openpyxl.worksheet import Worksheet
from openpyxl.chartsheet import Chartsheet
from openpyxl.packag | ing.relationship import Relationship, RelationshipList
from openpyxl.workbook.defined_name import DefinedName
from openpyxl.workbook.external_reference import ExternalReference
from openpyxl.workbook.parser import ChildSheet, WorkbookPackage
from openpyxl.workbook.properties import CalcProperties, WorkbookProperties
fr... |
import random
from .exceptions import ClientError
def catch_client_error(func):
"""
Decorator to catch the ClientError exception and translate it into a reply.
"""
def inner(message):
try:
return func(message)
except ClientError as e:
# If we catch a client er... | nihilus',
'Deadpool',
'Captain America',
'Fin Fang Foom',
'Daredevil',
'J Jonah Jameson',
'Kang the Conqueror',
'Beta Ray Bill',
'Doctor Stephen Strange',
'Wolverine',
'MODOK',
'Nick Fury',
'Emma Frost',
'Black Panth... | ictor Von Doom',
]
left = random.choice(adjective_list)
right = random.choice(subject_list)
name = '{} {}'.format(left, right)
return name
|
'http://as.anime-stream24.co/' #BACKUP URL
def load():
oGui = cGui()
params = ParameterHandler()
logger.info("Load %s" % SITE_NAME)
if showAdult():
params.setParam('entryMode', "a_z")
oGui.addFolder(cGuiElement('A BIS Z', SITE_IDENTIFIER, 'showMovies'), params)
params.setParam(... | est_link, 'name': 'Testing_link', 'resolveable': True})
reg_ex = re.compile('(?://|\.)?(?:[a-zA-Z0-9]+\.)?([a-zA-Z0-9-.]{0,})\..*?\/.*?\/?', re.I)
for sUrl in aResult[1]:
sName = re.search(reg_ex, sUrl).group(1)
| if not sUrl.startswith('http'):
if sUrl.startswith('//'):
sUrl = 'http:%s' % sUrl
else:
sUrl = 'http://%s' % sUrl
hosters.append({'link': sUrl, 'name': sName, 'resolveable': True})
if hosters:
hosters.append('getHosterUrl')
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# ===========================================================================
# iDevice Para Saber más creado para la FPD por José Ramón Jiménez Reyes
# ===========================================================================
"""
Para Saber mas iDevice
"""
import logging
fr... | ons = i.findAll(name='div | ', attrs={'id' : re.compile('^ta') })
# should be exactly two of these:
# 1st = field[0] == Activity
if len(reflections) >= 1:
self.activityTextArea.content_wo_resourcePaths = \
reflections[0].renderContents().decode('utf-8')
# and add the LOCAL resour... |
# vim: fdm=indent
# author: Fabio Zanini
# date: 02/08/17
# content: Support module for filenames related to LOOM files.
# Modules
import numpy as np
import pandas as pd
from singlet.config import config
# Parser
def parse_dataset(
path,
obsm_keys=None,
):
import anndata
... | key, array in adata.obsm.items():
if key.startswith('X_'):
newkey | = key[2:]
if (obsm_keys is not None) and (newkey not in obsm_keys):
continue
for j, col in enumerate(array.T, 1):
samplesheet[newkey+'_'+str(j)] = col
featuresheet = adata.var.copy()
count_mat = adata.X.toarray().T
counts_table = pd.DataFrame(
... |
# ===========================================================================
#
# Library: PyCTK
# Filename: test_axeswidget.py
#
# Copyright (c) 2015 Lamond Lab
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may ... | ==================================
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyCTK.Widgets import ctkAxesWidget
class Widget(QWidget):
def __init__(self, parent=None, **kwargs):
super().__init__(parent, **kwargs)
l=QVBoxLayout(self)
self._axe... | .show()
w.raise_()
exit(a.exec_()) |
prefix
), "NTURI path '%s' doesn't start with '%s'" % (value.path, prefix)
method = value.path[len(prefix) :]
parameters = convert_value_to_dict(value.query)
else:
# We got something else, take path from pvRequest method and our mri
# and parameter... | ver thread the child block c | ould be in, so
# must already be a good thread to take the lock
with self._lock:
if self.pv:
# onFirstConnect has been called, should be able to update it
try:
assert isinstance(response, Delta), (
"Expecting Delta r... |
wait:
cls._wait_for_load_balancer_status(lb.get('id'))
except Exception:
raise Exception(_("Failed to create load balancer..."))
cls._lbs_to_delete.append(lb.get('id'))
return lb
@classmethod
def _create_active_load_balancer(cls, **kwargs):
lb = cls._... | member_ids=None):
statuses = cls.load_balancers_client.get_load_balancer_status_tree(
load_balancer_id=load_balancer_id)
load_balancer = statuses['loadbalancer']
assert 'ONLINE' == load_balancer['operating_status']
assert 'ACTIVE' == load_balancer['provisioning_status']
... | |
DATASET_DIR = '/tmp'
BRAIN_DIR = '/tmp'
GENRES = [
'blues', 'classical', 'country', 'disco', 'hiphop',
'jazz', 'metal', 'pop', 'reggae', 'rock'
]
NUM_BEATS = 10
KEEP_FRAMES = 0
TRAIN_TEST_RATIO = [7, 3]
MODE = 'nn'
PCA = False
FEATURES = ['mfcc', 'dwt', 'beat']
MFCC_EXTRA = ['delta', 'ddelta', 'energy'... | ATCH_SIZE' : [5, 5],
'RANDOM' : False,
'STRIDES' : [1, 1, 1, 1],
'BATCH_SIZE' : 100,
'TRAINING_CYCLES' : 1000,
'LEARNING_RATE' : 0.01,
'DROPOUT_PROB' : | 0.6
} |
#!/usr/bin/python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | '\tReason not provided.'
else:
print 'No disapproved ads were found.'
if __name__ == '__main__':
# Initialize client object.
adwords_client = adwords.AdWordsClien | t.LoadFromStorage()
main(adwords_client, CAMPAIGN_ID)
|
from __future__ import print_function
import pickle, os, sys, glob, hashlib
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
test_files = set(pd.read_csv('./data/sampleSubmission_v2.csv').file.values)
train = pd.read_csv('./data/train_v2.csv')
df_full = pickle.load(open( "df_full.p", "rb"))
... | rt()
with pd.option_context('display.max_rows', len(feature_importances), 'display.max_columns', 10):
print(feature_importances)
print('--- Create predictions and submission')
submission = test[['file']].reset_index(drop=True)
submission['sponsored'] = clf.predict_proba(test.drop(['file', 'sponsored'], 1))[:, 1]
#... | the correct number of rows
if len(submission) != 66772:
print("Error: wrong dimension! Not generating submission CSV file.")
else:
submission.to_csv('native_btb_basic_submission.csv', index=False)
|
"""
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
... | - An int or float in the interval [1, inf]
Returns
| -------
int|float
"""
return self["size"]
@size.setter
def size(self, val):
self["size"] = val
# Self properties description
# ---------------------------
@property
def _prop_descriptions(self):
return """\
color
family
... |
from typing import NamedTuple, List
from data import crossword
class Clue(str):
def __ini | t__(self, value) -> None:
super(Clue, self).__init__(value)
self._tokens = crossword.tokenize_clue(value)
class _Node(object):
_clue: Clue
_occupied: int
def __init__(self, clue: Clue, oc | cupied: int) -> None:
self._clue = clue
self._occupied = occupied
class Parsed(List):
pass
# A list of nodes, initially Nulls
|
import logging
from gettext import gettext as _
from .l_connector import ConnectorBase
from .l_net import ModuleStrategyBase
from .main import OptionsWIFI
logger = logging.getLogger(__name__)
# noinspection PyAbstractClass
class Connector(ConnectorBase):
opti_: OptionsWIFI
class Module(ModuleStrategyBase):
... | def name(self) -> str:
return _('W | IFI')
|
from django.shortcuts import render
from services.genomics_test_generator.fhir_genomics_test_gene import *
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext, loader
import json
from home.task_runner import perform_t... | sk_id,
'time':task_time.strftime("%Y-%m-%d")
})
result['tasks'] = task_list
r | esult['isSuccessful'] = True
except:
pass
return HttpResponse(json.dumps(result), content_type="application/json")
@csrf_exempt
def search_task(request):
req_json = json.loads(request.body)
keyword = req_json['keyword']
result = {
'isSuccessful': True
}
result['tasks... |
'')
def _get_voltype_specs(self, volume):
"""Get specs suitable for volume creation."""
vtype = volume.get('volume_type_id', None)
extra_specs = None
if vtype:
extra_specs = volume_types.get_volume_type_extra_specs(vtype)
return self._get_specs(extra_s... | ault_ret
| tgt_asn = self.tgt_zfssa.get_asn()
src_asn = self.zfssa.get_asn()
# verify on the source system that the destination has been
# registered as a replication target
tgts = self.zfssa.get_replication_targets()
targets = []
for target in tgts['target... |
#!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import buildconfig
from mozbuild.preprocessor import preprocess
# By default, the pre-processor... | ch uses
# "%" as the marker so we invoke the pre- processor ourselves here with
# the marker specified. The resulting SVG files will get packaged by the
# processing of the jar file in the appropriate directory.
def _do_preprocessing(output_svg, input_svg_file, additional_defines):
additional_defines.update(buildco... | e],
marker='%',
defines=additional_defines)
def tab_side_start(output_svg, input_svg_file):
return _do_preprocessing(output_svg, input_svg_file, {'TAB_SIDE': 'start'})
def tab_side_end(output_svg, input_svg_file):
return _do_preprocessing(output_svg, input_svg_file,... |
# Licensed under GPL version 3 - see LICENSE.rst
import numpy as np
from astropy.io import ascii
from .base import FlatOpticalElement, FlatStack
from ..math.utils import norm_vector, e2h, h2e
class FlatBrewsterMirror(FlatOpticalElement):
'''Flat mirror operated at the Brewster angle.
Calculation of the Fres... | rall loss.
'''
display = {'color': (0., 1., 0.),
'shape': 'box',
'box-half': '+x',
}
def fresnel(self, photons, inter | sect, intersection, local):
'''The incident angle can easily be calculated from e_x and photons['dir'].
Returns
-------
refl_s, refl_p : np.array or float
Reflection probability for s and p polarized photons.
Typically, the number will depend on the incident angl... |
def find_token(self, key_set):
""" Return a token that can delete this key set. """
# Do we have a perfect match?
# FIXME: This is really awful...
provided_params = [self.index_of_param(param) for param in token_list_for(key_set)]
provided_params.sort()
provided_params =... | if create_token:
self.get_or_create_token(token_list_for(key_set))
def delete_cb(sender, **kwargs):
self.delete_key_sets(key_set)
signals.post_save.connect(delete_cb, sender=Model, weak=False)
signals.pre_delete.connect(delete_cb, sender=Model... | ncy(self, Model, resolve_depend_on_model)
depend_on_model.alters_data = True
def depend_on_row(self, Model, selector, filter=None):
"""
Depend on a row of a Model when a row of this Model changes.
When a row is changed, selector is called to determine the key_set
to evict. sele... |
#!/usr/bin/env python
"""
Download NLTK data
"""
__author__ = "Manan Kalra"
__email__ = "m | anankalr | 29@gmail.com"
import nltk
nltk.download() |
Fields"))
self.gridLayout_3.addWidget(self.lstSrcFields, 0, 1, 5, 1)
self.btnSrcUp = QtGui.QPushButton(self.groupBox_5)
self.btnSrcUp.setMaximumSize(QtCore.QSize(50, 16777215))
self.btnSrcUp.setText(_fromUtf8(""))
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(_f... | mUtf8("gridLayout_4"))
self.label_3 = QtGui.QLabel(self.groupBox_6)
self.label_3.setObjectName(_fromUtf8("label_3"))
self.gridLayout_4.addWidget(self.label_3, 4, 0, 1, 1)
self.btn_delete_translator = QtGui.QToolButton(self.groupBox_6)
self.btn_delete_translator.setMinimumSiz... | Pixmap(QtGui.QPixmap(_fromUtf8(":/plugins/stdm/images/icons/remove.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.btn_delete_translator.setIcon(icon2)
self.btn_delete_translator.setPopupMode(QtGui.QToolButton.InstantPopup)
self.btn_delete_translator.setObjectName(_fromUtf8("btn_delete_tran... |
#############################################
##
## Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
## Contact: http://www.qt-project.org/legal
##
## This file is part of Qt Creator.
##
## Commercial License Usage
## Licensees holding valid commercial Qt licenses may use this file in
## accordance with the co... | (waitForObject(getQModelIndexStr("text='Sample'", ":Add Bookmark.tr | eeView_QTreeView")))
clickButton(waitForObject(":Add Bookmark.New Folder_QPushButton"))
clickButton(waitForObject(":Add Bookmark.OK_QPushButton"))
# choose bookmarks
mouseClick(waitForObjectItem(":Qt Creator_Core::Internal::CommandComboBox", "Bookmarks"))
# verify if all folders are created and book... |
import numpy | as np
def rainbow(n):
"""
Returns a list of colors sampled at equal intervals over the spectrum.
Parameters
----------
n : int
The number of colors to return
Returns
-------
R : (n,3) array
An of rows of RGB color values
Notes
-----
Converts from HSV coor... | 1) to (1, 1, 1) to RGB. Based on
the Sage function of the same name.
"""
from matplotlib import colors
R = np.ones((1,n,3))
R[0,:,0] = np.linspace(0, 1, n, endpoint=False)
#Note: could iterate and use colorsys.hsv_to_rgb
return colors.hsv_to_rgb(R).squeeze()
|
import time
from copy import copy
import numpy as np
from gridworld import Gridworld, Position
from utilities.utils import argmax_ra | ndom_tie
# START
rows = 7
cols = 10
world = Gridworld(rows, cols)
moveset = [
# Position(1, 1),
# Position(1, -1),
# Position(-1, -1),
# Position(-1, 1),
Position(1, 0), # down
Position(0, -1), # left
Position(0, 1), # right
Position(-1, 0) # up
]
alpha = 0.2
e = 0.3
lambd = 0. | 2
e_decay = 0.9999
n_episodes = 100000
print_every = 10000
q = np.zeros((rows, cols, len(moveset)))
for episode in range(n_episodes):
print("episode {}".format(episode))
world.reset()
s = world.pos
found = False
e *= e_decay
step = 0
while not found:
step += 1
world.wind()
... |
"""Tests for greeneye_monitor sensors."""
from unittest.mock import AsyncMock, MagicMock
from homeassistant.components.greeneye_monitor.sensor import (
DATA_PULSES,
DATA_WATT_SECONDS,
)
from homeassistant.const import STATE_UNKNOWN
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_... |
"""Test that a voltage sensor reports its values properly."""
await setup_greeneye_monitor_component_with_config(
hass, SINGLE_MONITOR_CONFIG_VOLTAGE_SENSORS
)
connect_monitor(monitors, SINGLE_MONITOR_SERIAL_NUMBER)
assert_sensor_state(hass, "sensor.voltage_1", "120.0")
def connect_monito... | tor(serial_number)
monitors.add_monitor(monitor)
return monitor
async def disable_entity(hass: HomeAssistant, entity_id: str) -> None:
"""Disable the given entity."""
entity_registry = get_entity_registry(hass)
entity_registry.async_update_entity(entity_id, disabled_by="user")
await hass.async... |
def extractFaelicyTumblrCom(item):
'''
Parser for 'faelicy.tumblr.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
ta | gmap = [
('the scum villain\'s self saving system', 'the scum villain\'s self saving system', 'translated'),
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']... | essageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False |
import os
from conans.client.file_copier import FileCopier, report_copied_files
from conans.model.manifest import FileTreeManifest
from conans.paths import CONANINFO
from conans.util.files import mkdir, save
def export_pkg(conanfile, package_id, src_package_folder | , hook_manager, conanfile_path, ref):
# NOTE: The layout folder is not taken into account for the cache, it is not useful to introduce
# a subfolder there.
mkdir(conanfile.package_folder)
output = conanfile.output
output.info("Exporting to cache existing package from user folder")
output... | anfile_path=conanfile_path,
reference=ref, package_id=package_id)
copier = FileCopier([src_package_folder], conanfile.package_folder)
copier("*", symlinks=True)
hook_manager.execute("post_package", conanfile=conanfile, conanfile_path=conanfile_path,
refere... |
8
#import pygame
from Tkinter import *
import ttk
import time
from PIL import ImageTk,Image
from functools import partial
import os
import tkMessageBox
from urllib2 import *
from threading import Thread
import urllib as u
from window import *
###########################################################################... | an",self.Pencere,"NoteStudio PortScan","Hedef sistem port tarama","IP adresi yada Domain"],
| {"buton":"Robots.txt",
#"pencere":self.Pencere,
"title":"NoteStudio robots.txt",
"text":"Hedef sistemde robots.txt tespiti",
"bilgi":"Domain (http(s)://) ile yazın",
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('customers', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='address',
name='re... | _name='recipient',
name='city',
field=models.CharField(max_length=5 | 0, blank=True),
preserve_default=True,
),
migrations.AddField(
model_name='recipient',
name='country',
field=models.CharField(max_length=40, verbose_name=b'Country', blank=True),
preserve_default=True,
),
migrations.AddField(
... |
# ENH quadpy-optimize
import pathlib
from ...helpers import article
from .._helpers import _read, register
_source = article(
authors=["KyoungJoong Kim", "ManSuk Song"],
title="Symmetric quadrature formulas over a unit disk",
journal="Korean J. Comp. & Appl. Math.",
year="1997",
volume="4",
pa... | dir / "kim_song_07.js | on", _source)
# TODO find issue
def kim_song_8():
return _read(this_dir / "kim_song_08.json", _source)
def kim_song_9():
return _read(this_dir / "kim_song_09.json", _source)
def kim_song_10():
return _read(this_dir / "kim_song_10.json", _source)
def kim_song_11():
return _read(this_dir / "kim_so... |
"""
download a file named filename from the atsc301 downloads directory
and save it as a local file with the same name.
command line example::
python -m a301utils.a301_readfile photon_data.csv
module example::
from a301utils.a301_readfile import download
download('photon_data.csv')
"""
import a... | eption('Something is wrong, requests.get() failed with filename {}'.format(file | name))
for block in response.iter_content(1024):
if not block:
break
localfile.write(block)
the_size=temppath.stat().st_size
if the_size < 10.e3:
print('Warning -- your file is tiny (smaller than 10 Kbyte)\nDid something go wrong?')
shut... |
"""
Sensors of a KNX Device.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/knx/
"""
from enum import Enum
import logging
import voluptuous as vol
from homeassistant.const import (
CONF_NAME, CONF_MAXIMUM, CONF_MINIMUM,
CONF_TYPE, TEMP_CELSIUS
... | ant.components.knx import (KNXConfig, KNXGroupAddress)
from homeassistant.components.sensor import PLATFORM_SCHEMA
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['knx']
DEFAULT_NAME = "KNX sensor"
CONF_TEMPERATURE = 'temperature'
CONF_ADDRESS = 'address'
C... | FLOAT = 1
PERCENT = 2
# define the fixed settings required for each sensor type
FIXED_SETTINGS_MAP = {
# Temperature as defined in KNX Standard 3.10 - 9.001 DPT_Value_Temp
CONF_TEMPERATURE: {
'unit': TEMP_CELSIUS,
'default_minimum': -273,
'default_maximum': 670760,
'addres... |
if program_exists('brew') and 'jobber ' in \
sp_check_output(['brew', 'services']):
self._servicectl = BrewServiceCtl()
elif program_exists('launchctl'):
self._servicectl = LaunchctlServiceCtl()
else:
raise Exception("Cannot determine how to control Jo... | log += f.read()
except Exception as e:
log += "[{0}]".format(e)
# get config file
log += "\nConfig:\n"
try:
with open(_CONFIG_PATH) as f:
tmp = f.read()
if len(tmp) == 0:
log += "[empty]"
... | g += "[{0}]".format(e)
print(log)
def make_jobfile(self, job_name, cmd, time="*", \
notify_on_error=False, notify_on_success=False,
notify_output_path=None, file_run_log_path=None,
stdout_output_dir=None, stdout_output_max_age=None,
... |
s:
# - DNS
# - Record Set (uses DNS SDK)
# - Azure Graph
def legacy_credentials(self, scope):
# Track 2 SDKs use tuple
token = self.get_token((scope + '.default'))
return BasicTokenAuthentication(token={'access_token': token.token})
@property
def tenant_id(self):
... | authorization_file=self.authorization_file,
subscription_id_overri | de=self.subscription_id_override)
except Exception as e:
if hasattr(e, 'message'):
log.error(e.message)
else:
log.exception("Failed to authenticate.")
sys.exit(1)
if self.credentials is None:
log.error('Failed to authentica... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Matt Martz <matt@sivel.net>
#
# 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, ... | LES = '''
# Case insensitve password string match
- expect:
command: passwd username
responses:
(?i)password: "MySekretPa$$word"
# Generic question with multiple different responses
- expect:
command: /path/to/custom/command
responses:
Question:
- response1
- response2
... | mportError:
HAS_PEXPECT = False
from ansible.module_utils._text import to_text
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
def response_closure(module, question, responses):
resp_gen = (u'%s\n' % to_text(r).rstrip(u'\n') for r in responses)
... |
of forces/torques must be constructed, where each entry in the list
is a (Point, Vector) or (ReferenceFrame, Vector) tuple, where the Vectors
represent the Force or Torque.
Next a particle needs to be created, and it needs to have a point and mass
assigned to it.
Finally, a list of all bodies and p... | ere must be an equal number of dependent '
'speeds and constraints.')
if diffconeqs != None:
if len(udep) != len(diffconeqs):
raise ValueError('There must be an equal number of dependent '
| 'speeds and constraints.')
if len(udep) != 0:
u = self._u
uzero = dict(zip(u, [0] * len(u)))
coneqs = Matrix(coneqs)
udot = self._udot
udotzero = dict(zip(udot, [0] * len(udot)))
self._udep = udep
self._f_nh... |
tions or test_expectations.NEEDS_REBASELINE in expectations or test_expectations.NEEDS_MANUAL_REBASELINE in expectations
def _test_is_slow(self, test_file):
return test_expectations.SLOW in self._expectations.model().get_expectations(test_file)
def needs_servers(self, test_names):
return any(s... | s")
self._look_for_new_crash_logs(initial_results, start_time)
for retry_attempt_results in all_retry_results:
self._look_for_new_crash_logs(retry_attempt_results, start_time)
_log.debug("summarizing results")
summarized_full_results = test_run_results.summarize_resul | ts(
self._port, self._expectations, initial_results, all_retry_results,
enabled_pixel_tests_in_retry)
summarized_failing_results = test_run_results.summarize_results(
self._port, self._expectations, initial_results, all_retry_results,
enabled_pixel_tests_in_retry,... |
puts
self.internally_connectable = internally_connectable
self.multi_type = multi_type
self.i2c = i2c
self.frontend_id = frontend_id
self.__is_empty = is_empty
self.compatible = {
None: (None,),
"DVB-S": ("DVB-S", None),
"DVB-C": ("DVB-C", None),
"DVB-T": ("DVB-T", None),
"DVB-S2": ("DV... | "DVB-S2": ("DVB-S", "DVB-S2"),
"DVB-C2": ("DVB-C", "DVB-C2"),
"DVB-T2": ("DVB-T", "DVB-T2"),
"ATSC": ("ATSC"),
}
return connectable[self.getType()]
def getSlotName(self):
# get a friendly description for a slot name.
# we name them "Tuner A/B/C/...", because that's what's usually written on the... | lf):
return chr(ord('A') + self.slot)
def getI2C(self):
return self.i2c
def hasOutputs(self):
return self.has_outputs
def internallyConnectableTo(self):
return self.internally_connectable
def setInternalLink(self):
if self.internally_connectable is not None:
print "setting internal link on frontend... |
p(paths, "font_directory", text="")
sub.prop(paths, "texture_directory", text="")
sub.prop(paths, "render_output_directory", text="")
sub.prop(paths, "script_directory", text="")
sub.prop(paths, "sound_directory", text="")
sub.prop(paths, "temporary_directory", text="")
s... | , "use_tabs_as_spaces")
| colsplit = col.split(percentage=0.95)
col1 = colsplit.split(percentage=0.3)
sub = col1.column()
sub.label(text="Author:")
sub = col1.column()
sub.prop(system, "author", text="")
class USERPREF_MT_ndof_settings(Menu):
# accessed from the window key-bindings in C (only)
... |
import htt | pbenchmark
from unuk.benchmarks.base import r | untests
|
_compile_destruct(compiler, code, left, exp)
else:
# print " MATCH ASSIGN"
scope = _current_scope(compiler)
idx = scope.what_next_temporary()
exp_node = nodes.create_temporary_node(nodes.node_token(node), idx)
match = nodes.create_match_node(nodes.node_token(node), exp, [node... | node, cases, error.Errors.FUNCTION_MATCH_ERROR)
current_scope = _current_scope(compiler)
scope = current_scope.finalize(_previous_scope(compiler), None)
_exit_scope(compiler)
compiled_code = funccode.finalize_co | mpilation(scope)
source = space.newfuncsource(funcname, compiled_code)
source_index = _declare_literal(compiler, source)
code.emit_1(FUNCTION, source_index, info(node))
def is_simple_pattern(pattern, allow_unit):
ntype = node_type(pattern)
if ntype == NT_TUPLE:
for child in node_first(pat... |
# -*- coding: utf-8 -*-
###################################################################
# This widget will display the next appointment on your calendar in
# the qtile status bar. Appointments within the "reminder" time will be
# highlighted. Authentication credentials are stored on disk.
#
# This widget uses the k... | or of the YahooWeather widget (dmpayton). This code
# borrows liberally from that one.
#
# Copyright (c) 2016 by David R. Andersen <k | 0rx@RXcomm.net>
# New khal output format adjustment, 2016 Christoph Lassner
# Licensed under the Gnu Public License
#
# 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, incl... |
from unittest import mock
from bgmi.downloader.aria2_rpc import Aria2DownloadRPC
_token = "token:2333"
@mock.patch("bgmi.config.ARIA2_RPC_URL", "https://u | uu")
@mock.patch("bgmi.config.ARIA2_RPC_TOKEN", "token:t")
def test_use_config():
with mock.patch("xmlrpc.client.ServerProxy") as m1:
m1.return_value.aria2.getVersion.return_value = {"version": "1.19.1"}
Aria2DownloadRPC()
m1.assert_has_calls(
[
mock.call("https:/... | 2.getVersion("token:t"),
]
)
|
ng: iso-8859-1 -*-
"""
MoinMoin - Text CAPTCHAs
This is just asking some (admin configured) questions and
checking if the answer is as expected. It is up to the wiki
admin to setup questions that a bot can not easily answer, but
humans can. It is recommended to setup SITE SPECIFIC questions
... | werkzeug.security import safe_str_cmp as safe_str_equal
from MoinMoin.support.python_compatibility | import hmac_new
SHA1_LEN = 40 # length of hexdigest
TIMESTAMP_LEN = 10 # length of timestamp
class TextCha(object):
""" Text CAPTCHA support """
def __init__(self, request, question=None):
""" Initialize the TextCha.
@param request: the request object
@param ques... |
# sqlalchemy/__init__.py
# Copyright (C) 2005-2019 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from . import util as _util # noqa
from .inspection import inspect # noqa
f... | .types import BigInteger # noqa
from .types import BINARY # noqa
from .types import Binary # noqa
from .types import BLOB # noqa
from .types import BOOLEAN # noqa
from .types import Boolean # noqa
from .types import CHAR # noqa
from .types import CLOB # noqa
from .types import DATE # noqa
from .types import Da... | a
from .types import FLOAT # noqa
from .types import Float # noqa
from .types import INT # noqa
from .types import INTEGER # noqa
from .types import Integer # noqa
from .types import Interval # noqa
from .types import JSON # noqa
from .types import LargeBinary # noqa
from .types import NCHAR # noqa
from .types... |
from django.contrib im | port admin
# Register your models | here.
from .models import Engine
admin.site.register(Engine) |
from __future__ import absolute_import
import itertools
from django.contrib import messages
from django.core.context_processors import csrf
from django.db import transaction
from django.http import HttpResponseRedirect
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf... | prefix='project-%s' % (project.id,)
))
for project in sorted(project_list, key=lambda x: (
x.organization.name, x.name))
]
ext_forms = []
for plugin in plugins.all():
for form in safe_execute(plugin.get_notification_forms, _with_transaction... | form = safe_execute(form, plugin, request.user, request.POST or None, prefix=plugin.slug,
_with_transaction=False)
if not form:
continue
ext_forms.append(form)
if request.POST:
all_forms = list(itertoo... |
impor | t tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.bui | ld_model( ['Anscombe'] , ['MovingMedian'] , ['Seasonal_Minute'] , ['LSTM'] ); |
, either version 3 of the License, or (at your option) any later
# version.
#
# satpy is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You s... | "Test base class | with writing a fake file."""
def setUp(self) -> None:
"""Set up the test case."""
test_data = np.ones(NUMBER_OF_SCANS, dtype=dtype)
# Channel 3a
test_data["id"]["id"][:5] = 891
# Channel 3b
test_data["id"]["id"][5:] = 890
with NamedTemporaryFile(mode='w+', s... |
from __future__ import with_statement
import os
from setuptools import setup
# Do not update the version manually - it is managed by `bumpversion`.
version = '2.0.1rc'
setup(
name='pydocstyle',
v | ersion=version,
description="Python docstring style checker",
long_description=open('README.rst').read(), |
license='MIT',
author='Amir Rachum',
author_email='amir@rachum.com',
url='https://github.com/PyCQA/pydocstyle/',
classifiers=[
'Intended Audience :: Developers',
'Environment :: Console',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
... |
fr | om funtests import transport
class test_redis(transport.TransportCase):
transport = "redis"
prefix = "redis"
def after_connect(self, connection):
client = connection.channel().client
client.info()
def test_cant_connect_raises_connection_error(self):
conn = self.get_connection... | ct)
|
from copy import deepcopy, copy
from django.contrib import admin
from django.contrib.admin.views.main import ChangeList
from django.contrib.contenttypes.admin import GenericTabularInline, GenericStackedInline
from django.forms import ModelForm, NumberInput
from django.db import models
class SortableModelAdminBase(obj... | iginal_list_display
self.list_editable = self._original_list_editable
self.exclude = self._original_exclude
self.list_per_page = self._ori | ginal_list_per_page
def sortable_is_enabled(self):
return self.list_display and self.sortable in self.list_display
def save_model(self, request, obj, form, change):
if not obj.pk:
max_order = obj.__class__.objects.aggregate(
models.Max(self.sortable))
tr... |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the | "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distribute | d 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.
# =============================================================================
"""If possible, exports all symbols wit... |
from cyclone.web import asynchronous
from sockjs.cyclone import proto
from sockjs.cyclone.transports import streamingbase
# HTMLFILE template
HTMLFILE_HEAD = r'''
<!doctype html>
<html><head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8... | rite(msg) |
self.flush()
# Close connection based on amount of data transferred
if self.should_finish(len(msg)):
self._detach()
self.safe_finish()
|
l_membership:
group: read_only
target_roles:
- alice
- bob
state: present
# you can also use target_roles: alice,bob,etc to pass the role list
- name: Revoke role read_only and exec_func from bob. Ignore if roles don't exist
postgresql_membership:
groups:
- read_only
- exec_func
... | ct(type='str'),
)
| module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True,
)
if not HAS_PSYCOPG2:
module.fail_json(msg=missing_required_lib('psycopg2'))
groups = module.params['groups']
target_roles = module.params['target_roles']
fail_on_role = module.params['fail_... |
import os
from setuptools import setup
from setuptools import find_packages
version_file = 'VERSION.txt'
version = open(version_file).read().strip()
description_file = 'README.txt'
description = open(description_file).read().split('\n\n')[0].strip()
description = description.replace('\n', ' ')
l | ong_ | description_file = os.path.join('doc', 'README.txt')
long_description = open(long_description_file).read().strip()
setup(
name='ximenez',
version=version,
packages=find_packages('src'),
namespace_packages=(),
package_dir={'': 'src'},
include_package_data=True,
zip_safe=False,
entry_po... |
import os
from twisted.trial import unittest
from scrapy.contrib.djangoitem import DjangoItem, Field
from scrapy import optional_features
os.environ['DJANGO_SETTINGS_MODULE'] = 'scrapy.tests.test_djangoitem.settings'
if 'django' in optional_features:
from .models import Person, IdentifiedPerson
class BasePe... | t(i.errors), set(['age', 'name']))
i = BasePersonItem(name='John')
self.assertTrue(i.is_valid(exclude=['age']))
self.ass | ertEqual({}, i.errors)
# once the item is validated, it does not validate again
i['name'] = long_name
self.assertTrue(i.is_valid())
def test_override_validation(self):
i = OverrideFieldPersonItem()
i['name'] = 'John'
self.assertFalse(i.is_valid())
i = i = O... |
"""
Module for the Colorado Alliance of Research Libraries Metadata 2013
Presentation
Copyright (C) 2013 Jeremy Nelson
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the Licens... | y-2013/mods-to-bibframe.html")
def mods_to_bibframe():
return template | ('mods-bibframe',
category='slides',
next_slide=SLIDES[4],
slide=SLIDES[3],
slides=SLIDES)
@route("/metadata-day-2013/resources.html")
def resources():
return template('resources',
category='hom... |
import numpy as np
from esdl.cube_provider import CubeSourceProvider
from esdl.cube_config import CubeConfig
class TestCubeSourceProvider(CubeSourceProvider):
"""
CubeSourceProvider implementation used for testing cube generation without any source files.
The following usage generates a cube with two var... | loat32,
'fill_value': np.nan,
'scale_factor': 1.0,
'add_offset': 0.0,
}
}
def compute_variable_images(self, period_start, period_end):
self._value += 0.1
image_width = self.cube_config.grid_width
image_height = self.cube_co... | lf._variable_name: np.full(image_shape, self._value, dtype=np.float32)
}
def close(self):
pass
|
# Copyright 2021 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 agreed to in writing, s... | type="text/css"
href="https://ztzhang.info/assets/css/datatable.css">
</link>
<script>
$(document).ready(function () {{
var table = $('#myTable').DataTable({{
dom: 'Blfrtip',
autoWidth: false,
buttons: [
'columnsTog... | ,
"className": "dt-center"}}
],
"drawCallback": function( settings ) {{
$("#myTable img:visible").unveil();
}},
}});
}});
</script>
</head>
<body bgcolor='black'>
<table id="myTable" class="cell-border compact stripe">... |
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_KEY = '#zw#k0g76&a!ulj820of0+i#y(-y4%)sed3k-3q9mw8kzn7)jf'
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contentty... | DERS = ( |
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static/'),
)
|
ill be sharpen [ 0.05048273 0.13588945 0.81362782]\n
temperature = 1.0, the distribution will be the same [0.1 0.2 0.7]\n
temperature = 1.5, the distribution will be filtered [ 0.16008435 0.25411807 0.58579758]\n
If None, it will be ``np.argmax(a)``
Notes
------
No... | ne, if None, non end word will be appended.
Returns
---------
A list of strings; the processed caption.
Examples
-----------
>>> c = "how are you?"
>>> c = tl.nlp.process_sentence(c)
>>> print(c)
... ['<S>', 'how', 'are', 'you', '?', '</S>']
"""
try:
import nltk
... | int : NLTK is required.")
if start_word is not None:
process_sentence = [start_word]
else:
process_sentence = []
process_sentence.extend(nltk.tokenize.word_tokenize(sentence.lower()))
if end_word is not None:
process_sentence.append(end_word)
return process_sentence
def crea... |
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-usuario',
version='0.4',
... | :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
' | License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4... |
from dj | angothis.app import read_yaml, read_yaml_file, watchfil | e
|
#!/usr/bin/env python
from pythran import tables
TITLE = "Supported Modules and Functions"
DEPTHS = '=*-+:~#.^"`'
print(DEPTHS[0]*len(TITLE))
print(TITLE)
print(DEPTHS[0]*len(TITLE))
print("")
def format_name(name):
if name.endswith('_') and not name.startswith('_'):
name = name[:-1]
return name
... | s, sub_entries = [], []
for sym in entry_value:
w = sub_entries if isiterable(entry_value[sym]) else sym_entries
w.append(sym)
for k in sorted(sym_entries):
dump_entry(format_name(k), entry_value[k], depth + 1)
print("")
| for k in sorted(sub_entries):
dump_entry(format_name(k), entry_value[k], depth + 1)
print("")
else:
print(entry_name)
for MODULE in sorted(tables.MODULES):
if MODULE != '__dispatch__':
dump_entry(format_name(MODULE), tables.MODULES[MODULE], 1)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-11-02 21:54
from __future__ import unicode_literals
from decimal import Decimal
from django.db import migrations, models
class Migration(mi | grations.Migration):
dependencies = [
('round', '0013_plot_batch'),
]
operations = [
migrations.AlterField(
model_name='round',
name='score',
field=models.D | ecimalField(decimal_places=2, default=Decimal('0'), max_digits=4),
),
]
|
from django.test.testcases import TestCase
from django.utils import timezone
from edc_visit_schedule.site_visit_schedules import site_visit_schedules
from edc_visit_tracking.constants import SCHEDULED
from ba_namotswe.models import Appointment, SubjectVisit, RequisitionMetadata, CrfMetadata, SubjectConsent, Registere... | s."""
# EnrollmentFactory(dob=date(1900, 1, 1))
def test_subject_identifier(self):
"""Assert enrollment subject_identifier is updated after consent is created."""
enrollment = | EnrollmentFactory()
self.assertIsNotNone(enrollment.subject_identifier)
SubjectConsent.objects.get(subject_identifier=enrollment.subject_identifier)
RegisteredSubject.objects.get(subject_identifier=enrollment.subject_identifier)
def test_subject_consent_attrs(self):
"""Assert attrs ... |
"""nushellx_lpt/metafitter_abs.py
Function definitions for an abstract *.lpt metafitter
"""
from __future__ import print_function, division, unicode_literals
import numpy as np
from deprecated.int.metafitter_abs import single_particle_metafit_int
from constants import DPATH_SHELL_RESULTS, DPATH_PLOTS
from deprecated.... | list=exp_list, exp_filter_fn=exp_filter_fn,
dpath_sources=_sourcedir, dpath_plots=_savedir,
transform=transform,
xlabel=xlabel, ylabel=ylabel,
show_fit=show_fit,
_data_map=_data_map, _get_data=_get_data, _get_plots=_get_plots,
| _get_plot=_get_plot, _plot_sort_key=_plot_sort_key,
_title=_title, _label=_label, _idx=_idx,
print_results=_print_results,
_get_label_fmt_kwargs=_get_label_fmt_kwargs,
_code_pref=_code_pref,
**kwargs)
|
om django.http import HttpResponse
import os
from config.views import get_dir
from django.contrib.auth.decorators import login_required
from accounts.permission import permission_verify
import logging
from lib.log import log
from lib.setup import get_playbook, get_roles
# var info
ansible_dir = get_dir("a_path")
roles... | up/result.html', locals())
@login_required()
@permission_verify()
def ansible_command(request):
command_list = []
ret = []
count = 1
temp_name = "setup/setup-header.html"
if request.method == 'POST' | :
mcommand = request.POST.get('mcommand')
command_list = mcommand.split('\n')
for command in command_list:
if command.startswith("ansible"):
p = Popen(command, stdout=PIPE, stderr=PIPE,shell=True)
data = p.communicate()
ret.append(data)... |
#!/usr/bin/env python
# coding: utf-8
from .src import *
def plugin_loaded():
distraction | less.plugin_loaded(reload=Fa | lse)
def plugin_unloaded():
distractionless.plugin_unloaded()
|
o One ", acc_role=pyatspi.ROLE_RADIO_BUTTON))
sequence.append(utils.AssertPresentationAction(
"7. Move to Radio One radio button",
["BRAILLE LINE: 'SwingSet2 Application SwingSet2 Frame RootPane LayeredPane Button Demo TabList Button Demo Page Radio Buttons TabList Radio Buttons Page Image Radio Buttons Panel ... | 3000))
sequence.append(utils.AssertPresentationAction(
"12. Basic Where Am I",
["BRAILLE LINE: 'SwingSet2 Application SwingSet2 Frame RootPane LayeredPane Button Demo TabList Button Demo Page Radio Buttons TabList Radio Buttons Page Image Radio Buttons Panel Image Radio Buttons & y Radio Two RadioButton'",
... | "SPEECH OUTPUT: 'Image Radio Buttons Radio Two radio button not selected 2 of 3'"]))
########################################################################
# Expected output when radio button is selected.
#
sequence.append(utils.StartRecordingAction())
sequence.append(TypeAction(" "))
sequence.append(WaitA... |
nditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer. Redistributions in binary
# form must reproduce the above copyright notice, this list of conditions and
# the following disclaimer in the documentation and/or othe... | NCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#************************************************** | ****************************
import scipy.linalg.interpolative as pymatrixid
import numpy as np
from scipy.linalg import hilbert, svdvals, norm
from scipy.sparse.linalg import aslinearoperator
from scipy.linalg.interpolative import interp_decomp
import itertools
from numpy.testing import (assert_, assert_allclose, as... |
import os
from datetime import timedelta
BROKER_URL = os.environ['CELERY_BROKER_URL']
CELERY_IMPORTS = ('app.cabotapp.tasks', )
CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler"
CELERY_TASK_SERIALIZER = "json" |
CELERY_ACCEPT_CONTENT = ['json', 'msgpack', 'yaml']
CELERYBEAT_SCHEDULE = {
'run-all-checks': {
'task': 'app.cabotapp.tasks.run_all_checks',
'schedule': timedelta(seconds=60),
},
'update-shifts': {
'task | ': 'app.cabotapp.tasks.update_shifts',
'schedule': timedelta(seconds=1800),
},
'clean-db': {
'task': 'app.cabotapp.tasks.clean_db',
'schedule': timedelta(seconds=60*60*24),
},
}
CELERY_TIMEZONE = 'UTC'
|
import unittest
import mock
import SMBSR
import xs_errors
import XenAPI
import vhdutil
import util
import errno
class FakeSMBSR(SMBSR.SMBSR):
uuid = None
sr_ref = None
mountpoint = None
linkpath = None
path = None
session = None
remoteserver = None
def __init__(self, srcmd, none):
... | _checkmount):
smbsr = self.create_smbsr()
mock_checkmount = mock.Mock(return_value=True)
smbsr.attach('asr_uuid')
self.assertTrue(smbsr.attached)
#Detach
@mock.patch('SMBSR.SMBSR.unmount')
def test_detach_smbexception_raises_xenerror(self,mock_unmount):
smbsr = se | lf.create_smbsr()
mock_unmount = mock.Mock(side_effect=SMBSR.SMBException("unmount raised SMBException"))
try:
smbsr.detach('asr_uuid')
except Exception, exc:
self.assertTrue(isinstance(exc,xs_errors.XenError))
@mock.patch('SMBSR.SMBSR.checkmount',return_value=False)... |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the... | rench_number(int(list[1]))
cents_number = int(list[1])
cents_name = (cents_number > 1) and | ' Cents' or ' Cent'
final_result = start_word +' '+units_name+' '+ end_word +' '+cents_name
return final_result
#-------------------------------------------------------------
# Dutch
#-------------------------------------------------------------
to_19_nl = ( 'Nul', 'Een', 'Twee', 'Drie', 'Vier', 'Vijf',... |
# -*- coding:utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from django.utils.text import slugify
from django.contrib.auth.models import User
ROOM_TYPE = (
(1, u'Privado'),
(2, u'Grupo'),
)
class Room(models.Model):
name = models.TextField(... | return self.label
class Message | (models.Model):
room = models.ForeignKey(Room, verbose_name=u'Sala', related_name='messages')
handle = models.ForeignKey(User, verbose_name=u'Usuário', related_name='message_user')
message = models.TextField()
timestamp = models.DateTimeField(default=timezone.now, db_index=True)
def __unicode__(sel... |
"""
Import all modules and packages in the serverFeatures package
['account', 'connection', 'interface', 'package', 'process']
"""
from pycaf.architecture.devices. | server import Server
from pycaf.architecture.devices.lists.serverList import ServerList
from pycaf.architecture.devices.server_windows import ServerWindows
import pycaf.architecture.devices.server_features.lists
| |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from multiplexer.clients import connect_client
from obci.control.peer.peer_control import PeerControl, ConfigNotReadyError
import obci.control.common.config_message as cmsg
from obci.utils.openbci_logging import get_logger, log_crash
import sys
class ConfiguredClient(object)... | "config_params" : self._param_vals(),
"peer_id": self.config.peer_id,
"experiment_uuid": self.get_param("experiment_uuid")
}
def _crash_extra_tags(self, exception=None):
return {'ob | ci_part' : 'obci',
"experiment_uuid": self.get_param("experiment_uuid")} |
# -*- coding: utf-8 -*-
# scrapy_web
# Copyright (C) 2016-2017 Matteo.Redaelli@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# ... | S FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# usage:
# scrapy crawl auto-doc.it | -t jsonlines -o data/a.json
import scrapy
import re
class AutoDocIt(scrapy.Spider):
name = "auto-doc.it"
def __init__(self, width="195", height="65", diameter="15", *args, **kwargs):
super(AutoDocIt, self).__init__(*args, **kwargs)
self.allowed_domains = ["auto-doc.it"]
#self.star... |
# mammon - utility/third-party stuff, each thing has it's own header and provenance
# information.
# CaseInsensitiveDict from requests.
#
# Copyright 2015 Kenneth Reitz
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may... | f validate_chan(chan_name):
if chan_name[0] != '#':
| return False
badchars = chan_name[1:].translate(chan_allowed_chars_tbl)
return badchars == ''
def uniq(input):
output = []
for x in input:
if x not in output:
output.append(x)
return output
class UserHost:
def __init__(self, nuh):
self.nuh = nuh
# XXX - put tr... |
"""
To create an Attribute Editor template using python, do the following:
1. create a subclass of `uitypes.AETemplate`
2. set its ``_nodeType`` class attribute to the name of the desired node type, or name the class using the
convention ``AE<nodeType>Template``
3. import the module
AETemplates which do not meet o... | )
ui.AETemplate.addControl(self, control, label=label, **kwargs)
def beginLayout(self, name, collapse=True):
name = self._applyLocalization(name)
ui.AETemplate.beginLayout(self, name, collapse=collapse)
class mmbTemplateBase(LocalizedTemplate):
def __init__(self, nodeName):
Lo... | ame):
mel.AEswatchDisplay(nodeName)
|
flags={}):
url_get_metadata = 'http://api.bilibili.com/view?'
url_get_comment = 'http://comment.bilibili.com/%(cid)s.xml'
if source == 'overseas':
url_get_media = 'http://interface.bilibili.com/v_cdn_play?'
else:
url_get_media = 'http://interface.bilibili.com/playurl?'
def parse_ur... | s-', suffix='.ass', delete=False)
logging.info('Invoking Danmaku2ASS, converting to %s' % comment_out.name)
d2a_args = dict({'stage_width': video_size[0], 'stage_height': video_size[1], 'font_face': 'SimHei', 'font_size': math.ceil(video_size[1]/21.6), 'text_opacity': 0.8, 'duration_marquee': min(max(6.... | , **d2aflags)
for i, j in ((('stage_width', 'stage_height', 'reserve_blank'), int), (('font_size', 'text_opacity', 'comment_duration', 'duration_still', 'duration_marquee'), float)):
for k in i:
if k in d2aflags:
d2a_args[k] = j(d2aflags[k])
try:
... |
#!/usr/bin/env python
# coding=UTF-8
__author__ = "Pierre-Yves Langlois"
__copyright__ = "https://github.com/pylangl | ois/uwsa/blob/master/LICENCE"
__credits__ = ["Pierre-Yves Langlois"]
__license__ = "BSD"
__maintainer__ = "Pierre-Yves Langlois"
from uwsas.common import *
from uwsas.commands.abstract_command import AbstractCommand
class CommandManager(AbstractCommand):
NAME = 'CommandManager'
def __init__(self):
... | ef get_log_name(self):
return 'uwsas'
cmanager = CommandManager()
|
deos", category , "Aventura","http://www.nolomires.com/category/peliculas-de-aventura/","","")
xbmctools.addnewfolder( __channel__ ,"listvideos", category , "Bèlico Guerra ","http://www.nolomires.com/category/peliculas-de-guerra/","","")
xbmctools.addnewfolder( __channel__ ,"listvideos", category , "Ciencia-Fic... | om/category/documentales-online-completos/","","")
xbmctools.addnewfolder( __channel__ ,"listvideos", category , "Drama","http://www.nolomires.com/category/peliculas-de-drama/","","")
xbmctools.addnewfolder( __channel__ ,"listvideos", category , "Entretenimiento","http://www.nolomires.com/category/entretenimien... | tegory , "Estrenos","http://www.nolomires.com/category/ultimos-extrenos/","","")
xbmctools.addnewfolder( __channel__ ,"listvideos", category , "General","http://www.nolomires.com/category/general/","","")
xbmctools.addnewfolder( __channel__ ,"listvideos", category , "Intriga","http://www.nolomires.com/category/... |
""""""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable, Dict
if TYPE_CHECKING:
from .extension import Admin
class AdminPanel:
"""Base classe for admin panels.
Currently this class does nothing. It may be useful in the future
either as just a marker interface (for ... | _additional_rules(self, add_url_rule: Callable):
"""This method can be redefined in subclasses to install custom url
rules.
All rules are relative to panel 'base' rule, don't prefix rules with panel
id, it will be done by `add_url_rule`.
:param add_url_rule: function to use to ... | k.blueprint.Blueprint.add_url_rule`.
"""
|
set=1, playcards=7)
shallHighlightMatch = Game._shallHighlightMatch_SS
# ************************************************************************
# * Legion
# ************************************************************************
class Legion(Klondike):
def createGame(self):
Klondike.createGame(s... | ds() # deal first card to WasteStack
# register the game
registerGame(GameInfo(2, Klondike, "Klondike",
GI.GT_KLONDI | KE, 1, -1, GI.SL_BALANCED,
altnames=("Classic Solitaire", "American Patience")))
registerGame(GameInfo(61, CasinoKlondike, "Casino Klondike",
GI.GT_KLONDIKE | GI.GT_SCORE, 1, 2, GI.SL_BALANCED))
registerGame(GameInfo(129, VegasKlondike, "Vegas Klondike",
... |
env=self.env,
logEnviron=self.logEnviron,
timeout=self.timeout,
collectStdout=collectStdout,
colle... | ntry.getAttribute('path')
if filename in keep_on_purge or filename == '':
continue
yield filename
@defer.inlineCallb | acks
def removeFiles(self, files):
for filename in files:
res = yield self.runRmdir(filename, abandonOnFailure=False, timeout=self.timeout)
if res:
return res
return 0
@defer.inlineCallbacks
def checkSvn(self):
cmd = remotecommand.RemoteShellC... |
# Copyright 2017 IBM Corp.
from zvmconnector import connector
import os
import time
print("Setup client: client=connector.ZVMConnector('9.60.18.170', 8080)\n")
client=connector.ZVMConnector('9.60.18.170', 8080)
print("Test: send_request('vswitch_get_list')")
list = client.send_request('vswitch_get_list')
print("Resu... | power_state', '%s')" % GUEST_USERID)
info = client.send_request('guest_get_power_state', GUEST_USERID)
print('Result: %s\n' % info)
print("Start guest: send_request('guest_start', '%s')" % GUEST_US | ERID)
info = client.send_request('guest_start', GUEST_USERID)
print('Result: %s\n' % info)
print("Check power state: send_request('guest_get_power_state', '%s')" % GUEST_USERID)
info = client.send_request('guest_get_power_state', GUEST_USERID)
print('Result: %s\n' % info)
print("Get user direct: send_request('guest_g... |
subprocess.check_output(command, shell=True).strip().split("\n")
except subprocess.CalledProcessError:
pass
def check_boot():
if 'onboot' not in sys.argv:
return
init_dir = os.getenv('INIT_DIR', '/etc/init')
systemd_dir = os.getenv('SYSTEMD_DIR', '/etc/systemd/system')
nginx_dir = ... | f.write("ExecStart={0} selfdestruct\n".format(os.path.abspath(__file__)))
f.write("\n")
f.write("[Install]\n")
f.write("WantedBy=multi-user.target\ | n")
f.write("WantedBy=graphical.target\n")
if os.path.exists(nginx_dir):
with open('{0}/dokku-installer.conf'.format(nginx_dir), 'w') as f:
f.write("upstream dokku-installer { server 127.0.0.1:2000; }\n")
f.write("server {\n")
f.write(" listen 80;\n")
... |
ure non-file pa | ths are detected."""
os.environ[b'MOZCONFIG'] = gettempdir()
with self. | assertRaises(MozconfigFindException) as e:
self.get_loader().find_mozconfig()
self.assertIn('refers to a non-file', e.exception.message)
self.assertTrue(e.exception.message.endswith(gettempdir()))
def test_find_default_files(self):
"""Ensure default paths are used when present.... |
", "--copt=-fpic", "--linkopt=-znoexecstack",
"--linkopt=-zrelro", "--linkopt=-znow", "--linkopt=-fstack-protector"
]
class IntelPlatform(object):
min_gcc_major_version_ = 0
min_gcc_minor_version_ = 0
host_gcc_major_version_ = 0
host_gcc_minor_version_ = 0
BAZEL_PREFIX_ = "--copt="
ARCH_PREFIX_ = "-ma... | than the gcc version in which
# the new march flag became available.
# Specify the version in which the new name usage began
def use_old_arch_names(self, gcc_new_march_major_version,
gcc_new_march_minor_version):
if self.host_gcc_major_vers | ion_ < gcc_new_march_major_version:
return True
elif self.host_gcc_major_version_ == gcc_new_march_major_version and \
self.host_gcc_minor_version_ < gcc_new_march_minor_version:
return True
return False
class NehalemPlatform(IntelPlatform):
def __init__(self):
IntelPlatform.__init__... |
#!/usr/bin/env python
'''
Copyright (C) 2005 Aaron Spike, aaron@ekips.org
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Thi... | help="Randomly move nodes and handles within this radius, X")
self.OptionParser.add_option("-y", "--radiusy",
action="store", type="float",
dest="radiusy", default=10.0,
help="Randomly move nodes and handles within this ra... | Parser.add_option("-c", "--ctrl",
action="store", type="inkbool",
dest="ctrl", default=True,
help="Randomize control points")
self.OptionParser.add_option("-e", "--end",
action="store", type="inkbool",
... |
# Problem name: 12148 Electricity
# Problem url: https://uva.onlinejudge.org/external/121/12148.pdf
# Author: Andrey Yemelyanov
import sys
import math
import datetime
def readline():
return sys.stdin.readline().strip()
def main():
while True:
| n_readings = int(readline())
if n_readings == 0:
break
meter_re | adings = []
for i in range(n_readings):
reading = [int(x) for x in readline().split()]
date = datetime.date(reading[2], reading[1], reading[0])
consumption = reading[3]
meter_readings.append((date, consumption))
c = get_daily_consumption(meter_readings)
... |
import os
import sys
from django.core.management import setup_environ
thisdir = os.path.dirname(os.path.abspath(__file__))
appdir = os.path.realpath(os.path.join(thisdir, '..', '..', '..', 'lot'))
sys.path.append(appdir)
import settings
setup_environ(settings)
##############################
import pandas as pd
from dj... | t)
if __name__ == "__main__":
# This guy matches condition 1332 almost exactly
stand_list = [
# species, sizeclass, tpa
('Douglas-fir', 6, 160),
('Douglas-fir', 10, 31),
('Douglas-fir', 14, 7),
('Western hemlock', 14, 5),
#('West... | filter_stand_list(stand_list, )
|
last_request is None:
self.last_request = now
leak_value = now - self.last_request
self.water_level -= leak_value
self.water_level = max(self.water_level, 0)
self.water_level += self.request_value
difference = self.water_level - self.capacity
self.last_req... | it
unit = unit.upper()
if unit not in utils.TIME_UNITS:
raise ValueError("Invalid units specified")
unit = utils.TIME_UNITS[unit]
# Build a limit
| result.append(Limit(verb, uri, regex, value, unit))
return result
class WsgiLimiter(object):
"""Rate-limit checking from a WSGI application. Uses an in-memory
`Limiter`.
To use, POST ``/<username>`` with JSON data such as::
{
"verb" : GET,
"path" : "/servers... |
from celery.exceptions import Ignore
from django.urls import reverse
from oioioi.base.tests import TestCase
from oioioi.contests.models import Contest, ProblemInstance, Submission
from oioioi.evalmgr.tasks import create_environ
from oioioi.programs.controllers import ProgrammingContestController
from oioioi.suspendjud... | ),
env['recipe'],
)
self.assertIn(
(
'check_problem_instance_state',
'oioioi.suspendjudge.handlers.check_problem_instance_state',
),
env['recipe'],
)
def test_handler(self):
problem_instance = Proble... | em_instance)
env = {
'problem_instance_id': problem_instance.id,
'job_id': 'dummy',
'celery_task_id': 'dummy',
'submission_id': 1,
'is_rejudge': False,
'report_kinds': ['INITIAL', 'NORMAL'],
}
with self.assertRaises(Ignore):... |
# -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# ... | if not ancre:
return
if not ancre.jetee:
yield SignalInutile("l'ancre est déjà levée")
else:
ancre.lever(personnage)
i = 0
while "ancre" in p | ersonnage.etats:
i += 1
if i > 100:
yield SignalAbandonne("J'ai essayé trop longtemps.")
elif personnage.stats.endurance < 40:
yield SignalRelais("Je suis trop fatigué.")
else:
yield 2
... |
# coding=utf-8
# Copyright 2019 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 License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | = tagging.EditingTask(input_texts)
converter = tagging_converter.TaggingConverter(phrase_v | ocabulary)
tags = converter.compute_tags(task, target)
self.assertEqual(tags_to_str(tags), tags_to_str(target_tags))
def test_no_match(self):
input_texts = ['Turing was born in 1912 .', 'Turing died in 1954 .']
target = 'Turing was born in 1912 and died in 1954 .'
task = tagging.EditingTask(input... |
ntum, float,
msg='Beam: momentum is not a float')
self.assertIsInstance(self.beam.mean_dt, float,
msg='Beam: mean_dt is not a float')
self.assertIsInstance(self.beam.mean_dE, float,
msg='Beam: mean_dE is not a floa... | nal_tracker = RingAndRFTracker(self.rf_params, self.beam)
full_tracker = FullRingAndRF([longitudinal_tracker])
try:
matched_from_distribution_function(self.beam,
full_tracker,
| distribution_exponent=1.5,
distribution_type='binomial',
bunch_length=1.65e-9,
bunch_length_fit='fwhm',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.