prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
import json
import logging
import socket
from contextlib import closing
from django.core.exceptions import ValidationError
from django.db import connection
from zeroconf import get_all_addresses
from zeroconf import NonUniqueNameException
from zeroconf import ServiceInfo
from zeroconf import USE_IP_OF_OUTGOING_INTERFA... | )
SERVICE_TYPE = "Kolibri._sub._http._tcp.local."
LOCAL_DOMAIN = "kolibri.local"
ZEROCONF_STATE = {"zerocon | f": None, "listener": None, "service": None}
def _id_from_name(name):
assert name.endswith(SERVICE_TYPE), (
"Invalid service name; must end with '%s'" % SERVICE_TYPE
)
return name.replace(SERVICE_TYPE, "").strip(".")
def _is_port_open(host, port, timeout=1):
with closing(socket.socket(socket... |
# encoding: utf-8
#
#
# This Source Code Form is su | bject 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/.
#
# Contact: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __ | future__ import absolute_import, division, unicode_literals
from jx_base.expressions import BetweenOp as BetweenOp_
class BetweenOp(BetweenOp_):
pass
|
import json
from copy import copy
from collections import OrderedDict
# SSE "protocol" is described here: http://mzl.la/UPFyxY
class ServerSentEvent(object):
def __init__(self, data=None, event=None, retry=None, id=None):
if data is None and event is None:
raise ValueError('data and event can... | str):
pass
else:
items['data'] = json.dumps(items['data'])
return items
def __iter__(self):
if self.retry:
yield 'retry', self.retry
yield 'data', self.data
if self.event:
yield 'event', self.event
if self.id:
... | ['{}: {}'.format(k, v) for k, v in self.format().items()]
))
def __repr__(self):
return '<ServerSentEvent event="{}">'.format(self.event if self.event else '')
|
__author__ = 'a.paoletti'
import maya.cmds as cmd
import os
import sys
sys.path.append("C://Users//a.paoletti//Desktop//MY//CORSOSCRIPTING - DISPLACE_GEOTIFF//gdalwin32-1.6//bin")
import colorsys
def getTexture():
"""
:rtype : String
:return : Nome della texture applicata al canale color del lambert... | ys.exit(1)
# get image size
rows = ds.RasterYSize
cols = ds.RasterXSize
bands = ds.RasterCount
# get georeference info
transform = ds.GetGeoTransform()
xOrigin = transform[0]
yOrigin = transform[3]
pixelWidth = transform[1]
pixelHeight = transform[5]
# loop through the coordinates
for xVal... | e
y = yValue
# compute pixel offset
xOffset = int((x - xOrigin) / pixelWidth)
yOffset = int((y - yOrigin) / pixelHeight)
# create a string to print out
s = "%s %s %s %s " % (x, y, xOffset, yOffset)
# loop through the bands
for i in xrange(1, bands):
band = ds.GetRasterBand(i) # 1-based ... |
from satchless.item import InsufficientStock, StockedItem
from datetime import date
from django.utils.text import slugify
from django.core.urlresolvers import reverse
from django.utils import timezone
from django.db import models
from django_prices.models import PriceField
from django.core.exceptions import Validation... | tract class that embodies everything that can be sold."""
price = PriceField('Price',
currency='EUR',
max_digits=5,
decimal_places=2,
blank=False,
default=0.0)
stock = models.PositiveSmallIntegerFi... | ate added')
last_modified = models.DateTimeField('Last modified')
slug = models.SlugField('Product slug', max_length=256)
def get_price_per_item(self):
return price
class Meta:
abstract = True
class TournamentProductUtilitiesManager(models.Manager):
def create_tournament_product(... |
# Copyright 2015 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http | ://www | .apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# ... |
"""
Manages a Beaker cache of WMS capabilities documents.
@author: rwilkinson
"""
import logging
from beaker.cache import CacheManager
from beaker.util import parse_cache_config_options
from joj.lib.wmc_util import GetWebMapCapabilities
log = logging.getLogger(__name__)
class WmsCapabilityCache():
""" Manages a... | __doGet():
"""Makes request for capabilities.
"""
log.debu | g("WMS capabilities not found in cache for %s" % search_param)
return GetWebMapCapabilities(search_param)
search_param = wmsurl
if forceRefresh:
self.cache.remove_value(key = search_param)
log.debug("Looking for WMS capabilities in cache for %s" %... |
items = [1, 2, 3, 4, 5]
squared = []
for i in items:
squared.append(i**2)
print(squared)
squared = []
squared = list(map(lambda x: x**2, items))
| print(squared)
def multiply(x):
return (x*x)
def add(x):
return (x+x)
funcs = [multiply, add]
for i in range(5):
value = map(lambda x:x(i), funcs)
print(list(value))
number_list = range(-5, 5)
less_than_zero = filter(lambda x: x < 0, number_list)
print(list(less_than_zero))
from functools import red... | oduct) |
from nose.tools import with_setup, eq_ as eq
f | rom common import vim, cleanup
from threading import Timer
@with_setup(setup=cleanup)
def test_interrupt_from_another_thread():
session = vim.session
timer = Timer(0.5, lambda: session.threadsafe_call(lambda: session.stop()))
timer.start()
| eq(vim.session.next_message(), None)
|
m_abspath].metadata = dict(module_metadata)
def _CollectAllowedImportsFromBuildMetadata(build_metadata_filename):
allowed_imports = set()
processed_deps = set()
def collect(metadata_filename):
processed_deps.add(metadata_filename)
with open(metadata_filename) as f:
metadata = json.load(f)
a... | # into a module below; however it's also a dependency of another input
# module. We retain record of dependencies to help with input
# processing later.
input_dependencies[mojom_abspath].add(
(import_abspath, imp.import_filename))
elif import_abspath not in loaded_modules:... | e file sitting in a corresponding output
# location.
module_path = _GetModuleFilename(imp.import_filename)
module_abspath = _ResolveRelativeImportPath(
module_path, module_root_paths + [output_root_path])
with open(module_abspath, 'rb') as module_file:
loaded_module... |
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from functools import wr | aps
TRANSIENT_USER_TYPES = []
def is_transient_user(user):
return isinstance(user, tuple(TRANSIENT_USER_TYPES))
def prevent_access_to_transient_users(view_func):
def _wrapped_view(request, *args, **kwargs):
'''Test if the user is transient'''
for user_type in TRANSIENT_USER_TYPES:
... | w_func)(_wrapped_view))
def to_list(func):
@wraps(func)
def f(*args, **kwargs):
return list(func(*args, **kwargs))
return f
|
Callable, Iterable, List, MutableMapping, Optional,
Protocol, Sequence, Tuple, TypeVar, Union,
)
import xml.etree.ElementTree
from pip._vendor.requests import Response
from pip._internal.network.session import PipSession
HTMLElement = xml.etree.ElementTree.Element
ResponseHeader... | base"):
href = base.get("href")
if href is not None:
return href
| return page_url
def _clean_url_path_part(part):
# type: (str) -> str
"""
Clean a "part" of a URL path (i.e. after splitting on "@" characters).
"""
# We unquote prior to quoting to make sure nothing is double quoted.
return urllib_parse.quote(urllib_parse.unquote(part))
def _clean_file_url... |
import json
import sys
import logging
import logging.handlers
def load_config():
'''Loads application configuration from a JSON file'''
try:
json_data = open('config.json')
config = json.load(json_data)
json_data.close()
return config
except Exception:
print """T... | logger = logging.getLogger('clouddump')
log_file_handler = logging.handlers.RotatingFileHandler(
file_name, maxBytes = 10**9)
log_format = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
log_file_handler.setFormatter(log_format)
logger.addHandler(log_file_handler)
lo... | :
if sys.argv[1] == '-v' or sys.argv[1] == '--verbose':
console = logging.StreamHandler()
console.setLevel(logging.INFO)
logger.addHandler(console) |
# -*- coding: utf-8 -*-
#
# RERO ILS
# Copyright (C) 2020 RERO
# Copyright (C) 2020 UCLouvain
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# This program ... | t']['can']
assert data['update']['can']
# 'delete' should be true but return false because an event is linked
# assert not | data['delete']['can']
res = client.get(pttr_sion_permission_url)
assert res.status_code == 200
data = get_json(res)
assert not data['read']['can']
assert data['list']['can']
assert not data['update']['can']
assert not data['delete']['can']
# Logged as system librarian
# * sys_lib... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from . import SearchBa... | r] = getattr(module, _search_class)(server)
except AttributeError:
logging.warning("Search backend '%s'. No search class "
"'%s' defined." % (server, _search_class))
except ImportError:
logging.warnin... | import '%s'" %
(server, _module))
def search(self, unit):
if not self._servers:
return []
results = []
counter = {}
for server in self._servers:
for result in self._servers[server].search(unit):
translatio... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# This file is part of Androwarn.
#
# Copyright (C) 2012, 2019, Thomas Debize <tdebize at mail.com>
# All rights reserved.
#
# Androwarn is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
#... | , or
# (at your option) any later version.
#
# Androwarn is distribu | ted 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Androwa... |
import requests
import warnings
warnings.warn('\n\n\n**** data.session_client will be deprecated in the next py2cytoscape release. ****\n\n\n')
class Sess | ionClient(object):
def __init__(self, url):
self.__url = url + 'session'
def delete(self):
requests.delete(self.__url)
def save(self, file_name=None):
if file_name is None:
raise ValueError('Session file name is required.')
post_url = self.__url
params... | open(self, file_name=None):
if file_name is None:
raise ValueError('Session file name is required.')
get_url = self.__url
params = {'file': file_name}
res = requests.get(get_url, params=params)
return res
|
import os
import unittest
from mi.core.log import get_logger
from mi.dataset.dataset_driver import ParticleDataHandler
from mi.dataset.driver.ctdbp_p.dcl.resource import RESOURCE_PATH
from mi.dataset.driver.flord_g.ctdbp_p.dcl.flord_g_ctdbp_p_dcl_recovered_driver import parse
_author__ = 'jeff roy'
log = get_logger()... | particle_data_handler = ParticleDataHandler()
particle_data_handler = parse(None, source_file_path, particle_data_handler)
log.debug("SAMPLES: %s", particle_data_handler._samples)
log.debug("FAILURE: %s", particle_data_handler._failure)
self.assertEquals(particle_data_handler | ._failure, False)
if __name__ == '__main__':
test = DriverTest('test_one')
test.test_one()
|
from setting import MATCH_TYPE_JC,MATCH_TYPE_M14
#url_m14_fmt = "http://www.okooo.com/livecenter/zucai/?mf=ToTo&date=15077" |
#url_jc_fmt = "http://www.okooo.com/livecenter/jingcai/?date=2015-05-26"
url_jc_fmt = "http://www.okooo.com/livecenter/jingcai/?date={0}"
url_m14_fmt = "http://www.okooo.com/livecenter/zucai/?mf=ToTo&date={0}"
#url_jc_odds_change = "http://www.okooo.com/soccer/match/736957/odds/change/2/"
url_jc_odds_change_fmt = "htt... | tr)
def get_url_m14(sid):
return url_jc_m14.format(sid)
def get_url_odds_change(okooo_id,bookmaker_id=2):
return url_jc_odds_change_fmt.format(okooo_id,bookmaker_id)
OKOOO_BOOKMAKER_DATA = {
"jingcai":2,
}
|
from django.contrib import messages
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.http import Http404
from django.http import HttpResponseForbidden
from django.http import HttpResponseRedirect, JsonResponse
from django.shortcuts import render
from wye.base... | presenter=self.user, status=WorkshopStatus.COMPLETED)
for workshop in workshops:
feedback = WorkshopFeedBack.objects.filter(
workshop=workshop, feedback_type=FeedbackType.PRESENTER
).count()
if feedback == 0:
self.feedback_required.append(... | TED)
for workshop in workshops:
feedback = WorkshopFeedBack.objects.filter(
workshop=workshop, feedback_type=FeedbackType.ORGANISATION
).count()
if feedback == 0:
self.feedback_required.append(workshop)
def return_response(self, request):... |
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('form_processor', '0025_caseforms_server_date'),
]
operations = [
migrations.CreateModel(
name='CaseTransaction',
fields=[
('id', models.AutoField(ver... | eld(choices=[(0, 'form'), (1, 'rebuild')])),
('case', models.ForeignKey(related_query_name='xform', related_name='xform_set', db_column='case_uuid', to_field='case_uuid', to='form_processor.CommCareCaseSQL', db_index=False, on_delete=models.CASCADE)),
],
options={
... | ['server_date'],
},
bases=(models.Model,),
),
migrations.AlterUniqueTogether(
name='caseforms',
unique_together=None,
),
migrations.RemoveField(
model_name='caseforms',
name='case',
),
migrations.Del... |
# This script only works for OCLC UDEV reports created after December 31, 2015
import csv
import datetime
import re
import requests
import sys
import time
from lxml import html
user_date = raw_input('Enter report month and year (mm/yyyy) or year only (yyyy): ')
if len(user_date) == 7: # For running a report for a si... | ate
index_link = url + index_link
r = requests.get(index_link)
doc = html.fromstring(r.text)
page_links = doc.xpath('//a/@href') #Get report links on each dated report page
for page_link in page_links:
| page_link = index_link + '/' + page_link
report_links.append(page_link)
oclc_symbol = ['HHG'] #List of OCLC symbols to match in records; separate codes with commas; put '' in list to retrieve all OCLC symbols
output_data = []
for report_link in report_links: #Process each report
report_dat... |
"""Tests for Openstack cloud volumes"""
import fauxfactory
import pytest
from cfme.cloud.provider.openstack import OpenStackProvider
from cfme.utils.appliance.implementations.ui import navigate_to
from cfme.utils.blockers import BZ
from cfme.utils.log import logger
pytestmark = [
pytest.mark.usefixtures("setup_... | cope='function')
def volume(appliance, provider):
collection = appliance.collections.volumes
storage_manager = '{} Cinder Manager'.format(provider.name)
volume = collection.create(name=fauxfactory.gen_alpha(),
storage_manager=storage_manager,
ten... | rovider.data['provisioning']['cloud_tenant'],
size=VOLUME_SIZE,
provider=provider)
yield volume
try:
if volume.exists:
volume.delete(wait=False)
except Exception:
logger.warning('Exception during volume deletion - ski... |
2),
}
prior = {
"mu": np.random.randn(nchains, ndraws) / 2,
"tau": abs(np.random.randn(nchains, ndraws)) / 2,
"eta": np.random.randn(nchains, ndraws, ndim1, ndim2) / 2,
"theta": np.random.randn(nchains, ndraws, ndim1, ndim2) / 2,
}
prior_predictive = {"y": np.rand... | was not found in ``posterior``
as it was expected, however, in the other two cases, the preceding ``~`` (kept from the
input negation notation) indicates that ``observed_data`` group should not be present
but was found in the InferenceData and that ``log_likelihood`` variable was found
in ``sample_... | attributes in test_dict.items():
if dataset_name.startswith("~"):
if hasattr(parent, dataset_name[1:]):
failed_attrs.append(dataset_name)
elif hasattr(parent, dataset_name):
dataset = getattr(parent, dataset_name)
for attribute in attributes:
... |
# | pragma error
#pragma repy
removefile("this.file.does.not.exist") # should fail (FN | F)
|
9f4c432bf1c1775f3dc9da'
# 加密UID
def encryptUID(id):
return key + str(id)
# 解密SID
def decryptUID(uStr):
return int(uStr.split('a')[1])
# 获取cookies
def getCookie(name):
ck = web.cookies()
if ck.get(name):
return ck.get(name)
else:
return None
# 创建会话
def genSession(SID,Username,Show... | LastLocation = getData['location']
| if not ShowName:
ShowName = Username
if Status == 'yes':
# 符合登录要求,登录数据写入session,创建会话
genSession(SID,Username,ShowName,LastIP,LastLocation,LastDate,False,Lstat='ok',kpl=getPost.kpl)
#HTTP_REFERER = getCookie('HTTP_REFERER')
#if ... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.obj | ect import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/wearables/ithorian/shared_ith_bandolier_s08.iff"
result.attribute_template_id = 11
result.stfName("wearables_name","ith_bandolier_s08")
#### BEGIN MODIFICATIONS ####
#### END MODI | FICATIONS ####
return result |
class Solution:
def pushDominoesSim(self, dominoes: str) -> str:
prev, curr, N = None, ["."] + list(dominoes) + ["."], len(dominoes)
while prev != curr:
prev = curr[:]
i = 1
while i <= N:
if curr[i] == "." and prev[i - 1] == "R" and prev[i + 1] != ... | osl = float("Inf")
else:
distl[i] = min(distl[i], posl - i)
if distl[i] < distr[i]:
d[i] = "L"
elif distr[i] < distl[i]:
d[i] = "R"
return "".join(d[1:-1])
# TESTS
for dominoes, expected in [
("RR.L", "RR.L... | , "...."),
("R...", "RRRR"),
("....L", "LLLLL"),
]:
sol = Solution()
actual = sol.pushDominoes(dominoes)
print("Final domino state of", dominoes, "->", actual)
assert actual == expected
|
import numpy as np
from scipy.misc import imrotate
from ImFEATbox.__helperCommands import conv2float
from scipy.stats import skew, kurtosis
def SVDF(I, returnShape=False):
"""
Input: - I: A 2D image
Output: - Out: A (1x780) vector containing 780 metrics calculated
from singular... | ttps://github.com/annikaliebgott/ImFEATbox
#
# Contact: an | nika.liebgott@iss.uni-stuttgart.de
# ************************************************************************
if returnShape:
return (780,1)
## Calculate Singular Value Decomposition of the image
# convert image to float
I = conv2float(I)
I = I.T
# initialize feature variables
... |
import sys
import re
from Bio import Seq,SeqIO
iname=sys.argv[1]
cdr3p=re.compile("(TT[TC]|TA[CT])(TT[CT]|TA[TC]|CA[TC]|GT[AGCT]|TGG)(TG[TC])(([GA][AGCT])|TC)[AGCT]([ACGT]{3}){5,32}TGGG[G | CT][GCT]")
# Utility functions
def get_records(filename):
records=[]
for record in SeqIO.parse(filename,"fasta"):
records.append(record)
return records
records=get_records(iname)
numrecords=len(records)
results=[]
f | or i in range(numrecords):
r=records[i]
strseq=str(r.seq)
m=cdr3p.search(strseq)
if m!=None:
mspan=m.span()
result=strseq[mspan[0]:mspan[1]]
else:
result=""
results.append(result)
for i in range(numrecords):
r=records[i]
des=r.description
res=results[i]
if res!="":
print ">"+des+"\n... |
# the list of RGBA float values
self.ramp = []
# ordered array of color indices
self.keys = {}
# ready to use; boolean; we need at least two
# color points to define a ramp
self.ready = False
#
if 'handle' in kwargs:
self.handle = kwar... | pt):
"""
Returns a true index (horizontal potision) of a given point.
"""
if pt in self.canvas_ids:
return self.canvas_ids[pt]
return None
def getRampList(self):
"""
Returns a list of floats representing the color ramp.
"""
ramp_l... | ramp_list.append(float(x))
ramp_list.append(float(col[0]))
ramp_list.append(float(col[1]))
ramp_list.append(float(col[2]))
ramp_list.append(float(col[3]))
return ramp_list
def movePoint(self,pt,X,alpha):
if pt not in s... |
#!/usr/bin/python
############################################################
# Generates commands for the muscle alignment program
############################################################
import sys, os, core, argparse
############################################################
# Options
parser = argparse.Arg... | e + ".sh");
submit_file = os.path.join(cwd, "submit", "muscle_submit_" + name + ".sh");
logdir = os.path.join(args.output, "logs");
# Job files
##########################
# Reporting run-time info for records.
with open(output_file, "w") as outfile:
core.runTime("#!/bin/bash\n# MUSCLE command generator", outfile)... | PWS(core.spacedOut("# Input directory:", pad) + args.input, outfile);
if args.outname:
core.PWS(core.spacedOut("# --outname:", pad) + "Using end of output directory path as job name.", outfile);
if not args.name:
core.PWS("# -n not specified --> Generating random string for job name", outfile);
... |
eometry"]=s
s= marker_sets["particle_33 geometry"]
mark=s.place_marker((7057.62, 7493.13, 5358.24), (0.7, 0.7, 0.7), 673.585)
if "particle_34 geometry" not in marker_sets:
s=new_marker_set('particle_34 geometry')
marker_sets["particle_34 geometry"]=s
s= marker_sets["particle_34 geometry"]
mark=s.place_marker((7997.... | .7, 0.7), 869.434)
if "particle_65 geometry" not in marker_sets:
s=new_marker_set('particle_65 geometry')
marker_sets["particle_65 geometry"]=s
s= marker_sets["particle_65 geometry"]
mark=s.place_marker((-1226.96, 4387.94, 4009.78), (0.7, 0.7, 0.7), 818.463)
if "particle_66 geometry" not in marker_sets:
s=new_mar... | marker_sets["particle_66 geometry"]=s
s= marker_sets["particle_66 geometry"]
mark=s.place_marker((-1984.03, 5176.71, 5297.32), (0.7, 0.7, 0.7), 759.539)
if "particle_67 geometry" not in marker_sets:
s=new |
_ = 0
self.__page_ref__ = {}
HAR.log.__init__(self, {"version": "1.2",
"creator": {"name": "MITMPROXY HARExtractor",
"version": "0.1",
"comment": ""},
... | "httpVersion": response_http_version,
"cookies": response_cookies,
"headers": response_headers,
"content": {"size": response_body_size,
"comp... | ression,
"mimeType": response_mime_type},
"redirectURL": response_redirect_url,
"headersSize": response_headers_size,
"bodySize": response_body_size, },
... |
# -*- coding: utf-8 -*-
from module.plugins.internal.SimpleCrypter import SimpleCrypter
class CrockoComFolder(SimpleCrypter):
__name__ = "CrockoComFolder"
__type__ = "crypter"
__version__ = "0.06"
__status__ = "testing"
__pattern__ = r'ht | tp://(?:www\.)?crocko\.com/f/.+'
__config__ = [("activated", "bool", "Activated", True),
("use_premium", "bool", "Use premium account if available", True),
("folder_per_package", "Default;Yes;No",
"Create folder for | each package", "Default"),
("max_wait", "int", "Reconnect if waiting time is greater than minutes", 10)]
__description__ = """Crocko.com folder decrypter plugin"""
__license__ = "GPLv3"
__authors__ = [("zoidberg", "zoidberg@mujmail.cz")]
LINK_PATTERN = r'<td class="last"><a href="(.+... |
import numpy as np
import copy
import random
import deepchem
class TicTacToeEnvironment(deepchem.rl.Environment):
"""
Play tictactoe against a randomly acting opponent
"""
X = np.array([1.0, 0.0])
O = np.array([0.0, 1.0])
EMPTY = np.array([0.0, 0.0])
ILLEGAL_MOVE_PENALTY = -3.0
LOSS_PENALTY = -3.... | ent.O):
self._terminated = True
return TicTacToeEnvironment.LOSS_PENALTY
if self.game_over():
self._terminated = True
return TicTacToeEnvironment.DRAW_REWARD
return TicTacToeEnvironment.NOT_LOSS
def get_O_move(self):
empty_squares = []
for row in range(3):
for col in ra... | nner(self, player):
for i in range(3):
row = np.sum(self._state[0][i][:], axis=0)
if np.all(row == player * 3):
return True
col = np.sum(self._state[0][:][i], axis=0)
if np.all(col == player * 3):
return True
diag1 = self._state[0][0][0] + self._state[0][1][1] + self._st... |
078 = "lsisas1078"
VIRTIO_SCSI = "virtio-scsi"
VMPVSCSI = "vmpvscsi"
ALL = (BUSLOGIC, IBMVSCSI, LSILOGIC, LSISAS1068,
LSISAS1078, VIRTIO_SCSI, VMPVSCSI)
def __init__(self):
super(SCSIModel, self).__init__(
valid_values=SCSIModel.ALL)
def coerce(self, obj, attr, valu... | def __init__(self):
super(VIFModel, self).__init__(
valid_values=network_model.VIF_MODEL_ALL)
def _get_legacy(self, value):
return value
def coerce(self, obj, attr, value):
# Some compat for strings we'd see in the legacy
# hw_vif_model image property
valu... | e.lower()
value = VIFModel.LEGACY_VALUES.get(value, value)
return super(VIFModel, self).coerce(obj, attr, value)
class VMMode(Enum):
# TODO(berrange): move all constants out of 'nova.compute.vm_mode'
# into fields on this class
def __init__(self):
super(VMMode, self).__init__(
... |
# Copyright (c) 2014 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | self._validate_case(1, 0, 1, 1, 0, 1, 1)
cl = self._create_cluster(
1, 1, 1, 0, 3, 0, 0,
cluster_configs={'HDFS': {'dfs.replicat | ion': 4}})
with testtools.ExpectedException(ex.InvalidComponentCountException):
self.pl.validate(cl)
self.ng.append(tu.make_ng_dict("hi", "f1", ["hiveserver"], 0))
self.ng.append(tu.make_ng_dict("sh", "f1",
["spark history server"], 0))
... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'TtTrip.date'
db.add_column(u'timetable_tttrip', 'date',
... | u'timetable_tttrip', 'date')
models = {
u'timetable.ttstop': {
'Meta': {'ob | ject_name': 'TtStop'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'stop_id': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),
'stop_lat': ('django.db.models.fields.FloatField', [], {}),
'stop_lon': ('django.db.models.fiel... |
raw_y=0):
LTsv_Tkintercanvas_o.create_text(draw_x,draw_y,text=draw_t,font=LTsv_Tkintercanvas_font,anchor="nw",fill=LTsv_canvascolor,tag=LTsv_Tkintercanvas_TAG)
def LTsv_draw_text_shell(LTsv_GUI):
if LTsv_GUI == LTsv_GUI_GTK2: return LTsv_drawGTK_text
if LTsv_GUI == LTsv_GUI_Tkinter: return LTsv_drawTkinter... | Tsv_picturepath in LTsv_pictureOBJ:
LTsv_draw_picture_load(LTsv_picturepath)
picture_o=LT | sv_pictureOBJ[LTsv_picturepath]
if picture_o != None:
picture_divw,picture_divh=max(picture_divw,1),max(picture_divh,1)
picture_w=LTsv_libgdk.gdk_pixbuf_get_width(picture_o); cell_w=picture_w//picture_divw
picture_h=LTsv_libgdk.gdk_pixbuf_get_height(picture_o); cell_h=picture_h//picture_d... |
lues have a default; values that are commented out
# serve to show the default.
import sys
import os
from datetime import datetime
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
os.environ['SETUP_NORUN'] = '1'
import setup as setup_info # noqa
# The theme to use for HTML and HTML He... | n themes.
try:
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
except ImportError:
html_theme = 'default'
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the d... | os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') ... |
from nagm.engine.attack import Attack
from .types import *
from .defs import precision, stat, heal, offensive, faux_chage_effect
prec = precision(prec=0.9)
mimi_queue = Attack(name='Mimi-queue', type=normal, effects=(prec, stat(stat='dfse', value=-1),))
charge = Attack(name='Charge', type=normal, effects=(prec, offens... | (name='Flamèche', type=feu, effects=(prec, offensive(force=20),))
pistolet_a_o = Attack(name='Pistolet à o', t | ype=eau, effects=(prec, offensive(force=20),))
eclair = Attack(name='Éclair', type=electrik, effects=(prec, offensive(force=20),))
soin = Attack(name='Soin', type=normal, effects=(prec, heal(heal=50),), reflexive=True)
abime = Attack(name='Abîme', type=normal, effects=(precision(prec=0.1), offensive(force=1000),))
faux... |
# ScummVM - Graphic Adventure Engine
#
# ScummVM is the legal property of its developers, whose names
# are too numerous to list here. Please refer to the COPYRIGHT
# file distributed with this source distribution.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU ... | eval(text)
#print "if %s -> %s" %(text, value)
self.__stack.append(value)
def push_else(self):
#print "else"
self.__stack[-1] = not self.__stack[-1]
def pop_if(self):
#print "endif"
return self.__stack.pop()
def set_global(self, name, value):
if len(name) == 0:
raise Exception("empty name is not ... | fined", name)
self.__globals[name] = value
def get_global(self, name):
name = name.lower()
g = self.__globals[name]
g.used = True
return g
def get_globals(self):
return self.__globals
def has_global(self, name):
name = name.lower()
return self.__globals.has_key(name)
def set_offset(self, name, v... |
# -*- coding: utf-8 -*-
from django.db import models
from datetime import datetime
class Place(models.Model):
"""
Holder object for basic info about the rooms
in the university.
"""
room_place = models.CharField(max_length=255)
floor = models.IntegerField()
def __unicode__(self):
... | ilds(self):
return HierarchyUnit.objects.filter(parent=self)
def __unicode__(self):
return self.get_all_info_for_parents()
cla | ss Block(models.Model):
"""
Group representing a set of optional subjects.
Example: Core of Computer Science.
"""
name = models.CharField(max_length=255)
def __unicode__(self):
return self.name
class Subject(models.Model):
"""
Representation of all subjects.
Example: Calcu... |
from django import forms
from models import FormDataGroup
import re
# On this page, users can upload an xsd file from their laptop
# Then they get redirected to a page where they can download the xsd
class RegisterXForm(forms.Form):
file = forms.FileField()
form_display_name= forms.CharField(max_length=128, l... | forms.FileField()
class FormDataGroupForm(forms.ModelForm):
"""Fo | rm for basic form group data"""
display_name = forms.CharField(widget=forms.TextInput(attrs={'size':'80'}))
view_name = forms.CharField(widget=forms.TextInput(attrs={'size':'40'}))
def clean_view_name(self):
view_name = self.cleaned_data["view_name"]
if not re.match(r"^\w+$", view_name):
... |
################################# LICENSE ##################################
# Copyright (c) 2009, South African Astronomical Observatory (SAAO) #
# All rights reserved. #
# #
############... | 19 Jun 2011
"""
import os
import pyds9 as ds9
class ImageDisplay:
def __init__(self, target='ImageDisplay:*'):
self | .ds9 = ds9.ds9()
def display(self, filename, pa=None):
cmd='file %s' % filename
self.ds9.set(cmd)
self.ds9.set('zscale')
self.ds9.set('match frames wcs')
# print pa
if pa:
self.ds9.set('rotate to %f' % pa)
else:
self.ds9.set('rotate to %... |
# -*- coding: utf-8 -*-
# privacyIDEA is a fork of LinOTP
#
# 2014-12-07 Cornelius Kölbel <cornelius@privacyidea.org>
#
# Copyright (C) 2014 Cornelius Kölbel
# License: AGPLv3
#
# This code is free software; you can redistribute it and/or
# modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
# Licen... | ram challenge: The challenge to be found
:return: list of objects
"""
sql_query = Challenge.query
if serial is not None:
# filter for serial
sql_query = sql_query.filter(Challenge.serial == serial)
if transaction_id is not None:
# filter for transaction id
sql_query... | None:
# filter for this challenge
sql_query = sql_query.filter(Challenge.challenge == challenge)
challenges = sql_query.all()
return challenges
@log_with(log)
def get_challenges_paginate(serial=None, transaction_id=None,
sortby=Challenge.timestamp,
... |
'''
Created on Feb 26, 2014
@author: dstuart
'''
import LevelClass as L
import Util as U
class Region(object):
def __init__(self, **kwargs):
self.mapTiles = set()
self.name = None
self.worldMap = None
# TODO:
# worldMapId = Column(Integer, ForeignKey("levels.id"))
def a... |
self.creatures = set()
# Initialize self.hasTile
self.hasTile = []
for dummyx in range(self.width):
newCol = []
for dummyy in range(self.height):
newCol.append(False)
self.hasTile.append(newCol)
def load(self):
... | n self.mapTiles
def addTile(self, tile):
self.mapTiles.add(tile)
self.hasTile[tile.getX()][tile.getY()] = True
if tile.getLevel() is not self:
tile.setLevel(self)
def replaceTile(self, newtile):
oldtile = self.getTile(newtile.getX(), newtile.getY())
... |
by setting to negative value.
use_peephole: An optional `bool`. Defaults to `False`.
Whether to use peephole weights.
name: A name for the operation (optional).
Returns:
A tuple of `Tensor` objects (i, cs, f, o, ci, co, h).
i: A `Tensor`. Has the same type as `x`. The input gate.
cs: A `Ten... | t and bias matrices should be compatible as long as the
variable scope matches.
"""
def __init__(self,
num_units,
forget_bias=1.0,
cell_clip=None,
use_peephole=False,
| reuse=None,
name="lstm_cell"):
"""Initialize the basic LSTM cell.
Args:
num_units: int, The number of units in the LSTM cell.
forget_bias: float, The bias added to forget gates (see above).
cell_clip: An optional `float`. Defaults to `-1` (no clipping).
use_peep... |
class Base(object):
def meth(self):
pass
class Derived1(Base):
def meth(self):
return super().meth()
class Derived2(Derived1):
def meth(self):
return super().meth()
class Derived3(Derived1):
pass
class Derived4(Derived3, Derived2):
def meth(s | elf):
| return super().meth()
class Derived5(Derived1):
def meth(self):
return super().meth()
class Derived6(Derived5, Derived2):
def meth(self):
return super().meth()
|
import numpy as np
import unittest
import ray
from ray import tune
from ray.rllib import _register_all
MB = 1024 * 1024
@ray.remote(memory=100 * MB)
class Actor(object):
def __init__(self):
pass
def ping(self):
return "ok"
@ray.remote(object_store_memory=100 * MB)
class Actor2(object):
... | _failed_trial=False)
self.assertEqual(result.trials[0].status, "ERROR")
self.assertTrue(
| "RayOutOfMemoryError: Heap memory usage for ray_Rollout" in
result.trials[0].error_msg)
finally:
ray.shutdown()
def testTuneWorkerStoreLimit(self):
try:
_register_all()
self.assertRaisesRegexp(
ray.tune.error.TuneError,... |
dsn, host, username, password, database, driver = conn_key.split(":")
conn_str = ''
if dsn:
conn_str = 'DSN=%s;' % (dsn)
if driver:
conn_str += 'DRIVER={%s};' % (driver)
if host:
conn_str += 'Server=%s;' % (host)
if database:
co... | roc_check_guard(instance, guardSql)) or not guardSql:
self.open_db_connections(instance, self.DEFAULT_DB_KEY)
cursor = self.get_cursor(instance, self.DEFAULT_DB_KEY)
try:
cursor.callproc(proc)
rows = cursor.fetchall()
for row in rows:
... | ' else row.tags.split(',')
if row.type in self.proc_type_mapping:
self.proc_type_mapping[row.type](row.metric, row.value, tags)
else:
self.log.warning('%s is not a recognised type from procedure %s, metric %s'
... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
r_li_padcv.py
-------------
Date : February 2016
Copyright : (C) 2016 by Médéric Ribreux
Email : medspx at medspx dot fr
********************************... | **********************************************************************
"""
from __future__ import absolute_import
__author__ = 'Médéric Ribreux'
__date__ = 'February 2016' |
__copyright__ = '(C) 2016, Médéric Ribreux'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
from .r_li import checkMovingWindow, configFile
def checkParameterValuesBeforeExecuting(alg):
return checkMovingWindow(alg)
def processCommand(alg):
configFile(alg)... |
from setuptools import setup, find_packages
setup(
name='django-test-html-form',
version='0.1',
description="Make your Django HTML form tests more explicit and concise.",
long_description=open('README.rst').read(),
keywords='django test assert',
author='Dan Claudiu Pop',
author_email= | 'dancladiupop@gmail.com',
| url='https://github.com/danclaudiupop/assertHtmlForm',
license='BSD License',
packages=find_packages(),
include_package_data=True,
install_requires=[
'beautifulsoup4',
],
)
|
import datetime
from django.test import TestCase
from django.contrib.auth.models import User
from django_messages.models import Message
class SendTestCase(TestCase):
def setUp(self):
self.user1 = User.objects.create_user('user1', 'user1@example.com', '123456')
self.user2 = User.objects.create_user(... | Message(sender=self.user1, recipient=self.user2, subject='Subject Text 2', body='Body Text 2')
self.msg1.sender_deleted_at = datetime.date | time.now()
self.msg2.recipient_deleted_at = datetime.datetime.now()
self.msg1.save()
self.msg2.save()
def testBasic(self):
self.assertEquals(Message.objects.outbox_for(self.user1).count(), 1)
self.assertEquals(Message.objects.outbox_for(self.user1)[0].subject... |
* EPSG3395 : Rarely used by some commercial tile providers.
Uses Elliptical Mercator projection.
* Simple : A simple CRS that maps longitude and latitude into
x and y directly. May be used for maps of flat surfaces
(e.g. game maps). Note that the y axis should still be inverted
... | ey, and column 2 the values.
key_on: string, default None
Variable in the GeoJSON file to bind the data to. Must always
start with 'feature' and be in JavaScript objection notation.
Ex: 'feature.id' or 'feature.properties.statename'.
threshold_scale: list, default Non... | order-of-magnitude integer. Ex: 270 rounds to 200, 5600 to 6000.
fill_color: string, default 'blue'
Area fill color. Can pass a hex code, color name, or if you are
binding data, one of the following color brewer palettes:
'BuGn', 'BuPu', 'GnBu', 'OrRd', 'PuBu', 'PuBuGn', 'PuR... |
#!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the zapwallettxes functionality.
- start two iopd nodes
- create two transactions on node 0 - one... | es[0].gettransaction(txid2)['txid'], txid2)
# Stop-start node0. Both conf | irmed and unconfirmed transactions remain in the wallet.
self.stop_node(0)
self.start_node(0)
assert_equal(self.nodes[0].gettransaction(txid1)['txid'], txid1)
assert_equal(self.nodes[0].gettransaction(txid2)['txid'], txid2)
# Stop node0 and restart with zapwallettxes and persis... |
import | sys
import os
import shutil
def import_package(name):
_filepath = os.path.abspath(__file__)
path = backup = os.path.dirname(_filepath)
while os.path.basename(path) != name:
path = os.path.join(path, '..')
path = os.path.abspath(path)
if path != backup:
sys.path.insert(0, path)
... | ule
|
: None for standalone RBMs or symbolic variable pointing
to a shared hidden units bias vector in case RBM is part of a
different network
:param vbias: None for standalone RBMs or a symbolic variable
pointing to a shared visible units bias
"""
self.n_visible = n_visible
... |
W = theano.shared(value=initial_W, name='W', borrow=True)
if hbias is None:
# create shared variable for hidden units bias
hbias = theano.shared(value=numpy.zeros(n_hidden,
dtype=theano.config.floatX),
| name='hbias', borrow=True)
if vbias is None:
# create shared variable for visible units bias
vbias = theano.shared(value=numpy.zeros(n_visible,
dtype=theano.config.floatX),
... |
"" | "Provide common test tools for Z-Wave JS."""
AIR_TEMPERATURE_SENSOR = "sensor.multisensor_6_air_temperature"
HUMIDITY_SENSOR = "sensor.multisensor_6_humidity"
ENERGY_SENSOR = "sensor.smart_plug_with_two_usb_ports_value_electric_consumed_2"
POWER_SENSOR = "sensor.smart_plug_with_two_usb_ports_value_electric_consumed"
SW... | .z_wave_door_window_sensor_any"
DISABLED_LEGACY_BINARY_SENSOR = "binary_sensor.multisensor_6_any"
NOTIFICATION_MOTION_BINARY_SENSOR = (
"binary_sensor.multisensor_6_home_security_motion_detection"
)
NOTIFICATION_MOTION_SENSOR = "sensor.multisensor_6_home_security_motion_sensor_status"
PROPERTY_DOOR_STATUS_BINARY_SE... |
#! /usr/bin/env python
import sys
import PEAT_SA.Core as Core
import Protool
import itertools
def getPathSequence(combinations):
path = []
currentSet = set(combinations[0].split(','))
path.append(combinations[0])
for i in range(1, len(combinations)):
newSet = set(combinations[i].split(','))
newElement = newSe... | Name:
trimMatrix.addRow(row)
#Read in combination | s
combinationData = Core.Matrix.matrixFromCSVFile(sys.argv[1])
mutationCodes = combinationData.column(0)
combinations = codesToCombinations(mutationCodes)
print combinations
vitalities = combinationData.columnWithHeader(drugName+'Vitality')
fold = combinationData.columnWithHeader(drugName+'Fold')
pdb = Protool.struct... |
is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities and decorators for converting external types into the fqe
intrinsics
"""
#there are two... | t[1]:
opstr += str(element[0]) + '^ '
else:
opstr += str(element[0]) + ' '
newstr += FermionOperator(opstr, ops.terms[term])
return newstr
def split_openfermion_tensor(ops: 'FermionOperator'
) -> Tuple[Dict[int, 'FermionOp... | openfermion operators, split them according to their
rank.
Args:
ops (FermionOperator): a string of OpenFermion Fermion Operators
Returns:
split dict[int] = FermionOperator: a list of Fermion Operators sorted
according to their rank.
"""
e_0 = 0. + 0.j
split: Dict[... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | cs': {'required': True},
}
_attribute_map = {
'vm_diagnostics': {'key': 'vmDiagnostics', 'type': 'ContainerServiceVMDiagnostics'},
}
def __init__(self, vm_diagnostics):
super(ContainerServiceDiagnosticsProfile, sel | f).__init__()
self.vm_diagnostics = vm_diagnostics
|
.handler import FAMILY_NAME, OMI_ADDRESS_PREFIX, make_omi_address, _get_address_infix
from sawtooth_omi.handler import WORK, RECORDING, INDIVIDUAL, ORGANIZATION
from sawtooth_sdk.protobuf.batch_pb2 import Batch
from sawtooth_sdk.protobuf.batch_pb2 import BatchHeader
from sawtooth_sdk.protobuf.batch_pb2 import BatchLis... | er=batch_header_bytes,
header_signature=batch_signature_hex,
transactions=[txn],
)
batch_list = BatchList(batches=[batch])
batch_bytes = batch_list.SerializeToString()
batch_id = batch_signature_hex
url = "%s/batches" % base_url
headers = {
'Content-Type': 'application... | r.raise_for_status()
link = r.json()['link']
return BatchStatus(batch_id, link)
class BatchStatus:
"""
Provides a function to query for the current status of a submitted transaction.
That is, whether or not the transaction has been committed to the block chain.
"""
def __init__(self, ba... |
from .TestContainers | DeviceAndManager import TestContainerDeviceDataFlow
from .TestContainersReceivingSerialDataAndObserverPattern import TestContainersReceivingSerialDataAndObserverPattern | |
#===============================================================================
# Copyright (C) 2014-2019 Anton Vorobyov
#
# This file is part of Phobos.
#
# Phobos is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software ... | HANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Phobos. If not, see <http://www.gnu.org/licenses/>.
#============================================ | ===================================
from .cached_property import cachedproperty
from .eve_normalize import EveNormalizer
from .resource_browser import ResourceBrowser
from .translator import Translator
|
#!/usr/bin/env python
# Copyright (C) 2011 Rohan Jain
# Copyright (C) 2011 Alexis Le-Quoc
#
# 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
# (a... | rtError:
from distutils.core import setup
from sys import version
from os.path import expanduser
import paster
if version < '2.2.3':
from distutils.dist import DistributionMetadata
DistributionMetadata.classifiers = None
Distri | butionMetadata.download_url = None
setup(name='paster',
version=paster.version,
description='A generic pastebin posting tool',
author='Rohan Jain',
author_email='crodjer@gmail.com',
long_description=open('README.md').read(),
url='https://github.com/crodjer/paster',
packages = ... |
__author__ = 'Arunkumar Eli'
__email__ = "elrarun@gmail.com"
from selenium.webdriver.common.by import By
class DigitalOceanLocators(object):
ACCESS_KEY_INPUT = (By.ID, 'accessKey')
SECRET_KEY_INPUT = (By.ID, 'secretKey')
NEXT_BTN = (By.CSS_SELECTOR, "button.btn.btn-primary")
AVAILABILITY_ZONE = (By.XP... | v/span")
STD_RADIO_BTN=(By.XPATH,"//section[5]/div[1]/div[2]/div[2]/div[1]/label/input")
CUSTOM_RADIO_BTN=(By.XPATH,"//section[5]/div[1]/div[2]/div[2]/div[2]/label/input")
SET_INSTANCE_OPTION_BTN = (By.XPATH, "//div[2]/button")
SLIDE_BAR_CLICK_3 = (By.XPATH, "//div[2]/div[3]/div")
HOST_NAME_INPUT = ... | anceType")
HOST_MEM_SIZE_INPUT = (By.ID, "rootSize")
HOST_CREATE_BTN = (By.XPATH, "//div[2]/button")
|
#!/usr/bin/env python
"""
Script to fetch test status info from sqlit data base. Before use this
script, avocado We must be lanuch with '--journal' option.
"""
import os
import sys
import sqlite3
import argparse
from avocado.core import data_dir
from dateutil import parser as dateparser
def colour_result(result):
... | r = os.path.join(data_dir.get_logs_dir(), 'latest')
parser = argparse.ArgumentParser(description="Avocado journal dump tool")
parser.add_argument(
'-d',
| '--test-results-dir',
action='store',
default=default_results_dir,
dest='results_dir',
help="avocado test results dir, Default: %s" %
default_results_dir)
parser.add_argument(
'-s',
'--skip-timestamp',
action='store_true',
default=False,
... |
#!/usr/bin/python
import sys
import csv
import lxml.etree as ET
# This script creates a CSV file from an XCCDF file formatted in the
# structure of a STIG. This should enable its ingestion into VMS,
# as well as its comparison with VMS output.
xccdf_ns = "http://checklists.nist.gov/xccdf/1.1"
disa_cciuri = "http://... | ule" % xccdf_ns)
rulewriter = csv.writer( | sys.stdout, quoting=csv.QUOTE_ALL)
for rule in rules:
cci_refs = [ref.text for ref in rule.findall("{%s}ident[@system='%s']"
% (xccdf_ns, disa_cciuri))]
srg_refs = [ref.text for ref in rule.findall("{%s}ident[@system='%s']"
... |
if i > LINESIZE:
i = 0
t.write('\u200b')
return t.getvalue()
def output_visual(visual, path, indentstr, indentnum):
logger.debug('including image for %s', visual.source)
indent = tuple(indentstr * (indentnum + x) for x in range(3))
anchor = output_anchor(path)
return u""... | t = None
if difference.unified_diff:
ud_cont = HTMLSideBySidePresenter().output_unified_diff(
| ctx, difference.unified_diff, difference.has_internal_linenos)
udiff = next(ud_cont)
if isinstance(udiff, PartialString):
ud_cont = ud_cont.send
udiff = udiff.pformatl(PartialString.of(ud_cont))
else:
for _ in ud_cont:
pass # exhaust the i... |
# Uncomment to run this module directly. TODO comment out.
#import sys, os
#sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
# End of uncomment.
import unittest
import subprocess
import runserver
from flask import Flask, current_app, jsonify
from views import neo4j_driver
from views import my_patients
fr... | assert parsed_json['result'][i]['gender'] == 'F'
f | or pheno in parsed_json['result'][i]['phenotypes'] :
assert (pheno['name'] == 'Abnormality of the retina' or
pheno['name'] == 'Visual impairment' or
pheno['name'] == 'Macular dystrophy')
assert parsed_json['result'][i]['phenotypeS... |
"""
Course API Serializers. Representing course catalog data
"""
import urllib
from django.core.urlresolvers import reverse
from django.template import defaultfilters
from rest_framework import serializers
from lms.djangoapps.courseware.courses import course_image_url, get_course_about_section
from xmodule.course_... | eturn self.uri_parser(course)
class _CourseApiMediaCollectionSerializer(serializers.Serializer): # pylint: disable=abstract-method
"""
Nested serializer to represent a collection of media objects
"""
course_image = _MediaSerializer(source='*', uri_parser=course_image_url)
class CourseSerializer(ser... | Serializer for Course objects
"""
course_id = serializers.CharField(source='id', read_only=True)
name = serializers.CharField(source='display_name_with_default')
number = serializers.CharField(source='display_number_with_default')
org = serializers.CharField(source='display_org_with_default')
... |
er_bank_id.l10n_ch_isr_subscription_chf')
def _compute_l10n_ch_isr_subscription(self):
""" Computes the ISR subscription identifying your company or the bank that allows to generate ISR. And formats it accordingly"""
def _format_isr_subscription(isr_subscription):
#format the isr as per ... | id.name | == 'EUR':
isr_subscription = record.partner_bank_id.l10n_ch_isr_subscription_eur
elif record.currency_id.name == 'CHF':
isr_subscription = record.partner_bank_id.l10n_ch_isr_subscription_chf
else:
#we don't format if in another... |
from django.contrib import admin
from polls.models import Choice, Poll
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
class PollAdmin(admin.ModelAd | min):
fieldsets = [
(None, {'fields': ['question']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]
list_display = ('question','pub_date')
list_filter = ['pub_date']
search_fields = ['question']
date... | PollAdmin)
|
import json
import sys
import requests
from collections import Counter
from wapy.api import Wapy
from http.server import BaseHTTPRequestHandler, HTTPServer
wapy = Wapy('frt6ajvkqm4aexwjksrukrey')
def removes(yes):
no = ["Walmart.com", ".", ","]
for x in no:
yes = yes.replace(x, '')
return yes
def... | tion/json'}
r = requests.post("http://127.0.0.1:5000/search", data=json.dumps(dict), headers=headers)
return r.text
def parse_image(image):
out = json.loads(post_some_dict({"image_url": image}))['titles']
print(out)
#out = [x for x in out if 'walmart' in x]
threshold = len(out)-1
#out = [x[... | )
for word in line:
large.append(word)
#print(large)
c = Counter(large).most_common()
keywords = []
for x in c:
if x[1] > threshold:
keywords.append(x[0])
print(keywords)
return ' '.join(keywords)
def parse_wallmart(keywords):
products = wapy.search... |
s embedder has input character ids of size (batch_size, sequence_length, 50)
and returns (batch_size, sequence_length + 2, embedding_dim), where embedding_dim
is specified in the options file (typically 512).
We add special entries at the beginning and end of each sequence corresponding
to <S> and </S>... | ntext
insensitive token representations.
``'mask'``: ``torch.autograd.Variable``
Shape ``(batch_size, sequence_length | + 2)`` long tensor with sequence mask.
"""
# Add BOS/EOS
mask = ((inputs > 0).long().sum(dim=-1) > 0).long()
character_ids_with_bos_eos, mask_with_bos_eos = add_sentence_boundary_token_ids(
inputs,
mask,
self._beginning_of_sentence_characte... |
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | layLimit], spOutput[:(m+1)*displayLimit], w, m+1)
else:
print 'No more records to display'
pyl.show()
def drawFile(dataset, matrix, patterns, cells, w, fnum):
'''The similarity of two patterns in the bit-encoding space is displayed alongside
their similarity | in the sp-coinc space.'''
score=0
count = 0
assert len(patterns)==len(cells)
for p in xrange(len(patterns)-1):
matrix[p+1:,p] = [len(set(patterns[p]).intersection(set(q)))*100/w for q in patterns[p+1:]]
matrix[p,p+1:] = [len(set(cells[p]).intersection(set(r)))*5/2 for r in cells[p+1:]]
score +=... |
#
# HotC Server
# CTN2 Jackson
#
import socket
def _recv_data(conn):
data = conn.recv(1024)
command, _, arguments = data.partition(' ')
return command, arguments
def game(conn):
print 'success'
def login_loop(conn):
while True:
command, arguments = _recv_data(conn)... | urn
conn.send('login_failure')
elif command == 'register':
username, password = arguments.split()
# check if username already registered
with open('login.d', 'r') as f:
logins = eval(f.read())
for k, _ in logins.items()... |
logins[username] = password
with open('login.d', 'w') as f:
f.write(str(logins))
conn.send('register_success')
def main():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.... |
tine is in progress
self.attemptingToDetect = False
self.dbusDetectionTimer = None
self.dbusDetectionFailures = 0
# Set to True when sleep seems to be prevented from the perspective of the user.
# This does not necessarily mean that sleep really is prevented, because the
... | l languages use "s" for plural form.
def _m | concat(self, base, sep, app):
return (base + sep + app if base else app) if app else base
def _spokenConcat(self, ls):
and_str = _(" and ")
txt, n = '', len(ls)
for w in ls[0:n-1]:
txt = self._mconcat(txt, ', ', w)
return self._mconcat(txt, and_str, ls[n-1])
... |
orted')
input = numpy.asarray(input)
if numpy.iscomplexobj(input):
raise TypeError('Complex type not supported')
output, return_value = _ni_support._get_output(output, input)
if order not in [0, 1] and input.ndim > 0:
for axis in range(input.ndim):
spline_filter1d(input, orde... | he input if
``mode='constant'``. Default is 0.0
prefilter : bool, optional
The parameter prefilter determines if the input is pre-filtered with
`spline_filter` before interpolati | on (necessary for spline
interpolation of order > 1). If False, it is assumed that the input is
already filtered. Default is True.
extra_arguments : tuple, optional
Extra arguments passed to `mapping`.
extra_keywords : dict, optional
Extra keywords passed to `mapping`.
Retu... |
import pygame
from PacManMap import *
class MakeGraph:
def __init__(self):
self.shortest_path_from_one_to_other = {}
self.nod | es = self.find_nodes()
def get_shortest_path(self):
return self.shortest_path_from_one_to_other
def get_nodes(self):
return self.nodes
def find_nodes(self):
nodes = []
for row_n in range(1, len(Map) - 1):
for col_n in range(2, len(Map[0]) - 1):
if (Map[row_n][col_n] != 0 and Map[row_n][col_n + 1] ... | (row_n < len(Map[0]) - 2 and Map[row_n + 1][col_n] != 0)):
nodes.append((row_n, col_n))
Map[row_n][col_n] = 3
Map1 = list(zip(*Map))
for row_n in range(1, len(Map1) - 1):
for col_n in range(2, len(Map1[0]) - 1):
if (Map1[row_n][col_n] != 0 and Map1[row_n][col_n + 1] != 0 and
Map1[row_n][co... |
def cyclegesture2():
##for x in range(5):
welcome()
sleep(1)
relax()
sleep(2)
fingerright()
sleep(1)
isitaball()
sleep(2)
removeleftarm()
sleep(2)
handdown()
sleep(1)
fullspeed() |
i01.giving()
sleep(5)
removeleftarm()
sleep(4)
takeball()
sleep(1)
surrender()
sleep(6)
isitaball()
sleep(6)
dropit()
sleep(2)
removeleftarm()
sleep(5)
relax()
| sleep()
fullspeed()
sleep(5)
madeby()
relax()
sleep(5)
i01.disable()
|
import os
from setuptools import setup, find_packages
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
from watermarker import __version__
setup(
name='django-waterm... | ense='BSD License',
description="Quick and efficient way to apply watermarks to images in Django.",
long_description=README,
keywords='django, watermark, image, photo, logo',
url='http://g | ithub.com/bashu/django-watermark/',
author='Josh VanderLinden',
author_email='codekoala@gmail.com',
maintainer='Basil Shubin',
maintainer_email='basil.shubin@gmail.com',
install_requires=[
'django>=1.4',
'django-appconf',
'pillow',
'six',
],
classifiers=[
... |
# Copyright (c) 2015-2020 Contributors as noted in the AUTHORS file
#
# 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/.
# System imports
import json
import logging
import... | __, self).name, with_caller=False)
f = super(self.__class__, self).name
self._name = f()
return self._name
def uuid(self):
if self._uuid is None:
# f = w_spy_call(sup | er(self.__class__, self).uuid, with_caller=False)
f = super(self.__class__, self).uuid
self._uuid = f()
return self._uuid
|
been restored correctly.
beta1=1.0, beta2=1.0)
on_create_root = checkpointable_utils.Checkpoint(
optimizer=on_create_optimizer, model=on_create_model)
# Deferred restoration
status = on_create_root.restore(save_path=save_path)
status.assert_nontrivial_match()
status.assert_existing_o... | self.evaluate(
on_create_model._named_dense.variables[1]))
on_create_m_bias_slot = on_create_optimizer.get_slot(
on_create_model._named_dense.variables[1], "m")
status.assert_existing_objects_matched()
with self.assertRaises(AssertionError):
status.assert_consum... | e created when the original variable is
# restored.
self.assertAllEqual([1.5], self.evaluate(on_create_m_bias_slot))
self.assertAllEqual(optimizer_variables[2:],
self.evaluate(on_create_optimizer.variables()))
dummy_var = resource_variable_ops.ResourceVariable([1.])
on_create... |
# -*- coding: utf-8 -*-
################### | ###########################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from . import account_invoice
# vim:expandtab:smartindent:tabstop=4:softt | abstop=4:shiftwidth=4:
|
#!python3
from setuptools import setup
from irsdk import VERSION
setup(
name='pyirsdk',
version=VERSION,
description='Python 3 implementation of iRacing SDK',
author='Mihail Latyshov',
author_email='kutu182@gmail.com',
url='https://github.com/kutu/pyirsdk',
| py_modules=['irsdk'],
license='MIT',
platforms=['win64'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'License :: OSI Approved :: MIT License',
'Operating System :: Microsoft :: Wi | ndows',
'Programming Language :: Python :: 3.7',
'Topic :: Utilities',
],
entry_points={
'console_scripts': ['irsdk = irsdk:main'],
},
install_requires=[
'PyYAML >= 5.3',
],
)
|
#!/usr/bin/env python
# This file is part of tcollector.
# Copyright (C) 2013 The tcollector Authors.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, o... | l = 15
def print_stat(metric, value, tags=""):
if value is not None:
print("riak.%s %d %s %s" % (metric, ts, value, tags))
while True:
ts = int(time.time())
req = urlopen(CONFIG['stats_endpoint'])
if req is not None:
obj = json.loads(req.read())
... | key in obj:
if key not in MAP:
continue
# this is a hack, but Riak reports latencies in microseconds. they're fairly useless
# to our human operators, so we're going to convert them to seconds.
if 'latency' in MAP[key][0]:
... |
# -*- coding: utf-8 -*-
#
# http://www.privacyidea.org
# (c) cornelius kölbel, privacyidea.org
#
# 2018-11-21 Cornelius Kölbel <cornelius.koelbel@netknights.it>
# Remove the audit log based statistics
# 2016-12-20 Cornelius Kölbel <cornelius.koelbel@netknights.it>
# Restrict download to certain ti... | h_audit():
"""
return a paginated list of audit entries.
Params can be passed as key-value-pairs.
:httpparam timelimit: A timelimit, that limits the recent audit entries.
This param gets overwritten by a policy auditlog_age. Can be 1d, 1m, 1h.
**Example request**:
.. sourcecode:: htt... | T /audit?realm=realm1 HTTP/1.1
Host: example.com
Accept: application/json
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"status": true,
... |
"""
/******************************************************************************
This source file is part of the Avogadro project.
Copyright 2013 Kitware, Inc.
This source code is released under the New BSD License, (the "License").
Unless required by applicable law or agreed to in writing, software
di... | 'mimeTypes'] = ['chemical/x-zyx']
return metaData
def write():
result = ""
# Just copy the first two lines: numAtoms and comment/title
result += sys.stdin.readline()
result += sys.stdin.readline()
for line in sys.stdin:
words = line.split()
result += '%-3s %9.5f %9.5f %9.5f' ... | ]), float(words[1]))
if len(words) > 4:
result += words[4:].join(' ')
result += '\n'
return result
def read():
result = ""
# Just copy the first two lines: numAtoms and comment/title
result += sys.stdin.readline()
result += sys.stdin.readline()
for line in sys.st... |
import random
from subprocess import call
import yaml
with open('./venues.yml') as f:
venues = yaml.load(f)
venue = random.choice(venue | s)
print(venue['name'])
print(venue['url'])
call(['o | pen', venue['url']])
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-07-19 14:51
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('query_designer', '0012_query_dataset_query'),
]
operations = [
migrations.RemoveField | (
model_name='query',
name='dataset_query',
| ),
]
|
from widgets import messagebox as msg
class QtBaseException(Exception):
"""
Custom Exception base class used to handle exception with our on subset of options
"""
def __init__(self, message, displayPopup=False, *args):
| """initializes the exception, use cause to display the cause of the exception
:param message: The exception to display
:param cause: the cause of the error eg. a variable/class etc
:param args: std Exception args
"""
self.message = message
if displayPopup:
s... | alog(self):
messageBox = msg.MessageBox()
messageBox.setText(self.message)
messageBox.exec_()
|
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License | .
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
| # distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Requirements for Ruby codegen."""
from artman.tasks.requirements impo... |
#!/usr/bin/env python3
# Copyright (c) 2014-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 running pivxd with the -rpcbind and -rpcallowip options."""
import sys
from test_framework.netut... | self._run_loopback_tests()
if not self.options.run_ipv4 and not self.options.run_ipv6:
self._run_nonloopback_tests()
def _run_loopback_tests(self):
if self.options.run_ipv4:
# check only IPv4 localhost (explicit)
self.run_bind_test(['127.0.0.1'], '127.0.0.... | .1', self.defaultport)])
# check only IPv4 localhost (explicit) with alternative port
self.run_bind_test(['127.0.0.1'], '127.0.0.1:32171', ['127.0.0.1:32171'],
[('127.0.0.1', 32171)])
# check only IPv4 localhost (explicit) with multiple alternative ports on same host
... |
# -*- coding: utf-8 -*-
import os.path
files = os.li | stdir(os.path.dirname(__file__))
__all__ = [filename[:-3] for filename in files if not filename.startswith('__') | and filename.endswith('.py')]
|
.nic:
if nic.isdefault:
cls.virtual_machine1.ssh_ip = nic.ipaddress
cls.virtual_machine1.default_network_id = nic.networkid
break
except Exception as e:
cls.fail("Exception while deploying virtual machine: %s" % e)
... | id=vm_id
)
vm = virtual_machine[0]
hosts = list_hosts(
self.apiclient,
id=vm.hostid
| )
host = hosts[0]
if host.hypervisor.lower() not in "kvm":
return
host.user, host.password = get_host_credentials(self.config, host.ipaddress)
for nic in vm.nic:
secips = ""
if len(nic.secondaryip) > 0:
for secip in nic.secondaryi... |
def test_gen_generate_returns_generated_value():
from papylon.gen import Gen
def gen():
while True:
yield 1
sut = Gen(gen)
actual = sut.generate()
assert actual == 1
def test_such_that_returns_new_ranged_gen_instance():
from papylon.gen import choose
gen = choose(-20,... | erate()
assert type(generated_by_gen) == int
assert generated_by_gen in range(1, 11)
def test_given_a_value_v_when_constant_v_then_returns_gen_instance_which_generates_only_v():
from papylon.gen import constant
value = 6
sut = constant(value)
count = 0
trial = 10
for i in range(trial)... | if result == value:
count += 1
assert count == trial
|
from __future__ import print_function
import os
import time
import subprocess
from colorama import Fore, Style
from watchdog.events import (
FileSystemEventHandler, FileModifiedEvent, FileCreatedEvent,
FileMovedEvent, FileDeletedEvent)
from watchdog.observers import Observer
from watchdog.observers.polling im... | T_EXTENSIONS
self.args = args or []
self.spooler = None
if spool:
self.spooler = EventSpooler(0.2, self.on_queued_events)
self.verbose = verbose
self.quiet = quiet
def on_queued_events(self, events):
summary = []
for event | in events:
paths = [event.src_path]
if isinstance(event, FileMovedEvent):
paths.append(event.dest_path)
event_name = EVENT_NAMES[type(event)]
paths = tuple(map(os.path.relpath, paths))
if any(os.path.splitext(path)[1].lower() in self.extensions... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.