prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
# Copyright 2020 Red Hat, Inc. Jake Hunsaker <jhunsake@redhat.com>
# This f | ile is part of the sos project: https://github.com/sosreport/sos
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# version 2 of the GNU General Public License.
#
# See | the LICENSE file in the source distribution for further information.
from sos.cleaner.mappings import SoSMap
class SoSUsernameMap(SoSMap):
"""Mapping to store usernames matched from ``lastlog`` output.
Usernames are obfuscated as ``obfuscateduserX`` where ``X`` is a counter
that gets incremented for eve... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyIlmbase(AutotoolsPackage):
"""The PyIlmBase | libraries provides python bindings for the IlmBase libraries."""
homepage = "https://github.com/AcademySoftwareFoundation/openexr/tree/v2.3.0/PyIlmBase"
url = "https://github.com/AcademySoftwareFoundation/openexr/releases/download/v2.3.0/pyilmbase-2.3.0.tar.gz"
version('2.3.0', sha256='9c898bb16e7bc9... | ost+python')
# https://github.com/AcademySoftwareFoundation/openexr/issues/336
parallel = False
def configure_args(self):
spec = self.spec
args = [
'--with-boost-python-libname=boost_python{0}'.format(
spec['python'].version.up_to(2).joined)
]
... |
from __future__ import absolute_import, print_function, division
import unittest
from pony.orm.core import *
from pony.orm.tests.testutils import *
from pony.orm.tests import setup_database, teardown_database
db = Database()
db = Database('sqlite', ':memory:')
class Product(db.Entity):
id = PrimaryKey(int)
... | .0) for c in self.comments)
@property
def sum_11(self):
return select(sum(c.points) for c in self.comments)
@property
def sum_12(self):
return sum(self.comments.points)
@property
def sum_13(self | ):
return coalesce(sum(self.comments.points), 0)
@property
def sum_14(self):
return coalesce(sum(self.comments.points), 0.0)
class Comment(db.Entity):
id = PrimaryKey(int)
points = Required(int)
product = Optional('Product')
class TestQuerySetMonad(unittest.TestCase):
@class... |
def test_help_message(testdir):
result = t | estdir.runpytest(
'--help',
)
result.stdout.fnmatch_lines([
'pytest-random-order options:',
'*--random-order-bucket={global,package,module,class,parent,grandparent,none}*',
'*--random-order-seed=*',
])
def test_markers_message(testd | ir):
result = testdir.runpytest(
'--markers',
)
result.stdout.fnmatch_lines([
'*@pytest.mark.random_order(disabled=True): disable reordering*',
])
|
"core.Pixmap tests"
from unittest import SkipTest
from testutils import *
from gfxprim.core import Pixmap
from gfxprim import gfx, core
def test_gfx_submodule_loads():
"gfx is present in a Pixmap"
c = Pixmap(1, 1, core.C.PIXEL_RGB888)
assert c.gfx
def test_gfx_submodule_has_C():
"gfx contains C"
c = Pix... | end(0.5)
elif t == 'S':
args.append("")
else:
assert False
return tuple(args)
@for_each_case(gfx_params)
def test_method_call(n, params):
"Calling wi | th dummy parameters:"
c = PixmapRand(10, 10, core.C.PIXEL_RGB888)
if isinstance(params, str):
c.gfx.__getattribute__(n)(*gen_dummy_args(params))
else:
assert isinstance(params, tuple) and isinstance(params[-1], dict)
c.gfx.__getattribute__(n)(*params[:-1], **params[-1])
def test_Polygon():
"Polygon... |
"""Clean up notifications schema, some other parts.
Revision ID: 2979a1322381
Revises: 2b478162b2b7
Create Date: 2020-03-03 07:32:54.113550
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "2979a1322381"
down_revision = "2b478162b2b7"
def upgrade():
op.drop_index("ix_notification_... | cation")
op.drop_table("notification")
op.drop_column("diagram", "data")
op.drop_constraint("document_parent_id_fkey", "document", type_="foreignkey")
# op.alter_column('role', 'is_muted',
# existing_type=sa.BOOLEAN(),
# nullable=False)
op.drop_column("role", ... | pass
|
# Natural Language Toolkit: PanLex Corpus Reader
#
# Copyright (C) 2001-2016 NLTK Project
# Author: David Kamholz <kamholz@panlex.org>
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
"""
CorpusReader for PanLex Lite, a stripped down version of PanLex distributed
as an SQLite database. See the READ... | = {}
for i in self._c.execute(self.MEANING_Q, (expr_tt, e | xpr_lv)):
mn = i[0]
uid = self._lv_uid[i[5]]
if not mn in mn_info:
mn_info[mn] = { 'uq': i[1], 'ap': i[2], 'ui': i[3], 'ex': { expr_uid: [expr_tt] } }
if not uid in mn_info[mn]['ex']:
mn_info[mn]['ex'][uid] = []
mn_info[mn]['... |
dation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your option)
# any later version.
#
# GNU Radio is distributed in the hope... | = blocks.vector_source_c(data)
pfb = filter.pfb_arb_resampler_ccc(rrate, taps, nfilts)
snk = blocks.vector_sink_c()
self.tb.connect(signal, pfb, snk)
self.tb.run()
Ntest = 50
L = len(snk.data())
# Get group delay and estimate of phase offset from the filter its... | float(x) / (fs*rrate) for x in range(-delay, L-delay)]
# Data of the sinusoid at frequency freq with the delay and phase offset.
expected_data = [math.cos(2.*math.pi*freq*x+phase) + \
1j*math.sin(2.*math.pi*freq*x+phase) for x in t]
dst_data = snk.data()
... |
#! /usr/bin/python3
import | pygame
from colors import Colors
class Heart(pygame.sprite.Sprite):
def __init__(self, pos):
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = self.load_image("heart.png")
self | .rect.x = pos[0]
self.rect.y = pos[1]
def load_image(self, name, colorkey=None):
image = pygame.image.load(name)
image = image.convert_alpha()
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0,0))
image.set_colorkey(colork... |
__author__ = 'panzer'
from swampy.TurtleWorld import *
from math import radians, sin
def initTurtle(delay = 0.01):
"""
Initializes a turtle object
:param delay: Delay before each action of the turtle. Lower it is the faster the turtle moves.
:return: turtle object
"""
TurtleWorld()
t = Turtle()
t.delay... | t, angle)
fd(t, ineq_side)
lt(t, angle)
fd(t, eq_side)
def pie(t, n, length):
"""
Draws a pie
:param t: Turtle object
:param n: number of sides
:param length: length of each side
:return: Draws a Pie(Spiked polygon)
"""
angle = float(360.0/n)
eq_side = length/2.0/sin(radians(angle/2.0))
for _... | rtle(), 5, 100)
# Figure 4.2 a
pie(initTurtle(), 6, 100)
# Figure 4.2 a
pie(initTurtle(), 7, 100)
wait_for_user() |
__version | __ = "0.3.9 | "
|
(prot_list_file, 'w') as f:
f.write('\n'.join(prot_list))
print('Saved protein list to %s' % prot_list_file)
def get_prot_name_translations(gene_data, gen_pept_file):
print('Parsing %s...' % gen_pept_file)
prot_to_std, found_names = {}, set()
with open(gen_pept_file, 'r') as f:
prot_nam... | tr):
"""taxon_name is used to name the properties saved in gene_data."""
min_e_val = 1E-30
property_strs = ['num_%s_prots', '%s_prot_id', '%s_prot_identity', '%s_prot_coverage']
gi_split_regex = re.compile('\s?>gi\|\S+\|\S+\|\S+\|\s?')
gene_spc_regex = re.compile('(.+) \[(.+)\]$')
isoform_regex ... | terations = root.find('BlastOutput_iterations')
for q_hit in iterations:
gene = q_hit.find('Iteration_query-def').text
if gene not in gene_data:
continue
prot_len = float(q_hit.find('Iteration_query-len').text)
s_hits = q_hit.find('Iteration_hits')
hit_names, top_... |
from scipy import sparse
import numpy as np
import sys
##################################################################
# Constants
POS_IDX = 0
NEG_IDX = 1
NEUT_IDX = 2
POL_IDX = 1
SCORE_IDX = 2
MAX_I = 300
IDX2CLS = {POS_IDX: POSITIVE, NEG_IDX: NEGATIVE, NEUT_IDX: NEUTRAL}
######################################... | rms
mcs, _, pos, neg = sgraph.min_cut(a_pos, a_neg, a_seed_pos)
print("min_cut_score (pos. vs. neg.) = {:d}".format(mcs),
file=sys.stderr)
ret = [(inode[0], POSITIVE, 1.) for inode in pos]
ret.extend((inode[0], NEGATIVE, -1.) for inode in neg)
return ret
def rao_lbl_prop(a_germanet, a_po... | (2009).
@param a_germanet - GermaNet instance
@param a_pos - set of lexemes with positive polarity
@param a_neg - set of lexemes with negative polarity
@param a_neut - set of lexemes with neutral polarity
@param a_seed_pos - part-of-speech class of seed synsets ("none" for no
restriction)
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013, 2014 CERN
# Author: Pawel Szostek (pawel.szostek@cern.ch)
# Multi-tool support by Javier D. Garcia-Lasheras (javier@garcialasheras.com)
#
# This file is part of Hdlmake.
#
# Hdlmake is free software: you can redistribute it and/or modify
# it under the t... | _cmd sim_post_cmd
""")
if top_module.sim_pre_cmd:
sim_pre_cmd = top_module.sim_pre_cmd
else:
si | m_pre_cmd = ''
if top_module.sim_post_cmd:
sim_post_cmd = top_module.sim_post_cmd
else:
sim_post_cmd = ''
makefile_text_2 = makefile_tmplt_2.substitute(
sim_pre_cmd=sim_pre_cmd,
sim_post_cmd=sim_post_cmd,
)
self.write(makefile_tex... |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry import decorators
from telemetry.internal.actions import loop
from telemetry.testing import tab_test_case
import py_utils
AUDIO_1_LOOP_CHEC... | llRunAction(self._tab)
action.RunAction(self._tab)
# Assert only first video has played.
self.assertTrue(self._tab.EvaluateJavaScript(VIDEO_1_LOOP_CHECK))
self.assertFalse(self._tab.EvaluateJavaScript(AUDIO_1_LOOP_CHECK))
@decorators.Disabled('android', 'linux') # crbug.com/418577
def testLoopWith... | ion(loop_count=2, selector='all',
timeout_in_seconds=10)
action.WillRunAction(self._tab)
# Both videos not playing before running action.
self.assertFalse(self._tab.EvaluateJavaScript(VIDEO_1_LOOP_CHECK))
self.assertFalse(self._tab.EvaluateJavaScript(AUDIO_1_LOOP_CHECK))
... |
import _plotly_utils.basevalidators
class FontValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(
self, plotly_name="font", parent_name="sankey.link.hoverlabel", **kwargs
):
super(FontValidator, self).__init__(
plotly_name=plotly_name,
parent | _name=parent_name,
data_class_str=kwargs.pop("data_class_str", "Font"),
data_docs=kwargs.pop(
"data_docs",
"""
color
colorsrc
Sets the source reference on Chart Studio Cloud
for | color .
family
HTML font family - the typeface that will be
applied by the web browser. The web browser
will only be able to apply a font if it is
available on the system which it operates.
Provide multiple font families, sepa... |
connect_timeout=socket.getdefaulttimeout()):
if parse_yaml is True:
try:
parse_yaml = __import__('yaml').load
except ImportError:
logging.error('Failed to load PyYAML, will not parse YAML')
parse_yaml = False
self._co... | a Job, or None."""
return self._interact_peek('peek-ready\r\n')
def peek_delayed(self):
"""Peek at next delayed job. Returns a Job, or None."""
return self._interact_peek('peek-delayed\r\n')
def peek_buried(self):
"""Peek at next buried job. Returns a Job, or None."""
r... | es(self):
"""Return a list of all existing tubes."""
return self._interact_yaml('list-tubes\r\n', ['OK'])
def using(self):
"""Return the tube currently being used."""
return self._interact_value('list-tube-used\r\n', ['USING'])
def use(self, name):
"""Use a given tube."... |
"""
Imports all submodules
"""
from __future__ import print_function
from __future__ import divisio | n
from __future__ import unicode_literals
from deepchem.dock.pose_generation import | PoseGenerator
from deepchem.dock.pose_generation import VinaPoseGenerator
from deepchem.dock.pose_scoring import PoseScorer
from deepchem.dock.pose_scoring import GridPoseScorer
from deepchem.dock.docking import Docker
from deepchem.dock.docking import VinaGridRFDocker
from deepchem.dock.docking import VinaGridDNNDock... |
t row count
len(df.columns) #print column count
df.printSchema() #print schema, datatypes, nullable
## SCHEMA & DATATYPES
#--------------------------------------------------------
#changing the schema
from pyspark.sql.types import StructField,StringType,IntegerType,StructType
# true = nullable, false = n... | input
# difference illustrated here: https://www.linkedin.com/pulse/difference-between-map-flatmap-transformations-spark-pyspark-pandey
dicts | = sc.parallelize([{"foo": 1, "bar": 2}, {"foo": 3, "baz": -1, "bar": 5}])
dicts.flatMap(lambda x: x.items()).collect()
>>> [('bar', 2), ('foo', 1), ('bar', 5), ('foo', 3), ('baz', -1)]
#--------------
### RDD REDUCE
# key/value functions
# reduce by key, x & y represent values of same key
total = parsedLin... |
= mag( solution[i][2]-solution[i][3] )
self.bundles[i].magnitudes[0] = mag1
self.bundles[i].magnitudes[1] = mag2
## The lagrange multipliers changed, but not the locations of the zeros.
self._update_bundles( lagrange_only = True )
self.system_factored = None
## UPDATE: Actually, if fixed angl... | positions)
'''
Boundary Conditions are as follows:
lambda1 * ( P4x' - constraint_X' ) = 0
lambda2 * ( P4y' - constraint_Y' ) = 0
'''
R2 = zeros( ( dofs, dim ) )
for i in range( dim ):
R2[i*4+3, i] = 1
R = concatenate((R, R2), axis=1)
rhs = concatenate((rhs, fixed_positions))
| return R.T, rhs
def system_for_curve( self, bundle ):
'''
## A is computed using Sage, integral of (tbar.T * tbar) with respect to t.
# A = asarray( [[ 1./7, 1./6, 1./5, 1./4], [ 1./6, 1./5, 1./4, 1./3],
# [ 1./5, 1./4, 1./3, 1./2], [1./4, 1./3, 1./2, 1.]] )
## MAM is computed using Sage. MAM... |
from typing import Typed | Dict
class Point(TypedDict):
x: int
y: | int
def is_even(x: Point) -> bool:
pass
is_even({'<caret>'})
|
# -*- coding: utf-8 -*-
# Copyright (C) 2014 Accuvant, Inc. (bspengler@accuvant.com)
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
from lib.cuckoo.common.abstracts import Signature
class Authenticode(Signature):
name = "static_authentico... | for sign in self.results["static"]["digital_signers"]:
self.data.append(sign)
found_sig = Tr | ue
return found_sig
|
# -*- coding: utf-8 -*-
try:
from setuptools import setup, find_packages
except ImportError:
from e | z_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='historic_cadastre',
version='0.1',
description='SITN, a sitn project',
author='sitn',
author_email='sitn@ne.ch',
url='http://www.ne.ch/sitn',
install_requires=[
'pyramid',... | |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 OpenStack Foundation
# 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.apach... | networks]}
def show(self, req, id):
context = req.environ['nova.context']
authorize(context)
LOG.debug(_("Showing network with id %s") % id)
try:
network = self.network_api.get(context, id)
exc | ept exception.NetworkNotFound:
raise exc.HTTPNotFound(_("Network not found"))
return {'network': network_dict(network)}
def delete(self, req, id):
context = req.environ['nova.context']
authorize(context)
try:
if CONF.enable_network_quota:
rese... |
"""Axis switch platform tests."""
from unittest.mock import Mock, call as mock_call
from homeassistant.components import axis
import homeassistant.components.switch as switch
from homeassistant.setup import async_setup_component
from .test_device import NAME, setup_axis_integration
EVENTS = [
{
"operati... | )
device.api.vapix.ports = {"0": Mock(), "1": Mock()}
device.api.vapix.ports["0"].name = "Doorbell"
device.api.vapix.ports["1"].name = ""
for event in EVENTS:
device.api.s | tream.event.manage_event(event)
await hass.async_block_till_done()
assert len(hass.states.async_entity_ids("switch")) == 2
relay_0 = hass.states.get(f"switch.{NAME}_doorbell")
assert relay_0.state == "off"
assert relay_0.name == f"{NAME} Doorbell"
relay_1 = hass.states.get(f"switch.{NAME}_rel... |
# -*- coding: utf-8 -*-
import pytest
from numpy import array
from numpy.testing import assert_array_almost_equal
from gdal2mbtiles.constants import (EPSG_WEB_MERCATOR,
EPSG3857_EXTENTS)
from gdal2mbtiles.gdal import SpatialReference
@pytest.fixture
def epsg_3857_from_proj4():
... | with
3857 crs u | sing the FromEPSG method.
"""
spatial_ref = SpatialReference.FromEPSG(EPSG_WEB_MERCATOR)
return spatial_ref
def test_epsg_3857_proj4(epsg_3857_from_proj4):
extents = epsg_3857_from_proj4.GetWorldExtents()
extents = array(extents)
assert_array_almost_equal(extents, EPSG3857_EXTENTS, decimal=3)
... |
ored_bigips(self):
try:
errored_bigips = self.get_errored_bigips_hostnames()
if errored_bigips:
LOG.debug('attempting to recover %s BIG-IPs' %
len(errored_bigips))
for hostname in errored_bigips:
# try to conne... | nager.get_sync_status(bigip) == \
| 'Standalone':
raise f5ex.BigIPClusterInvalidHA(
'HA mode is pair and bigip %s in standalone mode'
% hostname)
if self.conf.f5_ha_type == 'scalen' and \
self.cluster_manager.get_sync_status(bigip) == \
... |
alse # --list-tests
run_tests = True # run tests (disabled by --list-foo)
postmortem = False # invoke pdb when an exception occurs
profile = False
# output verbosity
verbosity = 0 | # verbosity level (-v)
quiet = 0 # do not print anything on success (-q)
first_doctest_failure = False # report first doctest failure (-1)
print_import_time = True # print time taken to import test modules
| # (currently hardcoded)
progress = False # show running progress (-p)
colorize = False # colorize output (-c)
coverage = False # produce coverage reports (--coverage)
coverdir = 'coverage' # where to put them (currently hardcoded)
immedia... |
# -*- coding: utf-8 -*-
import cPickle as pickle
GEO_FILES = './geo_files'
def gen_db():
u'''Функция для генерации pickle базы ipgeobase.ru
'''
res = []
tmp_list = []
cities_dict = {}
# cidr_optim.txt
for line in open('%s/cidr_optim.txt' % GEO_FILES, 'r'):
a = line.split('\t'... | es.remove(item)
c += 1
# cities.txt
citi | es_file = open('%s/cities.txt' % GEO_FILES, 'r').read()
lines = cities_file.decode('CP1251').split('\n')
for line in lines:
a = line.split('\t')
if len(a) > 3:
cities_dict.update({int(a[0]): (a[1], a[2])})
f = open('%s/cidr_pickle.db' % GEO_FILES, 'w')
pi... |
= platform.system().lower() == 'linux'
if pyversion[:3] in ['2.6', '2.7']:
import urllib as urllib_request
import codecs
open = codecs.open
_unichr = unichr
if sys.maxunicode < 0x10000:
def unichr(i):
if i < 0x10000:
return _unichr(i)
else:
... | ret
def dictToSortedList( src_table, pos ):
return sorted( src_table.items(), key = lambda m: m[pos] )
def translate( text, conv_table ):
i = 0
while i < len( text ):
for j in range( len( text ) - i, 0, -1 ):
f = text[i:][:j]
t = conv_table.get( f )
if t:
... | f manualWordsTable( path, conv_table, reconv_table ):
fp = open( path, 'rb', 'U8' )
reconv_table = {}
wordlist = [line.split( '#' )[0].strip() for line in fp]
wordlist = list( set( wordlist ) )
wordlist.sort( key = len, reverse = True )
while wordlist:
word = wordlist.pop()
new_w... |
###############################################################################
# lazyflow: data flow based lazy parallel computation framework
#
# Copyright (C) 2011-2014, the il | astik developers
# <team@ilastik.org>
#
# This program is | free software; you can redistribute it and/or
# modify it under the terms of the Lesser GNU General Public License
# as published by the Free Software Foundation; either version 2.1
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
'''Pychemqt, Chemical Engineering Process simulator
Copyright (C) 2009-2017, Juan José Gómez Romera <jjgomera@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 Softwar... | lattice_edges
* lattice_angles
* electron_configuration
* oxidation
* electronegativity
* electron_affinity
* first_ionization
* Tf
* Tb
* Heat_f
* Heat_b
* Cp
* k
* T_debye
* color
* notes
'''
| import os
import sqlite3
from numpy import linspace, logspace, log
from PyQt5.QtCore import QLocale
from lib.utilities import colors
# Connection to database with element data
connection = sqlite3.connect(os.path.join(
os.environ["pychemqt"], "dat", "elemental.db"))
databank = connection.cursor()
# Load system... |
#!/usr/bin/env python
import os
import sys
import argparse
import json
# tempate2json.py -k SYSTEM=lonestar.tacc.utexas.edu
# PATH=/home/vaughn/apps -i template.jsonx -o file.json
if __name__ == '__mai | n__':
parser = argparse.ArgumentParser()
parser.add_argument("-k", dest='keys', help='Space-delimited VAR=Value sets', nargs='*')
parser.add_argument("-i", dest='input', help='Input (template.jsonx)')
parser.add_argument("-o", dest="output", help="Output (output.json)")
args = parser.parse_args()... | ided for -i"
sys.exit(1)
except IOError, e:
print >> sys.stderr, "[FATAL]", args.input, "was not available for reading"
print >> sys.stderr, "Exception: %s" % str(e)
sys.exit(1)
# Iterate through document, replacing variables with values
for kvp in args.keys:
try:
... |
#!/usr/bin/env python
#Takes a table and index of Exon Lens, calculates RPKMs
import sys
import os
import re
import fileinput
from decimal import Decimal
from decimal import getcontext
from fractions import Fraction
def main(table,index):
indf = open(index)
| out_file = "%s_rpkm.table" % os.path.splitext(table)[0]
dic = {}
for line in fileinput.input(index):
(key, val) = line.split('\t')
if val == 0:
print "We Ffd up at " + str(key)
dic[str(key.rstrip())] = Decimal(val)
print dic["Vocar20014554m.g.2.0"]
with open(out_fil... | listl = line.split('\t')
head = listl[0]
vals = listl[1:]
for i in xrange(len(vals)):
comp = Decimal(vals[i])
div = Decimal(dic[head.rstrip()])
print head.rstrip()
... |
tatsPaths import StatsPaths
from pxStats.lib.CpickleWrapper import CpickleWrapper
class LogFileAccessManager(object):
def __init__( self, accessDictionary = None, accessFile = "" ):
"""
@summary: LogFileAccessManager constructor.
@param accessArrays:
... | tifier: Identifier string of the following format:
fileType_client/sourcename_machineName
@return | : returns the first line of the last file accessed by the identifier.
If identifier has no associated line, the returned line will be "".
"""
line = ""
try:#In case the key does not exist.
line = self.accessDictionary[ identifier ][0]
... |
pESeriesVolume()
volume_object.get_storage_pool()
def test_check_storage_pool_sufficiency_pass(self):
"""Ensure passing logic."""
self._set_args({"state": "present", "name": "Matthew", "storage_pool_name": "pool", "size": 100})
volume_object = NetAppESeriesVolume()
v... | _data2", "metadata": {"key": "use", "value": "EmployeeData"}})
volume_object = NetAppESeriesVo | lume()
with self.assertRaisesRegexp(AnsibleFailJson, "Failed to create new workload tag."):
with mock.patch(self.REQUEST_FUNC, side_effect=[(200, self.WORKLOAD_GET_RESPONSE), Exception()]):
volume_object.update_workload_tags()
def test_get_volume_property_changes_pass(self):
... |
# This file is part of cclib (http://cclib.github.io), a library for parsing
# and interpreting the results of computational chemistry packages.
#
# Copyright (C) 2014, the cclib development team
#
# The library is free software, distributed under the terms of
# the GNU Lesser General Public version 2.1 or later. You s... | ccdata - An instance of ccData, parse from a logfile.
splitfiles - Boolean to write multiple files if | multiple files are requested. [TODO]
firstgeom - Boolean to write the first available geometry from the logfile.
lastgeom - Boolean to write the last available geometry from the logfile.
allgeom - Boolean to write all available geometries from the logfile.
"""
# Call the ... |
#!/usr/bin | /env python
from setuptools import setup
if __name__ == "__main__":
| setup()
|
from __future__ import print_function
from glyphNameFormatter.tools import camelCase
doNotProcessAsLigatureRanges = [
(0xfc5e, 0xfc63),
(0xfe70, 0xfe74),
#(0xfc5e, 0xfc61),
(0xfcf2, 0xfcf4),
(0xfe7 | 6, 0xfe80),
]
def process(self):
# Specifically: do not add suffixes to these ligatures,
# they're really arabic marks
for a, b in doNotProcessAsLigatureRanges:
if a <= self.uniNumber <= b:
self.replace('TAIL FRAGMENT', "kashida Fina")
self.replace('INITIAL FORM', "init")... |
self.replace('FINAL FORM', "fina")
self.replace('ISOLATED FORM', "isol")
self.replace('WITH SUPERSCRIPT', "")
self.replace('WITH', "")
self.replace("LIGATURE", "")
self.replace("ARABIC", "")
self.replace("SYMBOL", "")
self.... |
#!/usr/bin/env python
# coding=utf-8
import traceback
try:
raise SyntaxError, "traceback test"
except:
traceback.print_ | exc()
| |
#
# (C) Copyright 2001/2002 Kai Sterker <kaisterker@linuxgames.com>
# Part of the Adonthell Project http://adonthell.linuxgames.com
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License.
# This program is distributed in the hope that it will... | irection == adonthell.WALK_NORTH:
goal = (self.myself.posx (), self.min_y, adonthell.STAND_SOUTH, 0, 1)
elif self.direction == adonthell.WALK_SOUTH:
goal = (self.myself.posx (), self.max_y, adonthell.STAND_NORTH, 0, -1)
elif self | .direction == adonthell.WALK_EAST:
goal = (self.max_x, self.myself.posy (), adonthell.STAND_WEST, -1, 0)
else:
goal = (self.min_x, self.myself.posy (), adonthell.STAND_EAST, 1, 0)
x, y, d = goal[:3]
self.direction = d + 4
while not self.myself.set_goal (x, y, d)... |
KER>",
help="Last item of the previous listing. "
"Return the next results after this value")
parser.add_argument("--sort", action="append", metavar="<SORT>",
help="Sort of resource attribute "
"(exam... | ic in parsed_args.create_metric:
name, _, value = metric.partition(":")
if value:
resource['metrics'][name] = {'archive_policy_name': value}
else:
resource['metrics'][name] = {}
return resource
def take_action(self, pa... | res = utils.get_client(self).resource.create(
resource_type=parsed_args.resource_type, resource=resource)
if parsed_args.formatter == 'table':
normalize_metrics(res)
return self.dict2columns(res)
class CliResourceUpdate(CliResourceCreate):
"""Update a resource."""
de... |
import shutil
import os
import jinja2
import string
import subprocess
import re
from xen.provisioning.HdManager import HdManager
from settings.settingsLoader import OXA_XEN_SERVER_KERNEL,OXA_XEN_SERVER_INITRD,OXA_DEBIAN_INTERFACES_FILE_LOCATION,OXA_DEBIAN_UDEV_FILE_LOCATION, OXA_DEBIAN_HOSTNAME_FILE_LOCATION, OXA_DEB... | g("Creating SSH2 RSA key; this may take some time...")
subprocess.check_call("ssh-keygen -q -f "+path+"/etc/ssh/ssh_host_rsa_key -N '' -t rsa", shell=True, stdout=None)
OfeliaDebianVMConfigurator.logger.debug("Creating SSH2 DSA key; this may take some time...")
subprocess.check_call("ssh-keygen -q -f "+path+"/... | Aborting to prevent VM to be unreachable..."+str(e))
raise e
#Public methods
@staticmethod
def createVmConfigurationFile(vm):
#get env
template_dirs = []
template_dirs.append(os.path.join(os.path.dirname(__file__), 'templates/'))
env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dirs))
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
class UtilsTests(TestCase):
"""docstring for UtilsTests"""
def setUp(self):
self.username | = 'theskumar'
self.email = 'theskumar@example.com'
def test_foo(self):
self.assertEqual('foo' | , "foo")
|
import numpy as np
import matplotlib.pyplot as pl
d | ef f(x):
return np.exp(-x**2)
def main():
N = 100000
x = np.arange(N,dtype=np.float)
x[0] = 0.2
counter = 0
for i in range(0, N-1):
x_next = np.random.normal(x[i], 1.)
if np.random.random_sample() < min(1, f(x_next)/f(x[i])):
x[i+1] = x_next
cou... | name__ == '__main__':
main()
|
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 CO... | dev_token',
'link_id',
'app_event_type',
'rdid',
'id_type',
'lat',
'app_version',
'os_version',
'sdk_version',
'timestamp')
class AppEvent... | ssion_start'
IN_APP_PURCHASE = 'in_app_purchase'
VIEW_ITEM_LIST = 'view_item_list'
VIEW_ITEM = 'view_item'
VIEW_SEARCH_RESULTS = 'view_search_results'
ADD_TO_CART = 'add_to_cart'
ECOMMERCE_PURCHASE = 'ecommerce_purchase'
CUSTOM = 'custom'
class IdType(enum.Enum):
ANDROID = 'advertisingid'
IOS = 'idf... |
#Copyright ReportLab Europe Ltd. 2000-2012
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/pdfgen/pdfgeom.py
__version__=''' $Id: pdfgeom.py 3959 2012-09-27 14:39:39Z robin $ '''
__doc__="""
This module includes any mathematical methods ... | nd
(x3, y3) as their respective Bezier control points."""
x1,y1, x2,y2 = min(x1,x2), max(y1,y2), max(x1,x2), min(y1,y2)
if abs(extent) <= 90:
arcList = [startAng]
fragAngle = float(extent)
Nfrag = 1
else:
| arcList = []
Nfrag = int(ceil(abs(extent)/90.))
fragAngle = float(extent) / Nfrag
x_cen = (x1+x2)/2.
y_cen = (y1+y2)/2.
rx = (x2-x1)/2.
ry = (y2-y1)/2.
halfAng = fragAngle * pi / 360.
kappa = abs(4. / 3. * (1. - cos(halfAng)) / sin(halfAng))
if fragAngle < 0:
... |
import tensorflow as tf
import matplotlib.pyplot as plt
import math
x_node = tf.random_uniform([1], minval=-1, maxval=1, dtype=tf.float32,
name='x_node')
y_node = tf.random_uniform([1], minval=-1, maxval=1, dtype=tf.float32,
name='y_node')
times = 5000
hits = 0
pis = []
wi | th tf.Session() as session:
for i in range(1, times) | :
x = session.run(x_node)
y = session.run(y_node)
if x*x + y*y < 1:
hits += 1
pass
pi = 4 * float(hits) / i
print(pi)
pis.append(pi)
pass
pass
plt.plot(pis)
plt.plot([0, times], [math.pi, math.pi])
plt.show()
|
from django.db import models
from django.db.models.fields.related import ManyToOneRel, ForeignObjectRel
from elasticsearch_dsl.mapping import Mapping
from elasticsearch_dsl.field import Field
from djes.conf import settings
FIELD_MAPPINGS = {
"AutoField": {"type": "long"},
"BigIntegerField": {"type": "long"},... | "string"},
"CommaSeparatedIntegerField": {"type": "string"},
"DateField": {"type": "date"},
"DateTimeField": {"type": "date"},
"DecimalField": {"type": "string"},
"DurationField": {"type": "long"},
"EmailField": {"type": "string"},
# "FileField": {"type" | : ""}, # TODO: make a decision on this
"FilePathField": {"type": "string"},
"FloatField": {"type": "double"},
# "ImageField": {"type": ""}, # TODO: make a decision on this
"IntegerField": {"type": "long"},
"IPAddressField": {"type": "string", "index": "not_analyzed"},
"GenericIPAddressField": ... |
Set up the specification for model pruning.
If a spec is provided, the sparsity is set up based on the sparsity_function
in the spec. The effect of sparsity_function is overridden if the sparsity
variable is passed to the constructor. This enables setting up arbitrary
sparsity profiles externally and p... | n initial_sparsity = 0. Generalize
# to handle other cases as well.
return math_ops.mul(
self._sparsity,
math_ops.div(target_sparsity[0], self._spec.target_sparsity))
def _update_mask(self, weights, threshold):
"""Updates the mask for a given weight tensor.
This functions first compu... | ave magnitude less than the threshold.
Args:
weights: The weight tensor that needs to be masked.
threshold: The current threshold value. The function will compute a new
threshold and return the exponential moving average using the current
value of threshold
Returns:
new_thres... |
ew_states, xent = self.model.extend_step(states, ids)
return new_states, xent.logits
result = greedy_decode(
extend_step_fn,
decoder_state,
input_batch.tgt.ids,
input_batch.tgt.paddings,
p.decoder.seqlen,
eos_id=p.decoder.eos_id)
# Prefix lengths are not ... | , p.lm.vocab_size)
fill_prob = p.label_smoothing_prob / (p.lm.vocab_size - 1)
class_probabilities = (
(1.0 - p.label_smoothing_prob) * class_probabilities + fill_prob *
| (1.0 - class_probabilities)).astype(self.fprop_dtype)
# Only compute loss on masked pos.
labels = NestedMap(
class_probabilities=class_probabilities, class_weights=augmented_pos)
else:
# Only compute loss on masked pos.
labels = NestedMap(class_ids=labels, class_weights=augmen... |
class ComplexClause(object):
type_string = ''
def __init__(self, *args):
self.clauses = args
self.add_prefix(self.type_string)
def is_matrix(self):
for c in self.clauses:
if not c.is_matrix():
return False
return True
def involves(self, an... | fix + str(i)
except AttributeError:
pass
def generate_params(self):
"""
Generates dictionary of parameters of ComplexClause
Returns
-------
params : dict
a dictionary of parameters
"""
from .attributes import N... | .clauses:
if isinstance(c, ComplexClause):
params.update(c.generate_params())
else:
try:
if not isinstance(c.value, NodeAttribute):
params[c.cypher_value_string()[1:-1].replace('`', '')] = c.value
except ... |
import logging
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import views as auth_views, get_user_model, update_session_auth_hash, logout
from django.contrib.auth.tokens import default_token_generator
from django.contrib.messages.views import SuccessMessageMixin
from dja... | :
form.save()
messages.add_message(request, me | ssages.SUCCESS,
_('Your password has been set. You may go ahead and log in now.'),
fail_silently=True)
logger.info('Password for user %s has been reset.'
% user.email)
return HttpRespons... |
# -*- encoding: utf-8 -*-
import datetime
from django import forms
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from django.core import exceptions as django_exceptions
from lyra import models
class Reservation(forms.ModelForm):
def __init__(self, *args, **kw... | date_range(
start_date, stop_date)
if self.instance.pk:
would_conflict = would_conflict.exclude(pk=self.instance.pk)
if would_conflict.count():
(self._errors
.setdefault("start", self.error_class())
... | "The reservation would conflict with %(conflict_count)s "
u"other reservations.") % {
"conflict_count": would_conflict}))
return cleaned_data
class ReservationExclusiveEnable(ReservationExclusive):
exclusive = forms.BooleanField(
... |
# Copyright 2012, Nachi Ueno, NTT MCL, 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 applic... | redirect = reverse(self.failure_url)
msg = _("Unable to set gateway.")
exceptions.handle(self.request, msg, redirect=redirect)
def get_context_data(self, **kwargs):
context = super(SetGateway | View, self).get_context_data(**kwargs)
context['router'] = self.get_object()
return context
def get_initial(self):
router = self.get_object()
return {"router_id": self.kwargs['router_id'],
"router_name": router.name_or_id}
class DetailView(tabs.TabView):
tab_gr... |
import unittest
import nest
from nix4nest.nest_api.models.multimeter import NestMultimeter
class TestNode(unittest.TestCase):
def setUp(self):
nest.ResetKernel() |
self.neuron_id = nest.Create('iaf_neuron')[0]
rec_params = {'record_from': ['V_m'], 'withtime': True}
self.mm_id = nest.Create('multimeter', params=rec_params)[0]
nest.Connect([self.mm_id], [self.neuron | _id])
self.mm = NestMultimeter(self.mm_id, 'V_m')
def tearDown(self):
nest.ResetKernel()
def test_properties(self):
for k in nest.GetStatus([self.mm_id])[0].keys():
assert(k in self.mm.properties)
def test_data(self):
assert(len(self.mm.data) == 0)
ne... |
#!/usr/bin/env python2.7
# -*- encoding: utf-8 -*-
"""
Home-monitor
~~~~~~~~~~~~
:copyright: (c) 2013 by Aurélien Chabot <aurelien@chabot.fr>
:license: GPLv3, see COPYING for more details.
"""
try:
import threading
import sys, os, time, datetime
impo | rt json
import urll | ib2
from ConfigParser import SafeConfigParser
except ImportError as error:
print 'ImportError: ', str(error)
exit(1)
try:
sys.path.insert(0, '../rest/')
sys.path.insert(0, '/usr/local/bin/')
from restClientLib import get_nodes, set_switch, update_sensor, update_switch
except ImportError as error:
print 'Custom ... |
from phovea_server.ns import Namespace, abort
from phovea_server.util import jsonify
from phovea_server.config import get as get_config
from phovea_server.plugin import list as list_plugins
import logging
app = Namespace(__name__)
_log = logging.getLogger(__name__)
@app.route('/<path:path>')
def _config(path):
pat... | 0] = plugin.configKey
return jsonify(get_config('.'.join(path)))
def create():
re | turn app
|
# pywws - Python software for USB Wireless Weather Stations
# http://github.com/jim-easterbrook/pywws
# Copyright (C) 2018 pywws contributors
# 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; ei... | Weather: https://www.aerisweather.com/
"""
from __future__ import absolute_import, unicode_literals
from contextlib import contextmanager
from datetime import timedelta
import logging
import os
import sys
import requests
import pywws.service
__docformat__ = "restructuredtext en" |
service_name = os.path.splitext(os.path.basename(__file__))[0]
logger = logging.getLogger(__name__)
class ToService(pywws.service.CatchupDataService):
config = {
'station' : ('', True, 'ID'),
'password': ('', True, 'PASSWORD'),
}
fixed_data = {'action': 'updateraw', 'softwaretype': 'p... |
# coding: utf-8
import json
import logging
import webapp2
from webapp2_extras import sessions
from google.appengine.api.taskqueue import TombstonedTaskError, TaskAlreadyExistsError, DuplicateTaskNameError
from domain.entity import User
import error
class BaseHandler(webapp2.RequestHandler):
def dispatch(self):
... | dyExistsError,
DuplicateTaskNameError) as e:
| logging.error(e)
def signin_user_only(f):
"""Raise UnauthorizedException if session user is None
Examples:
class MyHandler(BaseHandler):
@singin_user_only
def get(self):
# following code is executed only if user is signed in.
...
"""
def wrapper(self, *ar... |
from glob import glob
import fitsio
import sys
from astrometry.util.fits import *
from astrometry.util.file import *
from astrometry.util.starutil_numpy import *
from astrometry.libkd.spherematch import *
from collections import Counter
from legacypipe.oneblob import _select_model
from legacypipe.survey import wcs_for_... | npatched = 0
for i,(d,ttype) in enumerate(zip(A.dchisq, T | 8.type)):
dchisqs = dict(zip(['ptsrc','rex','dev','exp','comp'], d))
mod = _select_model(dchisqs, nparams, galaxy_margin, rex)
ttype = ttype.strip()
# The DUP elements appear at the end, and we *zip* A and T8; A does not contain the DUPs
# so is shorter by the number of DUP eleme... |
# -*- coding: utf-8 -*-
"""
Copyright 2010 cloudControl UG (haftungsbeschraenkt)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this fil | e 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... |
#!/usr/bin/env python
import ibus
import dbus
bus = dbus.SessionBus()
e = ibus.interface.IPanel()
print e.Introspect("/", | bus)
| |
#!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved.
#
# This copy of Ice is licensed to you under the terms described in the
# ICE_LICENSE file included in this distribution.
#
# *************************************... | .ice')
import Demo
class Client(Ice.Application):
def run(self, args):
if len(args) > 1:
print self.appName() + ": too many arguments"
return 1
ping = Demo.PingPrx.checkedCast(self.comm | unicator().propertyToProxy('Ping.Proxy'))
if not ping:
print "invalid proxy"
return 1
# Initial ping to setup the connection.
ping.ice_ping();
repetitions = 100000
print "pinging server " + str(repetitions) + " times (this may take a while)"
tse... |
with open( self.projectPath(), 'r') as file:
project = file.read()
return project
# parse locally for programatic execution
def reload(self):
try:
self._project = json.loads(self.projectRaw())
except:
self._project ... | ["media"] == '...':
order["event"] = 'continue'
elif b["media"].startswith('fade'):
order["event"] = 'fade'
o | rder["data"] = b["media"].split('fade ')[1]
else:
order["event"] = 'playthen'
order["data"] = [ self._project["project"][0][sceneIndex]["name"] + '/' + b["media"] ]
# ON MEDIA END
if 'onend' in b:
... |
# -*- coding: utf-8 -*-
# Copyright 2007-2020 The HyperSpy developers
#
# This file is part of HyperSpy.
#
# HyperS | py is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# HyperSpy is distributed in the hope that it will be useful,
# but WITHOUT ANY W... | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with HyperSpy. If not, see <http://www.gnu.org/licenses/>.
from operator import attrgetter
from hyperspy.misc.utils import attrs... |
#!/usr/bin/env python
# encoding: utf-8
"""
For local testing purposes
"""
from itertools import compress, chain, product, ifilter
from functools import partial
from reader import read_input, list_files
def is_valid(task, solution):
"""
:param reader.Task task:
:param list[1|0] solution:
:return bool... | _configurations = product([0, 1], repeat=task.set_count)
valid_configurations = ifilter(partial(is_valid, task), all_configurations)
return min(valid_configurations, key=par | tial(calc_cost, task))
def check_solver(solver, inputs=list_files(max_size=20)):
"""
Prove optimality with comparing solution with control version.
Only for small examples, sorry. For big ones you can call is_valid()
:param task:
:param function(task) solver:
:return:
"""
for fn in inp... |
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import datetime
from collections import OrderedDict
from typing import Dict, List, Tuple, Union
import frappe
from frappe import _
from frappe.utils import date_diff
from erpnext.accounts.report.gen... | _map = get_item_groups_map(svd_list)
for item in svd_list:
item.item_group = ig_map[item.get("item_code")]
def get_item_groups_map(svd_list: SVDList) -> Dict[str, str]:
item_codes = set(i['item_code'] for i in svd_list)
ig_list = frappe.get_list(
'Item', fields=['item_code' | ,'item_group'],
filters=[('item_code', 'in', item_codes)]
)
return {i['item_code']:i['item_group'] for i in ig_list}
def get_item_groups_dict() -> ItemGroupsDict:
item_groups_list = frappe.get_all("Item Group", fields=("name", "is_group", "lft", "rgt"))
return {(i['lft'],i['rgt']):{'name':i['name'], 'is_group':... |
"""DeeCluster: provides a namespace for a set of DeeDatabases"""
__version__ = "0.1"
__author__ = "Greg Gaughan"
__copyright__ = "Copyright (C) 2007 Greg Gaughan"
__license__ = "MIT" #see Licence.txt for licence information
from Dee import Relation, Tuple
from DeeDatabase import Database
class Cluster(dict):... | ions, attributes etc. to define this...
def __getattr__(self, key):
if self.has_key(key):
return self[key]
raise AttributeError, repr(key)
def __setattr__(self, key, value):
#todo reject non-Database?
self[key] = value
#todo delattr
def __contai... | return True
return False
def __iter__(self):
for (k, v) in self.items():
#for (k, v) in self.__dict__.items():
if isinstance(v, Database):
yield (k, v)
def vdatabases(self):
return [Tuple(database_name=k)
... |
('th', gettext_noop('Thai')),
('tr', gettext_noop('Turkish')),
('uk', gettext_noop('Ukrainian')),
('ur', gettext_noop('Urdu')),
('vi', gettext_noop('Vietnamese')),
('zh-cn', gettext_noop('Simplified Chinese')),
('zh-tw', gettext_noop('Traditional Chinese')),
)
# Languages using BiDi (right... | sed to implement db routing behaviour
DATABASE_ROUTERS = []
# The email backend to use. For possible shortcuts see django.core.mail.
# The default is to use the SMTP backend.
# Third-party backends can be specified by providing a Python path
# to a module that defines an EmailBackend class.
EMAIL_BACKEND = 'django.cor... | nding e-mail.
EMAIL_HOST = 'localhost'
# Port for sending e-mail.
EMAIL_PORT = 25
# Optional SMTP authentication information for EMAIL_HOST.
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_USE_TLS = False
# List of strings representing installed apps.
INSTALLED_APPS = (
'django.contrib.contenttypes',
'django.con... |
import io
import math
import random
from contextlib import redirect_stdout
from unittest import TestCase
from hamcrest import *
from array_util import get_random_unique_array
from chapter16.problem16_1 import greedy_make_change, make_change, print_change
from datastructures.array import Array
from util import between... | uteforce(n, d)
actual_change_sum = sum(actual_change[i] * d[i] for i in between(1, d.length))
assert_that(sum(actual_change), is_(equal_to(expected_change_size)))
assert_that(actual_change_sum, is_(equal_to(n)))
def test_make_change(self):
| n = random.randint(1, 20)
k = random.randint(1, 5)
d, _ = get_random_unique_array(max_size=k, min_value=2, max_value=20)
d[1] = 1
captured_output = io.StringIO()
actual_change, actual_denominators = make_change(n, d)
with redirect_stdout(captured_output):
pr... |
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
# 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 F... | = self.object.project.task_statuses.get(pk=status_id)
new_status = new_project.task_statuses.get(slug=old_status.slug)
request.DATA['status'] = new_status.id
except TaskStatus.DoesNotExist:
request.DATA['status'] = new_project.... | *kwargs)
def pre_save(self, obj):
if obj.user_story:
obj.milestone = obj.user_story.milestone
if not obj.id:
obj.owner = self.request.user
super().pre_save(obj)
def pre_conditions_on_save(self, obj):
super().pre_conditions_on_save(obj)
if obj.m... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# @name: Wascan - Web Application Scanner
# @repo: https://github.com/m4ll0k/Wascan
# @author: Momo Outaadi (M4ll0k)
# @license: See the file 'LICENSE.txt
from re import search,I
def jiasule(headers,content):
_ = False
for header in headers.items():
_ | | = search(r'__jsluid=|jsl_tracking' | ,header[1],I) is not None
_ |= search(r'jiasule-waf',header[1],I) is not None
if _:break
_ |= search(r'static\.jiasule\.com/static/js/http_error\.js',content) is not None
if _ :
return "Jiasule Web Application Firewall (Jiasule)" |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import re
tags = ['Satellite_5', 'Spacewalk']
name = 'Basic Cobbler settings are correct'
def etc_cobbler_settings(data):
"""
Verify settings in /etc/cobbler/settings:
redhat_management_type: "site"
redhat_management_server: "satellite.example.com"
server... | += "Certain config options in Cobbler configuratin should be set as expected:\n"
for e in result['errors']:
| out += " %s\n" % e
out += "See https://access.redhat.com/solutions/27936"
return out
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015 Thomas Amland
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This ... | showid'],
}
episode = jsonrpc('VideoLibrary.GetEpisodeDetails', params)['result']['episodedetails']
params = {'tvshowid': episode['tvshowid'], 'properties': ['imdbnumber']}
tvshow = jsonrpc('VideoLibrary.GetTVShowDetails', params)['result']['tvshowdetails']
return _load_episode(e... | lf):
params = {'properties': self._movie_properties}
response = jsonrpc('VideoLibrary.GetMovies', params)
movies = response['result'].get('movies', [])
movies = map(_load_movie, movies)
return [m for m in movies if m is not None]
def episodes(self):
params = {'proper... |
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import unittest
from flypy import jit
class TestCallingConventionFromPython(unittest.TestCase):
def test_varargs(self):
@jit
def f(a, b, *args):
return [a, b, args[1]]
self.assertEqual(f... | @jit
def f(*args):
return g(*args)
self.assertEqual(f(1, 2, 3), [1, 2, 3])
def test_unpacking2(self):
raise unittest.SkipTest("unpacking with additional varargs")
@jit
def g(a, b, *args):
return [a, b, args[0]]
@jit
def f(*arg... | enericTuple
if __name__ == '__main__':
unittest.main() |
""" Scrape yahoo industry databa | se through YQL """
import mysql.connector
import stockretriever
import sys
cnx = mysql.connector.connect(user='root', password='root', database='yahoo')
cursor = cnx.cursor()
add_employee = ("INSERT INTO stocks "
"(symbol, name, industry) "
"VALUES (%s, %s, %s) "
| "ON DUPLICATE KEY UPDATE industry=VALUES(industry)")
sectors = stockretriever.get_industry_ids()
for sector in sectors:
for industry in sector['industry']:
try:
print "\nProcessing", industry['name'], industry['id']
except TypeError as E:
print E
con... |
# -*- coding: utf-8 -*-
import logging
import argparse
from .imdb import find_movies
logger = logging.getLogger('mrot')
def parse_args():
parser = argparse.ArgumentParser(prog='mrot', description='Show movie ratings over time.',
formatter_class=argparse.ArgumentDefaultsHelpF... | ncurrent requests to the wayback machine
concurrency = | min(args.concurrency, 10)
# Find the movies corresponding to the given movie name
imdb_movies = find_movies(args.movie_name)
if len(imdb_movies) > 0:
# Show rating for the first movie matching the given name
imdb_movie = imdb_movies[0]
imdb_movie.plot_ratings(concurrency, args.del... |
'''
Created on Apr 30, 2017
@author | : jamie
'''
import numpy as np
class CartState(object):
'''
Defines a Cartesian state information
'''
pos_I = np.array([0., 0., 0.])
| vel_I = np.array([0., 0., 0.])
|
short_name = "godot | "
name = "Godot Engine"
major = 2
minor = 1
patch = 4
| status = "beta"
|
from __future__ import division
import datetime
import pytz
from app.models import Patch
def get_match_patch(match_date):
utc = pytz.UTC
#pylint: disable=no-value-for-parameter
match_date = utc.localize(datetime.datetime.fromtimestamp(match_date))
for patch in Patch.objects.all().order_by('-start_dat... | (gmd, public=None, league=None, team=None, solo=None, \
ranked=None, ap=None, cm=None, ar=None, rap=None):
return check_lobby_type(gmd, public, league, team, solo, ranked) is True \
and check_game_mode(gmd, ap, cm, ar, rap) is True \
and check_abandon(gmd) is False
#pylint: disab... | None and league is None and team is None and solo is None and ranked is None:
public = league = team = solo = ranked = True
if match is not None:
match_type = match['lobby_type']
#pylint: disable=too-many-boolean-expressions
if (public and match_type == 0) or \
(leag... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'PushResult'
db.create_table(u'notos_pushresult', (
(u'id', self.gf('django.db.mo... | u'id': ('django.db.models.fields.Au | toField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'notos.pushresult': {
'Meta': {'object_name': 'PushResult'},
u'i... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-11-03 10:44
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(mig | rations.Migration):
dependencies = [
('domains', '0003_auto_20161103_1031'),
]
operations = [
migrations.RemoveField(
model_name='domain',
name='subtopics',
),
migrations.AddField(
model_name='subtopic',
name='dmain',
... | ),
]
|
from paraview.simple import *
import os
import sys
import numpy as np
path = os.getcwd() + "/"
file_name = sys.argv[1]
inp = file_name + ".e"
outCSV = file_name + ".csv"
reader = Ex | odusIIReader(FileName=path+inp)
tsteps = reader.TimestepValues
writer = CreateWriter(path+file_name+"_Cells.csv", reader)
writer.FieldAssociation = "Cells" | # or "Points"
writer.UpdatePipeline(time=tsteps[len(tsteps)-1])
del writer
writer = CreateWriter(path+file_name+"_Points.csv", reader)
writer.FieldAssociation = "Points" # or "Cells"
writer.UpdatePipeline(time=tsteps[len(tsteps)-1])
del writer
|
self.pkey = None
self.port = port
self.timeout = timeout
self.keepalive_interval = keepalive_interval
# Default values, overridable from Connection
self.compress = True
self.no_host_key_check = True
self.allow_host_key_change = False
self.host_proxy = ... | = str(no_host_key_check).lower() == "true"
if host_key is not None and no_host_key_check:
raise ValueError("Must check host key when provided")
self.no_host_key_check = no_host_key_check
if (
"allow_host_key_change" i... | ):
self.allow_host_key_change = True
if (
"look_for_keys" in extra_options
and str(extra_options["look_for_keys"]).lower() == 'false'
):
self.look_for_keys = False
if host_key ... |
601
import requests
import json
import re
import datetime
from yaml import load
from repoze.lru import lru_cache
from dateutil.parser import parse
from time import sleep
from retrying import retry
from logging import getLogger
RE = re.compile(r'(^.*)@(\d{4}-\d{2}-\d{2}--\d{4}-\d{2}-\d{2})?-([a-z\-]*)\.zip')
LOGGER ... | ate(period[1]))
raise ValueError("Invalid period")
def prepare_result_file_name(utility):
| start, end = "", ""
if utility.start_date:
start = convert_date(
utility.start_date,
timezone="UTC",
to="Europe/Kiev",
format="%Y-%m-%d"
)
if not utility.end_date.startswith("9999"):
end = convert_date(
... |
#!/usr/bin/env pyt | hon3
########################################################################
# Solves problem 142 from projectEuler.net.
# ???
# Copyright (C) 2011 Santiago Alessandri
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publishe... | Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public Licen... |
# 'the .identification and .serviceidentification properties will merge into '
# '.identification being a list of properties. This is currently implemented '
# 'in .identificationinfo. '
# 'Please see https://github.com/geopython/OWSLib/issues/38 for more in... | self.aggregationinfo = None
self.uricode = []
self.uricodespace = []
self.date = []
self.datetype = []
self.uselimitation = | []
self.accessconstraints = []
self.classification = []
self.otherconstraints = []
self.securityconstraints = []
self.useconstraints = []
self.denominators = []
self.distance = []
self.uom = []
self.resourcelang... |
import lie_group_diffeo as lgd
import odl
import numpy as np
# Select space and interpolation
space = odl.uniform_discr([-1, -1], [1, 1], [200, 200], interp='linear')
# Select template and target as gaussians
template = space.element(lambda x: np.exp(-(5 * x[0]**2 + x[1]**2) / 0.4**2))
target = space.element(lambda x... | .ndim)
deform_action = lgd.MatrixImageAffineAction(lie_grp, space)
elif lie_grp_type == 'rigid':
lie_grp = lgd.EuclideanGroup(space.ndim)
deform_action = lgd.MatrixImageAffineAction(lie_grp, space)
else:
assert False
# Define what regularizer to use
regularizer = 'determinant'
if regularizer == 'image'... | s().T)
# Create regularizing functional
regularizer = 0.01 * odl.solvers.L2NormSquared(W).translated(w)
# Create action
regularizer_action = lgd.ProductSpaceAction(deform_action, W.size)
elif regularizer == 'point':
W = odl.ProductSpace(odl.rn(space.ndim), 3)
w = W.element([[0, 0],
... |
from radar.auth.passwords import (
check_password_hash,
generate_password,
generate_password_hash,
get_password_length,
is_strong_password,
password_to_nato_str,
)
from radar.models.users import User
def test_password_to_nato_str():
password = 'aAzZ123'
assert password_to_nato_str(pass... | sword = 'password123'
password_hash = generate_password_hash('password123')
assert password_hash != password
assert check_password_hash(password_hash, password)
def test_generate_password(app):
with app.app_context():
password = generate_password()
assert len(password) == get_password_... | p.app_context():
assert not is_strong_password('password123')
def test_strong_passwords(app):
with app.app_context():
assert is_strong_password('besiderisingwoodennearer')
assert is_strong_password('7pJnW4yUWx')
def test_weak_passwords_for_user(app):
user = User()
user.username =... |
wn': 'Greenwich Standard Time',
'Africa/Gaborone': 'South Africa Standard Time',
'Africa/Harare': 'South Africa Standard Time',
'Africa/Johannesburg': 'South Africa Standard Time',
'Africa/Juba': 'E. Africa Standard Time',
'Africa/Kampala': 'E. Africa Standard Time',
'Africa/Khartoum': 'E. Afric... | Eastern Standard Time',
'America/Belize': 'Central America Standard T | ime',
'America/Blanc-Sablon': 'SA Western Standard Time',
'America/Boa_Vista': 'SA Western Standard Time',
'America/Bogota': 'SA Pacific Standard Time',
'America/Boise': 'Mountain Standard Time',
'America/Buenos_Aires': 'Argentina Standard Time',
'America/Cambridge_Bay': 'Mountain Standard Time'... |
# -----------------------------------------------------------------------------
# Download data:
# - Browser:
# http://midas3.kitware.com/midas/folder/10409 => VisibleMale/vm_head_frozenct.mha
# - Terminal
# curl "http://midas3.kitware.com/midas/download?folders=&items=235235" -o vm_head_frozenct.mha
# ----... | 4
# -----------------------------------------------------------------------------
# VTK Helper methods
# -----------------------------------------------------------------------------
def updatePieceWise(pwf, dataRange, center, halfSpread):
scalarOpac | ity.RemoveAllPoints()
if (center - halfSpread) <= dataRange[0]:
scalarOpacity.AddPoint(dataRange[0], 0.0)
scalarOpacity.AddPoint(center, 1.0)
else:
scalarOpacity.AddPoint(dataRange[0], 0.0)
scalarOpacity.AddPoint(center - halfSpread, 0.0)
scalarOpacity.AddPoint(center, 1.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# C | opyright (C) 2017-2020 The Project X-Ray Authors.
#
# Use of this source code is governed by a ISC-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/ISC
#
# SPDX-License-Identifier: ISC
import sys
import json
from prjxray.xjson import pprint
if __name__ == "__main__":
i... | st.testmod()
else:
assert len(sys.argv) == 2
d = json.load(open(sys.argv[1]))
pprint(sys.stdout, d)
|
Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies... | Y CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
'''
This script is a check for lookup at m | emory consumption over ssh without
having an agent on the other side
'''
import os
import sys
import optparse
# Ok try to load our directory to load the plugin utils.
my_dir = os.path.dirname(__file__)
sys.path.insert(0, my_dir)
try:
import schecks
except ImportError:
print "ERROR : this plugin needs the loc... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from abc import ABCMeta
import csv
from performance_tools.exceptions import ProgressBarException, ElasticsearchException
from performance_tools.utils.progress_bar import create_progress_bar
class BaseURLFlowBackend(object):
"""Collect URL flow fro... | not found any resu | lt.
"""
progress = None
try:
with open(filename, 'w') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(['Referrer', 'Request', 'Time'])
count = 0
for result in self:
# Create progress bar o... |
"""
Python script 'process_NCEI_03_prcp_180d.py'
by Matthew Garcia, PhD student
Dept. of Forest and Wildlife Ecology
University of Wisconsin - Madison
matt.e.garcia@gmail.com
Copyright (C) 2015-2016 by Matthew Garcia
Licensed Gnu GPL v3; see 'LICENSE_GnuGPLv3.txt' for complete terms
Send questions, bug reports, any re... | data=datetime.datetime.now().isoformat())
del h5outfile['meta/at']
outstr = 'prcp_180d'
| h5outfile.create_dataset('meta/at', data=outstr)
write_to_file(h5outfile, 'prcp_180d_sum', grid_prcp_180d,
'prcp_180d_stns', prcp_180d_stns_all)
message(' ')
#
# save rolling accounting variable for next year's run
varfname = '%s/%d_year_end_prcp_180d.h5' % (path, this_year)
message(... |
# Copyright 2012 Leonidas Poulopoulos
#
# 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 w... | ee the License for t | he specific language governing permissions and
# limitations under the License. |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Runs linker tests on a particular device."""
import logging
import os.path
import sys
import traceback
from pylib import constants
from pylib.base impor... | nfo
super(LinkerExceptionTestResult, self).__init__(
test_name,
base_test_result.ResultType.FAIL,
log = "%s %s" % (exc_type, log_msg))
class LinkerTestRunner(base_test_runner.BaseTestRunner):
"""Orchestrates running a set of linker tests.
Any Python e | xceptions in the tests are caught and translated into a failed
result, rather than being re-raised on the main thread.
"""
#override
def __init__(self, device, tool, push_deps, cleanup_test_files):
"""Creates a new LinkerTestRunner.
Args:
device: Attached android device.
tool: Name of the ... |
def linear_search(lst,size,value):
i = 0
while i < size:
if lst[i] == value:
return i
i = i + 1
return -1
def main():
lst = [-31, 0, 1, 2, 2, 4, 65, 83, 99, 782]
size = len(lst)
original_list = ""
| value = int(input("\nInput a value to search for: "))
print("\nOriginal Array: ")
for i in lst:
original_list += str(i) + " "
print(original_list)
print("\nLinear Search Big O Notation:\n--> Best Case: O(1)\n--> Average Case: O(n)\n--> Worst Case: O(n)\n")
index = linear_search(lst | ,size,value)
if index == -1:
print(str(value) + " was not found in that array\n")
else:
print(str(value) + " was found at index " + str(index))
if __name__ == '__main__':
main()
|
import pytest
import numpy as np
import noisily as ns
# FIXME This has got to be an abuse of fixtures, right?
@pytest.fixture(scope='module', params=[(1, 1), (37, 57), (128, 128)])
def indices2D(request):
shape = request.param
return np.transpose(np.indices(shape))
@pytest.fixture(scope='module', params=[(1... | f generator2D(request, noise2D):
return ns.generator(noise2D, **request.param)
@pytest.fixture(scope='module', params=[{'seed': 123}, {'period': 64}, {'seed': 12345, 'period': 16}])
def generator3D(request, noise3D):
return ns.generator(noise3D, **request.param) |
@pytest.fixture(scope='module', params=[{'seed': 123}, {'period': 64}, {'seed': 12345, 'period': 16}])
def generator4D(request, noise4D):
return ns.generator(noise4D, **request.param)
def test_output2D(generator2D, indices2D):
output = generator2D(indices2D)
assert output.shape == indices2D.shape[:-1]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.