repo_name stringlengths 5 100 | path stringlengths 4 231 | language stringclasses 1 value | license stringclasses 15 values | size int64 6 947k | score float64 0 0.34 | prefix stringlengths 0 8.16k | middle stringlengths 3 512 | suffix stringlengths 0 8.17k |
|---|---|---|---|---|---|---|---|---|
filipp/Servo | servo/migrations/0014_orderstatus_duration.py | Python | bsd-2-clause | 439 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
| ('servo', '0013_auto_2015020 | 4_1113'),
]
operations = [
migrations.AddField(
model_name='orderstatus',
name='duration',
field=models.IntegerField(default=0),
preserve_default=True,
),
]
|
wsricardo/mcestudos | treinamento-webScraping/Abraji/p11.py | Python | gpl-3.0 | 468 | 0.021786 | import urllib.request
import | time
preço = 99.99 #algum valor maior
while preço >= 4.74:
pagina = urllib.request.urlopen(
'http://beans.itcarlow.ie/prices-loyalty.html')
texto = pagina.read().decode('ut | f8')
onde = texto.find('>$')
início = onde + 2
fim = início + 4
preço = float(texto[início:fim])
if preço >= 4.74:
print ('Espera...')
time.sleep(600)
print ('Comprar! Preço: %5.2f' %preço)
|
openEduConnect/eduextractor | eduextractor/sis/illuminate/illuminate_exporter.py | Python | mit | 1,702 | 0.006463 | import pandas as pd
from ...config import _load_secrets
import sqlalchemy
import os
from tqdm import tqdm
class IlluminateSQLInterface:
"""A class representing a SQL interface to
Illuminate
"""
def __init__(self, secrets=None):
if secrets is None:
secrets = _load_secrets()
try:
SECRETS = secrets['illuminate']
self.username = SECRETS['username']
self.password = SECRETS['password']
self.host = SECRETS['host']
self.dbname = SECRETS['dbname']
self.port = str(SECRETS['port'])
except KeyError:
print("Please check the configuration of your config file")
engine = sqlalchemy.create_engine('postgres://' + self.username +
':' + self.password +
'@' + self.host + ':' +
self.port + '/' +
self.dbname)
self.conn = engine.connect()
def query_to_df(query):
"""executes query, converts to pd.dataframe"""
df = pd.read_sql(query, conn)
return df
def _list_queries( | file_dir='./sql'):
return os.listdir(file_dir)
def download_files():
files = self._list_queries()
for file_name in tqdm(files):
with open('./sql/' + file_name, 'r') as filebuf:
data = filebuf.read()
df = query_to_df(data)
| file_name = file_name.replace('.sql','.csv')
df.to_csv('/tmp/' + file_name)
if __name__ == '__main__':
IlluminateSQLInterface.download_files()
|
Nablaquabla/sns-analysis | run-ba-analysis-v4.py | Python | gpl-3.0 | 5,144 | 0.033826 | import os
import time as tm
import sys
# Handles the creation of condor files for a given set of directories
# -----------------------------------------------------------------------------
def createCondorFile(dataDir,outDir,run,day,times):
# Condor submission file name convention: run-day-time.condor
with open('/home/bjs66/CondorFiles/%s-%s.condor'%(run,day),'w') as f:
# Fixed program location'
f.write('Executable = /home/bjs66/GitHub/sns-analysis/sns-analysis-v4\n')
# Arguments passed to the exe:
# Set main run directory, e.g. Run-15-10-02-27-32-23/151002
# Set current time to be analzyed (w/o .zip extension!), e.g. 184502
# Set output directory, eg Output/ Run-15-10-02-27-32-23/151002
f.write('Arguments = \"3 %s $(Process) %s 0\"\n'%(dataDir,outDir))
# Standard cluster universe
f.write('universe = vanilla\n')
f.write('getenv = true\n')
# Program needs at least 300 MB of free memory to hold unzipped data
f.write('request_memory = 300\n')
# Output, error and log name convention: run-day-time.log/out/err
f.write('log = ../../Logs/%s-%s-$(Process).log\n'%(run,day))
f.write('Output = ../../Outs/%s-%s-$(Process).out\n'%(run,day))
f.write('Error = ../../Errs/%s-%s-$(Process).err\n'%(run,day))
# Do not write any emails
f.write('notification = never\n')
f.write('+Department = Physics\n')
f.write('should_transfer_files = NO\n')
# Add single job to queue
f.write('Queue %i'%times)
# Main function handling all internals
# -----------------------------------------------------------------------------
def main():
# Choose main directory, i.e. ~/csi/beam_on_data/Run-15-06-25-xyz/
mainRunDir = '/var/phy/project/phil/grayson/COHERENT/CsI/'
# Choose output directory, i.e. ~/output/Run-15-06-25-xyz/
mainOutDir = '/var/phy/project/phil/grayson/COHERENT/CsI/bjs-analysis/'
# Choose run to analyze
# runDirs = ['Run-15-03-27-12-42-26']
# run = 'Run-15-03-30-13-33-05'
# run = 'Run-15-04-08-11-38-28'
# run = 'Run-15-04-17-16-56-59'
# run = 'Run-15-04-29-16-34-44'
# runDirs = ['Run-15-05-05-1 | 6-09-12']
# run = 'Run-15-05-11-11-46-30'
# run = 'Run-15-05-19-17-04-44'
# run = 'Run-15-05-27-11-13-46'
# runDirs = ['Run-15-05-05-16-09-12','Run-15-05-11-11-46-30','Run-15-05-19-17-04-44','Run-15-05-27-11-13-46']
runDirs = ['Run-15-03-27-12-42-26','Run-15-03-30-13-33-05','Run-15-04-08-11-38-28','Run-15-04-17-16-56-59','Run-15-04-29-16-34-44',
'Run-15-05-05-16-09-12','Run-15-05-11-11-46-30','Run-15-05-19-17-04-44','Run-15-05-27-11-13-46']
subdirs = {}
d | ays_in = {'Run-15-03-27-12-42-26': ['150327','150328','150329','150330'],
'Run-15-03-30-13-33-05': ['150330','150331','150401','150402','150403','150404','150405','150406','150407','150408'],
'Run-15-04-08-11-38-28': ['150408','150409','150410','150411','150412','150413','150414','150415','150416'],
'Run-15-04-17-16-56-59': ['150417','150418','150419','150420','150421','150422','150423','150424','150425','150426','150427','150428','150429'],
'Run-15-04-29-16-34-44': ['150429','150430','150501','150502','150503','150504','150505'],
'Run-15-05-05-16-09-12': ['150505','150506','150507','150508','150509','150510','150511'],
'Run-15-05-11-11-46-30': ['150512','150513','150514','150515','150516','150517','150518','150519'],
'Run-15-05-19-17-04-44': ['150519','150520','150521','150522','150523','150524','150525','150526','150527'],
'Run-15-05-27-11-13-46': ['150527','150528','150529','150530','150531','150601','150602','150603','150604','150605','150606','150607','150608','150609']}
for run in runDirs:
subdirs[run] = 'brillance_data'
# Iterate through all days in a given run folder, create a condor file and run it.
for day in days_in[run]:
# Prepare paths for further processing
dataRunDir = mainRunDir + '%s/%s/%s'%(subdirs[run],run,day)
outDir = mainOutDir + '%s/%s'%(run,day)
# Create output directory if it does not exist
if not os.path.exists(outDir):
os.makedirs(outDir)
# Get all times within the day folder chosen and prepare condor submit files
tList = [x.split('.')[0] for x in os.listdir(dataRunDir)]
createCondorFile(dataRunDir,outDir,run,day,len(tList))
# createCondorFile(dataRunDir,outDir,run,day,2)
cmd = 'condor_submit /home/bjs66/CondorFiles/%s-%s.condor'%(run,day)
os.system(cmd)
tm.sleep(1)
if __name__ == '__main__':
main()
|
arrabito/DIRAC | Core/Utilities/File.py | Python | gpl-3.0 | 7,925 | 0.012744 | """Collection of DIRAC useful file related modules.
.. warning::
By default on Error they return None.
"""
# pylint: skip-file
# getGlobbedFiles gives "RuntimeError: maximum recursion depth exceeded" in pylint
import os
import hashlib
import random
import glob
import sys
import re
import errno
__RCSID__ = "$Id$"
# Translation table of a given unit to Bytes
# I know, it should be kB...
SIZE_UNIT_CONVERSION = {
'B': 1,
'KB': 1024,
'MB': 1024 *
1024,
'GB': 1024 *
1024 *
1024,
'TB': 1024 *
1024 *
1024 *
1024,
'PB': 1024 *
1024 *
1024 *
1024 *
1024}
def mkDir(path):
""" Emulate 'mkdir -p path' (if path exists already, don't raise an exception)
"""
try:
if os.path.isdir(path):
return
os.makedirs(path)
except OSError as osError:
if osError.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def mkLink(src, dst):
""" Protected creation of simbolic link
"""
try:
os.symlink(src, dst)
except OSError as osError:
if osError.errno == errno.EEXIST and os.path.islink(dst) and os.path.realpath(dst) == src:
pass
else:
raise
def makeGuid(fileName=None):
"""Utility to create GUID. If a filename is provided the
GUID will correspond to its content's hexadecimal md5 checksum.
Otherwise a random seed is used to create the GUID.
The format is capitalized 8-4-4-4-12.
.. warning::
Could return None in case of OSError or IOError.
:param string fileName: name of file
"""
myMd5 = hashlib.md5()
if fileName:
try:
with open(fileName, 'r') as fd:
data = fd.read(10 * 1024 * 1024)
myMd5.update(data)
except BaseException:
return None
else:
myMd5.update(str(random.getrandbits(128)))
md5HexString = myMd5.hexdigest().upper()
return generateGuid(md5HexString, "MD5")
def generateGuid(checksum, checksumtype):
""" Generate a GUID based on the file checksum
"""
if checksum:
if checksumtype == "MD5":
checksumString = checksum
elif checksumtype == "Adler32":
checksumString = str(checksum).zfill(32)
else:
checksumString = ''
if checksumString:
guid = "%s-%s-%s-%s-%s" % (checksumString[0:8],
checksumString[8:12],
checksumString[12:16],
checksumString[16:20],
checksumString[20:32])
guid = guid.upper()
return guid
# Failed to use the check sum, generate a new guid
myMd5 = hashlib.md5()
myMd5.update(str(random.getrandbits(128)))
md5HexString = myMd5.hexdigest()
guid = "%s-%s-%s-%s-%s" % (md5HexString[0:8],
md5HexString[8:12],
md5HexString[12:16],
md5HexString[16:20],
md5HexString[20:32])
guid = guid.upper()
return guid
def checkGuid(guid):
"""Checks whether a supplied GUID is of the correct format.
The guid is a string of 36 characters [0-9A-F] long split into 5 parts of length 8-4-4-4-12.
.. warning::
As we are using GUID produced by various services and some of them could not follow
convention, this function is passing by a guid which can be made of lower case chars or even just
have 5 parts of proper length with whatever chars.
:param string guid: string to be checked
:return: True (False) if supplied string is (not) a valid GUID.
"""
reGUID = re.compile("^[0-9A-F]{8}(-[0-9A-F]{4}){3}-[0-9A-F]{12}$")
if reGUID.match(guid.upper()):
return True
else:
guid = [len(x) for x in guid.split("-")]
if (guid == [8, 4, 4, 4, 12]):
return True
return False
def getSize(fileName):
"""Get size of a file.
:param string fileName: name of file to be checked
The os module claims only OSError can be thrown,
but just for curiosity it's catching all possible exceptions.
.. warning::
On any exception it returns -1.
" | ""
try:
return os.stat(fileName)[6]
except OSError:
return - 1
def getGlobbedTotalSize(files):
"""Get total size of a list of files or a single file.
Globs the parameter to all | ow regular expressions.
:params list files: list or tuple of strings of files
"""
totalSize = 0
if isinstance(files, (list, tuple)):
for entry in files:
size = getGlobbedTotalSize(entry)
if size == -1:
size = 0
totalSize += size
else:
for path in glob.glob(files):
if os.path.isdir(path):
for content in os.listdir(path):
totalSize += getGlobbedTotalSize(os.path.join(path, content))
if os.path.isfile(path):
size = getSize(path)
if size == -1:
size = 0
totalSize += size
return totalSize
def getGlobbedFiles(files):
"""Get list of files or a single file.
Globs the parameter to allow regular expressions.
:params list files: list or tuple of strings of files
"""
globbedFiles = []
if isinstance(files, (list, tuple)):
for entry in files:
globbedFiles += getGlobbedFiles(entry)
else:
for path in glob.glob(files):
if os.path.isdir(path):
for content in os.listdir(path):
globbedFiles += getGlobbedFiles(os.path.join(path, content))
if os.path.isfile(path):
globbedFiles.append(path)
return globbedFiles
def getCommonPath(files):
"""Get the common path for all files in the file list.
:param files: list of strings with paths
:type files: python:list
"""
def properSplit(dirPath):
"""Splitting of path to drive and path parts for non-Unix file systems.
:param string dirPath: path
"""
nDrive, nPath = os.path.splitdrive(dirPath)
return [nDrive] + [d for d in nPath.split(os.sep) if d.strip()]
if not files:
return ""
commonPath = properSplit(files[0])
for fileName in files:
if os.path.isdir(fileName):
dirPath = fileName
else:
dirPath = os.path.dirname(fileName)
nPath = properSplit(dirPath)
tPath = []
for i in range(min(len(commonPath), len(nPath))):
if commonPath[i] != nPath[i]:
break
tPath .append(commonPath[i])
if not tPath:
return ""
commonPath = tPath
return tPath[0] + os.sep + os.path.join(*tPath[1:])
def getMD5ForFiles(fileList):
"""Calculate md5 for the content of all the files.
:param fileList: list of paths
:type fileList: python:list
"""
fileList.sort()
hashMD5 = hashlib.md5()
for filePath in fileList:
if os.path.isdir(filePath):
continue
with open(filePath, "rb") as fd:
buf = fd.read(4096)
while buf:
hashMD5.update(buf)
buf = fd.read(4096)
return hashMD5.hexdigest()
def convertSizeUnits(size, srcUnit, dstUnit):
""" Converts a number from a given source unit to a destination unit.
Example:
In [1]: convertSizeUnits(1024, 'B', 'kB')
Out[1]: 1
In [2]: convertSizeUnits(1024, 'MB', 'kB')
Out[2]: 1048576
:param size: number to convert
:param srcUnit: unit of the number. Any of ( 'B', 'kB', 'MB', 'GB', 'TB', 'PB')
:param dstUnit: unit expected for the return. Any of ( 'B', 'kB', 'MB', 'GB', 'TB', 'PB')
:returns: the size number converted in the dstUnit. In case of problem -sys.maxint is returned (negative)
"""
srcUnit = srcUnit.upper()
dstUnit = dstUnit.upper()
try:
convertedValue = float(size) * SIZE_UNIT_CONVERSION[srcUnit] / SIZE_UNIT_CONVERSION[dstUnit]
return convertedValue
# TypeError, ValueError: size is not a number
# KeyError: srcUnit or dstUnit are not in the conversion list
except (TypeError, ValueError, KeyError):
return -sys.maxsize
if __name__ == "__main__":
for p in sys.argv[1:]:
print "%s : %s bytes" % (p, getGlobbedTotalSize(p))
|
otherway/loc-spain | l10n_es_account_asset/account_asset.py | Python | agpl-3.0 | 9,813 | 0.002244 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2012 Serv. Tecnol. Avanzados (http://www.serviciosbaeza.com)
# Pedro Manuel Baeza <pedro.baeza@serviciosbaeza.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 Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without ev | en the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import calendar
from datetime import datetime
from openerp.osv import orm, fields
from openerp.tools import DEFAULT_SERVER_DATE_FORMAT as DSDF
class account_asset_category(orm.Model):
_inherit = 'account.asset.category'
_columns = {
'ext_method_time': fields.selection(
[('number', 'Number of Depreciations'),
('end', 'Ending Date'),
('percentage', 'Fixed percentage')], 'Time Method', required=True,
help="Choose the method to use to compute the dates and number of "
"depreciation lines.\n"
" * Number of Depreciations: Fix the number of depreciation "
"lines and the time between 2 depreciations.\n"
" * Ending Date: Choose the time between 2 depreciations "
"and the date the depreciations won't go beyond.\n"
" * Fixed percentage: Choose the time between 2 "
"depreciations and the percentage to depreciate."),
'method_percentage': fields.float('Depreciation percentage',
digits=(3,2)),
}
_defaults = {
'method_percentage': 100.0,
'ext_method_time': 'percentage',
}
_sql_constraints = [
('method_percentage',
' CHECK (method_percentage > 0 and method_percentage <= 100)',
'Wrong percentage!'),
]
def onchange_ext_method_time(self, cr, uid, ids, ext_method_time,
context=None):
res = {'value':{}}
res['value']['method_time'] = 'end' if ext_method_time == 'end' else 'number'
return res
class account_asset_asset(orm.Model):
_inherit = 'account.asset.asset'
_columns = {
'move_end_period': fields.boolean("At the end of the period",
help='Move the depreciation entry at the end of the period. If '
'the period are 12 months, it is put on 31st of December, '
'and in the end of the month in other case.'),
# Hay que definir un nuevo campo y jugar con los valores del antiguo
# (method_time) para pasar el constraint _check_prorata y no tener que
# modificar mucho código base
'ext_method_time': fields.selection(
[('number', 'Number of Depreciations'),
('end','Ending Date'),
('percentage','Fixed percentage')], 'Time Method', required=True,
help="Choose the method to use to compute the dates and number of "
"depreciation lines.\n"
" * Number of Depreciations: Fix the number of depreciation "
"lines and the time between 2 depreciations.\n"
" * Ending Date: Choose the time between 2 depreciations "
"and the date the depreciations won't go beyond.\n"
" * Fixed percentage: Choose the time between 2 "
"depreciations and the percentage to depreciate."),
'method_percentage': fields.float('Depreciation percentage',
digits=(3,2)),
}
_defaults = {
'method_percentage': 100.0,
'move_end_period': True,
}
_sql_constraints = [
('method_percentage',
' CHECK (method_percentage > 0 and method_percentage <= 100)',
'Wrong percentage!'),
]
def onchange_ext_method_time(self, cr, uid, ids, ext_method_time,
context=None):
res = {'value':{}}
res['value']['method_time'] = ('end' if ext_method_time == 'end'
else 'number')
return res
def onchange_category_id(self, cr, uid, ids, category_id, context=None):
res = super(account_asset_asset, self).onchange_category_id(cr, uid,
ids, category_id, context=context)
if category_id:
category_obj = self.pool.get('account.asset.category')
category = category_obj.browse(cr, uid, category_id,
context=context)
res['value']['ext_method_time'] = category.ext_method_time
res['value']['method_percentage'] = category.method_percentage
return res
def _compute_board_undone_dotation_nb(self, cr, uid, asset,
depreciation_date, total_days, context=None):
if asset.ext_method_time == 'percentage':
number = 0
percentage = 100.0
while percentage > 0:
if number == 0 and asset.prorata:
days = (total_days -
float(depreciation_date.strftime('%j'))) + 1
percentage -= asset.method_percentage * days / total_days
else:
percentage -= asset.method_percentage
number += 1
return number
else:
val = super(account_asset_asset, self).\
_compute_board_undone_dotation_nb(cr, uid, asset,
depreciation_date,
total_days, context=context)
if depreciation_date.day == 1 and depreciation_date.month == 1:
# Quitar una depreciación del nº total si el activo se compró
# el 1 de enero, ya que ese año sería completo
val -= 1
return val
def _compute_board_amount(self, cr, uid, asset, i, residual_amount,
amount_to_depr, undone_dotation_number,
posted_depreciation_line_ids, total_days,
depreciation_date, context=None):
if asset.ext_method_time == 'percentage':
# Nuevo tipo de cálculo
if i == undone_dotation_number:
return residual_amount
else:
if i == 1 and asset.prorata:
days = (total_days -
float(depreciation_date.strftime('%j'))) + 1
percentage = asset.method_percentage * days / total_days
else:
percentage = asset.method_percentage
return amount_to_depr * percentage / 100
elif (asset.method == 'linear' and asset.prorata and
i != undone_dotation_number):
# Caso especial de cálculo que cambia
amount = amount_to_depr / asset.method_number
if i == 1:
days = (total_days -
float(depreciation_date.strftime('%j'))) + 1
amount *= days / total_days
return amount
else:
return super(account_asset_asset, self)._compute_board_amount(cr,
uid, asset, i, residual_amount, amount_to_depr,
undone_dotation_number, posted_depreciation_line_ids,
total_days, depreciation_date, context=context)
def compute_depreciation_board(self, cr, uid, id |
ospaceteam/outerspace | client/osci/dialog/ColorDefinitionDlg.py | Python | gpl-2.0 | 6,398 | 0.027665 | #
# Copyright 2001 - 2016 Ludek Smid [http://www.ospace.net/]
#
# This file is part of Outer Space.
#
# Outer Space is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Outer Space is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Outer Space; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
import pygameui as ui
from osci import client, gdata, res
from ige import log
class ColorDefinitionDlg:
def __init__(self, app):
self.app = app
self.createUI()
def | display(self, color = None, confirmAction = None):
self.confirmAction = confirmAction
if color == None:
self.color = (0xff,0xff,0xff)
else:
self.color = color
self.show()
def show(self):
self.win.vR.text = hex(self.color[0])
self.win.vG.text = hex(self.color[1])
self.win. | vB.text = hex(self.color[2])
self.win.vRS.slider.min = 0
self.win.vRS.slider.max = 265
self.win.vRS.slider.position = self.color[0]
self.win.vGS.slider.min = 0
self.win.vGS.slider.max = 265
self.win.vGS.slider.position = self.color[1]
self.win.vBS.slider.min = 0
self.win.vBS.slider.max = 265
self.win.vBS.slider.position = self.color[2]
log.debug("ColorDefinitionDlg(%s,%s,%s)" % (self.win.vR.text,self.win.vG.text,self.win.vB.text))
self.win.show()
# colorbox
self.win.vColor.color = self.color
# register for updates
if self not in gdata.updateDlgs:
gdata.updateDlgs.append(self)
def hide(self):
self.win.setStatus(_("Ready."))
self.win.hide()
# unregister updates
if self in gdata.updateDlgs:
gdata.updateDlgs.remove(self)
def update(self):
self.show()
def onChangeRed(self, widget, action, data):
self.color = (int(self.win.vRS.slider.position), self.color[1], self.color[2])
self.win.vR.text = hex(self.color[0])
self.win.vColor.color = (int(self.win.vRS.slider.position), self.color[1], self.color[2])
def onChangeGreen(self, widget, action, data):
self.color = (self.color[0], int(self.win.vGS.slider.position), self.color[2])
self.win.vG.text = hex(self.color[1])
self.win.vColor.color = (self.color[0], int(self.win.vGS.slider.position), self.color[2])
def onChangeBlue(self, widget, action, data):
self.color = ( self.color[0], self.color[1], int(self.win.vBS.slider.position))
self.win.vB.text = hex(self.color[2])
self.win.vColor.color = ( self.color[0], self.color[1], int(self.win.vBS.slider.position))
def onOK(self, widget, action, data):
try:
r = int(self.win.vR.text,16)
g = int(self.win.vG.text,16)
b = int(self.win.vB.text,16)
if not r in range(0,256):
self.app.setFocus(self.win.vR)
raise ValueError
elif not g in range(0,256):
self.app.setFocus(self.win.vG)
raise ValueError
elif not b in range(0,256):
self.app.setFocus(self.win.vB)
raise ValueError
except ValueError:
self.win.setStatus(_("Values must be hexa numbers between 0x00 - 0xff"))
return
self.hide()
self.color = (r, g, b)
if self.confirmAction:
self.confirmAction()
def onCancel(self, widget, action, data):
self.color = None
self.hide()
def createUI(self):
w, h = gdata.scrnSize
cols = 14
rows = 8
width = cols * 20 + 5
height = rows * 20 + 4
self.win = ui.Window(self.app,
modal = 1,
escKeyClose = 1,
movable = 0,
title = _('Color Definition'),
rect = ui.Rect((w - width) / 2, (h - height) / 2, width, height),
layoutManager = ui.SimpleGridLM(),
tabChange = True,
)
# creating dialog window
self.win.subscribeAction('*', self)
# R
ui.Label(self.win,text = _("Red:"), align = ui.ALIGN_W, layout = (0, 0, 3, 1))
ui.Entry(self.win, id = 'vR',align = ui.ALIGN_W,layout = (7, 0, 3, 1), orderNo = 1, reportValueChanged = True,)
ui.Scrollbar(self.win,layout = ( 0,1,10,1), id='vRS',action = "onChangeRed")
# G
ui.Label(self.win,text = _("Green:"),align = ui.ALIGN_W,layout = (0, 2, 3, 1))
ui.Entry(self.win, id = 'vG',align = ui.ALIGN_W,layout = (7, 2, 3, 1), orderNo = 2, reportValueChanged = True,)
ui.Scrollbar(self.win,layout = (0,3,10,1), id='vGS',action = "onChangeGreen")
# B
ui.Label(self.win,text = _("Blue:"),align = ui.ALIGN_W,layout = (0, 4, 3, 1))
ui.Entry(self.win, id = 'vB',align = ui.ALIGN_W,layout = (7, 4, 3, 1), orderNo = 3, reportValueChanged = True,)
ui.Scrollbar(self.win,layout = (0,5,10,1), id='vBS',action = "onChangeBlue")
# color example
ui.ColorBox(self.win, id = 'vColor', layout = (10, 0, 4, 6), margins = (4, 3, 4, 4))
#i.Title(self.win, layout = (0, 4, 2, 1))
ui.TitleButton(self.win, layout = (0, 6, 7, 1), text = _("Cancel"), action = "onCancel")
okBtn = ui.TitleButton(self.win, layout = (7, 6, 7, 1), text = _("OK"), action = 'onOK')
self.win.acceptButton = okBtn
def onValueChanged(self, widget, action, data):
try:
r = int(self.win.vR.text,16)
g = int(self.win.vG.text,16)
b = int(self.win.vB.text,16)
except:
return
if not r in range(0,256) or not g in range(0,256) or not b in range(0,256):
return
self.win.vColor.color = (r, g, b)
self.win.vRS.slider.position = r
self.win.vGS.slider.position = g
self.win.vBS.slider.position = b
|
fharenheit/template-spark-app | src/main/python/mllib/ranking_metrics_example.py | Python | apache-2.0 | 2,197 | 0.00091 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
#
# $example on$
from pyspark.mllib.recommendation import ALS, Rating
from pyspark.mllib.evaluation | import RegressionMetrics, RankingMetrics
# $example off$
from pyspark import SparkContext
if __name__ == "__main__":
sc = SparkContext(appName="Ranking Metrics Example")
# Several of the methods available in scala are currently missing from pyspark
# $exampl | e on$
# Read in the ratings data
lines = sc.textFile("data/mllib/sample_movielens_data.txt")
def parseLine(line):
fields = line.split("::")
return Rating(int(fields[0]), int(fields[1]), float(fields[2]) - 2.5)
ratings = lines.map(lambda r: parseLine(r))
# Train a model on to predict user-product ratings
model = ALS.train(ratings, 10, 10, 0.01)
# Get predicted ratings on all existing user-product pairs
testData = ratings.map(lambda p: (p.user, p.product))
predictions = model.predictAll(testData).map(lambda r: ((r.user, r.product), r.rating))
ratingsTuple = ratings.map(lambda r: ((r.user, r.product), r.rating))
scoreAndLabels = predictions.join(ratingsTuple).map(lambda tup: tup[1])
# Instantiate regression metrics to compare predicted and actual ratings
metrics = RegressionMetrics(scoreAndLabels)
# Root mean squared error
print("RMSE = %s" % metrics.rootMeanSquaredError)
# R-squared
print("R-squared = %s" % metrics.r2)
# $example off$
|
ktan2020/legacy-automation | win/Lib/site-packages/jpype/_jpackage.py | Python | mit | 1,988 | 0.013078 | #*****************************************************************************
# Copyright 2004-2008 Steve Menard
#
# 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.
#
#*****************************************************************************
import _jpype
import _jclass
class JPackage(object) :
def __init__(self, name) :
self.__name = name
def __getattribute__(self, n) :
try :
return object.__getattribute__(self, n)
except :
# not found ...
# perhaps it is a class?
subname = "%s.%s" % (self.__name, n)
cc = _jpype.findClass(subname)
if cc is None :
# can only assume it is a sub-package then ...
cc = JPackage(subname)
else:
cc = _jclass._getClassFor(cc)
self.__setattr__(n, cc, True)
return cc
def __setattr__(self, n, v, intern=Fals | e) :
if not n[:len("_JPackage")] == '_JPackage' and not intern : # NOTE this shadows name mangling
raise RuntimeError, "Cannot set attributes in a package"+n
object.__setattr__(self, n, v)
def __str__(self) :
return "<Java package %s>" % self.__name
def __call__(self, *arg, **kwarg) :
raise TypeError, "Package "+self.__name+" is not Calla | ble"
|
kenshay/ImageScript | ProgramData/SystemFiles/Python/Lib/site-packages/spyderlib/widgets/internalshell.py | Python | gpl-3.0 | 16,008 | 0.005748 | # -*- coding: utf-8 -*-
#
# Copyright © 2009-2010 Pierre Raybaut
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
"""Internal shell widget : PythonShellWidget + Interpreter"""
# pylint: disable=C0103
# pylint: disable=R0903
# pylint: disable=R0911
# pylint: disable=R0201
#FIXME: Internal shell MT: for i in range(100000): print i -> bug
#----Builtins*
from spyderlib.py3compat import builtins
from spyderlib.widgets.objecteditor import oedit
builtins.oedit = oedit
import os
import threading
from time import time
from subprocess import Popen
from spyderlib.qt.QtGui import QMessageBox
from spyderlib.qt.QtCore import SIGNAL, QObject, QEventLoop
# Local import
from spyderlib import get_versions
from spyderlib.utils.qthelpers import create_action, get_std_icon
from spyderlib.interpreter import Interpreter
from spyderlib.utils.dochelpers import getargtxt, getsource, getdoc, getobjdir
from spyderlib.utils.misc import get_error_match
#TODO: remove the CONF object and make it work anyway
# In fact, this 'CONF' object has nothing to do in package spyderlib.widgets
# which should not contain anything directly related to Spyder's main app
from spyderlib.baseconfig import get_conf_path, _, DEBUG
from spyderlib.config import CONF
from spyderlib.widgets.shell import PythonShellWidget
from spyderlib.py3compat import to_text_string, getcwd, to_binary_string, u
def create_banner(message):
"""Create internal shell banner"""
if message is None:
versions = get_versions()
return 'Python %s %dbits [%s]'\
% (versions['python'], versions['bitness'], versions['system'])
else:
return message
class SysOutput(QObject):
"""Handle standard I/O queue"""
def __init__(self):
QObject.__init__(self)
self.queue = []
self.lock = threading.Lock()
def write(self, val):
self.lock.acquire()
self.queue.append(val)
self.lock.release()
self.emit(SIGNAL("void data_avail()"))
def empty_queue(self):
self.lock.acquire()
s = "".join(self.queue)
self.queue = []
self.lock.release()
return s
# We need to add this method to fix Issue 1789
def flush(self):
pass
class WidgetProxyData(object):
pass
class WidgetProxy(QObject):
"""Handle Shell widget refresh signal"""
def __init__(self, input_condition):
QObject.__init__(self)
self.input_data = None
self.input_condition = input_condition
def new_prompt(self, prompt):
self.emit(SIGNAL("new_prompt(QString)"), prompt)
def set_readonly(self, state):
self.emit(SIGNAL("set_readonly(bool)"), state)
def edit(self, filename, external_editor=False):
self.emit(SIGNAL("edit(QString,bool)"), filename, external_editor)
def data_available(self):
"""Return True if input data is available"""
return self.input_data is not WidgetProxyData
def wait_input(self, prompt=''):
self.input_data = WidgetProxyData
self.emit(SIGNAL("wait_input(QString)"), prompt)
def end_input(self, cmd):
self.input_condition.acquire()
self.input_data = cmd
self.input_condition.notify()
self.input_condition.release()
class InternalShell(PythonShellWidget):
"""Shell base widget: link between PythonShellWidget and Interpreter"""
def __init__(self, parent=None, namespace=None, commands=[], message=None,
max_line_count=300, font=None, exitfunc=None, profile=False,
multithreaded=True, light_background=True):
PythonShellWidget.__init__(self, parent,
get_conf_path('history_internal.py'),
profile)
self.set_light_background(light_background)
self.multithreaded = multithreaded
self.setMaximumBlockCount(max_line_count)
# For compatibility with ExtPythonShellWidget
self.is_ipykernel = False
if font is not None:
self.set_font(font)
# Allow raw_input support:
self.input_loop = None
self.input_mode = False
# KeyboardInterrupt support
self.interrupted = False # used only for not-multithreaded mode
self.connect(self, SIGNAL("keyboard_interrupt()"),
self.keyboard_interrupt)
# Code completion / calltips
getcfg = lambda option: CONF.get('internal_console', option)
case_sensitive = getcfg('codecompletion/case_sensitive')
self.set_codecompletion_case(case_sensitive)
# keyboard events management
self.eventqueue = []
# Init interpreter
self.exitfunc = exitfunc
self.commands = commands
self.message = message
self.interpreter = None
self.start_interpreter(namespace)
# Clear status bar
self.emit(SIGNAL("status(QString)"), '')
# Embedded shell -- requires the monitor (which installs the
# 'open_in_spyder' function in builtins)
| if hasattr(builtins, 'open_in_spyder'):
self.connect(self, SIGNAL("go_to_error(QString)"),
self.open_with_external_spyder)
#------ Interpreter
def start_interpreter(self, namespace):
"""Start Python interpreter"""
self.clear()
if self.interpreter is not None:
self.interpreter.closing()
self.inte | rpreter = Interpreter(namespace, self.exitfunc,
SysOutput, WidgetProxy, DEBUG)
self.connect(self.interpreter.stdout_write,
SIGNAL("void data_avail()"), self.stdout_avail)
self.connect(self.interpreter.stderr_write,
SIGNAL("void data_avail()"), self.stderr_avail)
self.connect(self.interpreter.widget_proxy,
SIGNAL("set_readonly(bool)"), self.setReadOnly)
self.connect(self.interpreter.widget_proxy,
SIGNAL("new_prompt(QString)"), self.new_prompt)
self.connect(self.interpreter.widget_proxy,
SIGNAL("edit(QString,bool)"), self.edit_script)
self.connect(self.interpreter.widget_proxy,
SIGNAL("wait_input(QString)"), self.wait_input)
if self.multithreaded:
self.interpreter.start()
# Interpreter banner
banner = create_banner(self.message)
self.write(banner, prompt=True)
# Initial commands
for cmd in self.commands:
self.run_command(cmd, history=False, new_prompt=False)
# First prompt
self.new_prompt(self.interpreter.p1)
self.emit(SIGNAL("refresh()"))
return self.interpreter
def exit_interpreter(self):
"""Exit interpreter"""
self.interpreter.exit_flag = True
if self.multithreaded:
self.interpreter.stdin_write.write('\n')
self.interpreter.restore_stds()
def edit_script(self, filename, external_editor):
filename = to_text_string(filename)
if external_editor:
self.external_editor(filename)
else:
self.parent().edit_script(filename)
def stdout_avail(self):
"""Data is available in stdout, let's empty the queue and write it!"""
data = self.interpreter.stdout_write.empty_queue()
if data:
self.write(data)
def stderr_avail(self):
"""Data is available in stderr, let's empty the queue and write it!"""
data = self.interpreter.stderr_write.empty_queue()
if data:
self.write(data, error=True)
self.flush(error=True)
#------Raw input support
def wait_input(self, prompt=''):
"""Wait for input (raw_input support)"""
self.new_prompt(prompt)
self.setFocus()
self.input_mode = True
self.input_loop |
ayziao/niascape | niascape/usecase/postcount.py | Python | mit | 1,264 | 0.01494 | """
nias | cape.usecase.postcount
投稿件数ユースケース
"""
import niascape
from niascape.repository import postcount
from niascape.utility.database import get_db
def day(option: dict) -> list:
with get_db(niascape.ini['database']) as db: # type: ignore # XXX セクションぶっこむとmypyさんにおこられ 辞書化すべきか
return postcount.day(db, **option)
def month(option: dict) -> list:
with get_db(niascape.ini['database']) as db: # type: ignore # XXX セクションぶっこむとmypyさんにおこられ 辞書化すべきか
return postcount.month(db, **option)
|
def hour(option: dict) -> list:
with get_db(niascape.ini['database']) as db: # type: ignore # XXX セクションぶっこむとmypyさんにおこられ 辞書化すべきか
return postcount.hour(db, **option)
def week(option: dict) -> list:
with get_db(niascape.ini['database']) as db: # type: ignore # XXX セクションぶっこむとmypyさんにおこられ 辞書化すべきか
return postcount.week(db, **option)
def tag(option: dict) -> list:
with get_db(niascape.ini['database']) as db: # type: ignore # XXX セクションぶっこむとmypyさんにおこられ 辞書化すべきか
return postcount.tag(db, **option)
|
waseem18/oh-mainline | vendor/packages/celery/funtests/suite/test_leak.py | Python | agpl-3.0 | 3,713 | 0.001616 | import gc
import os
import sys
import shlex
import subprocess
sys.path.insert(0, os.getcwd())
sys.path.insert(0, os.path.join(os.getcwd(), os.pardir))
from nose import SkipTest
from celery import current_app
from celery.tests.utils import unittest
import suite
GET_RSIZE = "/bin/ps -p %(pid)s -o rss="
QUICKTEST = int(os.environ.get("QUICKTEST", 0))
class Sizes(list):
def add(self, item):
if item not in self:
| self.append(item)
def average(self):
return sum(self) / len(self)
class LeakFunCase(unittest.TestCase):
def setUp(self):
self.app = current_app
self.debug = os.enviro | n.get("TEST_LEAK_DEBUG", False)
def get_rsize(self, cmd=GET_RSIZE):
try:
return int(subprocess.Popen(
shlex.split(cmd % {"pid": os.getpid()}),
stdout=subprocess.PIPE).communicate()[0].strip())
except OSError, exc:
raise SkipTest("Can't execute command: %r: %r" % (cmd, exc))
def sample_allocated(self, fun, *args, **kwargs):
before = self.get_rsize()
fun(*args, **kwargs)
gc.collect()
after = self.get_rsize()
return before, after
def appx(self, s, r=1):
"""r==1 (10e1): Keep up to hundred kB,
e.g. 16,268MB becomes 16,2MB."""
return int(s / 10.0 ** (r + 1)) / 10.0
def assertFreed(self, n, fun, *args, **kwargs):
# call function first to load lazy modules etc.
fun(*args, **kwargs)
try:
base = self.get_rsize()
first = None
sizes = Sizes()
for i in xrange(n):
before, after = self.sample_allocated(fun, *args, **kwargs)
if not first:
first = after
if self.debug:
print("%r %s: before/after: %s/%s" % (
fun, i, before, after))
else:
sys.stderr.write(".")
sizes.add(self.appx(after))
self.assertEqual(gc.collect(), 0)
self.assertEqual(gc.garbage, [])
try:
assert self.appx(first) >= self.appx(after)
except AssertionError:
print("BASE: %r AVG: %r SIZES: %r" % (
base, sizes.average(), sizes, ))
raise
finally:
self.app.control.discard_all()
class test_leaks(LeakFunCase):
def test_task_apply_leak(self):
its = QUICKTEST and 10 or 1000
self.assertNotEqual(self.app.conf.BROKER_TRANSPORT, "memory")
@self.app.task
def task1():
pass
try:
pool_limit = self.app.conf.BROKER_POOL_LIMIT
except AttributeError:
return self.assertFreed(self.iterations, foo.delay)
self.app.conf.BROKER_POOL_LIMIT = None
try:
self.app._pool = None
self.assertFreed(its, task1.delay)
finally:
self.app.conf.BROKER_POOL_LIMIT = pool_limit
def test_task_apply_leak_with_pool(self):
its = QUICKTEST and 10 or 1000
self.assertNotEqual(self.app.conf.BROKER_TRANSPORT, "memory")
@self.app.task
def task2():
pass
try:
pool_limit = self.app.conf.BROKER_POOL_LIMIT
except AttributeError:
raise SkipTest("This version does not support autopool")
self.app.conf.BROKER_POOL_LIMIT = 10
try:
self.app._pool = None
self.assertFreed(its, task2.delay)
finally:
self.app.conf.BROKER_POOL_LIMIT = pool_limit
if __name__ == "__main__":
unittest.main()
|
antiface/Django-Actuary | actuary/tasks.py | Python | mit | 377 | 0.005305 | from celery.task import Task
from celery.registry import tasks
import datetime
import requests
import datetime
import settings
c | lass Actuary(Task):
def run(self, user_id, page, **kwargs):
logger = self.get_logger(**kwargs)
logger.error("Actuary event captured.")
ts = datetime.datetime.now()
| print "%s - %s - %s" % (ts, user_id, page)
|
Shaswat27/scipy | scipy/sparse/csc.py | Python | bsd-3-clause | 6,349 | 0.001733 | """Compressed Sparse Column matrix format"""
from __future__ import division, print_function, absolute_import
__docformat__ = "restructuredtext en"
__all__ = ['csc_matrix', 'isspmatrix_csc']
import numpy as np
from scipy._lib.six import xrange
from ._sparsetools import csc_tocsr
from . import _sparsetools
from .sputils import upcast, isintlike, IndexMixin, get_index_dtype
from .compressed import _cs_matrix
class csc_matrix(_cs_matrix, IndexMixin):
"""
Compressed Sparse Column matrix
This can be instantiated in several ways:
csc_matrix(D)
with a dense matrix or rank-2 ndarray D
csc_matrix(S)
with another sparse matrix S (equivalent to S.tocsc())
csc_matrix((M, N), [dtype])
to construct an empty matrix with shape (M, N)
dtype is optional, defaulting to dtype='d'.
csc_matrix((data, (row_ind, col_ind)), [shape=(M, N)])
where ``data``, ``row_ind`` and ``col_ind`` satisfy the
relationship ``a[row_ind[k], col_ind[k]] = data[k]``.
csc_matrix((data, indices, indptr), [shape=(M, N)])
is the standard CSC representation where the row indices for
column i are stored in ``indices[indptr[i]:indptr[i+1]]``
and their corresponding values are stored in
``data[indptr[i]:indptr[i+1]]``. If the shape parameter is
not supplied, the matrix dimensions are inferred from
the index arrays.
Attributes
----------
dtype : dtype
Data type of the matrix
shape : 2-tuple
Shape of the matrix
ndim : int
Number of dimensions (this is always 2)
nnz
Number of nonzero elements
data
Data array of the matrix
indices
CSC format index array
indptr
CSC format index pointer array
has_sorted_indices
Whether indices are sorted
Notes
-----
Sparse matrices can be used in arithmetic operations: they support
addition, subtraction, multiplication, division, and matrix power.
Advantages of the CSC format
- efficient arithmetic operations CSC + CSC, CSC * CSC, etc.
- efficient column slicing
- fast matrix vector products (CSR, BSR may be faster)
Disadvantages of the CSC format
- slow row slicing operations (consider CSR)
- changes to the sparsity structure are expensive (consider LIL or DOK)
Examples
--------
>>> import numpy as np
>>> from scipy.sparse import csc_matrix
>>> csc_matrix((3, 4), dtype=np.int8).toarray()
array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]], dtype=int8)
>>> row = np.array([0, 2, 2, 0, 1, 2])
>>> col = np.array([0, 0, 1, 2, 2, 2])
>>> data = np.array([1, 2, 3, 4, 5, 6])
>>> csc_matrix((data, (row, col)), shape=(3, 3)).toarray()
array([[1, 0, 4],
[0, 0, 5],
[2, 3, 6]])
>>> | indptr = np.array([0, 2, 3, 6])
>>> indices = np.array([0, 2, 2, 0, 1, 2])
>>> data = np.array([1, 2, 3, 4, 5, 6])
>>> csc_matrix((data, indices, indptr), shape=(3, 3)).toarray()
array([[1, 0, 4],
[0, 0, 5],
[2, 3, 6]])
"""
format = 'csc'
def transpose(self, copy=False):
from .csr import csr_matrix
M,N = self.shape
return csr_matrix((self.data,self.indices,self.indptr),(N,M),copy=copy)
def __iter__(self):
csr = | self.tocsr()
for r in xrange(self.shape[0]):
yield csr[r,:]
def tocsc(self, copy=False):
if copy:
return self.copy()
else:
return self
def tocsr(self):
M,N = self.shape
idx_dtype = get_index_dtype((self.indptr, self.indices),
maxval=max(self.nnz, N))
indptr = np.empty(M + 1, dtype=idx_dtype)
indices = np.empty(self.nnz, dtype=idx_dtype)
data = np.empty(self.nnz, dtype=upcast(self.dtype))
csc_tocsr(M, N,
self.indptr.astype(idx_dtype),
self.indices.astype(idx_dtype),
self.data,
indptr,
indices,
data)
from .csr import csr_matrix
A = csr_matrix((data, indices, indptr), shape=self.shape)
A.has_sorted_indices = True
return A
def __getitem__(self, key):
# Use CSR to implement fancy indexing.
row, col = self._unpack_index(key)
# Things that return submatrices. row or col is a int or slice.
if (isinstance(row, slice) or isinstance(col, slice) or
isintlike(row) or isintlike(col)):
return self.T[col, row].T
# Things that return a sequence of values.
else:
return self.T[col, row]
def nonzero(self):
# CSC can't use _cs_matrix's .nonzero method because it
# returns the indices sorted for self transposed.
# Get row and col indices, from _cs_matrix.tocoo
major_dim, minor_dim = self._swap(self.shape)
minor_indices = self.indices
major_indices = np.empty(len(minor_indices), dtype=self.indptr.dtype)
_sparsetools.expandptr(major_dim, self.indptr, major_indices)
row, col = self._swap((major_indices, minor_indices))
# Sort them to be in C-style order
ind = np.lexsort((col, row))
row = row[ind]
col = col[ind]
return row, col
nonzero.__doc__ = _cs_matrix.nonzero.__doc__
def getrow(self, i):
"""Returns a copy of row i of the matrix, as a (1 x n)
CSR matrix (row vector).
"""
# we convert to CSR to maintain compatibility with old impl.
# in spmatrix.getrow()
return self._get_submatrix(i, slice(None)).tocsr()
def getcol(self, i):
"""Returns a copy of column i of the matrix, as a (m x 1)
CSC matrix (column vector).
"""
return self._get_submatrix(slice(None), i)
# these functions are used by the parent class (_cs_matrix)
# to remove redudancy between csc_matrix and csr_matrix
def _swap(self,x):
"""swap the members of x if this is a column-oriented matrix
"""
return (x[1],x[0])
def isspmatrix_csc(x):
return isinstance(x, csc_matrix)
|
ankur0493/google_python_exercises | basic/list2.py | Python | apache-2.0 | 2,574 | 0.012044 | #!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
# Additional basic list exercises
# D. Given a list of numbers, return a list where
# all adjacent == elements have been reduced to a single element,
# so [1, 2, 2, 3] returns [1, 2, 3]. You may crea | te a new list or
# modify the passed i | n list.
def remove_adjacent(nums):
num1 = nums[:]
for index,num in enumerate(nums[1:], start=1):
if num == nums[index-1]:
num1.remove(num)
else:
pass
return num1
# E. Given two lists sorted in increasing order, create and return a merged
# list of all the elements in sorted order. You may modify the passed in lists.
# Ideally, the solution should work in "linear" time, making a single
# pass of both lists.
def linear_merge(list1, list2):
for elem_list1 in list1[:]:
for index, elem_list2 in enumerate(list2[:]): #Need to be modified for linear time
if elem_list1<elem_list2:
list2.insert(index,elem_list1)
break
else:
pass
if (index>=len(list2)-1):
list2.insert(index+1,elem_list1)
break
return list2
# Note: the solution above is kind of cute, but unforunately list.pop(0)
# is not constant time with the standard python list implementation, so
# the above is not strictly linear time.
# An alternate approach uses pop(-1) to remove the endmost elements
# from each list, building a solution list which is backwards.
# Then use reversed() to put the result back in the correct order. That
# solution works in linear time, but is more ugly.
# Simple provided test() function used in main() to print
# what each function returns vs. what it's supposed to return.
def test(got, expected):
if got == expected:
prefix = ' OK '
else:
prefix = ' X '
print '%s got: %s expected: %s' % (prefix, repr(got), repr(expected))
# Calls the above functions with interesting inputs.
def main():
print 'remove_adjacent'
test(remove_adjacent([1, 2, 2, 3]), [1, 2, 3])
test(remove_adjacent([2, 2, 3, 3, 3]), [2, 3])
test(remove_adjacent([]), [])
print
print 'linear_merge'
test(linear_merge(['aa', 'xx', 'zz'], ['bb', 'cc']),
['aa', 'bb', 'cc', 'xx', 'zz'])
test(linear_merge(['aa', 'xx'], ['bb', 'cc', 'zz']),
['aa', 'bb', 'cc', 'xx', 'zz'])
test(linear_merge(['aa', 'aa'], ['aa', 'bb', 'bb']),
['aa', 'aa', 'aa', 'bb', 'bb'])
if __name__ == '__main__':
main()
|
nopassword/nopassword.py | tests/test_keyfile.py | Python | apache-2.0 | 707 | 0.015559 | import math
import sys
sys.path.append("..")
import nopassword
print
print "Predfined runes"
runes = nopassword.get_runes()
for k, v in runes.item | s():
print k.ljust(20), len(v),"\t", v
p | rint
print "Generate alphabets"
alphabets = {}
length = 5
itterations = 0
rr = runes["digits"]
while True:
itterations += 1
alphabet = nopassword.generate_alphabet(runes = rr, length=length)
if alphabet in alphabets:
print "Duplicate after %d itterations" % itterations
print "Length:%d\tRunes:[%s]\t Possible permuations:%d\tPairs:%d" %( length, rr, len(rr)**length, itterations*(itterations-1))
print sorted(alphabets.keys())
break
alphabets[alphabet] = True
|
eayunstack/neutron | neutron/tests/unit/agent/l3/test_dvr_snat_ns.py | Python | apache-2.0 | 2,142 | 0 | # Copyright (c) 2016 OpenStack Foundation
#
# 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.
import mock
from oslo_config import cfg
from oslo_utils import uuidutils
from neutron.agent.common import utils
from neutron.agent.l3 import dvr_snat_ns
from neutron.agent.linux import ip_lib
from neutron.tests import base
_uuid = uuidutils.generate_uui | d
class TestDvrSnatNs(base.BaseTestCase):
def setUp(self):
super(TestDvrSnatNs, self).setUp()
self.conf = mock.Mock()
self.conf.state_path = cfg.CONF.state_path
self.driver = mock.Mock()
self.driver.DEV_NAME_LEN = 14
self.router_id = _uuid()
self.snat_ns = dvr_snat_ns.SnatNamespace(self.router_id,
self.conf,
self.driver,
| use_ipv6=False)
@mock.patch.object(utils, 'execute')
@mock.patch.object(ip_lib, 'create_network_namespace')
@mock.patch.object(ip_lib, 'network_namespace_exists')
def test_create(self, exists, create, execute):
exists.return_value = False
self.snat_ns.create()
netns_cmd = ['ip', 'netns', 'exec', self.snat_ns.name]
loose_cmd = ['sysctl', '-w', 'net.netfilter.nf_conntrack_tcp_loose=0']
expected = [mock.call(netns_cmd + loose_cmd,
check_exit_code=True, extra_ok_codes=None,
log_fail_as_error=True, run_as_root=True)]
create.assert_called_once_with(self.snat_ns.name)
execute.assert_has_calls(expected)
|
lvisdd/qnabot | webapp/data/jmafaq.py | Python | mit | 3,058 | 0.024526 | # -*- coding: utf-8 -*-
import csv
import os
import re
try:
# Python 3
from urllib import request
except ImportError:
# Python 2
import urllib2 as request
from bs4 import BeautifulSoup
def extractFaqURL(url):
html = request.urlopen(url).rea | d()
soup = BeautifulSoup(html, "html.parser")
faqs = soup.find_all("ul", class_="pagelink mtx")
urls = []
for faq in faqs:
for a in faq.findAll('a'):
try:
pattern = r"^http://"
if re.match(pattern , a.attrs['href']):
# urls.append(a.attrs['href'])
pass
else:
urls.append(url + a.attrs['href'])
| except Exception as ex:
print(ex)
# print(urls)
return urls
def extractFaqText(url):
html = request.urlopen(url).read()
soup = BeautifulSoup(html, "html.parser")
if soup.find_all("div", class_="qa-box"):
main = soup.find_all("div", class_="qa-box")
else:
main = soup.find_all("div", id="main")
for faq in main:
tag = faq.find("div", class_="mtx")
if tag:
tag.clear()
tag = faq.find_all(["h2","p"])
dict={}
### print(tag)
for t in tag:
del(t["id"])
del(t["mtx"])
# print(t)
# print(dir(t))
# print(t.name)
if t.name=="h2":
### print("Q !!!")
### print(str(t.text).strip('\n\r'))
question=str(t.text).strip('\n\r').replace('\r','').replace('\n','')
dict[question]=""
else:
### print("A !!!")
### print(t.text + "\n")
### print(str(t.text).strip('\n\r'))
answer=str(t.text).strip('\n\r').replace('\r','').replace('\n','')
if dict[question]:
answer=dict[question] + answer
dict[question]=answer
### print(dict)
for key, value in dict.items():
print("question:\r\n", key)
print("answer:\r\n", value)
return dict
if __name__ == "__main__":
if os.path.isfile("faq.tsv"):
os.remove("faq.tsv")
with open('faq.tsv', 'w', newline='', encoding="UTF-8") as csvfile:
fieldnames = ['question', 'answer']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter='\t', quoting=csv.QUOTE_NONNUMERIC)
writer.writeheader()
url = "http://www.jma.go.jp/jma/kishou/know/faq/"
urls = extractFaqURL(url)
### urls = ["http://www.jma.go.jp/jma/kishou/know/faq/faq1.html"]
### urls = ["http://www.jma.go.jp/jma/kishou/know/faq/faq25.html"]
for url in urls:
if url in {"http://www.jma.go.jp/jma/kishou/know/faq/../yougo_hp/mokuji.html", "http://www.jma.go.jp/jma/kishou/know/faq/../../minkan/q_a_m.html", "http://www.jma.go.jp/jma/kishou/know/faq/../../minkan/q_a_s.html"}:
pass
else:
try:
print(url)
dict=extractFaqText(url)
for key, value in dict.items():
writer.writerow({'question': key, 'answer': value})
except Exception as ex:
print(ex)
|
chudichudichudi/neuro-tedx-2 | tedx2/extensions.py | Python | bsd-3-clause | 655 | 0.010687 | # -*- coding: utf-8 -*-
"""Extensions module. Each extension is initialized in the app fact | ory located
in app.py
"""
from flask.ext.bcrypt import Bcrypt
bcrypt = Bcrypt()
from flask.ext.login import LoginManager
login_manager = LoginManager()
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()
from flask.ext.migrate import Migrate
migrate = Migrate()
from flask.ext.cache import Cache
cache = Cache()
from flask.ext.debugtoolbar import DebugToolbarExtension
debug_toolbar = DebugToolbarExtension()
from flask.ext.restless import APIManager
apimanager = APIManager()
f | rom flask.ext.admin import Admin
admin = Admin(url='/its_a_secret')
|
BillBillBillBill/Tickeys-linux | tickeys/kivy_32/kivy/uix/bubble.py | Python | mit | 12,590 | 0.000715 | '''
Bubble
======
.. versionadded:: 1.1.0
.. image:: images/bubble.jpg
:align: right
The Bubble widget is a form of menu or a small popup where the menu options
are stacked either ve | rtically or horizontally.
The :class:`Bubble` contains an arrow pointing in the direction you
choose.
Simple example
------ | --------
.. include:: ../../examples/widgets/bubble_test.py
:literal:
Customize the Bubble
--------------------
You can choose the direction in which the arrow points::
Bubble(arrow_pos='top_mid')
The widgets added to the Bubble are ordered horizontally by default, like a
Boxlayout. You can change that by::
orientation = 'vertical'
To add items to the bubble::
bubble = Bubble(orientation = 'vertical')
bubble.add_widget(your_widget_instance)
To remove items::
bubble.remove_widget(widget)
or
bubble.clear_widgets()
To access the list of children, use content.children::
bubble.content.children
.. warning::
This is important! Do not use bubble.children
To change the appearance of the bubble::
bubble.background_color = (1, 0, 0, .5) #50% translucent red
bubble.border = [0, 0, 0, 0]
background_image = 'path/to/background/image'
arrow_image = 'path/to/arrow/image'
'''
__all__ = ('Bubble', 'BubbleButton', 'BubbleContent')
from kivy.uix.image import Image
from kivy.uix.widget import Widget
from kivy.uix.scatter import Scatter
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.properties import ObjectProperty, StringProperty, OptionProperty, \
ListProperty, BooleanProperty
from kivy.clock import Clock
from kivy.base import EventLoop
from kivy.metrics import dp
class BubbleButton(Button):
'''A button intended for use in a Bubble widget.
You can use a "normal" button class, but it will not look good unless
the background is changed.
Rather use this BubbleButton widget that is already defined and provides a
suitable background for you.
'''
pass
class BubbleContent(GridLayout):
pass
class Bubble(GridLayout):
'''Bubble class. See module documentation for more information.
'''
background_color = ListProperty([1, 1, 1, 1])
'''Background color, in the format (r, g, b, a).
:attr:`background_color` is a :class:`~kivy.properties.ListProperty` and
defaults to [1, 1, 1, 1].
'''
border = ListProperty([16, 16, 16, 16])
'''Border used for :class:`~kivy.graphics.vertex_instructions.BorderImage`
graphics instruction. Used with the :attr:`background_image`.
It should be used when using custom backgrounds.
It must be a list of 4 values: (top, right, bottom, left). Read the
BorderImage instructions for more information about how to use it.
:attr:`border` is a :class:`~kivy.properties.ListProperty` and defaults to
(16, 16, 16, 16)
'''
background_image = StringProperty(
'atlas://data/images/defaulttheme/bubble')
'''Background image of the bubble.
:attr:`background_image` is a :class:`~kivy.properties.StringProperty` and
defaults to 'atlas://data/images/defaulttheme/bubble'.
'''
arrow_image = StringProperty(
'atlas://data/images/defaulttheme/bubble_arrow')
''' Image of the arrow pointing to the bubble.
:attr:`arrow_image` is a :class:`~kivy.properties.StringProperty` and
defaults to 'atlas://data/images/defaulttheme/bubble_arrow'.
'''
show_arrow = BooleanProperty(True)
''' Indicates whether to show arrow.
.. versionadded:: 1.8.0
:attr:`show_arrow` is a :class:`~kivy.properties.BooleanProperty` and
defaults to `True`.
'''
arrow_pos = OptionProperty('bottom_mid', options=(
'left_top', 'left_mid', 'left_bottom', 'top_left', 'top_mid',
'top_right', 'right_top', 'right_mid', 'right_bottom',
'bottom_left', 'bottom_mid', 'bottom_right'))
'''Specifies the position of the arrow relative to the bubble.
Can be one of: left_top, left_mid, left_bottom top_left, top_mid, top_right
right_top, right_mid, right_bottom bottom_left, bottom_mid, bottom_right.
:attr:`arrow_pos` is a :class:`~kivy.properties.OptionProperty` and
defaults to 'bottom_mid'.
'''
content = ObjectProperty(None)
'''This is the object where the main content of the bubble is held.
:attr:`content` is a :class:`~kivy.properties.ObjectProperty` and
defaults to 'None'.
'''
orientation = OptionProperty('horizontal',
options=('horizontal', 'vertical'))
'''This specifies the manner in which the children inside bubble
are arranged. Can be one of 'vertical' or 'horizontal'.
:attr:`orientation` is a :class:`~kivy.properties.OptionProperty` and
defaults to 'horizontal'.
'''
limit_to = ObjectProperty(None, allownone=True)
'''Specifies the widget to which the bubbles position is restricted.
.. versionadded:: 1.6.0
:attr:`limit_to` is a :class:`~kivy.properties.ObjectProperty` and
defaults to 'None'.
'''
def __init__(self, **kwargs):
self._prev_arrow_pos = None
self._arrow_layout = BoxLayout()
self._bk_img = Image(
source=self.background_image, allow_stretch=True,
keep_ratio=False, color=self.background_color)
self.background_texture = self._bk_img.texture
self._arrow_img = Image(source=self.arrow_image,
allow_stretch=True,
color=self.background_color)
self.content = content = BubbleContent(parent=self)
super(Bubble, self).__init__(**kwargs)
content.parent = None
self.add_widget(content)
self.on_arrow_pos()
def add_widget(self, *l):
content = self.content
if content is None:
return
if l[0] == content or l[0] == self._arrow_img\
or l[0] == self._arrow_layout:
super(Bubble, self).add_widget(*l)
else:
content.add_widget(*l)
def remove_widget(self, *l):
content = self.content
if not content:
return
if l[0] == content or l[0] == self._arrow_img\
or l[0] == self._arrow_layout:
super(Bubble, self).remove_widget(*l)
else:
content.remove_widget(l[0])
def clear_widgets(self, **kwargs):
content = self.content
if not content:
return
if kwargs.get('do_super', False):
super(Bubble, self).clear_widgets()
else:
content.clear_widgets()
def on_show_arrow(self, instance, value):
self._arrow_img.opacity = int(value)
def on_parent(self, instance, value):
Clock.schedule_once(self._update_arrow)
def on_pos(self, instance, pos):
lt = self.limit_to
if lt:
self.limit_to = None
if lt is EventLoop.window:
x = y = 0
top = lt.height
right = lt.width
else:
x, y = lt.x, lt.y
top, right = lt.top, lt.right
self.x = max(self.x, x)
self.right = min(self.right, right)
self.top = min(self.top, top)
self.y = max(self.y, y)
self.limit_to = lt
def on_background_image(self, *l):
self._bk_img.source = self.background_image
def on_background_color(self, *l):
if self.content is None:
return
self._arrow_img.color = self._bk_img.color = self.background_color
def on_orientation(self, *l):
content = self.content
if not content:
return
if self.orientation[0] == 'v':
content.cols = 1
content.rows = 99
else:
content.cols = 99
content.rows = 1
def on_arrow_image(self, *l):
self._arrow_img.source = self.arrow_image
def on_arrow_pos(self, *l):
self_content = self.content
if not self_content:
Clock.schedule_once(self.on_arrow_pos)
ret |
mn1del/rpi_cnc_img | secondboot_arduino.py | Python | gpl-3.0 | 1,627 | 0.014136 | #!/usr/bin/env python
# deals with uploading grbl to arduino
# placed in a separate script to secondboot.py because I couldn't figure out how to CD into
# the right directory within python, so instead I'll do the "cd'ing" in rc.local, and call standalone script***
#*** EDIT: apparently passing cwd="directory" as an argument after the list in subprocess.call() is how to run the subprocess
# from another directory - which would negate the need to "pre-cd" into the right directory in rc.local
import subprocess as sp
debugmode = False
# upload GRBL to Arduino
if debugmode == False:
yesno = "y"
else:
yesno = raw_input("Upload GRBL to Arduino? (y/n) ")
if yesno == "y" or debugmode == False:
#sp.call(["sudo", "make"], | cwd="") # test that the sketch compiles
sp.call(["sudo", "make", "upload"], cwd="/usr/share/arduino/libraries/grbl | /examples/GRBLtoArduino") # upload to arduino
# set call for everyboot.py
# replaces previous call for secondboot.py
#sp.call(["sudo", "sed", "-i", "/cd \/home\/pi/,/^exit 0/{//!d}", "/etc/rc.local"])
sp.call(["sudo", "sed", "-i", "/^exit 0/ i\sudo python /home/pi/rpi_cnc_img/everyboot.py", "/etc/rc.local"]) #check backslashes
sp.call(["sudo", "sed", "-i", "/^exit 0/ i\sudo startx", "/etc/rc.local"])
sp.call(["sudo", "sed", "-i", "/^exit 0/ i\\/home\/pi\/bCNC", "/etc/rc.local"])
sp.call(["sudo", "sed", "-i", "/^exit 0/ i\chromium-browser --kiosk http://localhost:8080", "/etc/rc.local"])
# reboot
if debugmode == False:
yesno = "y"
else:
yesno = raw_input("Reboot? (y/n) ")
if yesno == "y" or debugmode == False:
sp.call(["sudo", "shutdown", "-r"])
|
Ultimaker/Cura | plugins/DigitalLibrary/src/ExportFileJob.py | Python | lgpl-3.0 | 2,208 | 0.00317 | # Copyright (c) 2021 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
import io
from typing import List, Optional, Union
from UM.FileHandler.FileHandler import FileHandler
from UM.FileHandler.FileWriter import FileWriter
from UM.FileHandler.WriteFileJob import WriteFileJob
from UM.Logger import Logger
from UM.MimeTypeDatabase import MimeTypeDatabase
from UM.OutputDevice import OutputDeviceError
from UM.Scene.SceneNode import SceneNode
class ExportFileJob(WriteFileJob):
"""Job that exports the build plate to the correct file format for the Digital Factory Library project."""
def __init__(self, file_handler: FileHandler, nodes: List[SceneNode], job_name: str, extension: str) -> None:
file_types = file_handler.getSupportedFileTypesWrite()
if len(file_types) == 0:
Logger.log("e", "There are no file types available to write with!")
raise OutputDeviceError.WriteRequestFailedError("There are no file types available to write with!")
mode = None
file_writer = None
for file_type in file_types:
if file_type["extension"] == extension:
file_writer = file_handler.getWriter(file_type["id"])
mode = file_type.get("mo | de")
super().__init__(file_writer, self.createStream(mode = mode), nodes, mode)
# Determine the filename.
self.setFileName("{}.{}".format(job_name, extension))
| def getOutput(self) -> bytes:
"""Get the job result as bytes as that is what we need to upload to the Digital Factory Library."""
output = self.getStream().getvalue()
if isinstance(output, str):
output = output.encode("utf-8")
return output
def getMimeType(self) -> str:
"""Get the mime type of the selected export file type."""
return MimeTypeDatabase.getMimeTypeForFile(self.getFileName()).name
@staticmethod
def createStream(mode) -> Union[io.BytesIO, io.StringIO]:
"""Creates the right kind of stream based on the preferred format."""
if mode == FileWriter.OutputMode.TextMode:
return io.StringIO()
else:
return io.BytesIO()
|
ayust/pluss | pluss/util/ratelimit.py | Python | mit | 1,111 | 0.007201 | import functools
from pluss.app import app
from pluss.util.cache import Cache
RATE_LIMIT_ | CACHE_KEY_TEMPLATE = 'pluss--remoteip--ratelimit--1--%s' |
def ratelimited(func):
"""Includes the wrapped handler in the global rate limiter (60 calls/min)."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
ratelimit_key = RATE_LIMIT_CACHE_KEY_TEMPLATE % flask.request.remote_addr
# Increment the existing minute's counter, or start a new one if none exists
# (relies on the short-circuiting of 'or')
remote_ip_rate = Cache.incr(ratelimit_key) or Cache.set(ratelimit_key, 1, time=60)
if remote_ip_rate > 60:
if remote_ip_rate in (61, 100, 1000, 10000):
app.logging.info('Rate limited %s - %d requests/min.',
flask.request.remote_addr, remote_ip_rate)
message = 'Rate limit exceeded. Please do not make more than 60 requests per minute.'
return message, 503, {'Retry-After': 60} # Service Unavailable
return func(*args, **kwargs)
return wrapper
# vim: set ts=4 sts=4 sw=4 et:
|
mtils/ems | ems/qt/graphics/storage/dict_scene_serializer.py | Python | mit | 921 | 0.003257 |
from ems.qt.graphics.storage.interfaces import SceneSerializer
from ems.qt.graphics.page_item import PageItem
class DictSceneSerializer(SceneSerializer):
def serialize(self, scene, tools):
| saveData = {
'@author': 'Michael Tils',
'@desciption': 'Graphics Scene Contents',
'@data': {
'pages': []
| }
}
items = []
for item in scene.items():
if isinstance(item, PageItem):
continue
items.append(tools.serialize(item))
saveData['@data']['pages'].append({'items':items})
return saveData
def deserialize(self, sceneData, scene, tools):
page = PageItem()
scene.addItem(page)
for page in sceneData['@data']['pages']:
for item in page['items']:
item = tools.deserialize(item)
scene.addItem(item) |
miltonsarria/dsp-python | filters/FIR/filter_sine1.py | Python | mit | 1,128 | 0.027482 | #Milton Orlando Sarria
#filtrado elemental de ruido sinusoidal
from scipy import signal
import matplotlib.pyplot as plt
import numpy as np
#disenar el filtro usando una ventana hamming
b = signal.firwin(9, 0.8, window='hamming', pass_zero=True)
#definir la frecuencia de mu | estreo y generar un vector de tiempo hasta 5 segundos
fs=1e3
longitud = 5
t=np.linspace(1./fs,longitud,fs*longitud);
F=10 #frecuencia fundamental 10 hz
w=2*np.pi*F #frecuencia an | gular
Vm=4 #valor de amplitud de la onda
#generar onda sinusoidal pura
x=Vm*np.cos(w*t)
#generar onda de ruido sinusoidal, alta frecuencia y baja amplitud
#usar una frecuencia 30 veces mayor a la inicial
ruido=2*np.cos(30*w*t)
#onda con ruido: sumar las dos sinusoidales
x_n=x+ruido
#filtrar la onda con ruido usando el filtro FIR
yf=signal.lfilter(b, [1.0],x_n)
#visualizar las tres ondas, limpia, contaminada y filtrada
plt.subplot(311)
plt.plot(t,x)
plt.title('onda sin ruido')
plt.subplot(312)
plt.plot(t,x_n)
plt.title('onda con ruido')
plt.subplot(313)
plt.plot(t,yf)
plt.title('onda filtrada')
plt.xlabel('tiempo')
plt.show()
|
ricomoss/open-west-2015-fixtureless | owc_fixtureless/owc_fixtureless/tests.py | Python | mit | 927 | 0 | from django.test import TestCase
from fixtureless import Factory
from owc_fixtureless import co | nstants
from owc_fixtureless import models
class MageTestCase(TestCase):
def setUp(self):
self.factory = Factory()
def test_brothers_in_arms(self):
# Exclude the mage itself
mage_1 = self.factory.create(
models.Mage, {'magic_type': constants.ARCANE})
expected = 0
self.assertEqual(mage_1.b | rothers_in_arms.count(), expected)
# Let's add another mage with another magic_type
self.factory.create(models.Mage, {'magic_type': constants.BLACK})
expected = 0
self.assertEqual(mage_1.brothers_in_arms.count(), expected)
# Let's add another mage with the same magic_type
self.factory.create(models.Mage, {'magic_type': constants.ARCANE})
expected = 1
self.assertEqual(mage_1.brothers_in_arms.count(), expected)
|
hydroshare/hydroshare | hs_core/migrations/0036_auto_20171117_0422.py | Python | bsd-3-clause | 639 | 0.00313 | # -*- coding: utf-8 -*-
from dja | ngo.db import migrations, models
import django.contrib.postgres.fields.hstore
class Migration(migrations.Migration):
dependencies = [
('hs_core', '0035_remove_deprecated_fields'),
]
operations = [
migrations.AddField(
model_name='contributor',
name='identifiers',
fiel | d=django.contrib.postgres.fields.hstore.HStoreField(default={}),
),
migrations.AddField(
model_name='creator',
name='identifiers',
field=django.contrib.postgres.fields.hstore.HStoreField(default={}),
),
]
|
pramitchoudhary/Experiments | notebook_gallery/other_experiments/explore-models/modelinterpretation/lime/LIME_Explanation.py | Python | unlicense | 3,638 | 0.007971 |
# coding: utf-8
# In[1]:
import lime
import sklearn
import numpy as np
import sklearn
import sklearn.ensemble
import sklearn.metrics
from __future__ import print_function
# In[2]:
from sklearn.datasets import fetch_20newsgroups
categories = ['alt.atheism', 'soc.religion.christian']
newsgroups_train = fetch_20newsgroups(subset='train', categories=categories)
newsgroups_test = fetch_20newsgroups(subset='test', categories=categories)
class_names = ['atheism', 'christian']
# In[3]:
vectorizer = sklearn.feature_extraction.text.TfidfVectorizer(lowercase=False)
train_vectors = vectorizer.fit_transform(newsgroups_train.data)
test_vectors = vectorizer.transform(newsgroups_test.data)
# In[46]:
len(train_vectors.data)
# In[4]:
rf = sklearn.ensemble.RandomForestClassifier(n_estimators=500)
rf.fit(train_vectors, newsgroups_train.target)
# In[5]:
pred = rf.predict(test_vectors)
sklearn.metrics.f1_score(newsgroups_test.target, pred, average='binary')
# In[6]:
from lime import lime_text
from sklearn.pipeline import make_pipeline
c = make_pipeline(vectorizer, rf)
# In[7]:
print(c.predict_proba([newsgroups_test.data[0]]))
# In[63]:
from lime.lime_text import LimeTextExplainer
explainer = LimeTextExplainer(class_names=class_names)
# In[64]:
idx = 83
exp = explainer.explain_instance(newsgroups_test.data[idx], c.predict_proba, num_features=10)
print("value to be predicted")
print(newsgroups_test.data[idx])
print(newsgroups_test.target[idx])
print(newsgroups_test.target_names)
# In[17]:
print('Document id: %d' % idx)
print('Probability(christian) =', c.predict_proba([newsgroups_test.data[idx]])[0,1])
print('True class: %s' % class_names[newsgroups_test.target[idx]])
# In[18]:
# Explanation of the method
get_ipython().magic(u'pinfo explainer.explain_instance')
# In[20]:
# ravel is used for array flattening
x = np.array([[1, 2, 3], [4, 5, 6]])
np.ravel(x)
# In[22]:
import sklearn.metrics.pairwise
# In[30]:
X = [[0, 1], [1, 1]]
sklearn.metrics.pairwise_distances(X, X, metric='cosine')
# In[65]:
exp.as_list()
#exp.show_in_notebook(text=False)
# In[35]:
print('Original prediction:', rf.predict_proba(test_vectors[idx])[0,1])
tmp = test_vectors[idx].copy()
tmp[0,vectorizer.vocabulary_['Posting']] = 0
tmp[0,vectorizer.vocabulary_['Host']] = 0
print('Prediction removing some features:', rf.predict_proba(tmp)[0,1])
print('Difference:', rf.predict_proba(tmp)[0,1] - rf.predict_proba(test_vectors[idx])[0,1])
# In[66]:
get_ipython().magic(u'matplotlib inline')
fig = exp.as_pyplot_figure()
# # Numeric Format
# In[49]:
import sklearn
import sklearn.datasets
import sklearn.ensemble
import numpy as np
import lime
import lime.lime_tabular
from __future__ import print_function
np.random.seed(1)
# In[50]:
iris = sklearn.datasets.load_iris()
# In[51]:
train, test, labels_train, labels_test = sklearn.model_selection.train_test_split(iris.data, iris.target, train_size=0.80)
# In[52]:
rf = sklearn.ensemble.RandomForestClassifier(n_estimators=500)
rf.fit(train, labels_train)
# In[53]:
sklea | rn.metrics.accuracy_score(labels_test, rf.predict(test))
# In[101]:
import pandas as pd
pd.DataFrame(test).head()
# In[115]:
explainer | = lime.lime_tabular.LimeTabularExplainer(train, feature_names=iris.feature_names,
class_names=iris.target_names, discretize_continuous=True)
i = np.random.randint(0, test.shape[0])
exp_num = explainer.explain_instance(test[i], rf.predict_proba, num_features=4, top_labels=1)
# In[103]:
exp_num.predict_proba
# In[104]:
exp_num.class_names
# In[116]:
exp_num.as_list()
|
paulross/cpip | tests/integration/util/UnitTestsPerf.py | Python | gpl-2.0 | 4,715 | 0.009332 | #!/usr/bin/env python
# CPIP is a C/C++ Preprocessor implemented in Python.
# Copyright (C) 2008-2017 Paul Ross
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# 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 License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Paul Ross: apaulross@gmail.com
"""Performance tests for the modules in this directory.
"""
__author__ = 'Paul Ross'
__date__ = '2011-07-10'
__rights__ = 'Copyright (c) 2008-2017 Paul Ross'
import os
import time
import logging
import collections
class TestResult(collections.namedtuple('TestResult', 'testsRun errors failures')):
#__slots__ = ()
def __iadd__(self, other):
"""+= implementation. other is None or TestResult(testsRun, errors, failures)."""
if other is not None:
self = self._replace(
testsRun = self.testsRun + other.testsRun,
errors = self.errors + other.errors,
failures = self.failures + other.failures,
)
return self
def __str__(self):
return ''.join(
[
' Tests: %d\n' % self.testsRun,
' Errors: %d\n' % self.errors,
'Failures: %d\n' % self.failures,
]
)
def retPyModuleList():
retList = []
for aName in os.listdir(os.path.dirname(__file__)):
if aName != os.path.basename(__file__) \
and os.path.splitext(aName)[1] == '.py':
retList.append(os.path.splitext(aName)[0])
return retList
def unitTest(theVerbosity=0):
myResult = TestResult(0, 0, 0)
print('File:', __file__)
#print 'TRACE:', os.listdir(os.path.dirname(__file__))
#print dir()
#print globals()
myModules = (
'test_MaxMunchGenPerf',
)
#myModules = retPyModuleList()
#print 'myModules:'
#print '\n'.join(["'%s'," % x for x in myModules])
for aName in myModules:
try:
mod = __import__(aName)
#print dir(mod)
print('Testing %s' % aName)
c = mod.unitTest(theVerbosity=theVerbosity) or (0, 0, 0)
#print c
myResult += TestResult(c[0], c[1], c[2])
except ImportError as err:
logging.error('Can not import "%s", error: %s' % (aName, err))
except AttributeError as err:
logging.error('Can not run unittests on "%s", error: %s' % (aName, err))
print('Results')
print(myResult)
##################
# End: Unit tests.
####### | ###########
def usage():
print(
"""spam.py -
Usage:
python spam.py [-hl: --help]
Options:
-h, --help ~ Help (this screen) and exit.
-l: ~ set the logging level higher is quieter.
Default is 20 (INFO) e.g.:
CRITICAL 50
ERROR 40
WARNING 30
INFO 20
DEBUG 10
NOTSET 0
""")
def main():
print('spam.py script version "%s", dated %s | ' % (__version__, __date__))
print('Author: %s' % __author__)
print(__rights__)
print
import sys, getopt
print('Command line:')
print(' '.join(sys.argv))
print()
try:
opts, args = getopt.getopt(sys.argv[1:], "hl:", ["help",])
except getopt.GetoptError as myErr:
usage()
print('ERROR: Invalid option: %s' % str(myErr))
sys.exit(1)
logLevel = logging.INFO
for o, a in opts:
if o in ("-h", "--help"):
usage()
sys.exit(2)
elif o == '-l':
logLevel = int(a)
if len(args) != 0:
usage()
print('ERROR: Wrong number of arguments[%d]!' % len(args))
sys.exit(1)
clkStart = time.clock()
# Initialise logging etc.
logging.basicConfig(level=logLevel,
format='%(asctime)s %(levelname)-8s %(message)s',
#datefmt='%y-%m-%d % %H:%M:%S',
stream=sys.stdout)
#
# Your code here
#
unitTest()
clkExec = time.clock() - clkStart
print('CPU time = %8.3f (S)' % clkExec)
print('Bye, bye!')
if __name__ == "__main__":
main()
|
kadarakos/funktional | funktional/context.py | Python | mit | 540 | 0.007407 | imp | ort sys
from contextlib import contextmanager
# Are we training (or testing)
training = False
@contextmanager
def context(**kwargs):
"""Temporarily change the values of context variables passed.
Enables the `with` syntax:
>>> with context(training=True):
...
"""
current = dict((k, getattr(sys.modules[__name__], k)) for k in kwargs)
for k,v in kwargs.items():
setattr(sys.modules[__name__], k, v)
yield
for k,v in c | urrent.items():
setattr(sys.modules[__name__], k, v)
|
vponomaryov/manila | manila/tests/api/v1/test_limits.py | Python | apache-2.0 | 29,404 | 0.000034 | # Copyright 2011 OpenStack LLC.
# 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 permis | sions and limitations
# under the License.
"""
Tests dealing with HTTP rate-limiting.
"""
from oslo_serialization import jsonutils
import six
from six import moves
from six.moves import http_client
import webob
from manila.api.v1 import limits
from manila.api import views
import manila.context
from manila import test
TEST_LIMITS = [
limits.Limit("GET", "/delayed", "^/delayed", 1, limits.PER_MINUTE),
limits.Limit("POST", "*", ".*", 7, limits.PER_MINUTE),
limits.Limit("POST", "/shares", "^/shares", 3, limits.PER_MINUTE),
limits.Limit("PUT", "*", "", 10, limits.PER_MINUTE),
limits.Limit("PUT", "/shares", "^/shares", 5, limits.PER_MINUTE),
]
NS = {
'atom': 'http://www.w3.org/2005/Atom',
'ns': 'http://docs.openstack.org/common/api/v1.0'
}
class BaseLimitTestSuite(test.TestCase):
"""Base test suite which provides relevant stubs and time abstraction."""
def setUp(self):
super(BaseLimitTestSuite, self).setUp()
self.time = 0.0
self.mock_object(limits.Limit, "_get_time", self._get_time)
self.absolute_limits = {}
def stub_get_project_quotas(context, project_id, usages=True):
quotas = {}
for mapping_key in ('limit', 'in_use'):
for k, v in self.absolute_limits.get(mapping_key, {}).items():
if k not in quotas:
quotas[k] = {}
quotas[k].update({mapping_key: v})
return quotas
self.mock_object(manila.quota.QUOTAS, "get_project_quotas",
stub_get_project_quotas)
def _get_time(self):
"""Return the "time" according to this test suite."""
return self.time
class LimitsControllerTest(BaseLimitTestSuite):
"""Tests for `limits.LimitsController` class."""
def setUp(self):
"""Run before each test."""
super(LimitsControllerTest, self).setUp()
self.controller = limits.create_resource()
def _get_index_request(self, accept_header="application/json"):
"""Helper to set routing arguments."""
request = webob.Request.blank("/")
request.accept = accept_header
request.environ["wsgiorg.routing_args"] = (None, {
"action": "index",
"controller": "",
})
context = manila.context.RequestContext('testuser', 'testproject')
request.environ["manila.context"] = context
return request
def _populate_limits(self, request):
"""Put limit info into a request."""
_limits = [
limits.Limit("GET", "*", ".*", 10, 60).display(),
limits.Limit("POST", "*", ".*", 5, 60 * 60).display(),
limits.Limit("GET", "changes-since*", "changes-since",
5, 60).display(),
]
request.environ["manila.limits"] = _limits
return request
def test_empty_index_json(self):
"""Test getting empty limit details in JSON."""
request = self._get_index_request()
response = request.get_response(self.controller)
expected = {
"limits": {
"rate": [],
"absolute": {},
},
}
body = jsonutils.loads(response.body)
self.assertEqual(expected, body)
def test_index_json(self):
"""Test getting limit details in JSON."""
request = self._get_index_request()
request = self._populate_limits(request)
self.absolute_limits = {
'limit': {
'shares': 11,
'gigabytes': 22,
'snapshots': 33,
'snapshot_gigabytes': 44,
'share_networks': 55,
},
'in_use': {
'shares': 3,
'gigabytes': 4,
'snapshots': 5,
'snapshot_gigabytes': 6,
'share_networks': 7,
},
}
response = request.get_response(self.controller)
expected = {
"limits": {
"rate": [
{
"regex": ".*",
"uri": "*",
"limit": [
{
"verb": "GET",
"next-available": "1970-01-01T00:00:00Z",
"unit": "MINUTE",
"value": 10,
"remaining": 10,
},
{
"verb": "POST",
"next-available": "1970-01-01T00:00:00Z",
"unit": "HOUR",
"value": 5,
"remaining": 5,
},
],
},
{
"regex": "changes-since",
"uri": "changes-since*",
"limit": [
{
"verb": "GET",
"next-available": "1970-01-01T00:00:00Z",
"unit": "MINUTE",
"value": 5,
"remaining": 5,
},
],
},
],
"absolute": {
"totalSharesUsed": 3,
"totalShareGigabytesUsed": 4,
"totalShareSnapshotsUsed": 5,
"totalSnapshotGigabytesUsed": 6,
"totalShareNetworksUsed": 7,
"maxTotalShares": 11,
"maxTotalShareGigabytes": 22,
"maxTotalShareSnapshots": 33,
"maxTotalSnapshotGigabytes": 44,
"maxTotalShareNetworks": 55,
},
},
}
body = jsonutils.loads(response.body)
self.assertEqual(expected, body)
def _populate_limits_diff_regex(self, request):
"""Put limit info into a request."""
_limits = [
limits.Limit("GET", "*", ".*", 10, 60).display(),
limits.Limit("GET", "*", "*.*", 10, 60).display(),
]
request.environ["manila.limits"] = _limits
return request
def test_index_diff_regex(self):
"""Test getting limit details in JSON."""
request = self._get_index_request()
request = self._populate_limits_diff_regex(request)
response = request.get_response(self.controller)
expected = {
"limits": {
"rate": [
{
"regex": ".*",
"uri": "*",
"limit": [
{
"verb": "GET",
"next-available": "1970-01-01T00:00:00Z",
"unit": "MINUTE",
"value": 10,
"remaining": 10,
},
],
},
{
"regex": "*.*",
"uri": "*",
"limit": [
{
"verb": "GET",
"next-available": "1970-01-01T00:00:00Z",
"unit": "MINUTE",
|
AsherBond/MondocosmOS | grass_trunk/temporal/tr3.unregister/tr3.unregister.py | Python | agpl-3.0 | 1,642 | 0.017052 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
################## | ##########################################################
#
# MODULE: tr3.unregister
# AUTHOR(S): Soeren Gebbert
#
# PURPOSE: Unregister raster3d maps from space time raster3d datasets
# COPYRIGHT: (C) 2011 by the GRASS Development Team
#
# This program is free software under the GNU General Public
# License (version 2). Read the file COPYING that comes with GRASS
# for details.
#
###################################################################### | #######
#%module
#% description: Unregister raster3d map(s) from a specific or from all space time raster3d dataset in which it is registered
#% keywords: spacetime raster3d dataset
#% keywords: raster3d
#%end
#%option
#% key: dataset
#% type: string
#% description: Name of an existing space time raster3d dataset. If no name is provided the raster3d map(s) are unregistered from all space time datasets in which they are registered.
#% required: no
#% multiple: no
#%end
#%option
#% key: maps
#% type: string
#% description: Name(s) of existing raster3d map(s) to unregister
#% required: yes
#% multiple: yes
#%end
import grass.script as grass
import grass.temporal as tgis
############################################################################
def main():
# Get the options
name = options["dataset"]
maps = options["maps"]
# Make sure the temporal database exists
tgis.create_temporal_database()
# Unregister maps
tgis.unregister_maps_from_space_time_datasets("raster3d", name, maps)
if __name__ == "__main__":
options, flags = grass.parser()
main()
|
deepforge-dev/deepforge-keras | test/test-cases/activations.py | Python | apache-2.0 | 2,712 | 0.000369 | from __future__ import absolute_import
import six
import warnings
from . import backend as K
from .utils.generic_utils import deserialize_keras_object
from .engine import Layer
def softmax(x, axis=-1):
"""Softmax activation function.
# Arguments
x : Tensor.
axis: Integer, axis along which the softmax normalization is applied.
# Returns
Tensor, output of softmax transformation.
# Raises
ValueError: In case `dim(x) == 1`.
"""
ndim = K.ndim(x)
if ndim == 2:
return K.softmax(x)
elif ndim > 2:
e = K.exp(x - K.max(x, axis=axis, keepdims=True))
s = K.sum(e, axis=axis, keepdims=True)
return e / s |
else:
raise ValueError('Cannot apply softmax to a tensor that is 1D')
def elu(x, alpha=1.0):
return K.elu(x, alpha)
def selu(x):
"""Scaled Exponential Linear Unit. (Klambauer et al., 2017)
# Arguments
x: A tensor or variable to compute the activation function for.
# References
- [ | Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515)
"""
alpha = 1.6732632423543772848170429916717
scale = 1.0507009873554804934193349852946
return scale * K.elu(x, alpha)
def softplus(x):
return K.softplus(x)
def softsign(x):
return K.softsign(x)
def relu(x, alpha=0., max_value=None):
return K.relu(x, alpha=alpha, max_value=max_value)
def tanh(x):
return K.tanh(x)
def sigmoid(x):
return K.sigmoid(x)
def hard_sigmoid(x):
return K.hard_sigmoid(x)
def linear(x):
return x
def serialize(activation):
return activation.__name__
def deserialize(name, custom_objects=None):
return deserialize_keras_object(name,
module_objects=globals(),
custom_objects=custom_objects,
printable_module_name='activation function')
def get(identifier):
if identifier is None:
return linear
if isinstance(identifier, six.string_types):
identifier = str(identifier)
return deserialize(identifier)
elif callable(identifier):
if isinstance(identifier, Layer):
warnings.warn((
'Do not pass a layer instance (such as {identifier}) as the '
'activation argument of another layer. Instead, advanced '
'activation layers should be used just like any other '
'layer in a model.'
).format(identifier=identifier.__class__.__name__))
return identifier
else:
raise ValueError('Could not interpret '
'activation function identifier:', identifier)
|
amagdas/superdesk | server/apps/item_lock/components/item_lock.py | Python | agpl-3.0 | 5,241 | 0.00229 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
from ..models.item import ItemModel
from eve.utils import config
from superdesk.errors import SuperdeskApiError
from superdesk.utc import utcnow
from superdesk.notification import push_notification
from apps.common.components.base_component import BaseComponent
from apps.common.models.utils import get_model
from superdesk.users.services import current_user_has_privilege
import superdesk
LOCK_USER = 'lock_user'
LOCK_SESSION = 'lock_session'
STATUS = '_status'
TASK = 'task'
class ItemLock(BaseComponent):
def __init__(self, app):
self.app = app
self.app.on_session_end += self.on_session_end
@classmethod
def name(cls):
return 'item_lock'
def lock(self, item_filter, user_id, session_id, etag):
item_model = get_model(ItemModel)
item = item_model.find_one(item_filter)
if not item:
raise SuperdeskApiError.notFoundError()
can_user_lock, error_message = self.can_lock(item, user_id, session_id)
if can_user_lock:
self.app.on_item_lock(item, user_id)
updates = {LOCK_USER: user_id, LOCK_SESSION: session_id, 'lock_time': utcnow()}
item_model.update(item_filter, updates)
if item.get(TASK):
item[TASK]['user'] = user_id
else:
item[TASK] = {'user': user_id}
superdesk.get_resource_service('tasks').assign_user(item[config.ID_FIELD], item[TASK])
self.app.on_item_locked(item, user_id)
push_notification('item:lock', item=str(item.get(config.ID_FIELD)),
user=str(user_id), lock_time=updates['lock_time'],
lock_session=str(session_id))
else:
raise SuperdeskApiError.forbiddenError(message=error_message)
item = item_model.find_one(item_filter)
return item
def unlock(self, item_filter, user_id, session_id, etag):
item_model = get_model(ItemModel)
item = item_model.find_one(item_filter)
if not item:
raise SuperdeskApiError.notFoundError()
if not item.get(LOCK_USER):
raise SuperdeskApiError.badRequestError(message="Item is not locked.")
can_user_unlock, error_message = self.can_unlock(item, user_id)
if can_user_unlock:
self.app.on_item_unlock(item, user_id)
# delete the item if nothing is saved so far
# version 0 created on lock item
if item.get(config.VERSION, 0) == 0 and item['state'] == 'draft':
superdesk.get_resource_service('archive').delete(lookup={'_id': item['_id']})
return
updates = {LOCK_USER: None, LOCK_SESSION: None, 'lock_time': None, 'force_unlock': True}
item_model.update(item_filter, updates)
self.app.on_item_unlocked(item, user_id)
push_notification('item:unlock', item=str(item_filter.get(config.ID_FIELD)), user=str(user_id),
lock_session=str(session_id))
else:
raise SuperdeskApiError.forbiddenError(message=error_message)
item = item_model.find_one(item_filter)
return item
def unlock_session(self, user_id, session_id):
item_model = get_model(ItemModel)
items = item_model.find({'lock_session': session_id})
for item in items:
self.unlock({'_id': item['_id']}, user_id, session_id, None)
def can_lock(self, item, user_id, session_id):
"""
Function checks whether user can lock the item or not. If not then raises exception.
"""
can_user_edit, error_message = superdesk.get_resource_service('archive').can_edi | t(item, user_id)
if can_user_edi | t:
if item.get(LOCK_USER):
if str(item.get(LOCK_USER, '')) == str(user_id) and str(item.get(LOCK_SESSION)) != str(session_id):
return False, 'Item is locked by you in another session.'
else:
if str(item.get(LOCK_USER, '')) != str(user_id):
return False, 'Item is locked by another user.'
else:
return False, error_message
return True, ''
def can_unlock(self, item, user_id):
"""
Function checks whether user can unlock the item or not.
"""
can_user_edit, error_message = superdesk.get_resource_service('archive').can_edit(item, user_id)
if can_user_edit:
if not (str(item.get(LOCK_USER, '')) == str(user_id) or
(current_user_has_privilege('archive') and current_user_has_privilege('unlock'))):
return False, 'You don\'t have permissions to unlock an item.'
else:
return False, error_message
return True, ''
def on_session_end(self, user_id, session_id):
self.unlock_session(user_id, session_id)
|
tilacog/rows | rows/cli.py | Python | gpl-3.0 | 4,322 | 0.000231 | # coding: utf-8
# Copyright 2014-2015 Álvaro Justen <https://github.com/turicas/rows/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# TODO: test | this whole module
# TODO: add option to pass 'create_table' options in command-line (like force
# fields)
import click
import rows
from rows.utils import import_from_uri, export_to_uri
@click.group()
def cli():
pass
@cli.command(help='Convert table on `source` URI to `destination`')
@click.option('--input-encoding' | , default='utf-8')
@click.option('--output-encoding', default='utf-8')
@click.option('--input-locale', default='en_US.UTF-8')
@click.option('--output-locale', default='en_US.UTF-8')
@click.argument('source')
@click.argument('destination')
def convert(input_encoding, output_encoding, input_locale, output_locale,
source, destination):
input_locale = input_locale.split('.')
output_locale = output_locale.split('.')
with rows.locale_context(input_locale):
table = import_from_uri(source)
with rows.locale_context(output_locale):
export_to_uri(destination, table)
@cli.command(help='Join tables from `source` URIs using `key(s)` to group rows and save into `destination`')
@click.option('--input-encoding', default='utf-8')
@click.option('--output-encoding', default='utf-8')
@click.option('--input-locale', default='en_US.UTF-8')
@click.option('--output-locale', default='en_US.UTF-8')
@click.argument('keys')
@click.argument('sources', nargs=-1, required=True)
@click.argument('destination')
def join(input_encoding, output_encoding, input_locale, output_locale, keys,
sources, destination):
keys = [key.strip() for key in keys.split(',')]
input_locale = input_locale.split('.')
output_locale = output_locale.split('.')
with rows.locale_context(input_locale):
tables = [import_from_uri(source) for source in sources]
result = rows.join(keys, tables)
with rows.locale_context(output_locale):
export_to_uri(destination, result)
@cli.command(help='Sort from `source` by `key(s)` and save into `destination`')
@click.option('--input-encoding', default='utf-8')
@click.option('--output-encoding', default='utf-8')
@click.option('--input-locale', default='en_US.UTF-8')
@click.option('--output-locale', default='en_US.UTF-8')
@click.argument('key')
@click.argument('source')
@click.argument('destination')
def sort(input_encoding, output_encoding, input_locale, output_locale, key,
source, destination):
input_locale = input_locale.split('.')
output_locale = output_locale.split('.')
key = key.replace('^', '-')
with rows.locale_context(input_locale):
table = import_from_uri(source)
table.order_by(key)
with rows.locale_context(output_locale):
export_to_uri(destination, table)
@cli.command(help='Sum tables from `source` URIs and save into `destination`')
@click.option('--input-encoding', default='utf-8')
@click.option('--output-encoding', default='utf-8')
@click.option('--input-locale', default='en_US.UTF-8')
@click.option('--output-locale', default='en_US.UTF-8')
@click.argument('sources', nargs=-1, required=True)
@click.argument('destination')
def sum(input_encoding, output_encoding, input_locale, output_locale, sources,
destination):
input_locale = input_locale.split('.')
output_locale = output_locale.split('.')
with rows.locale_context(input_locale):
tables = [import_from_uri(source) for source in sources]
result = tables[0]
for table in tables[1:]:
result = result + table
with rows.locale_context(output_locale):
export_to_uri(destination, result)
if __name__ == '__main__':
cli()
|
fokusov/moneyguru | core/model/date.py | Python | gpl-3.0 | 21,665 | 0.004339 | # Created By: Eric Mc Sween
# Created On: 2007-12-12
# Copyright 2015 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-3.0.html
import re
from calendar import monthrange
from datetime import date, datetime, timedelta
from hscommon.trans import tr
from hscommon.util import iterdaterange
ONE_DAY = timedelta(1)
# --- Date Ranges
class DateRange:
"""A range between two dates.
Much of the information supplied by moneyGuru is done so in a date range context. Give me a
profit report for this year, give me a running total chart for this month, and so on and so on.
This class represents that range, supplies a couple of useful methods, and can be subclassed to
represent more specific ranges, such as :class:`YearRange`.
Some ranges are :attr:`navigable <can_navigate>`, which means that they mostly represent a
duration, which can be placed anywhere in time. We can thus "navigate" time with this range
using prev/next buttons. Example: :class:`MonthRange`.
Other ranges, such as :class:`YearToDateRange`, represent two very fixed points in time: 1st of
january to today. These are not navigable.
The two most important attributes of a date range: :attr:`start` and :attr:`end`.
A couple of operators that can be used with ranges:
* r1 == r2 -> only if start and end are the same.
* bool(r) == True -> if it's a range that makes sense (start <= end)
* r1 & r2 -> intersection range between the two.
* date in r -> if start <= date <= end
* iter(r) -> iterates over all dates between start and end (inclusive).
The thing is hashable while, at the same time, being mutable. Use your common sense: don't go
around using date ranges as dict keys and then mutate them. Also, mutation of a date range is
a rather rare occurence and is only needed in a couple of tight spots. Try avoiding them.
"""
def __init__(self, start, end):
#: ``datetime.date``. Start of the range.
self.start = start
#: ``datetime.date``. End of the range.
self.end = end
def __repr__(self):
start_date_str = self.start.strftime('%Y/%m/%d') if self.start.year > 1900 else 'MINDATE'
return '<%s %s - %s>' % (type(self).__name__, start_date_str, self.end.strftime('%Y/%m/%d'))
def __bool__(self):
return self.start <= self.end
def __and__(self, other):
maxstart = max(self.start, other.start)
minend = min(self.end, other.end)
return DateRange(maxstart, minend)
def __eq__(self, other):
if not isinstance(other, DateRange):
raise TypeError()
return type(self) == type(other) and self.start == other.start and self.end == other.end
def __ne__(self, other):
return not self == other
def __contains__(self, date):
return self.start <= date <= self.end
def __iter__(self):
yield from iterdaterange(self.start, self.end)
def __hash__(self):
return hash((self.start, self.end))
def adjusted(self, new_date):
"""Kinda like :meth:`around`, but it can possibly enlarge the range.
Returns ``None`` if ``new_date`` doesn't trigger any adjustments.
To be frank, that method is there only for :class:`AllTransactionsRange`. When we add a new
transaction, we call this method to possibly enlarge/reposition the range. If it isn't
changed, we don't want to trigger all UI updated related to a date range adjustment, so we
return ``None`` to mean "nope, nothing happened here" (which is most of the time).
If it's changed, we return the new range.
"""
return None
def around(self, date):
"""Returns a date range of the same type as ``self`` that contains ``new_date``.
Some date ranges change when new transactions are beind added or changed. This is where
it happens. Returns a new adjusted date range.
For a non-navigable range, returns ``self``.
"""
return self
def next(self):
"""Returns the next range if navigable.
For example, if we're a month range, return a range with start and end increased by a month.
"""
return self
def prev(self):
"""Returns the previous range if navigable.
For example, if we're a month range, return a range with start and end decreased by a month.
We make a bit of an exception for this method and implement it in all ranges, rather than
only navigable ones. This is because it's used in the profit report for the "Last" column
(we want to know what our results were for the last date range). Some ranges, although not
navigable, can return a meaningful result here, like :class:`YearToDateRange`, which can
return the same period last year. Others, like :class:`AllTransactionsRange`, have nothing
to return, so they return an empty range.
"""
return self
@property
def can_navigate(self):
"""Returns whether this range is navigable.
In other words, if it's possible to use prev/next to navigate in date ranges.
"""
return False
@property
def days(self):
"""The number of days in the date range."""
return (self.end - self.start).days + 1
@property
def future(self):
"""The future part of the date range.
That is, the part of the range that is later than today.
"""
today = date.today()
if self.start > today:
return self
else:
return DateRange(today + ONE_DAY, self.end)
@property
def past(self):
"""The past part of the date ra | nge.
That is, the part of the range that is earlier than today.
"""
today = date.today()
if self.end < today:
return self
| else:
return DateRange(self.start, today)
class NavigableDateRange(DateRange):
"""A navigable date range.
Properly implements navigation-related methods so that subclasses don't have to.
Subclasses :class:`DateRange`.
"""
def adjusted(self, new_date):
result = self.around(new_date)
if result == self:
result = None
return result
def around(self, date):
return type(self)(date)
def next(self):
return self.around(self.end + ONE_DAY)
def prev(self):
return self.around(self.start - ONE_DAY)
@property
def can_navigate(self): # if it's possible to use prev/next to navigate in date ranges
return True
class MonthRange(NavigableDateRange):
"""A navigable date range lasting one month.
``seed`` is a date for the range to wrap around.
A monthly range always starts at the first of the month and ends at the last day of that same
month.
Subclasses :class:`NavigableDateRange`.
"""
def __init__(self, seed):
if isinstance(seed, DateRange):
seed = seed.start
month = seed.month
year = seed.year
days_in_month = monthrange(year, month)[1]
start = date(year, month, 1)
end = date(year, month, days_in_month)
DateRange.__init__(self, start, end)
@property
def display(self):
"""String representation of the range (ex: "July 2013")."""
return self.start.strftime('%B %Y')
class QuarterRange(NavigableDateRange):
"""A navigable date range lasting one quarter.
``seed`` is a date for the range to wrap around.
A quarterly range always starts at the first day of the first month of the quarter and ends at
the last day of the last month of that same quarter.
Subclasses :class:`NavigableDateRange`.
"""
def __init__(self, seed):
if isinstance(seed, DateRange):
seed = seed.start
month = seed.month
year = seed.year
first_month = (month - 1) // 3 * 3 + 1
last |
tbelhalfaoui/giddle | giddle/controllers/autocomplete_api.py | Python | gpl-2.0 | 2,924 | 0.005472 | import logging
import requests
from collections import OrderedDict
import operator as op
from ..lib import text
from ..controllers.request_maker import Reque | stMaker, RequestException
class AutocompleteApi(object):
base_url | = 'http://suggestqueries.google.com/complete/search'
base_params = {'client': 'firefox'}
def __init__(self, n_secondary_results=0):
self.n_secondary_results = n_secondary_results
self.request_maker = RequestMaker()
self.tokenise = text.get_tokeniser(clean=False)
def run(self, query):
logging.info("Fetching autocomplete results for '%s'" % query)
results_raw = self._fetch_results(query)
results = self._filter_results(results_raw, query)
logging.info("Retrieved %d suggestions" % len(results))
return results
def _fetch_results(self, query):
results = self._execute_query(query)
subqueries = self._generate_subqueries(query, results)
if not self.n_secondary_results:
return results
for subquery in subqueries:
new_results = self._execute_query(subquery)
new_results_filtered = filter(lambda x: x not in results,
new_results)
if new_results_filtered:
results += filter(lambda x: x not in results,
new_results_filtered)[0:self.n_secondary_results]
return results
def _generate_subqueries(self, query, results):
query_n_words = len(self.tokenise(query))
resultset_words = [self.tokenise(result)
for result in results]
subqueries = set(' '.join(r[0:query_n_words+2]) for r in resultset_words)
return subqueries
def _execute_query(self, query):
params = {'q': query}
params.update(self.base_params)
req = self.request_maker.run(self.base_url, params=params)
if req.status_code != requests.codes.ok:
raise RequestException("Error while executing autocomplete request %s"+\
"(status code: %s)" % (query, req.status_code))
return req.json()[1]
# Filter out the results that does not stricly begin with the query
# and truncate each result to remove the query
def _filter_results(self, raw_results, query):
results_words = [self.tokenise(r) for r in raw_results]
query_words = self.tokenise(query)
filter_func = lambda x: \
text.case_insensitive_list_equals(
x[0:len(query_words)],
query_words
) \
and len(x)>len(query_words)
filtered_results_words = filter(filter_func, results_words)
return [' '.join(frw[len(query_words):])
for frw in filtered_results_words]
|
wileeam/airflow | tests/providers/amazon/aws/sensors/test_sagemaker_base.py | Python | apache-2.0 | 4,728 | 0.000212 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
import unittest
from airflow.exceptions import AirflowException
from airflow.providers.amazon.aws.sensors.sagemaker_base import SageMakerBaseSensor
class TestSagemakerBaseSensor(unittest.TestCase):
def test_execute(self):
class SageMakerBaseSensorSubclass(SageMakerBaseSensor):
def non_terminal_states(self):
return ['PENDING', 'RUNNING', 'CONTINUE']
def failed_states(self):
return ['FAILED']
def get_sagemaker_response(self):
return {
'SomeKey': {'State': 'COMPLETED'},
'ResponseMetadata': {'HTTPStatusCode': 200}
}
def state_from_response(self, response):
return response['SomeKey']['State']
sensor = SageMakerBaseSensorSubclass(
task_id='test_task',
poke_interval=2,
aws_conn_id='aws_test'
)
sensor.execute(None)
def test_poke_with_unfinished_job(self) | :
class SageMakerBaseSensorSubclass(SageMakerBaseSensor):
def non_terminal_states(self):
return ['PENDING', 'RUNNING', 'CONTIN | UE']
def failed_states(self):
return ['FAILED']
def get_sagemaker_response(self):
return {
'SomeKey': {'State': 'PENDING'},
'ResponseMetadata': {'HTTPStatusCode': 200}
}
def state_from_response(self, response):
return response['SomeKey']['State']
sensor = SageMakerBaseSensorSubclass(
task_id='test_task',
poke_interval=2,
aws_conn_id='aws_test'
)
self.assertEqual(sensor.poke(None), False)
def test_poke_with_not_implemented_method(self):
class SageMakerBaseSensorSubclass(SageMakerBaseSensor):
def non_terminal_states(self):
return ['PENDING', 'RUNNING', 'CONTINUE']
def failed_states(self):
return ['FAILED']
sensor = SageMakerBaseSensorSubclass(
task_id='test_task',
poke_interval=2,
aws_conn_id='aws_test'
)
self.assertRaises(NotImplementedError, sensor.poke, None)
def test_poke_with_bad_response(self):
class SageMakerBaseSensorSubclass(SageMakerBaseSensor):
def non_terminal_states(self):
return ['PENDING', 'RUNNING', 'CONTINUE']
def failed_states(self):
return ['FAILED']
def get_sagemaker_response(self):
return {
'SomeKey': {'State': 'COMPLETED'},
'ResponseMetadata': {'HTTPStatusCode': 400}
}
def state_from_response(self, response):
return response['SomeKey']['State']
sensor = SageMakerBaseSensorSubclass(
task_id='test_task',
poke_interval=2,
aws_conn_id='aws_test'
)
self.assertEqual(sensor.poke(None), False)
def test_poke_with_job_failure(self):
class SageMakerBaseSensorSubclass(SageMakerBaseSensor):
def non_terminal_states(self):
return ['PENDING', 'RUNNING', 'CONTINUE']
def failed_states(self):
return ['FAILED']
def get_sagemaker_response(self):
return {
'SomeKey': {'State': 'FAILED'},
'ResponseMetadata': {'HTTPStatusCode': 200}
}
def state_from_response(self, response):
return response['SomeKey']['State']
sensor = SageMakerBaseSensorSubclass(
task_id='test_task',
poke_interval=2,
aws_conn_id='aws_test'
)
self.assertRaises(AirflowException, sensor.poke, None)
if __name__ == '__main__':
unittest.main()
|
statik/grr | lib/flows/general/timelines_test.py | Python | apache-2.0 | 1,939 | 0.011346 | #!/usr/bin/env python
# -*- mode: python; encoding: utf-8 -*-
"""Tests for the Timelines flow."""
from grr.lib import action_mocks
from grr.lib import aff4
from grr.lib import flags
from grr.lib | import test_lib
| # pylint: disable=unused-import
from grr.lib.flows.general import timelines as _
# pylint: enable=unused-import
from grr.lib.rdfvalues import paths as rdf_paths
class TestTimelines(test_lib.FlowTestsBaseclass):
"""Test the timelines flow."""
client_id = "C.0000000000000005"
def testMACTimes(self):
"""Test that the timelining works with files."""
with test_lib.VFSOverrider(
rdf_paths.PathSpec.PathType.OS, test_lib.ClientVFSHandlerFixture):
client_mock = action_mocks.ActionMock("ListDirectory")
output_path = "analysis/Timeline/MAC"
pathspec = rdf_paths.PathSpec(path="/",
pathtype=rdf_paths.PathSpec.PathType.OS)
for _ in test_lib.TestFlowHelper(
"RecursiveListDirectory", client_mock, client_id=self.client_id,
pathspec=pathspec, token=self.token):
pass
# Now make a timeline
for _ in test_lib.TestFlowHelper(
"MACTimes", client_mock, client_id=self.client_id, token=self.token,
path="/", output=output_path):
pass
fd = aff4.FACTORY.Open(self.client_id.Add(output_path), token=self.token)
timestamp = 0
events = list(fd.Query("event.stat.pathspec.path contains grep"))
for event in events:
# Check the times are monotonously increasing.
self.assert_(event.event.timestamp >= timestamp)
timestamp = event.event.timestamp
self.assert_("grep" in event.event.stat.pathspec.path)
# 9 files, each having mac times = 27 events.
self.assertEqual(len(events), 27)
def main(argv):
# Run the full test suite
test_lib.GrrTestProgram(argv=argv)
if __name__ == "__main__":
flags.StartMain(main)
|
KelSolaar/sIBL_GUI | sibl_gui/globals/ui_constants.py | Python | gpl-3.0 | 9,825 | 0.002239 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
**ui_constants.py**
**Platform:**
Windows, Linux, Mac Os X.
**Description:**
Defines **sIBL_GUI** package ui constants through the :class:`UiConstants` class.
**Others:**
"""
from __future__ import unicode_literals
__author__ = "Thomas Mansencal"
__copyright__ = "Copyright (C) 2008 - 2014 - Thomas Mansencal"
__license__ = "GPL V3.0 - http://www.gnu.org/licenses/"
__maintainer__ = "Thomas Mansencal"
__email__ = "thomas.mansencal@gmail.com"
__status__ = "Production"
__all__ = ["UiConstants"]
class UiConstants():
"""
Defines **sIBL_GUI** package ui constants.
"""
ui_file = "sIBL_GUI.ui"
"""
:param ui_file: Application ui file.
:type ui_file: unicode
"""
windows_stylesheet_file = "styles/Windows_styleSheet.qss"
"""
:param windows_stylesheet_file: Application Windows Os stylesheet file.
:type windows_stylesheet_file: unicode
"""
darwin_stylesheet_file = "styles/Darwin_styleSheet.qss"
"""
:param darwin_stylesheet_file: Application Mac Os X Os stylesheet file.
:type darwin_stylesheet_file: unicode
"""
linux_stylesheet_file = "styles/Linux_styleSheet.qss"
"""
:param linux_stylesheet_file: Application Linux Os stylesheet file.
:type linux_stylesheet_file: unicode
"""
windows_style = "plastique"
"""
:param windows_style: Application Windows Os style.
:type windows_style: unicode
"""
darwin_style = "plastique"
"""
:param darwin_style: Application Mac Os X Os style.
:type darwin_style: unicode
"""
linux_style = "plastique"
"""
:param linux_style: Application Linux Os style.
:type linux_style: unicode
"""
settings_file = "preferences/Default_Settings.rc"
"""
:param settings_file: Application defaults settings file.
:type settings_file: unicode
"""
layouts_file = "layouts/Default_Layouts.rc"
"""
:param layouts_file: Application defaults layouts file.
:type layouts_file: unicode
"""
application_windows_icon = "images/Icon_Light.png"
"""
:param application_windows_icon: Application icon file.
:type application_windows_icon: unicode
"""
splash_screen_image = "images/sIBL_GUI_SpashScreen.png"
"""
:param splash_screen_image: Application splashscreen image.
:type splash_screen_image: unicode
"""
logo_image = "images/sIBL_GUI_Logo.png"
"""
:param logo_image: Application logo image.
:type logo_image: unicode
"""
default_toolbar_icon_size = 32
"""
:param default_toolbar_icon_size: Application toolbar icons size.
:type default_toolbar_icon_size: int
"""
central_widget_icon = "images/Central_Widget.png"
"""
:param central_widget_icon: Application **Central Widget** icon.
:type central_widget_icon: unicode
"""
central_widget_hover_icon = "images/Central_Widget_Hover.png"
"""
:param central_widget_hover_icon: Application **Central Widget** hover icon.
:type central_widget_hover_icon: unicode
"""
central_widget_active_icon = "images/Central_Widget_Active.png"
"""
:param central_widget_active_icon: Application **Central Widget** active icon.
:type central_widget_active_icon: unicode
"""
custom_layouts_icon = "images/Custom_Layouts.png"
"""
:param custom_layouts_icon: Application **Custom Layouts** icon.
:type custom_layouts_icon: unicode
"""
custom_layouts_hover_icon = "images/Custom_Layouts_Hover.png"
"""
:param custom_layouts_hover_icon: Application **Custom Layouts** hover icon.
:type custom_layouts_hover_icon: unicode
"""
custom_layouts_active_icon = "images/Custom_Layouts_Active.png"
"""
:param custom_layouts_active_icon: Application **Custom Layouts** active icon.
:type custom_layouts_active_icon: unicode
"""
miscellaneous_icon = "images/Miscellaneous.png"
"""
:param miscellaneous_icon: Application **Miscellaneous** icon.
:type miscellaneous_icon: unicode
"""
miscellaneous_hover_icon = "images/Miscellaneous_Hover.pn | g"
"""
:param miscellaneous_hover_icon: Application **Miscellaneous** hover icon.
:type miscellaneous_hover_icon: unicode
"""
miscellaneous_active_icon = "images/Miscellaneous_Active.png"
"""
:param miscellaneous_active_icon: Applic | ation **Miscellaneous** active icon.
:type miscellaneous_active_icon: unicode
"""
library_icon = "images/Library.png"
"""
:param library_icon: Application **Library** icon.
:type library_icon: unicode
"""
library_hover_icon = "images/Library_Hover.png"
"""
:param library_hover_icon: Application **Library** hover icon.
:type library_hover_icon: unicode
"""
library_active_icon = "images/Library_Active.png"
"""
:param library_active_icon: Application **Library** active icon.
:type library_active_icon: unicode
"""
inspect_icon = "images/Inspect.png"
"""
:param inspect_icon: Application **Inspect** icon.
:type inspect_icon: unicode
"""
inspect_hover_icon = "images/Inspect_Hover.png"
"""
:param inspect_hover_icon: Application **Inspect** hover icon.
:type inspect_hover_icon: unicode
"""
inspect_active_icon = "images/Inspect_Active.png"
"""
:param inspect_active_icon: Application **Inspect** active icon.
:type inspect_active_icon: unicode
"""
export_icon = "images/Export.png"
"""
:param export_icon: Application **Export** icon.
:type export_icon: unicode
"""
export_hover_icon = "images/Export_Hover.png"
"""
:param export_hover_icon: Application **Export** hover icon.
:type export_hover_icon: unicode
"""
export_active_icon = "images/Export_Active.png"
"""
:param export_active_icon: Application **Export** active icon.
:type export_active_icon: unicode
"""
edit_icon = "images/Edit.png"
"""
:param edit_icon: Application **Edit** icon.
:type edit_icon: unicode
"""
edit_hover_icon = "images/Edit_Hover.png"
"""
:param edit_hover_icon: Application **Edit** hover icon.
:type edit_hover_icon: unicode
"""
edit_active_icon = "images/Edit_Active.png"
"""
:param edit_active_icon: Application **Edit** active icon.
:type edit_active_icon: unicode
"""
preferences_icon = "images/Preferences.png"
"""
:param preferences_icon: Application **Preferences** icon.
:type preferences_icon: unicode
"""
preferences_hover_icon = "images/Preferences_Hover.png"
"""
:param preferences_hover_icon: Application **Preferences** hover icon.
:type preferences_hover_icon: unicode
"""
preferences_active_icon = "images/Preferences_Active.png"
"""
:param preferences_active_icon: Application **Preferences** active icon.
:type preferences_active_icon: unicode
"""
format_error_image = "images/Thumbnail_Format_Not_Supported_Yet.png"
"""
:param format_error_image: Application format error image thumbnail.
:type format_error_image: unicode
"""
missing_image = "images/Thumbnail_Not_Found.png"
"""
:param missing_image: Application missing image thumbnail.
:type missing_image: unicode
"""
loading_image = "images/Loading.png"
"""
:param loading_image: Application loading image thumbnail.
:type loading_image: unicode
"""
startup_layout = "startup_centric"
"""
:param startup_layout: Application startup layout.
:type startup_layout: unicode
"""
development_layout = "edit_centric"
"""
:param development_layout: Application development layout.
:type development_layout: unicode
"""
help_file = "http://kelsolaar.hdrlabs.com/sIBL_GUI/Support/Documentation/Help/index.html"
"""Application online help file:
'**http://kelsolaar.hdrlabs.com/sIBL_GUI/Support/Documentation/Help/index.html**' ( String )"""
api_file = "http://kelsolaar.hdrlabs.com/sIBL_GUI/Support/Documentation/Api/index.html"
"""Application online api file:
'**http://kelsol |
pjryan126/solid-start-careers | store/api/zillow/venv/lib/python2.7/site-packages/pandas/tests/frame/test_replace.py | Python | gpl-2.0 | 42,783 | 0.000093 | # -*- coding: utf-8 -*-
from __future__ import print_function
from datetime import datetime
import re
from pandas.compat import (zip, range, lrange, StringIO)
from pandas import (DataFrame, Series, Index, date_range, compat,
Timestamp)
import pandas as pd
from numpy import nan
import numpy as np
from pandas.util.testing import (assert_series_equal,
assert_frame_equal)
import pandas.util.testing as tm
from pandas.tests.frame.common import TestData
class TestDataFrameReplace(tm.TestCase, TestData):
_multiprocess_can_split_ = True
def test_replace_inplace(self):
self.tsframe['A'][:5] = nan
self.tsframe['A'][-5:] = nan
tsframe = self.tsframe.copy()
tsframe.replace(nan, 0, inplace=True)
assert_frame_equal(tsframe, self.tsframe.fillna(0))
self.assertRaises(TypeError, self.tsframe.replace, nan, inplace=True)
self.assertRaises(TypeError, self.tsframe.replace, nan)
# mixed type
self.mixed_frame.ix[5:20, 'foo'] = nan
self.mixed_frame.ix[-10:, 'A'] = nan
result = self.mixed_frame.replace(np.nan, 0)
expected = self.mixed_frame.fillna(value=0)
assert_frame_equal(result, expected)
tsframe = self.tsframe.copy()
tsframe.replace([nan], [0], inplace=True)
assert_frame_equal(tsframe, self.tsframe.fillna(0))
def test_regex_replace_scalar(self):
obj = {'a': list('ab..'), 'b': list('efgh')}
dfobj = DataFrame(obj)
mix = {'a': lrange(4), 'b': list('ab..')}
dfmix = DataFrame(mix)
# simplest cases
# regex -> value
# obj frame
res = dfobj.replace(r'\s*\.\s*', nan, regex=True)
assert_frame_equal(dfobj, res.fillna('.'))
# mixed
res = dfmix.replace(r'\s*\.\s*', nan, regex=True)
assert_frame_equal(dfmix, res.fillna('.'))
# regex -> regex
# obj frame
res = dfobj.replace(r'\s*(\.)\s*', r'\1\1\1', regex=True)
objc = obj.copy()
objc['a'] = ['a', 'b', '...', '...']
expec = DataFrame(objc)
assert_frame_equal(res, expec)
# with mixed
res = dfmix.replace(r'\s*(\.)\s*', r'\1\1\1', regex=True)
mixc = mix.copy()
mixc['b'] = ['a', 'b', '...', '...']
expec = DataFrame(mixc)
assert_frame_equal(res, expec)
# everything with compiled regexs as well
res = dfobj.replace(re.compile(r'\s*\.\s*'), nan, regex=True)
assert_frame_equal(dfobj, res.fillna('.'))
# mixed
res = dfmix.replace(re.compile(r'\s*\.\s*'), nan, regex=True)
assert_frame_equal(dfmix, res.fillna('.'))
# regex -> regex
# obj frame
res = dfobj.replace(re.compile(r'\s*(\.)\s*'), r'\1\1\1')
objc = obj.copy()
objc['a'] = ['a', 'b', '...', '...']
expec = DataFrame(objc)
assert_frame_equal(res, expec)
# with mixed
res = dfmix.replace(re.compile(r'\s*(\.)\s*'), r'\1\1\1')
mixc = mix.copy()
mixc['b'] = ['a', 'b', '...', '...']
expec = DataFrame(mixc)
assert_frame_equal(res, expec)
res = dfmix.replace(regex=re.compile(r'\s*(\.)\s*'), value=r'\1\1\1')
mixc = mix.copy()
mixc['b'] = ['a', 'b', '...', '...']
expec = DataFrame(mixc)
assert_frame_equal(res, expec)
res = dfmix.replace(regex=r'\s*(\.)\s*', value=r'\1\1\1')
mixc = mix.copy()
mixc['b'] = ['a', 'b', '...', '...']
expec = DataFrame(mixc)
assert_frame_equal(res, expec)
def test_regex_replace_scalar_inplace(self):
obj = {'a': list('ab..'), 'b': list('efgh')}
dfobj = DataFrame(obj)
mix = {'a': lrange(4), 'b': list('ab..')}
dfmix = DataFrame(mix)
# simplest cases
# regex -> value
# obj frame
res = dfobj.copy()
res.replace(r'\s*\.\s*', nan, regex=True, inplace=True)
assert_frame_equal(dfobj, res.fillna('.'))
# mixed
res = dfmix.copy()
res.replace(r'\s*\.\s*', nan, regex=True, inplace=True)
assert_frame_equal(dfmix, res.fillna('.'))
# regex -> regex
# obj frame
res = dfobj.copy()
res.replace(r'\s*(\.)\s*', r'\1\1\1', regex=True, inplace=True)
objc = obj.copy()
objc['a'] = ['a', 'b', '...', '...']
expec = DataFrame(objc)
assert_frame_equal(res, expec)
# with mixed
res = dfmix.copy()
res.replace(r'\s*(\.)\s*', r'\1\1\1', regex=True, inplace=True)
mixc = mix.copy()
mixc['b'] = ['a', 'b', '...', '...']
expec = DataFrame(mixc)
assert_frame_equal(res, expec)
# everything with compiled regexs as well
res = dfobj.copy()
res.replace(re.compile(r'\s*\.\s*'), nan, regex=True, inplace=True)
assert_frame_equal(dfobj, res.fillna('.'))
# mixed
res = dfmix.copy()
res.replace(re.compile(r'\s*\.\s*'), nan, regex=True, inplace=True)
assert_frame_equal(dfmix, res.fillna('.'))
# regex -> regex
# obj frame
res = dfobj.copy()
res.replace(re.compile(r'\s*(\.)\s*'), r'\1\1\1', regex=True,
inplace=True)
objc = obj.copy()
objc['a'] = ['a', 'b', '...', '...']
expec = DataFrame(objc)
assert_frame_equal(res, expec)
# with mixed
res = dfmix.copy()
res.replace(re.compile(r'\s*(\.)\s*'), r'\1\1\1', regex=True,
inplace=True)
mixc = mix.copy()
mixc['b'] = ['a', 'b', '...', '...']
expec = DataFrame(mixc)
assert_frame_equal(res, expec)
res = dfobj.copy()
res.replace(regex=r'\s*\.\s*', value=nan, inplace=True)
assert_frame_equal(dfobj, res.fillna('.'))
# mixed
res = dfmix.copy()
res.replace(regex=r'\s*\.\s*', value=nan, inplace=True)
assert_frame_equal(dfmix, res.fillna('.'))
# regex -> regex
# obj frame
res = dfobj.copy()
res.replace(regex=r'\s*(\.)\s*', value=r'\1\1\1', inplace=True)
objc = obj.copy()
objc['a'] = ['a', 'b', '...', '...']
expec = DataFrame(objc)
assert_frame_equal(res, expec)
# with mixed
res = dfmix.copy()
res.replace(regex=r'\s*(\.)\s*', value=r'\1\1\1', inplace=True)
mixc = mix.copy()
mixc['b'] = ['a', 'b', '...', '...']
expec = DataFrame(mixc)
assert_frame_equal(res, expec)
# everything with compiled regexs as well
res = dfobj.copy()
res.replace(regex=re.compile(r'\s*\.\s*'), value=nan, inplace=True)
assert_frame_equal(dfobj, res.fillna('.'))
# mixed
res = dfmix.copy()
res.replace(regex=re.compile(r'\s*\.\s*'), value=nan, inplace=True)
assert_frame_equal(dfmix, res.fillna('.'))
# regex -> regex
# obj frame
res = dfobj.copy()
res.replace(regex=re.compile(r'\s*(\.)\s*'), value=r'\1\1\1',
inplace=True)
objc = obj.copy()
objc['a'] = ['a', 'b', '...', '...']
expec = DataFrame(objc)
assert_frame_equal(res, expec)
# with mixed
res = dfmix.copy()
res.replace(regex=re.compile(r'\s*(\.)\s*'), value=r'\1\1\1',
inplace=True)
mixc = mix.copy()
mixc['b'] = ['a', 'b', '...', '...']
expec = DataFrame(mixc)
assert_frame_equal(res, expec)
def test_regex_replace_list_obj(self):
obj = {'a': list('ab..'), 'b': list('efgh'), 'c': list('helo')}
dfobj = Da | taFrame(obj)
# lists of regexes and values
# list of [re1, re2, ..., reN] -> [v1, v2, ..., vN]
to_replace_res = [r'\s*\.\s*', r'e|f|g']
values = [nan, 'cr | ap']
res = dfobj.replace(to_replace_res, values, regex=True)
expec = DataFrame({'a': ['a', 'b', nan, nan], 'b': ['crap'] * 3 +
['h'], 'c': ['h', 'crap', 'l', 'o']})
assert_frame_equal(res, expec)
|
mancoast/CPythonPyc_test | cpython/242_test_codecs.py | Python | gpl-3.0 | 27,615 | 0.001811 | from test import test_support
import unittest
import codecs
import sys, StringIO
class Queue(object):
"""
queue: write bytes at one end, read bytes from the other end
"""
def __init__(self):
self._buffer = ""
def write(self, chars):
self._buffer += chars
def read(self, size=-1):
if size<0:
s = self._buffer
self._buffer = ""
return s
else:
s = self._buffer[:size]
self._buffer = self._buffer[size:]
return s
class ReadTest(unittest.TestCase):
def test_seek(self):
# all codecs should be able to encode these
s = u"%s\n%s\n" % (100*u"abc123", 100*u"def456")
encoding = self.encoding
reader = codecs.getreader(encoding)(StringIO.StringIO(s.encode(encoding)))
for t in xrange(5):
# Test that calling seek resets the internal codec state and buffers
reader.seek(0, 0)
line = reader.readline()
self.assertEqual(s[:len(line)], line)
def check_partial(self, input, partialresults):
# get a StreamReader for the encoding and feed the bytestring version
# of input to the reader byte by byte. Read every available from
# the StreamReader and check that the results equal the appropriate
# entries from partialresults.
q = Queue()
r = codecs.getreader(self.encoding)(q)
result = u""
for (c, partialresult) in zip(input.encode(self.encoding), partialresults):
q.write(c)
result += r.read()
self.assertEqual(result, partialresult)
# check that there's nothing left in the buffers
self.assertEqual(r.read(), u"")
self.assertEqual(r.bytebuffer, "")
self.assertEqual(r.charbuffer, u"")
def test_readline(self):
def getreader(input):
stream = StringIO.StringIO(input.encode(self.encoding))
return codecs.getreader(self.encoding)(stream)
def readalllines(input, keepends=True):
reader = getreader(input)
lines = []
while True:
line = reader.readline(keepends=keepends)
if not line:
break
lines.append(line)
return "".join(lines)
s = u"foo\nbar\r\nbaz\rspam\u2028eggs"
self.assertEqual(readalllines(s, True), s)
self.assertEqual(readalllines(s, False), u"foobarbazspameggs")
# Test long lines (multiple calls to read() in readline())
vw = []
vwo = []
for (i, lineend) in enumerate(u"\n \r\n \r \u2028".split()):
vw.append((i*200)*u"\3042" + lineend)
vwo.append((i*200)*u"\3042")
self.assertEqual(readalllines("".join(vw), True), "".join(vw))
self.assertEqual(readalllines("".join(vw), False),"".join(vwo))
# Test lines where the first read might end with \r, so the
# reader has to look ahead whether this is a lone \r or a \r\n
for size in xrange(80):
for lineend in u"\n \r\n \r \u2028".split():
s = 10*(size*u"a" + lineend + u"xxx\n")
reader = getreader(s)
for i in xrange(10):
self.assertEqual(
reader.readline(keepends=True),
size*u"a" + lineend,
)
reader = getreader(s)
for i in xrange(10):
self.assertEqual(
reader.readline(keepends=False),
size*u"a",
)
def test_bug1175396(self):
s = [
'<%!--===================================================\r\n',
' BLOG index page: show recent articles,\r\n',
' today\'s articles, or articles of a specific date.\r\n',
'========================================================--%>\r\n',
'<%@inputencoding="ISO-8859-1"%>\r\n',
'<%@pagetemplate=TEMPLATE.y%>\r\n',
'<%@import=import frog.util, frog%>\r\n',
'<%@import=import frog.objects%>\r\n',
'<%@import=from frog.storageerrors import StorageError%>\r\n',
'<%\r\n',
'\r\n',
'import logging\r\n',
'log=logging.getLogger("Snakelets.logger")\r\n',
'\r\n',
'\r\n',
'user=self.SessionCtx.user\r\n',
'storageEngine=self.SessionCtx.storageEngine\r\n',
'\r\n',
'\r\n',
'def readArticlesFromDate(date, count=None):\r\n',
' entryids=storageEngine.listBlogEntries(date)\r\n',
' entryids.reverse() # descending\r\n',
' if count:\r\n',
' entryids=entryids[:count]\r\n',
' try:\r\n',
' return [ frog.objects.BlogEntry.load(storageEngine, date, Id) for Id in entryids ]\r\n',
' except StorageError,x:\r\n',
' log.error("Error loading articles: "+str(x))\r\n',
' self.abort("cannot load articles")\r\n',
'\r\n',
'showdate=None\r\n',
'\r\n',
'arg=self. | Request.getArg()\r\n',
'if arg=="today":\r\n',
' #-------------------- TODAY\'S ARTICLES\r\n',
' self.write("<h2>Today\'s articles</h2>")\r\n',
' showdate = frog.util.isodatestr() \r\n',
' entries = readArticlesFromDate(showdate)\r\n',
| 'elif arg=="active":\r\n',
' #-------------------- ACTIVE ARTICLES redirect\r\n',
' self.Yredirect("active.y")\r\n',
'elif arg=="login":\r\n',
' #-------------------- LOGIN PAGE redirect\r\n',
' self.Yredirect("login.y")\r\n',
'elif arg=="date":\r\n',
' #-------------------- ARTICLES OF A SPECIFIC DATE\r\n',
' showdate = self.Request.getParameter("date")\r\n',
' self.write("<h2>Articles written on %s</h2>"% frog.util.mediumdatestr(showdate))\r\n',
' entries = readArticlesFromDate(showdate)\r\n',
'else:\r\n',
' #-------------------- RECENT ARTICLES\r\n',
' self.write("<h2>Recent articles</h2>")\r\n',
' dates=storageEngine.listBlogEntryDates()\r\n',
' if dates:\r\n',
' entries=[]\r\n',
' SHOWAMOUNT=10\r\n',
' for showdate in dates:\r\n',
' entries.extend( readArticlesFromDate(showdate, SHOWAMOUNT-len(entries)) )\r\n',
' if len(entries)>=SHOWAMOUNT:\r\n',
' break\r\n',
' \r\n',
]
stream = StringIO.StringIO("".join(s).encode(self.encoding))
reader = codecs.getreader(self.encoding)(stream)
for (i, line) in enumerate(reader):
self.assertEqual(line, s[i])
def test_readlinequeue(self):
q = Queue()
writer = codecs.getwriter(self.encoding)(q)
reader = codecs.getreader(self.encoding)(q)
# No lineends
writer.write(u"foo\r")
self.assertEqual(reader.readline(keepends=False), u"foo")
writer.write(u"\nbar\r")
self.assertEqual(reader.readline(keepends=False), u"")
self.assertEqual(reader.readline(keepends=False), u"bar")
writer.write(u"baz")
self.assertEqual(reader.readline(keepends=False), u"baz")
self.assertEqual(reader.readline(keepends=False), u"")
# Lineends
writer.write(u"foo\r")
self.assertEqual(reader.readline(keepends=True), u"foo\r")
writer.write(u"\nbar\r")
self.assertEqual(reader.readline(keepends=True), u"\n")
self.assertEqual(reader.readline(keepends=True), u"bar\r")
writer.write(u"baz")
self.assertEqual(reader.readline(keepends=True), u"baz")
self.assertEqual(reader.readline(keepends=True), u"")
writer.write(u"foo\r\n")
self.assertEqua |
rehmanz/salt-reactors-demo | salt/formulas/base/reactor/ui_reactor.py | Python | mit | 2,365 | 0.00592 | #!/usr/bin/env python
import os
import time
import logging
import argparse
from Queue import Queue
from threading import Thread
from salt.utils.event import LocalClientEvent
LOGGER = logging.getLogger()
MAX_TIMEOUT_VALUE=60*5
def __parse_record(event):
payload = event.get('data', {})
return payload.get('record', {})
def get_event_payload(tag_id):
for event in client.iter_events(tag=tag_id):
payload = __parse_record(event)
return payload
def process_events():
while True:
if not q.empty():
LOGGER.debug("#TODO: Implement correlation logic")
LOGGER.debug("Waiting 20 seconds for all events to be registered")
time.sleep(20)
LOGGER.debug("Fetching all events from the event queue")
while not q.empty():
msg_payload = q.get()
LOGGER.debug("msg_payload=%s" %msg_payload)
timeout = time.time() + MAX_TIMEOUT_VALUE
while time.time() < timeout:
try:
LOGGER.debug("#TODO: Implement complex reaction")
except Exception as e:
LOGGER.error("Failed to complete the reaction: %s" %(e))
# Send failure notification
break
LOGGER.debug("#TODO: Implement validation & notification")
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
parser = argparse.ArgumentParser()
""" Required Parameters Definition """
parser.add_argument("environment", help="demo")
args = parser.parse_args()
target_env = args.en | vironment
tag_id = 'salt/%s/ui/slave/dead' %(target_env)
client = LocalClientEvent("/var/run/salt/master")
# Setup file handler
fh= logging.FileHandler("/var/log/%s.log" %target_env)
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
LOGGER.addHandler(fh)
LOGGER.debug("##")
LOGGER.debug("# Setting up UI Reactor for %s" %target_env)
LOGGER.debug("##")
q = Queue( | )
worker = Thread(target=process_events)
worker.setDaemon(True)
worker.start()
while True:
event_payload = get_event_payload(tag_id)
q.put(event_payload)
LOGGER.info("Received an event=%s" %event_payload) |
leetreveil/tulip | examples/cachesvr.py | Python | apache-2.0 | 9,357 | 0 | """A simple memcache-like server.
The basic data structure maintained is a single in-memory dictionary
mapping string keys to string values, with operations get, set and
delete. (Both keys and values may contain Unicode.)
This is a TCP server listening on port 54321. There is no
authentication.
Requests provide an operation and return a response. A connection may
be used for multiple requests. The connection is closed when a client
sends a bad request.
If a client is idle for over 5 seconds (i.e., it does not send another
request, or fails to read the whole response, within this time), it is
disconnected.
Framing of requests and responses within a connection uses a
line-based protocol. The first line of a request is the frame header
and contains three whitespace-delimited token followed by LF or CRLF:
- the keyword 'request'
- a decimal request ID; the first request is '1', the second '2', etc.
- a decimal byte count giving the size of the rest of the request
Note that the requests ID *must* be consecutive and start at '1' for
each connection.
Response frames look the same except the keyword is 'response'. The
response ID matches the request ID. There should be exactly one
response to each request and responses should be seen in the same
order as the requests.
After the frame, individual requests and responses are JSON encoded.
If the frame header or the JSON request body cannot be parsed, an
unframed error message (always starting with 'error') is written back
and the connection is closed.
JSON-encoded requests can be:
- {"type": "get", "key": <string>}
- {"type": "set", "key": <string>, "value": <string>}
- {"type": "delete", "key": <string>}
Responses are also JSON-encoded:
- {"status": "ok", "value": <string>} # Successful get request
- {"status": "ok"} # Successful set or delete request
- {"status": "notfound"} # Key not found for get or delete request
If the request is valid JSON but cannot be handled (e.g., the type or
key field is absent or invalid), an error response of the following
form is returned, but the connection is not closed:
- {"error": <string>}
"""
import argparse
import asyncio
import json
import logging
import os
import random
ARGS = argparse.ArgumentParser(description='Cache server example.')
ARGS.add_argument(
'--tls', action='store_true', dest='tls',
default=False, help='Use TLS')
ARGS.add_argument(
'--iocp', action='store_true', dest='iocp',
default=False, help='Use IOCP event loop (Windows only)')
ARGS.add_argument(
'--host', action='store', dest='host',
default='localhost', help='Host name')
ARGS.add_argument(
'--port', action='store', dest='port',
default=54321, type=int, help='Port number')
ARGS.add_argument(
'--timeout', action='store', dest='timeout',
default=5, type=float, help='Timeout')
ARGS.add_argument(
'--random_failure_percent', action='store', dest='fail_percent',
default=0, type=float, help='Fail randomly N percent of the time')
ARGS.add_argument(
'--random_failure_sleep', action='store', dest='fail_sleep',
default=0, type=float, help='Sleep time when randomly failing')
ARGS.add_argument(
'--random_response_sleep', action='store', dest='resp_sleep',
default=0, type=float, help='Sleep time before responding')
args = ARGS.parse_args()
class Cache:
def __init__(self, loop):
self.loop = loop
self.table = {}
@asyncio.coroutine
def handle_client(self, reader, writer):
# Wrapper to log stuff and close writer (i.e., transport).
peer = writer.get_extra_info('socket').getpeername()
logging.info('got a connection from %s', peer)
try:
yield from self.frame_parser(reader, writer)
except Exception as exc:
logging.error('error %r from %s', exc, peer)
else:
logging.info('end connection from %s', peer)
finally:
writer.close()
@asyncio.coroutine
def frame_parser(self, reader, writer):
# This takes care of the framing.
last_request_id = 0
while True:
# Read the frame header, parse it, read the data.
# NOTE: The readline() and readexactly() calls will hang
# if the client doesn't send enough data but doesn't
# disconnect either. We add a timeout to each. (But the
# timeout should really be implemented by StreamReader.)
framing_b = yield from asyncio.wait_for(
reader.readline(),
timeout=args.timeout, loop=self.loop)
if random.random()*100 < args.fail_percent:
logging.warn('Inserting random failure')
yield from asyncio.sleep(args.fail_sleep*random.random(),
loop=self.loop)
writer.write(b'error random failure\r\n')
break
logging.debug('framing_b = %r', framing_b)
if not framing_b:
break # Clean close.
try:
frame_keyword, request_id_b, byte_count_b = framing_b.split()
except ValueError:
writer.write(b'error unparseable frame\r\n')
break
if frame_keyword != b'request':
writer.write(b'error frame does not start with request\r\n')
break
try:
request_id, byte_count = int(request_id_b), int(byte_count_b)
except ValueError:
writer.write(b'error unparsable frame parameters\r\n')
break
if request_id != last_request_id + 1 or byte_count < 2:
writer.write(b'error invalid frame parameters\r\n')
break
last_request_id = request_id
request_b = yield from asyncio.wait_for(
reader.readexactly(byte_count),
timeout=args.timeout, loop=self.loop)
try:
request = json.loads(request_b.decode('utf8'))
except ValueError:
writer.write(b'error unparsable json\r\n')
break
response = self.handle_request(request) # Not a coroutine.
if response is None:
writer.write(b'error unhandlable request\r\n')
break
response_b = json.dumps(response).encode('utf8') + b'\r\n'
byte_count = len(response_b)
framing_s = 'response {} {}\r\n'.format(request_id, byte_count)
writer.write(framing_s.encode('ascii'))
yield from asyncio.sleep(args.resp_sleep*random.random(),
loop=self.loop)
writer.write(response_b)
def handle_request(self, request):
# This parses one request and farms it out to a specific handler.
# Return None for all errors.
if not isinstance(request, dict):
return {'error': 'request is not a dict'}
request_type = request.get('type')
if reque | st_type is None:
return {'error': 'no type in request'}
if request_type not in {'get', 'set', 'delete'}:
return {'error': 'unknown request type'}
key = request.get('key')
if not isinstance(key, str):
| return {'error': 'key is not a string'}
if request_type == 'get':
return self.handle_get(key)
if request_type == 'set':
value = request.get('value')
if not isinstance(value, str):
return {'error': 'value is not a string'}
return self.handle_set(key, value)
if request_type == 'delete':
return self.handle_delete(key)
assert False, 'bad request type' # Should have been caught above.
def handle_get(self, key):
value = self.table.get(key)
if value is None:
return {'status': 'notfound'}
else:
return {'status': 'ok', 'value': value}
def handle_set(self, key, value):
self.table[key] = value
return {'status': 'ok'}
def handle_delete(self, key):
if key not in self.table:
|
cbertinato/pandas | pandas/tests/io/parser/test_mangle_dupes.py | Python | bsd-3-clause | 3,885 | 0 | """
Tests that duplicate columns are handled appropriately when parsed by the
CSV engine. In general, the expected result is that they are either thoroughly
de-duplicated (if mangling requested) or ignored otherwise.
"""
from io import StringIO
import pytest
from pandas import DataFrame
import pandas.util.testing as tm
@pytest.mark.parametrize("kwargs", [dict(), dict(mangle_dupe_cols=True)])
def test_basic(all_parsers, kwargs):
# TODO: add test for condition "mangle_dupe_cols=False"
# once it is actually supported (gh-12935)
parser = all_parsers
data = "a,a,b,b,b\n1,2,3,4,5"
result = parser.read_csv(StringIO(data), sep=",", **kwargs)
expected = DataFrame([[1, 2, 3, 4, 5]],
columns=["a", "a.1", "b", "b.1", "b.2"])
tm.assert_frame_equal(result, expected)
def test_basic_names(all_parsers):
# See gh-7160
parser = all_parsers
data = "a,b,a\n0,1,2\n3,4,5"
expected = DataFrame([[0, 1, 2], [3, 4, 5]],
columns=["a", "b", "a.1"])
result = parser.read_csv(StringIO(data))
tm.assert_frame_equal(result, expected)
def test_basic_names_warn(all_parsers):
# See gh-7160
parser = all_parsers
data = "0,1,2\n3,4,5"
expected = DataFrame([[0, 1, 2], [3, 4, 5]],
columns=["a", "b", "a.1"])
with tm.assert_produces_warning(UserWarning, check_stacklevel=False):
result = parser.read_csv(StringIO(data), names=["a", "b", "a"])
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("data,expected", [
("a,a,a.1\n1,2,3",
DataFrame([[1, 2, 3]], columns=["a", "a.1", "a.1.1"])),
("a,a,a.1,a.1.1,a.1.1.1,a.1.1.1.1\n1,2,3,4,5,6",
DataFrame([[1, 2, 3, 4, 5, 6]], columns=["a", "a.1", "a.1.1", "a.1.1.1",
| "a.1.1.1.1", "a.1.1.1.1.1"])),
("a,a,a.3,a.1,a.2,a,a\n1,2,3,4,5,6,7",
DataFrame([[1, 2, 3, 4, 5, 6, 7]], columns=["a", "a.1", "a.3", "a.1.1",
| "a.2", "a.2.1", "a.3.1"]))
])
def test_thorough_mangle_columns(all_parsers, data, expected):
# see gh-17060
parser = all_parsers
result = parser.read_csv(StringIO(data))
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("data,names,expected", [
("a,b,b\n1,2,3",
["a.1", "a.1", "a.1.1"],
DataFrame([["a", "b", "b"], ["1", "2", "3"]],
columns=["a.1", "a.1.1", "a.1.1.1"])),
("a,b,c,d,e,f\n1,2,3,4,5,6",
["a", "a", "a.1", "a.1.1", "a.1.1.1", "a.1.1.1.1"],
DataFrame([["a", "b", "c", "d", "e", "f"],
["1", "2", "3", "4", "5", "6"]],
columns=["a", "a.1", "a.1.1", "a.1.1.1",
"a.1.1.1.1", "a.1.1.1.1.1"])),
("a,b,c,d,e,f,g\n1,2,3,4,5,6,7",
["a", "a", "a.3", "a.1", "a.2", "a", "a"],
DataFrame([["a", "b", "c", "d", "e", "f", "g"],
["1", "2", "3", "4", "5", "6", "7"]],
columns=["a", "a.1", "a.3", "a.1.1",
"a.2", "a.2.1", "a.3.1"])),
])
def test_thorough_mangle_names(all_parsers, data, names, expected):
# see gh-17095
parser = all_parsers
with tm.assert_produces_warning(UserWarning, check_stacklevel=False):
result = parser.read_csv(StringIO(data), names=names)
tm.assert_frame_equal(result, expected)
def test_mangled_unnamed_placeholders(all_parsers):
# xref gh-13017
orig_key = "0"
parser = all_parsers
orig_value = [1, 2, 3]
df = DataFrame({orig_key: orig_value})
# This test recursively updates `df`.
for i in range(3):
expected = DataFrame()
for j in range(i + 1):
expected["Unnamed: 0" + ".1" * j] = [0, 1, 2]
expected[orig_key] = orig_value
df = parser.read_csv(StringIO(df.to_csv()))
tm.assert_frame_equal(df, expected)
|
taghq/radcity_site | pdxrad/cms_plugins.py | Python | apache-2.0 | 573 | 0.005236 | from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_po | ol
from cms.models.pluginmodel import CMSPlugin
from django.utils.translation import ug | ettext_lazy as _
from .models import Feature
class FeaturePlugin(CMSPluginBase):
model = Feature
name = _("RAD Feature Plugin")
render_template = "plugins/feature.html"
cache = False
def render(self, context, instance, placeholder):
context = super(FeaturePlugin, self).render(context, instance, placeholder)
return context
plugin_pool.register_plugin(FeaturePlugin)
|
GoogleCloudPlatform/sap-deployment-automation | third_party/github.com/ansible/awx/awx_collection/plugins/modules/tower_receive.py | Python | apache-2.0 | 5,506 | 0.001453 | #!/usr/bin/python
# coding: utf-8 -*-
# (c) 2017, John Westcott IV <john.westcott.iv@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['deprecated'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: tower_receive
deprecated:
removed_in: "14.0.0"
why: Deprecated in favor of upcoming C(_export) module.
alternative: Once published, use M(tower_export) instead.
author: "John Westcott IV (@john-westcott-iv)"
short_description: Receive assets from Ansible Tower.
description:
- Receive assets from Ansible Tower. See
U(https://www.ansible.com/tower) for an overview.
options:
all:
description:
- Export all assets
type: bool
default: 'False'
organization:
description:
- List of organization names to export
default: []
type: list
elements: str
user:
description:
- List of user names to export
default: []
type: list
elements: str
team:
description:
- List of team names to export
default: []
type: list
elements: str
credential_type:
description:
- List of credential type names to export
default: []
type: list
elements: str
credential:
description:
- List of credential names to export
default: []
type: list
elements: str
notification_template:
description:
- List of notification template names to export
default: []
type: list
elements: str
inventory_script:
description:
- List of inventory script names to export
default: []
type: list
elements: str
inventory:
description:
- List of inventory names to export
default: []
type: list
elements: str
project:
description:
- List of project names to export
default: []
type: list
elements: str
job_template:
description:
- List of job template names to export
default: []
type: list
elements: str
workflow:
description:
- List of workflow names to export
default: []
type: list
elements: str
requirements:
- "ansible-tower-cli >= 3.3.0"
notes:
- Specifying a name of "all" for any asset type will export all items of that asset type.
extends_documentation_fragment: awx.awx.auth_legacy
'''
EXAMPLES = '''
- name: Export all tower assets
tower_receive:
all: True
tower_config_file: "~/tower_cli.cfg"
- name: Export all inventories
tower_receive:
inventory:
- all
- name: Export a job template named "My Template" and all Credentials
tower_receive:
job_template:
- "My Template"
credential:
- all
'''
RETURN = '''
assets:
description: The exported assets
returned: success
type: dict
sample: [ {}, {} ]
'''
from ..module_utils.tower_legacy import TowerLegacyModule, tower_auth_config, HAS_TOWER_CLI
try:
from tower_cli.cli.transfer.receive import Receiver
from tower_cli.cli.transfer.common import SEND_ORDER
from tower_cli.utils.exceptions import TowerCLIError
from tower_cli.conf import settings
TOWER_CLI_HAS_EXPORT = True
except ImportError:
TOWER_CLI_HAS_EXPORT = False
def main():
argument_spec = dict(
all=dict(type='bool', default=False),
credential=dict(type='list', default=[], elements='str'),
credential_type=dict(type='list', default=[], elements='str'),
inventory=dict(type='list', default=[], elements='str'),
inventory_script=dict(type='list', default=[], el | ements='str'),
job_template=dict(type='list', default=[], elements='str'),
notification_ | template=dict(type='list', default=[], elements='str'),
organization=dict(type='list', default=[], elements='str'),
project=dict(type='list', default=[], elements='str'),
team=dict(type='list', default=[], elements='str'),
user=dict(type='list', default=[], elements='str'),
workflow=dict(type='list', default=[], elements='str'),
)
module = TowerLegacyModule(argument_spec=argument_spec, supports_check_mode=False)
module.deprecate(msg="This module is deprecated and will be replaced by the AWX CLI export command.", version="awx.awx:14.0.0")
if not HAS_TOWER_CLI:
module.fail_json(msg='ansible-tower-cli required for this module')
if not TOWER_CLI_HAS_EXPORT:
module.fail_json(msg='ansible-tower-cli version does not support export')
export_all = module.params.get('all')
assets_to_export = {}
for asset_type in SEND_ORDER:
assets_to_export[asset_type] = module.params.get(asset_type)
result = dict(
assets=None,
changed=False,
message='',
)
tower_auth = tower_auth_config(module)
with settings.runtime_values(**tower_auth):
try:
receiver = Receiver()
result['assets'] = receiver.export_assets(all=export_all, asset_input=assets_to_export)
module.exit_json(**result)
except TowerCLIError as e:
result['message'] = e.message
module.fail_json(msg='Receive Failed', **result)
if __name__ == '__main__':
main()
|
lsalzman/iqm | blender-2.49/iqm_export.py | Python | mit | 40,875 | 0.006312 | #!BPY
"""
Name: 'Inter-Quake Model'
Blender: 249
Group: 'Export'
Tip: 'Export Inter-Quake Model files'
"""
import struct, math
import Blender
import BPyArmature
IQM_POSITION = 0
IQM_TEXCOORD = 1
IQM_NORMAL = 2
IQM_TANGENT = 3
IQM_BLENDINDEXES = 4
IQM_BLENDWEIGHTS = 5
IQM_COLOR = 6
IQM_CUSTOM = 0x10
IQM_BYTE = 0
IQM_UBYTE = 1
IQM_SHORT = 2
IQM_USHORT = 3
IQM_INT = 4
IQM_UINT = 5
IQM_HALF = 6
IQM_FLOAT = 7
IQM_DOUBLE = 8
IQM_LOOP = 1
IQM_HEADER = struct.Struct('<16s27I')
IQM_MESH = struct.Struct('<6I')
IQM_TRIANGLE = struct.Struct('<3I')
IQM_JOINT = struct.Struct('<Ii10f')
IQM_POSE = struct.Struct('<iI20f')
IQM_ANIMATION = struct.Struct('<3IfI')
IQM_VERTEXARRAY = struct.Struct('<5I')
IQM_BOUNDS = struct.Struct('<8f')
MAXVCACHE = 32
class Vertex:
def __init__(self, index, coord, normal, uv, weights):
self.index = index
self.coord = coord
self.normal = normal
self.uv = uv
self.weights = weights
def normalizeWeights(self):
# renormalizes all weights such that they add up to 255
# the list is chopped/padded to exactly 4 weights if necessary
if not self.weights:
self.weights = [ (0, 0), (0, 0), (0, 0), (0, 0) ]
return
self.weights.sort(key = lambda weight: weight[0], reverse=True)
if len(self.weights) > 4:
del self.weights[4:]
totalweight = sum([ weight for (weight, bone) in self.weights])
if totalweight > 0:
self.weights = [ (int(round(weight * 255.0 / totalweight)), bone) for (weight, bone) in self.weights]
while len(self.weights) > 1 and self.weights[-1][0] <= 0:
self.weights.pop()
else:
totalweight = len(self.weights)
self.weights = [ (int(round(255.0 / totalweight)), bone) for (weight, bone) in self.weights]
totalweight = sum([ weight for (weight, bone) in self.weights])
while totalweight != 255:
for i, (weight, bone) in enumerate(self.weights):
if totalweight > 255 and weight > 0:
self.weights[i] = (weight - 1, bone)
totalweight -= 1
elif totalweight < 255 and weight < 255:
self.weights[i] = (weight + 1, bone)
totalweight += 1
while len(self.weights) < 4:
self.weights.append((0, self.weights[-1][1]))
def calcScore(self):
if self.uses:
self.score = 2.0 * pow(len(self.uses), -0.5)
if self.cacherank >= 3:
self.score += pow(1.0 - float(self.cacherank - 3)/MAXVCACHE, 1.5)
elif self.cacherank >= 0:
self.score += 0.75
else:
self.score = -1.0
def neighborKey(self, other):
if self.coord < other.coord:
return (self.coord.x, self.coord.y, self.coord.z, other.coord.x, other.coord.y, other.coord.z, tuple(self.weights), tuple(other.weights))
else:
return (other.coord.x, other.coord.y, other.coord.z, self.coord.x, self.coord.y, self.coord.z, tuple(other.weights), tuple(self.weights))
def __hash__(self):
return self.index
def __eq__(self, v):
return self.coord == v.coord and self.normal == v.normal and self.uv == v.uv and self.weights == v.weights
class Mesh:
def __init__(self, name, material, verts):
self.name = name
self.material = material
self.verts = [ None for v in verts ]
self.vertmap = {}
self.tris = []
def calcTangents(self):
# See "Tangent Space Calculation" at http://www.terathon.com/code/tangent.html
for v in self.verts:
v.tangent = Blender.Mathutils.Vector(0.0, 0.0, 0.0)
v.bitangent = Blender.Mathutils.Vector(0.0, 0.0, 0.0)
for (v0, v1, v2) in self.tris:
dco1 = v1.coord - v0.coord
dco2 = v2.coord - v0.coord
duv1 = v1.uv - v0.uv
duv2 = v2.uv - v0.uv
tangent = dco2*duv1.y - dco1*duv2.y
bitangent = dco2*duv1.x - dco1*duv2.x
if dco2.cross(dco1).dot(bitangent.cross(tangent)) < 0:
tangent.negate()
bitangent.negate()
v0.tangent += tangent
v1.tangent += tangent
v2.tangent += tangent
v0.bitangent += bitangent
v1.bitangent += bitangent
v2.bitangent += bitangent
for v in self.verts:
v.tangent = (v.tangent - v.normal*v.tangent.dot(v.normal)).normalize()
if v.normal.cross(v.tangent).dot(v.bitangent) < 0:
v.bitangent = -1.0
else:
v.bitangent = 1.0
def optimize(self):
# Linear-speed vertex cache optimization algorithm by Tom Forsyth
for v in self.verts:
if v:
v.index = -1
v.uses = []
v.cacherank = -1
for i, (v0, v1, v2) in enumerate(self.tris):
v0.uses.append(i)
v1.uses.append(i)
v2.uses.append(i)
for v in self.verts:
if v:
v.calcScore()
besttri = -1
bestscore = -42.0
scores = []
for i, (v0, v1, v2) in enumerate(self.tris):
scores.append(v0.score + v1.score + v2.score)
if scores[i] > bestscore:
besttri = i
bestscore = scores[i]
vertloads = 0 # debug info
vertschedule = []
trischedule = []
vcache = []
while besttri >= 0:
tri = self.tris[b | esttri]
scores[besttri] = -666.0
trischedule.append(tri)
for v in tri:
if v.cacherank < 0: # debug info
vertloads += 1 # debug info
if v.index < 0:
v.index = len(vertschedule)
vertschedule.append(v)
v.uses.remove(besttri)
v.cacherank = -1
v.score = -1.0
vcache = [ v for v | in tri if v.uses ] + [ v for v in vcache if v.cacherank >= 0 ]
for i, v in enumerate(vcache):
v.cacherank = i
v.calcScore()
besttri = -1
bestscore = -42.0
for v in vcache:
for i in v.uses:
v0, v1, v2 = self.tris[i]
scores[i] = v0.score + v1.score + v2.score
if scores[i] > bestscore:
besttri = i
bestscore = scores[i]
while len(vcache) > MAXVCACHE:
vcache.pop().cacherank = -1
if besttri < 0:
for i, score in enumerate(scores):
if score > bestscore:
besttri = i
bestscore = score
print '%s: %d verts optimized to %d/%d loads for %d entry LRU cache' % (self.name, len(self.verts), vertloads, len(vertschedule), MAXVCACHE)
#print '%s: %d verts scheduled to %d' % (self.name, len(self.verts), len(vertschedule))
self.verts = vertschedule
# print '%s: %d tris scheduled to %d' % (self.name, len(self.tris), len(trischedule))
self.tris = trischedule
def meshData(self, iqm):
return [ iqm.addText(self.name), iqm.addText(self.material), self.firstvert, len(self.verts), self.firsttri, len(self.tris) ]
class Bone:
def __init__(self, name, index, parent, matrix):
self.name = name
self.index = index
self.parent = parent
self.matrix = matrix
self.localmatrix = matrix
if self.parent:
self.localmatrix *= parent.matrix.copy().invert()
self.numchannels = 0
self.ch |
webcomponents/webcomponents.org | src/datamodel_test.py | Python | apache-2.0 | 5,078 | 0.007089 | from datamodel import Library, Version, Status, VersionCache, CollectionReference, Dependency
from google.appengine.ext import ndb
from test_base import TestBase
class VersionCacheTests(TestBase):
def test_versions_for_key(self):
library_key = ndb.Key(Library, 'a/b')
Version(id='v2.0.0', sha='x', status=Status.ready, parent=library_key).put()
Version(id='v1.0.0', sha='x', status=Status.ready, parent=library_key).put()
Version(id='v3.0.0', sha='x', status=Status.ready, parent=library_key).put()
Version(id='v3.0.X', sha='x', status=Status.ready, parent=library | _key).put()
Version(id='v4.0.0', sha='x', status=Status.error, parent=library_key).put()
Version(id='v5.0.0', sha='x', status=Status.pending, parent=library_key).put()
Version(id='xxx', sha='x', status=Status.ready, parent=library_key).put()
versions = yield Library.uncached_versions_for_key_async( | library_key)
self.assertEqual(versions, ['v1.0.0', 'v2.0.0', 'v3.0.0'])
@ndb.toplevel
def test_version_cache(self):
library_key = ndb.Key(Library, 'a/b')
Version(id='v2.0.0', sha='x', status=Status.ready, parent=library_key).put()
Version(id='v1.0.0', sha='x', status=Status.ready, parent=library_key).put()
Version(id='v3.0.0', sha='x', status=Status.ready, parent=library_key).put()
Version(id='v3.0.X', sha='x', status=Status.ready, parent=library_key).put()
Version(id='v4.0.0', sha='x', status=Status.error, parent=library_key).put()
Version(id='v5.0.0', sha='x', status=Status.pending, parent=library_key).put()
Version(id='xxx', sha='x', status=Status.ready, parent=library_key).put()
versions = yield Library.versions_for_key_async(library_key)
self.assertEqual(versions, [])
latest_changed = VersionCache.update(library_key)
self.assertTrue(latest_changed)
versions = yield Library.versions_for_key_async(library_key)
self.assertEqual(versions, ['v1.0.0', 'v2.0.0', 'v3.0.0', 'v4.0.0'])
Version(id='v6.0.0', sha='x', status=Status.ready, parent=library_key).put()
latest_changed = VersionCache.update(library_key)
self.assertTrue(latest_changed)
versions = yield Library.versions_for_key_async(library_key)
self.assertEqual(versions, ['v1.0.0', 'v2.0.0', 'v3.0.0', 'v4.0.0', 'v6.0.0'])
class CollectionReferenceTests(TestBase):
@ndb.toplevel
def test_stale_ref_is_removed(self):
# Stale since the collection version doesn't actually exist.
collection_v0 = ndb.Key(Library, 'collection/1', Version, 'v0.5.0')
element_key = ndb.Key(Library, 'ele/ment')
element_v1 = Version(id='v1.0.0', sha='x', status=Status.ready, parent=element_key).put()
ref0 = CollectionReference.ensure(element_key, collection_v0, '^1.0.0')
collections = yield Version.collections_for_key_async(element_v1)
collection_keys = [collection.key for collection in collections]
self.assertIsNone(ref0.get())
self.assertEqual(collection_keys, [])
@ndb.toplevel
def test_latest_matching_collection_version_is_returned(self):
collection_key = ndb.Key(Library, 'collection/1')
collection_v1 = Version(id='v1.0.0', sha='x', status=Status.ready, parent=collection_key).put()
collection_v2 = Version(id='v2.0.0', sha='x', status=Status.ready, parent=collection_key).put()
collection_v3 = Version(id='v3.0.0', sha='x', status=Status.ready, parent=collection_key).put()
element_key = ndb.Key(Library, 'ele/ment')
element_v1 = Version(id='v1.0.0', sha='x', status=Status.ready, parent=element_key).put()
CollectionReference.ensure(element_key, collection_v1, '^1.0.0')
CollectionReference.ensure(element_key, collection_v2, '^1.0.0')
CollectionReference.ensure(element_key, collection_v3, '^2.0.0')
collections = yield Version.collections_for_key_async(element_v1)
collection_keys = [collection.key for collection in collections]
# Only latest matching version of the collection should be present.
self.assertEqual(collection_keys, [
collection_v2,
])
class DependencyTests(TestBase):
def test_from_string(self):
dependency = Dependency.from_string('owner/repo')
self.assertEqual(dependency.owner, 'owner')
self.assertEqual(dependency.repo, 'repo')
self.assertEqual(dependency.version, '*')
dependency = Dependency.from_string('https://github.com/owner/repo.git#master')
self.assertEqual(dependency.owner, 'owner')
self.assertEqual(dependency.repo, 'repo')
self.assertEqual(dependency.version, 'master')
dependency = Dependency.from_string('https://github.com/owner/repo')
self.assertEqual(dependency.owner, 'owner')
self.assertEqual(dependency.repo, 'repo')
self.assertEqual(dependency.version, '*')
class LibraryGithubFromUrl(TestBase):
def test_from_url(self):
self.assertEqual(Library.github_from_url('owner/repo'), ('owner', 'repo'))
self.assertEqual(Library.github_from_url('git+https://github.com/owner/repo.git'), ('owner', 'repo'))
self.assertEqual(Library.github_from_url('git://github.com/owner/repo.git'), ('owner', 'repo'))
|
devopshq/vspheretools | pysphere/ZSI/generate/pyclass.py | Python | mit | 9,999 | 0.007101 | ############################################################################
# Joshua R. Boverhof, LBNL
# See LBNLCopyright for copyright notice!
###########################################################################
import pydoc, sys
from pysphere.ZSI import TC
# If function.__name__ is read-only, fail
def _x(): return
try:
_x.func_name = '_y'
except:
raise RuntimeError(
'use python-2.4 or later, cannot set function names in python "%s"'
%sys.version)
del _x
#def GetNil(typecode=None):
# """returns the nilled element, use to set an element
# as nilled for immutable instance.
# """
#
# nil = TC.Nilled()
# if typecode is not None: nil.typecode = typecode
# return nil
#
#
#def GetNilAsSelf(cls, typecode=None):
# """returns the nilled element with typecode specified,
# use returned instance to set this element as nilled.
#
# Key Word Parameters:
# typecode -- use to specify a derived type or wildcard as nilled.
# """
# if typecode is not None and not isinstance(typecode, TC.TypeCode):
# raise TypeError, "Expecting a TypeCode instance"
#
# nil = TC.Nilled()
# nil.typecode = typecode or cls.typecode
# return nil
class pyclass_type(type):
"""Stability: Unstable
type for pyclasses used with typecodes. expects the typecode to
be available in the classdict. creates python properties for accessing
and setting the elements specified in the ofwhat list, and factory methods
for constructing the elements.
Known Limitations:
1)Uses XML Schema element names directly to create method names,
using characters in this set will cause Syntax Errors:
(NCNAME)-(letter U digit U "_")
"""
def __new__(cls, classname, bases, classdict):
"""
"""
#import new
typecode = classdict.get('typecode')
assert typecode is not None, 'MUST HAVE A TYPECODE.'
# Assume this means immutable type. ie. str
if len(bases) > 0:
#classdict['new_Nill'] = classmethod(GetNilAsSelf)
pass
# Assume this means mutable type. ie. ofwhat.
else:
assert hasattr(typecode, 'ofwhat'), 'typecode has no ofwhat list??'
assert hasattr(typecode, 'attribute_typecode_dict'),\
'typecode has no attribute_typecode_dict??'
#classdict['new_Nill'] = staticmethod(GetNil)
if typecode.mixed:
get,_set = cls.__create_text_functions_from_what(typecode)
if get.__name__ in classdict:
raise AttributeError('attribute %s previously defined.' %get.__name__)
if _set.__name__ in classdict:
raise AttributeError('attribute %s previously defined.' %_set.__name__)
classdict[get.__name__] = get
classdict[_set.__name__] = _set
for what in typecode.ofwhat:
get,_set,new_func = cls.__create_functions_from_what(what)
if get.__name__ in classdict:
raise AttributeError('attribute %s previously defined.' %get.__name__)
classdict[get.__name__] = get
if _set.__name__ in classdict:
raise AttributeError('attribute %s previously defined.' %_set.__name__)
classdict[_set.__name__] = _set
if new_func is not None:
if new_func.__name__ in classdict:
raise AttributeError('attribute %s previously defined.' %new_func.__name__)
classdict[new_func.__name__] = new_func
assert what.pname not in classdict,\
'collision with pname="%s", bail..' %what.pname
pname = what.pname
if pname is None and isinstance(what, TC.AnyElement): pname = 'any'
assert pname is not None, 'Element with no name: %s' %what
# TODO: for pname if keyword just uppercase first letter.
pname = pname[0].upper() + pname[1:]
assert pname not in pydoc.Helper.keywords, 'unexpected keyword: %s' %pname
classdict[pname] =\
property(get, _set, None,
'property for element (%s,%s), minOccurs="%s" maxOccurs="%s" nillable="%s"'\
%(what.nspname,what.pname,what.minOccurs,what.maxOccurs,what.nillable)
)
#
# mutable type <complexType> complexContent | modelGroup
# or immutable type <complexType> simpleContent (float, str, etc)
#
if hasattr(typecode, 'attribute_typecode_dict'):
attribute_typecode_dict = typecode.attribute_typecode_dict or {}
for key,what in attribute_typecode_dict.iteritems():
get,_set = cls.__create_attr_functions_from_what(key, what)
if get.__name__ in classdict:
raise AttributeError,\
'attribute %s previously defined.' %get.__name__
if _set.__name__ in classdict:
raise AttributeError,\
'attribute %s previously defined.' %_set.__name__
classdict[get.__name__] = get
classdict[_set.__name__] = _set
return type.__new__(cls,classname,bases,classdict)
def __create_functions_from_what(what):
if not callable(what):
def ge | t(self):
return getattr(self, what.aname)
if what.maxOccurs > 1:
def _set(self, value):
if not (value is None or hasattr(value, '__iter__')):
raise Typ | eError('expecting an iterable instance')
setattr(self, what.aname, value)
else:
def _set(self, value):
setattr(self, what.aname, value)
else:
def get(self):
return getattr(self, what().aname)
if what.maxOccurs > 1:
def _set(self, value):
if not (value is None or hasattr(value, '__iter__')):
raise TypeError, 'expecting an iterable instance'
setattr(self, what().aname, value)
else:
def _set(self, value):
setattr(self, what().aname, value)
#
# new factory function
# if pyclass is None, skip
#
if not callable(what) and getattr(what, 'pyclass', None) is None:
new_func = None
elif (isinstance(what, TC.ComplexType) or
isinstance(what, TC.Array)):
def new_func(self):
'''returns a mutable type
'''
return what.pyclass()
elif not callable(what):
def new_func(self, value):
'''value -- initialize value
returns an immutable type
'''
return what.pyclass(value)
elif (issubclass(what.klass, TC.ComplexType) or
issubclass(what.klass, TC.Array)):
def new_func(self):
'''returns a mutable type or None (if no pyclass).
'''
p = what().pyclass
if p is None: return
return p()
else:
def new_func(self, value=None):
'''if simpleType provide initialization value, else
if complexType value should be left as None.
Parameters:
value -- initialize value or None
returns a mutable instance (value is None)
or an immutable instance or None (if no pyclass)
'''
p = what().pyclass
if p is None: return
if value is None: return p()
return p(value)
#TODO: sub all illegal characters in _set
# (NCNAME)-(letter U digit U "_")
if new_func is not None:
new_func.__name__ = 'new_%s' %what.pname
get.func_nam |
nwoeanhinnogaehr/live-python-jacker | examples/pitchshift.py | Python | gpl-3.0 | 349 | 0.002865 | fr | om stft import STFT
from pvoc import PhaseVocoder
import numpy as np
stft = STFT(1024, 2, 4)
pvoc = PhaseVocoder(stft)
def process(input, output):
for x in stft.forward(input):
x = pvoc.forward(x)
x = pvoc.shift(x, lambda y: y * 1.5)
x = pvoc.backward(x)
| stft.backward(x)
stft.pop(output)
output *= 2
|
divmain/GitSavvy | common/util/file.py | Python | mit | 4,644 | 0.000861 | from collections import defaultdict
from contextlib import contextmanager
import os
import plistlib
import re
import threading
import yaml
import sublime
MYPY = False
if MYPY:
from typing import DefaultDict, List, Optional
if 'syntax_file_map' not in globals():
syntax_file_map = defaultdic | t(list) # type: DefaultDict[str, List[str]]
if 'determine_syntax_thread' not in globals():
determine_syntax_thread = None
def determine_syntax_files():
# type: () -> None
global determine_syntax_thread
if not syntax_file_map:
determine_syntax_thread | = threading.Thread(
target=_determine_syntax_files)
determine_syntax_thread.start()
def try_parse_for_file_extensions(text):
# type: (str) -> Optional[List[str]]
match = re.search(r"^file_extensions:\n((.*\n)+?)^(?=\w)", text, re.M)
if match:
return _try_yaml_parse(match.group(0))
return _try_yaml_parse(text)
def _try_yaml_parse(text):
# type: (str) -> Optional[List[str]]
try:
return yaml.safe_load(text)["file_extensions"]
except Exception:
return None
def _determine_syntax_files():
# type: () -> None
handle_tm_language_files()
handle_sublime_syntax_files()
def handle_tm_language_files():
# type: () -> None
syntax_files = sublime.find_resources("*.tmLanguage")
for syntax_file in syntax_files:
try:
resource = sublime.load_binary_resource(syntax_file)
except Exception:
print("GitSavvy: could not load {}".format(syntax_file))
continue
try:
extensions = plistlib.readPlistFromBytes(resource).get("fileTypes", [])
except Exception:
print("GitSavvy: could not parse {}".format(syntax_file))
continue
for extension in extensions:
syntax_file_map[extension].append(syntax_file)
def handle_sublime_syntax_files():
# type: () -> None
syntax_files = sublime.find_resources("*.sublime-syntax")
for syntax_file in syntax_files:
try:
resource = sublime.load_resource(syntax_file)
except Exception:
print("GitSavvy: could not load {}".format(syntax_file))
continue
for extension in try_parse_for_file_extensions(resource) or []:
syntax_file_map[extension].append(syntax_file)
def guess_syntax_for_file(window, filename):
# type: (sublime.Window, str) -> str
view = window.find_open_file(filename)
if view:
syntax = view.settings().get("syntax")
remember_syntax_choice(filename, syntax)
return syntax
return get_syntax_for_file(filename)
def remember_syntax_choice(filename, syntax):
# type: (str, str) -> None
registered_syntaxes = (
syntax_file_map.get(filename, [])
or syntax_file_map.get(get_file_extension(filename), [])
)
if syntax in registered_syntaxes:
registered_syntaxes.remove(syntax)
registered_syntaxes.append(syntax)
def get_syntax_for_file(filename, default="Packages/Text/Plain text.tmLanguage"):
# type: (str, str) -> str
if not determine_syntax_thread or determine_syntax_thread.is_alive():
return default
syntaxes = (
syntax_file_map.get(filename, [])
or syntax_file_map.get(get_file_extension(filename), [])
or [default]
)
return syntaxes[-1]
def get_file_extension(filename):
# type: (str) -> str
return os.path.splitext(filename)[1][1:]
def get_file_contents_binary(repo_path, file_path):
"""
Given an absolute file path, return the binary contents of that file
as a string.
"""
file_path = os.path.join(repo_path, file_path)
with safe_open(file_path, "rb") as f:
binary = f.read()
binary = binary.replace(b"\r\n", b"\n")
binary = binary.replace(b"\r", b"")
return binary
def get_file_contents(repo_path, file_path):
"""
Given an absolute file path, return the text contents of that file
as a string.
"""
binary = get_file_contents_binary(repo_path, file_path)
try:
return binary.decode('utf-8')
except UnicodeDecodeError:
return binary.decode('latin-1')
@contextmanager
def safe_open(filename, mode, *args, **kwargs):
try:
with open(filename, mode, *args, **kwargs) as file:
yield file
except PermissionError as e:
sublime.ok_cancel_dialog("GitSavvy could not access file: \n{}".format(e))
raise e
except OSError as e:
sublime.ok_cancel_dialog("GitSavvy encountered an OS error: \n{}".format(e))
raise e
|
braams/shtoom | shtoom/doug/conferencing.py | Python | lgpl-2.1 | 8,770 | 0.005701 | "Conferencing code"
# XXX A relatively simple enhancement to this would be to store the
# volumes for each source in the conference, and use an exponential
# decay type algorithm to determine the "loudest".
from shtoom.doug.source import Source
from twisted.internet.task import LoopingCall
from twisted.python import log
from sets import Set
class ConferenceError(Exception): pass
class ConferenceClosedError(ConferenceError): pass
class ConferenceMemberNotFoundError(ConferenceError): pass
CONFDEBUG = True
CONFDEBUG = False
class ConfSource(Source):
"A ConfSource connects a voiceapp, and via that, a leg, to a room"
def __init__(self, room, leg):
self._user = leg.getDialog().getRemoteTag().getURI()
self._room = room
self._room.addMember(self)
self._quiet = False
self.makeBuffer()
super(ConfSource, self).__init__()
def makeBuffer(self):
try:
from collections import deque
except ImportError:
# not optimal, but the queue isn't large
self.deque = list()
self.popleft = lambda: self.deque.pop(0)
else:
self.deque = deque()
self.popleft = self.deque.popleft
def truncBuffer(self):
while len(self.deque) > 3:
self.popleft()
def isPlaying(self):
return True
def isRecording(self):
return True
def read(self):
try:
ret = self._room.readAudio(self)
except ConferenceClosedError:
return self.app._va_sourceDone(self)
if not ret:
if not self._quiet:
log.msg("%r is now receiving silence"%(self))
self._quiet = True
elif self._quiet:
log.msg("%r has stopped receiving silence"%(self))
self._quiet = False
return ret
def close(self):
self._room.removeMember(self)
def write(self, bytes):
self.deque.append(bytes)
self.truncBuffer()
if not self._room.isOpen():
self.app._va_sourceDone(self)
def getAudioForRoom(self):
"get audio into the room"
# XXX tofix - might not have enough data (short packets). rock on.
if len(self.deque):
bytes = self.popleft()
return bytes
def __repr__(self):
return "<ConferenceUser %s in room %s at %x>"%(self._user,
self._room.getName(), id(self))
class Room:
"""A room is a conference. Everyone in the room hears everyone else
(well, kinda)
"""
# Theory of operation. Rather than rely on the individual sources
# timer loops (which would be, well, horrid), we trigger off our
# own timer.
# This means we don't have to worry about the end systems not
# contributing during a window.
_open = False
def __init__(self, name, MaxSpeakers=4):
self._name = name
self._members = Set()
self._audioOut = {}
self._audioOutDefault = ''
self._maxSpeakers = MaxSpeakers
self.start()
def start(self):
self._audioCalcLoop = LoopingCall(self.mixAudio)
self._audioCalcLoop.start(0.020)
self._open = True
def getName(self):
return self._name
def __repr__(self):
if self._open:
o = ''
else:
o = ' (closed)'
return "<ConferenceRoom %s%s with %d members>"%(self._name, o,
len(self._members))
def shutdown(self):
if | hasattr(self._audioCalcLoop, 'cancel'):
self._audioCalcLoop.cancel()
else:
| self._audioCalcLoop.stop()
# XXX close down any running sources!
self._members = Set()
del self._audioOut
self._open = False
removeRoom(self._name)
def addMember(self, confsource):
self._members.add(confsource)
if CONFDEBUG:
print "added", confsource, "to room", self
if not self._open:
self.start()
def removeMember(self, confsource):
if len(self._members) and confsource in self._members:
self._members.remove(confsource)
if CONFDEBUG:
print "removed", confsource, "from", self
else:
raise ConferenceMemberNotFoundError(confsource)
if not len(self._members):
if CONFDEBUG:
print "No members left, shutting down"
self.shutdown()
def isMember(self, confsource):
return confsource in self._members
def isOpen(self):
return self._open
def memberCount(self):
return len(self._members)
def readAudio(self, confsource):
if self._open:
return self._audioOut.get(confsource, self._audioOutDefault)
else:
raise ConferenceClosedError()
def mixAudio(self):
# XXX see the comment above about storing a decaying number for the
# volume. For instance, each time round the loop, take the calculated
# volume, and the stored volume, and do something like:
# newStoredVolume = (oldStoredVolume * 0.33) + (thisPacketVolume * 0.66)
import audioop
self._audioOut = {}
if not self._open:
log.msg('mixing closed room %r'%(self,), system='doug')
return
audioIn = {}
for m in self._members:
bytes = m.getAudioForRoom()
if bytes: audioIn[m] = bytes
if CONFDEBUG:
print "room %r has %d members"%(self, len(self._members))
print "got %d samples this time"%len(audioIn)
print "samples: %r"%(audioIn.items(),)
# short-circuit this case
if len(self._members) < 2:
if CONFDEBUG:
print "less than 2 members, no sound"
self._audioOutDefault = ''
return
# Samples is (confsource, audio)
samples = audioIn.items()
# power is three-tuples of (rms,audio,confsource)
power = [ (audioop.rms(x[1],2),x[1], x[0]) for x in samples ]
power.sort(); power.reverse()
if CONFDEBUG:
for rms,audio,confsource in power:
print confsource, rms
# Speakers is a list of the _maxSpeakers loudest speakers
speakers = Set([x[2] for x in power[:self._maxSpeakers]])
# First we calculate the 'default' audio. Used for everyone who's
# not a speaker in the room.
samples = [ x[1] for x in power[:self._maxSpeakers] ]
scaledsamples = [ audioop.mul(x, 2, 1.0/len(samples)) for x in samples ]
if scaledsamples:
# ooo. a use of reduce. first time for everything...
try:
combined = reduce(lambda x,y: audioop.add(x, y, 2), scaledsamples)
except audioop.error, exc:
# XXX tofix!
print "combine got error %s"%(exc,)
print "lengths", [len(x) for x in scaledsamples]
combined = ''
else:
combined = ''
self._audioOutDefault = combined
# Now calculate output for each speaker.
allsamples = {}
for p,sample,speaker in power:
allsamples[speaker] = p, sample
for s in speakers:
# For each speaker, take the set of (other speakers), grab
# the top N speakers, and combine them. Add to the _audioOut
# dictionary
all = allsamples.copy()
del all[s]
power = all.values()
power.sort() ; power.reverse()
samples = [ x[1] for x in power[:self._maxSpeakers] ]
if samples:
scaled = [ audioop.mul(x, 2, 1.0/len(samples)) for x in samples]
try:
out = reduce(lambda x,y: audioop.add(x, y, 2), scaled)
except audioop.error, exc:
# XXX tofix!
print "combine got error %s"%(exc,)
print "lengths", [len(x) for x in scaled]
out = ''
else:
out = ''
|
gilt/nova | nova/core/cfn_pyplates/options.py | Python | mit | 1,386 | 0 | # Copyright (c) 2013 MetaMetrics, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
from __future__ import absolute_import
from collections import defaultdict
from six.moves import input
prompt_str = '''Key "{0}" not found in the supplied options mapping.
Yo | u can enter it now (or | leave blank for None/null):
> '''
class OptionsMapping(defaultdict):
def __init__(self, *args, **kwargs):
super(OptionsMapping, self).__init__(None, *args, **kwargs)
def __missing__(self, key):
try:
value = input(prompt_str.format(key))
except KeyboardInterrupt:
# Catch the sigint here, since the user's pretty likely to
# Ctrl-C and go fix the options mapping input file
raise SystemExit
if not value:
value = None
self[key] = value
return value
|
hsolbrig/shexypy | shexypy/utils/dict_compare.py | Python | mit | 3,967 | 0.005294 | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Mayo Clinic
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# Neither the name of the <ORGANIZATION> nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
# OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
def compare_dicts(d1: dict, d2: dict, d1name: str="dict1", d2name: str="dict2", file=sys.stdout, filtr=None) -> bool:
""" Recursively compare the two dictionaries.
:param d1: First dictionary
:param d2: Second dictionary
:param d1name: Name of the first dictionary
:param d2name: Name of the second dictionary
:param file: Output file (default: sys.stdout)
:param filtr: comparison filter. Signature: filtr( i1: (k,v), i2: (k, v)) -> bool:
:return: Whether the dictionaries match
"""
def n1(k):
return d1name + '.' + k
def n2(k):
return d2name + '.' + k
def f(t1, t2):
return False if filtr is None else filtr(t1, t2)
def d_key(d):
return ':'.join(d.keys())
if d1 == d2:
return True
n_errors = 0
for e in sorted(list(set(d1. | keys()) - set(d2.keys()))):
if not f((e, d1[e]), None):
n_errors += 1
print("+ %s: | %s" % (n1(e), d1[e]), file=file)
for e in sorted(list(set(d2.keys()) - set(d1.keys()))):
if not f(None, (e, d2[e])):
n_errors += 1
print("- %s: %s" % (n2(e), d2[e]), file=file)
for k, v in sorted(d1.items()):
if k in d2 and d2[k] != d1[k] and not f((k, d1[k]), (k, d2[k])):
if isinstance(d1[k], dict) and isinstance(d2[k], dict):
if not compare_dicts(d1[k], d2[k], n1(k), n2(k), file, filtr):
n_errors += 1
elif isinstance(d1[k], list) and isinstance(d2[k], list):
if len(d1[k]) == len(d2[k]) and all(e in d1[k] for e in d2[k]):
n_errors += 1
print("<ordering> %s: %s" % (d1name + '.' + k, d1[k]), file=file)
else:
n_errors += 1
print("< %s: %s" % (d1name + '.' + k, d1[k]), file=file)
print("> %s: %s" % (d2name + '.' + k, d2[k]), file=file)
return n_errors == 0
def dict_compare(d1: dict, d2: dict, d1name: str="dict1", d2name: str="dict2", filtr=None) -> (bool, str):
class MemFile:
def __init__(self):
self.text = ""
def write(self, txt):
self.text += txt
of = MemFile()
print("--- %s" % d1name, file=of)
print("+++ %s" % d2name, file=of)
print(file=of)
return compare_dicts(d1, d2, d1name, d2name, file=of, filtr=filtr), of.text
|
openstack/python-congressclient | doc/source/conf.py | Python | apache-2.0 | 3,547 | 0.000282 | # -*- coding: utf-8 -*-
# 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.
import os
import sys
sys.path.insert(0, os.path.abspath('../..'))
# -- General configuration ----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
'openstackdocstheme',
'sphinxcontrib.apidoc'
]
# openstackdocstheme options
repository_name = 'openstack/python-congressclient'
bug_project = 'python-congressclient'
bug_tag = ''
# sphinxcontrib.apidoc options
apidoc_module_dir = '../../congressclient'
apidoc_output_dir = 'reference/api'
apidoc_excluded_paths = ['tests/*']
apidoc_separate_modules = True
html_last_updated_fmt = '%Y-%m-%d %H:%M'
# autodoc generation is a bit aggressive and a nuisance when doing heavy
# text edit cycles.
# execute "export SPHINX_DEBUG=1" in your terminal to disable
# The suffix of source filenames.
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'python-congressclient'
copyright = u'2013, OpenStack Foundation'
# If true, '()' will be appended to :func: etc. cross-reference text.
add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
add_module_names = True
# Th | e name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of glob-style pattern | s that should be excluded when looking for
# source files. They are matched against the source file names relative to the
# source directory, using slashes as directory separators on all platforms.
exclude_patterns = ['reference/api/congressclient.tests.*']
# -- Options for HTML output --------------------------------------------------
# The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
# html_theme_path = ["."]
html_theme = 'openstackdocs'
# html_static_path = ['static']
# Output file base name for HTML help builder.
htmlhelp_basename = '%sdoc' % project
# A list of ignored prefixes for module index sorting.
modindex_common_prefix = ['congressclient.']
# Disable usage of xindy https://bugzilla.redhat.com/show_bug.cgi?id=1643664
latex_use_xindy = False
latex_domain_indices = False
latex_elements = {
'makeindex': '',
'printindex': '',
'preamble': r'\setcounter{tocdepth}{3}',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto/manual]).
# NOTE: Specify toctree_only=True for a better document structure of
# the generated PDF file.
latex_documents = [
('index',
'doc-%s.tex' % project,
u'Congress Client Documentation',
u'OpenStack Foundation', 'manual', True),
]
# Example configuration for intersphinx: refer to the Python standard library.
#intersphinx_mapping = {'http://docs.python.org/': None}
|
SuLab/biothings.api | biothings/www/api/es/handlers/query_handler.py | Python | apache-2.0 | 15,331 | 0.006392 | from tornado.web import HTTPError
from biothings.www.api.es.handlers.base_handler import BaseESRequestHandler
from biothings.www.api.es.transform import ScrollIterationDone
from biothings.www.api.es.query import BiothingScrollError, BiothingSearchError
from biothings.www.api.helper import BiothingParameterTypeError
from biothings.utils.www import sum_arg_dicts
import logging
class QueryHandler(BaseESRequestHandler):
''' Request handlers for requests to the query endpoint '''
def initialize(self, web_settings):
''' | Tornado handler `.initialize() <http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.initialize>`_ function for all requests to the query endpoint.
Here, the allowed arguments are set (depending on the request method) for each kwarg category.'''
super(QueryHandler, self | ).initialize(web_settings)
self.ga_event_object_ret['action'] = self.request.method
if self.request.method == 'GET':
self.ga_event_object_ret['action'] = self.web_settings.GA_ACTION_QUERY_GET
self.control_kwargs = self.web_settings.QUERY_GET_CONTROL_KWARGS
self.es_kwargs = self.web_settings.QUERY_GET_ES_KWARGS
self.esqb_kwargs = self.web_settings.QUERY_GET_ESQB_KWARGS
self.transform_kwargs = self.web_settings.QUERY_GET_TRANSFORM_KWARGS
elif self.request.method == 'POST':
self.ga_event_object_ret['action'] = self.web_settings.GA_ACTION_QUERY_POST
self.control_kwargs = self.web_settings.QUERY_POST_CONTROL_KWARGS
self.es_kwargs = self.web_settings.QUERY_POST_ES_KWARGS
self.esqb_kwargs = self.web_settings.QUERY_POST_ESQB_KWARGS
self.transform_kwargs = self.web_settings.QUERY_POST_TRANSFORM_KWARGS
else:
# handle other verbs?
pass
self.kwarg_settings = sum_arg_dicts(self.control_kwargs, self.es_kwargs,
self.esqb_kwargs, self.transform_kwargs)
logging.debug("QueryHandler - {}".format(self.request.method))
logging.debug("Google Analytics Base object: {}".format(self.ga_event_object_ret))
logging.debug("Kwarg Settings: {}".format(self.kwarg_settings))
def _pre_scroll_transform_GET_hook(self, options, res):
''' Override me. '''
return res
def get(self):
''' Handle a GET to the query endpoint. '''
###################################################
# Get/type/alias query parameters
###################################################
try:
kwargs = self.get_query_params()
except BiothingParameterTypeError as e:
self._return_data_and_track({'success': False, 'error': "{0}".format(e)}, ga_event_data={'total':0})
return
except Exception as e:
self.log_exceptions("Error in get_query_params")
self._return_data_and_track({'success': False, 'error': "Error parsing input parameter, check input types"}, ga_event_data={'total': 0})
return
###################################################
# Split query parameters into categories
###################################################
options = self.get_cleaned_options(kwargs)
logging.debug("Request kwargs: {}".format(kwargs))
logging.debug("Request options: {}".format(options))
if not options.control_kwargs.q and not options.control_kwargs.scroll_id:
self._return_data_and_track({'success': False, 'error': "Missing required parameters."},
ga_event_data={'total': 0})
return
options = self._pre_query_builder_GET_hook(options)
###################################################
# Instantiate pipeline classes
###################################################
# Instantiate query builder, query, and transform classes
_query_builder = self.web_settings.ES_QUERY_BUILDER(options=options.esqb_kwargs,
index=self._get_es_index(options), doc_type=self._get_es_doc_type(options),
es_options=options.es_kwargs, userquery_dir=self.web_settings.USERQUERY_DIR,
scroll_options={'scroll': self.web_settings.ES_SCROLL_TIME, 'size': self.web_settings.ES_SCROLL_SIZE},
default_scopes=self.web_settings.DEFAULT_SCOPES)
_backend = self.web_settings.ES_QUERY(client=self.web_settings.es_client, options=options.es_kwargs)
_result_transformer = self.web_settings.ES_RESULT_TRANSFORMER(options=options.transform_kwargs,
host=self.request.host, jsonld_context=self.web_settings._jsonld_context,
doc_url_function=self.web_settings.doc_url, output_aliases=self.web_settings.OUTPUT_KEY_ALIASES)
###################################################
# Scroll request pipeline
###################################################
if options.control_kwargs.scroll_id:
###################################################
# Build scroll query
###################################################
try:
_query = _query_builder.scroll(options.control_kwargs.scroll_id)
except Exception as e:
self.log_exceptions("Error building scroll query")
self._return_data_and_track({'success': False, 'error': 'Error building scroll query for scroll_id "{}"'.format(options.control_kwargs.scroll_id)}, ga_event_data={'total': 0})
return
###################################################
# Get scroll results
###################################################
try:
res = _backend.scroll(_query)
except BiothingScrollError as e:
self._return_data_and_track({'success': False, 'error': '{}'.format(e)}, ga_event_data={'total': 0})
return
except Exception as e:
self.log_exceptions("Error getting scroll batch")
self._return_data_and_track({'success': False, 'error': 'Error retrieving scroll results for scroll_id "{}"'.format(options.control_kwargs.scroll_id)}, ga_event_data={'total': 0})
return
#logging.debug("Raw scroll query result: {}".format(res))
if options.control_kwargs.raw:
self._return_data_and_track(res, ga_event_data={'total': res.get('total', 0)})
return
res = self._pre_scroll_transform_GET_hook(options, res)
###################################################
# Transform scroll result
###################################################
try:
res = _result_transformer.clean_scroll_response(res)
except ScrollIterationDone as e:
self._return_data_and_track({'success': False, 'error': '{}'.format(e)}, ga_event_data={'total': res.get('total', 0)})
return
except Exception as e:
self.log_exceptions("Error transforming scroll batch")
self._return_data_and_track({'success': False, 'error': 'Error transforming scroll results for scroll_id "{}"'.format(options.control_kwargs.scroll_id)})
return
else:
##### Non-scroll query GET pipeline #############
###################################################
# Build query
###################################################
try:
_query = _query_builder.query_GET_query(q=options.control_kwargs.q)
except Exception as e:
self.log_exceptions("Error building query")
self._return_data_and_track({'success': False, 'error': 'Error building query from q="{}"'.format(options.control_kwargs.q)}, ga_event_object={'total': 0})
|
adngdb/socorro | alembic/versions/3a5471a358bf_adding_a_migration_f.py | Python | mpl-2.0 | 1,624 | 0.010468 | """Adding a migration for the exploitability report.
Revision ID: 3a5471a358bf
Revises: 191d0453cc07
Create Date: 2013-10-25 07:07:33.968691
"""
# revision identifiers, used by Alembic.
revision = '3a5471a358bf'
down_revision = '4aacaea3eb48'
from alembic import op
from socorro.lib import citexttype, jsontype
from socorro.lib.migrations import load_stored_proc
import sqlalchemy as sa
from sqlalchemy import types
from sqlalchemy.dialects import postgresql
from sqlalchemy.sql import table, column
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.execute('TRUNCATE exploitability_reports CASCADE');
op.add_column(u'exploitability_reports', sa.Column(u'version_string', sa.TEXT(), nullable=True))
op.add_column(u'exploitability_reports', sa.Column(u'product_name', sa.TEXT(), nullable=True))
op.add_column(u'exploitability_r | eports', sa.Column(u'product_version_id', sa.INTEGER(), nullable=False))
### end Alembic commands ###
load_stored_proc(op, ['update_exploitability.sql'])
for i in range(15, 30):
backfill_date = '2013-11-%s' % i
op.execute("""
SELECT backfill_exploitability('%s')
""" % backf | ill_date)
op.execute(""" COMMIT """)
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column(u'exploitability_reports', u'product_version_id')
op.drop_column(u'exploitability_reports', u'product_name')
op.drop_column(u'exploitability_reports', u'version_string')
load_stored_proc(op, ['update_exploitability.sql'])
### end Alembic commands ###
|
mlperf/training_results_v0.7 | Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/tvm/tests/python/relay/test_op_level5.py | Python | apache-2.0 | 27,128 | 0.003834 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
""" Support level5 operator test cases.
"""
import math
import numpy as np
import tvm
from tvm import relay
from tvm.relay import transform
from tvm.relay.testing import ctx_list
import topi.testing
def run_infer_type(expr):
mod = relay.Module.from_expr(expr)
mod = transform.InferType()(mod)
entry = mod["main"]
return entry if isinstance(expr, relay.Function) else entry.body
def test_resize_infer_type():
n, c, h, w = tvm.var("n"), tvm.var("c"), tvm.var("h"), tvm.var("w")
x = relay.var("x", relay.TensorType((n, c, h, w), "int8"))
th, tw = tvm.var("th"), tvm.var("tw")
z = relay.image.resize(x, (th, tw))
zz = run_infer_type(z)
assert zz.checked_type == relay.TensorType((n, c, th, tw), "int8")
x = relay.var("x", relay.TensorType((n, c, h, w), "int8"))
z= relay.image.resize(x, (100, 200), "NCHW", "BILINEAR", False)
assert "size=" in z.astext()
zz = run_infer_type(z)
assert zz.checked_type == relay.TensorType((n, c, 100, 200), "int8")
def test_resize():
def verify_resize(dshape, scale, method, layout):
if layout == "NHWC":
size = (dshape[1] * scale, dshape[2] * scale)
else:
size = (dshape[2] * scale, dshape[3] * scale)
x_data = np.random.uniform(size=dshape).astype("float32")
if method == "BILINEAR":
ref_res = topi.testing.bilinear_resize_python(x_data, size, layout)
else:
ref_res = topi.testing.upsampling_python(x_data, (scale, scale), layout)
x = relay.var("x", relay.TensorType(dshape, "float32"))
z = relay.image.resize(x, size, layout, method, False)
assert "size=" in z.astext()
zz = run_infer_type(z)
assert zz.checked_type == relay.TensorType(ref_res.shape, "float32")
func = relay.Function([x], z)
for target, ctx in ctx_list():
for kind in ["graph", "debug"]:
intrp = relay.create_executor(kind, ctx=ctx, target=target)
op_res = intrp.evaluate(func)(x_data)
tvm.testing.assert_allclose(op_res.asnumpy(), ref_res, rtol=1e-5)
for method in ["BILINEAR", "NEAREST_NEIGHBOR"]:
for layout in ["NHWC", "NCHW"]:
verify_resize((1, 4, 4, 4), 2, method, layout)
def test_multibox_prior():
def get_ref_result(dshape, sizes=(1.0,),
ratios=(1.0,), steps=(-1.0, -1.0),
offsets=(0.5, 0.5), clip=True):
in_height = dshape[2]
in_width = dshape[3]
num_sizes = len(sizes)
num_ratios = len(ratios)
size_ratio_concat = sizes + ratios
steps_h = steps[0] if steps[0] > 0 else 1.0 / in_height
steps_w = steps[1] if steps[1] > 0 else 1.0 / in_width
offset_h = offsets[0]
offset_w = offsets[1]
oshape = (1, in_height * in_width * (num_sizes + num_ratios - 1), 4)
dtype = "float32"
np_out = np.zeros(oshape).astype(dtype)
for i in range(in_height):
center_h = (i + offset_h) * steps_h
| for j in range(in_width):
center_w = (j + offset_w) * steps_w
for k in range(num_sizes + num_ratios - 1):
| w = size_ratio_concat[k] * in_height / in_width / 2.0 if k < num_sizes else \
size_ratio_concat[0] * in_height / in_width * math.sqrt(size_ratio_concat[k + 1]) / 2.0
h = size_ratio_concat[k] / 2.0 if k < num_sizes else \
size_ratio_concat[0] / math.sqrt(size_ratio_concat[k + 1]) / 2.0
count = i * in_width * (num_sizes + num_ratios - 1) + j * (num_sizes + num_ratios - 1) + k
np_out[0][count][0] = center_w - w
np_out[0][count][1] = center_h - h
np_out[0][count][2] = center_w + w
np_out[0][count][3] = center_h + h
if clip:
np_out = np.clip(np_out, 0, 1)
return np_out
def verify_multibox_prior(x, dshape, ref_res, sizes=(1.0,),
ratios=(1.0,), steps=(-1.0, -1.0),
offsets=(0.5, 0.5), clip=True, check_size=False,
check_type_only=False):
z = relay.vision.multibox_prior(x, sizes, ratios, steps, offsets, clip)
zz = run_infer_type(z)
if check_size:
assert "sizes=" in z.astext()
assert zz.checked_type == relay.TensorType(
(1, dshape[2] * dshape[3] * (len(sizes) + len(ratios) - 1), 4),
"float32")
if check_type_only:
return
data = np.random.uniform(low=-1, high=1, size=dshape).astype("float32")
func = relay.Function([x], z)
func = run_infer_type(func)
for target, ctx in ctx_list():
intrp1 = relay.create_executor("graph", ctx=ctx, target=target)
op_res1 = intrp1.evaluate(func)(data)
tvm.testing.assert_allclose(op_res1.asnumpy(), ref_res, rtol=1e-5)
intrp2 = relay.create_executor("debug", ctx=ctx, target=target)
op_res2 = intrp2.evaluate(func)(data)
tvm.testing.assert_allclose(op_res2.asnumpy(), ref_res, rtol=1e-5)
sizes = (0.3, 1.5, 0.7)
ratios = (1.3, 2.4)
steps = (2.0, 1.5)
offsets = (0.2, 0.3)
dshape = (1, 3, 56, 56)
ref_res = get_ref_result(dshape, sizes, ratios, steps, offsets)
x = relay.var("x", relay.TensorType(dshape, "float32"))
verify_multibox_prior(x, dshape, ref_res, sizes, ratios, steps, offsets,
check_size=True)
y = relay.var("y", relay.TensorType((tvm.var("n"), 3, 56, 56), "float32"))
verify_multibox_prior(x, dshape, ref_res, sizes, ratios, steps, offsets,
check_size=True, check_type_only=True)
dshape = (1, 24, 32, 32)
ref_res = get_ref_result(dshape, clip=False)
x = relay.var("x", relay.TensorType(dshape, "float32"))
verify_multibox_prior(x, dshape, ref_res, clip=False)
y = relay.var("y", relay.TensorType((tvm.var("n"), 24, 32, 32), "float32"))
verify_multibox_prior(x, dshape, ref_res, clip=False, check_type_only=True)
def test_get_valid_counts():
def verify_get_valid_counts(dshape, score_threshold, id_index, score_index):
dtype = "float32"
batch_size, num_anchor, elem_length = dshape
np_data = np.random.uniform(low=-2, high=2, size=dshape).astype(dtype)
np_out1 = np.zeros(shape=(batch_size,))
np_out2 = np.zeros(shape=dshape).astype(dtype)
for i in range(batch_size):
np_out1[i] = 0
inter_idx = 0
for j in range(num_anchor):
score = np_data[i, j, score_index]
if score > score_threshold and (id_index < 0 or np_data[i, j, id_index] >= 0):
for k in range(elem_length):
np_out2[i, inter_idx, k] = np_data[i, j, k]
np_out1[i] += 1
inter_idx += 1
if j >= np_out1[i]:
for k in range(elem_length):
np_out2[i, j, k] = -1.0
x = relay.var("x", relay.ty.TensorType(dshape, dtype))
z = relay.vision.get_valid_counts(x, score_threshold, id_index, score_index)
assert "score_threshold" in z.astext()
func = relay.Function([x], z.astupl |
baalkor/timetracking | opconsole/templatetags/duration.py | Python | apache-2.0 | 253 | 0.007905 | from django impor | t template
register = template.Library()
@register.filter
def duration(td):
seconds = td
minutes, seconds = divmod(seconds, 60)
| hours, minutes = divmod(minutes, 60)
return "%d:%02d:%02d" % (hours, minutes, seconds) |
xzturn/tensorflow | tensorflow/python/training/warm_starting_util.py | Python | apache-2.0 | 23,798 | 0.005042 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is 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 to warm-start TF.Learn Estimators."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import six
from tensorflow.python.framework import errors
from tensorflow.python.framework import ops
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables as variables_lib
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.training import checkpoint_ops
from tensorflow.python.training import checkpoint_utils
from tensorflow.python.training import saver as saver_lib
from tensorflow.python.training.saving import saveable_object_util
from tensorflow.python.util.tf_export import tf_export
@tf_export(v1=["train.VocabInfo"])
class VocabInfo(
collections.namedtuple("VocabInfo", [
"new_vocab",
"new_vocab_size",
"num_oov_buckets",
"old_vocab",
"old_vocab_size",
"backup_initializer",
"axis",
])):
"""Vocabulary information for warm-starting.
See `tf.estimator.WarmStartSettings` for examples of using
VocabInfo to warm-start.
Args:
new_vocab: [Required] A path to the new vocabulary file (used with the model
to be trained).
new_vocab_size: [Required] An integer indicating how many entries of the new
vocabulary will used in training.
num_oov_buckets: [Required] An integer indicating how many OOV buckets are
associated with the vocabulary.
old_vocab: [Required] A path to the old vocabulary file (used with the
checkpoint to be warm-started from).
old_vocab_size: [Optional] An integer indicating how many entries of the old
vocabulary were used in the creation of the checkpoint. If not provided,
the entire old vocabulary will be used.
backup_initializer: [Optional] A variable initializer used for variables
corresponding to new vocabulary entries and OOV. If not provided, these
entries will be zero-initialized.
axis: [Optional] Denotes what axis the vocabulary corresponds to. The
default, 0, corresponds to the most common use case (embeddings or
linear weights for binary classification / regression). An axis of 1
could be used for warm-starting output layers with class vocabularies.
Returns:
A `VocabInfo` which represents the vocabulary information for warm-starting.
Raises:
ValueError: `axis` is neither 0 or 1.
Example Usage:
```python
embeddings_vocab_info = tf.VocabInfo(
new_vocab='embeddings_vocab',
new_vocab_size=100,
num_oov_buckets=1,
old_vocab='pretrained_embeddings_vocab',
old_vocab_size=10000,
backup_initializer=tf.compat.v1.truncated_normal_initializer(
mean=0.0, stddev=(1 / math.sqrt(embedding_dim))),
axis=0)
softmax_output_layer_kernel_vocab_info = tf.VocabInfo(
new_vocab='class_vocab',
new_vocab_size=5,
num_oov_buckets=0, # No OOV for classes.
old_vocab='old_class_vocab',
old_vocab_size=8,
backup_initializer=tf.compat.v1.glorot_uniform_initializer(),
axis=1)
softmax_output_layer_bias_vocab_info = tf.VocabInfo(
new_vocab='class_vocab',
new_vocab_size=5,
num_oov_buckets=0, # No OOV for classes.
old_vocab='old_class_vocab',
old_vocab_size=8,
backup_initializer=tf.compat.v1.zeros_initializer(),
axis=0)
#Currently, only axis=0 and axis=1 are supported.
```
"""
def __new__(cls,
new_vocab,
new_vocab_size,
num_oov_buckets,
old_vocab,
old_vocab_size=-1,
backup_initializer=None,
axis=0):
if axis != 0 and axis != 1:
raise ValueError("The only supported values for the axis argument are 0 "
"and 1. Provided axis: {}".format(axis))
return super(VocabInfo, cls).__new__(
cls,
new_vocab,
new_vocab_size,
num_oov_buckets,
old_vocab,
old_vocab_size,
backup_initializer,
axis,
)
def _infer_var_name(var):
"""Returns name of the `var`.
Args:
var: A list. The list can contain either of the following:
(i) A single `Variable`
(ii) A single `ResourceVariable`
(iii) Multiple `Variable` objects which must be slices of the same larger
variable.
(iv) A single `PartitionedVariable`
Returns:
Name of the `var`
"""
name_to_var_dict = saveable_object_util.op_list_to_dict(var)
if len(name_to_var_dict) > 1:
raise TypeError("`var` = %s passed as arg violates the constraints. "
"name_to_var_dict = %s" % (var, name_to_var_dict))
return list(name_to_var_dict.keys())[0]
def _get_var_info(var, prev_tensor_name=None):
"""Helper method for standarizing Variable and naming.
Args:
var: Current graph's variable that needs to be warm-started (initialized).
Can be either of the following: (i) `Variable` (ii) `ResourceVariable`
(iii) list of `Variable`: The list must contain slices of the same larger
variable. (iv) `PartitionedVariable`
prev_tensor_name: Name of the tensor to lookup in provided `prev_ckpt`. If
None, we lookup tensor with same name as given `var`.
Returns:
A tuple of the Tensor name and var.
"""
if checkpoint_utils._is_variable(var): # pylint: disable=protected-access
current_var_name = _infer_var_name([var])
elif (isinstance(var, list) and
all(checkpoint_utils._is_variable(v) for v in var)): # pylint: disable=protected-access
current_var_name = _infer_var_name(var)
elif isinstance(var, variables_lib.PartitionedVariable):
current_var_name = _infer_var_name([var])
var = var._get_variable_list() # pylint: disable=protected-access
else:
raise TypeError(
"var MUST be one of the following: a Variable, list of Variable or "
"PartitionedVariable, but is {}".format(type(var)))
if not prev_tensor_ | name:
# Assume tensor name remains the same.
prev_tensor_name = current_var_name
return prev_tensor_name, var
# pylint: disable=protected-access
# Accesses protected members of tf.Variable to reset the variable's internal
# state.
def _warm_start_var_with_vocab(var,
current_vocab_path,
current_vocab_size,
| prev_ckpt,
prev_vocab_path,
previous_vocab_size=-1,
current_oov_buckets=0,
prev_tensor_name=None,
initializer=None,
axis=0):
"""Warm-starts given variable from `prev_tensor_name` tensor in `prev_ckpt`.
Use this method when the `var` is backed by vocabulary. This method stitches
the given `var` such that values corresponding to individual features in the
vocabulary remain consistent irrespective of changing order of the features
between old and new vocabularies.
Args:
var: Current graph's variable that needs to be warm-started (initialized).
Can be either of the following:
(i) `Variable`
(ii) `ResourceVariable`
(iii) list of `Variable`: The list must cont |
intel-ctrlsys/actsys | actsys/control/commands/resource_pool/resource_pool_remove.py | Python | apache-2.0 | 933 | 0.003215 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2016 Intel Corp.
#
"""
Resource Pool Remove Plugin
"""
from control.commands.command import CommandResult
from control.plugin.manager import DeclarePlugin
from .resource_p | ool import ResourcePoolCommand
@DeclarePlugin('resource_pool_remove', 100)
class ResourcePoolRemoveCommand(ResourcePoolCommand):
"""ResourcePoolRemoveCommand"""
def __init__(self, device_name, configuration, plugin_manager, logger=None):
"""Retrieve dependencies and prepare for power on"""
ResourcePoolCommand.__init__(self, devi | ce_name, configuration, plugin_manager, logger)
def execute(self):
"""Execute the command"""
setup_results = self.setup()
if setup_results is not None:
return setup_results
ret_code, message = self.resource_manager.remove_nodes_from_resource_pool(self.device_name)
return CommandResult(ret_code, message)
|
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_11_01/models/virtual_network_gateway_connection_list_entity_py3.py | Python | mit | 7,889 | 0.004056 | # 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 may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .resource import Resource
class VirtualNetworkGatewayConnectionListEntity(Resource):
"""A common class for general resource information.
Variables are only populated by the server, and will be ignored when
sending a request.
All required parameters must be populated in order to send to Azure.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: Resource tags.
:type tags: dict[str, str]
:param authorization_key: The authorizationKey.
:type authorization_key: str
:param virtual_network_gateway1: Required. The reference to virtual
network gateway resource.
:type virtual_network_gateway1:
~azure.mgmt.network.v2017_11_01.models.VirtualNetworkConnectionGatewayReference
:param virtual_network_gateway2: The reference to virtual network gateway
resource.
:type virtual_network_gateway2:
~azure.mgmt.network.v2017_11_01.models.VirtualNetworkConnectionGatewayReference
:param local_network_gateway2: The reference to local network gateway
resource.
:type local_network_gateway2:
~azure.mgmt.network.v2017_11_01.models.VirtualNetworkConnectionGatewayReference
:param connection_type: Required. Gateway connection type. Possible values
are: 'Ipsec','Vnet2Vnet','ExpressRoute', and 'VPNClient. Possible values
include: 'IPsec', 'Vnet2Vnet', 'ExpressRoute', 'VPNClient'
:type connection_type: str or
~azure.mgmt.network.v2017_11_01.models.VirtualNetworkGatewayConnectionType
:param routing_weight: The routing weight.
:type routing_weight: int
:param shared_key: The IPSec shared key.
:type shared_key: str
:ivar connection_status: Virtual network Gateway connection status.
Possible values are 'Unknown', 'Connecting', 'Connected' and
'NotConnected'. Possible values include: 'Unknown', 'Connecting',
'Connected', 'NotConnected'
:vartype connection_status: str or
~azure.mgmt.network.v2017_11_01.models.VirtualNetworkGatewayConnectionStatus
:ivar tunnel_connection_status: Collection of all tunnels' connection
health status.
:vartype tunnel_connection_status:
list[~azure.mgmt.network.v2017_11_01.models.TunnelConnectionHealth]
:ivar egress_bytes_transferred: The egress bytes transferred in this
connection.
:vartype egress_bytes_transferred: long
:ivar ingress_bytes_transferred: The ingress bytes transferred in this
connection.
:vartype ingress_bytes_transferred: long
:param peer: The reference to peerings resource.
:type peer: ~azure.mgmt.network.v2017_11_01.models.SubResource
:param enable_bgp: EnableBgp flag
:type enable_bgp: bool
:param use_policy_based_traffic_selectors: Enable policy-based traffic
selectors.
:type use_policy_based_traffic_selectors: bool
:param ipsec_policies: The IPSec Policies to be considered by this
connection.
:type ipsec_policies:
list[~azure.mgmt.network.v2017_11_01.models.IpsecPolicy]
:param resource_guid: The resource GUID property of the
VirtualNetworkGatewayConnection resource.
:type resource_guid: str
:ivar provisioning_state: The provisioning state of the
VirtualNetworkGatewayConnection resource. Possible values are: 'Updating',
'Deleting', and 'Failed'.
:vartype provisioning_state: str
:param etag: Gets a unique read-only string that changes whenever the
resource is updated.
:type etag: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'virtual_network_gateway1': {'required': True},
'connection_type': {'required': True},
'connection_status': {'readonly': True},
'tunnel_connection_status': {'readonly': True},
'egress_bytes_transferred': {'readonly': True},
'ingress_bytes_transferred': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'authorization_key': {'key': 'properties.authorizationKey', 'type': 'str'},
'virtual_network_gateway1': {'key': 'properties.virtualNetworkGateway1', 'type': 'VirtualNetworkConnectionGatewayReference | '},
'virtual_network_gateway2': {'key': 'properties.virtualNetworkGateway2', 'type': 'VirtualNetworkConnectionGatewayReference'},
'local_network_gateway2': {'key': 'properties.localNetworkGateway2', 'type': 'VirtualNetworkConnectionGatewayReference'},
'con | nection_type': {'key': 'properties.connectionType', 'type': 'str'},
'routing_weight': {'key': 'properties.routingWeight', 'type': 'int'},
'shared_key': {'key': 'properties.sharedKey', 'type': 'str'},
'connection_status': {'key': 'properties.connectionStatus', 'type': 'str'},
'tunnel_connection_status': {'key': 'properties.tunnelConnectionStatus', 'type': '[TunnelConnectionHealth]'},
'egress_bytes_transferred': {'key': 'properties.egressBytesTransferred', 'type': 'long'},
'ingress_bytes_transferred': {'key': 'properties.ingressBytesTransferred', 'type': 'long'},
'peer': {'key': 'properties.peer', 'type': 'SubResource'},
'enable_bgp': {'key': 'properties.enableBgp', 'type': 'bool'},
'use_policy_based_traffic_selectors': {'key': 'properties.usePolicyBasedTrafficSelectors', 'type': 'bool'},
'ipsec_policies': {'key': 'properties.ipsecPolicies', 'type': '[IpsecPolicy]'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
}
def __init__(self, *, virtual_network_gateway1, connection_type, id: str=None, location: str=None, tags=None, authorization_key: str=None, virtual_network_gateway2=None, local_network_gateway2=None, routing_weight: int=None, shared_key: str=None, peer=None, enable_bgp: bool=None, use_policy_based_traffic_selectors: bool=None, ipsec_policies=None, resource_guid: str=None, etag: str=None, **kwargs) -> None:
super(VirtualNetworkGatewayConnectionListEntity, self).__init__(id=id, location=location, tags=tags, **kwargs)
self.authorization_key = authorization_key
self.virtual_network_gateway1 = virtual_network_gateway1
self.virtual_network_gateway2 = virtual_network_gateway2
self.local_network_gateway2 = local_network_gateway2
self.connection_type = connection_type
self.routing_weight = routing_weight
self.shared_key = shared_key
self.connection_status = None
self.tunnel_connection_status = None
self.egress_bytes_transferred = None
self.ingress_bytes_transferred = None
self.peer = peer
self.enable_bgp = enable_bgp
self.use_policy_based_traffic_selectors = use_policy_based_traffic_selectors
self.ipsec_policies = ipsec_policies
self.resource_guid = resource_guid
self.provisioning_state = None
self.etag = etag
|
TheStackBox/xuansdk | SDKLibrary/com/cloudMedia/theKuroBox/sdk/paramComponents/kbxSlider.py | Python | gpl-3.0 | 1,696 | 0.005896 | ################################ | ##############################################################
# Copyright 2014-2015 Cloud Media Sdn. Bhd.
#
# This file is part of Xuan Application Development SDK.
#
# Xuan A | pplication Development SDK 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.
#
# Xuan Application Development SDK is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Xuan Application Development SDK. If not, see <http://www.gnu.org/licenses/>.
##############################################################################################
from com.cloudMedia.theKuroBox.sdk.paramComponents.kbxParamComponent import KBXParamComponent
from com.cloudMedia.theKuroBox.sdk.paramTypes.kbxRange import KBXRange
from com.cloudMedia.theKuroBox.sdk.util.logger import Logger
from com.cloudMedia.theKuroBox.sdk.util.util import Util
class KBXSlider(KBXRange, KBXParamComponent):
COM_NAME = "kbxSlider"
def __init__(self, kbxParamName, kbxParamMinValue, kbxParamMaxValue, kbxParamIsRequired=True, kbxParamDecimal=0, kbxParamStep=1,
kbxParamDefaultValue=None, kbxParamLabel=None, kbxParamDesc=None, **kbxParamProps):
pass
def set_kbx_param_default_value(self, value):
pass
|
th0th/harmony | setup.py | Python | gpl-3.0 | 403 | 0 | # -*- coding: utf-8 -*-
from dis | tutils.core import setup
setup(
name='Harmony',
version='0.1',
author='H. Gökhan Sarı',
author_email='th0th@returnfalse.net',
packages=['harmony'],
scripts=['bin/harmony'],
url='https://github.com/th0th/harmony/',
license='LICENSE.txt',
description='Musi | c folder organizer.',
long_description=open('README.asciidoc').read(),
)
|
MakeHer/edx-platform | common/lib/xmodule/xmodule/contentstore/content.py | Python | agpl-3.0 | 14,964 | 0.003609 | import re
import uuid
from xmodule.assetstore.assetmgr import AssetManager
XASSET_LOCATION_TAG = 'c4x'
XASSET_SRCREF_PREFIX = 'xasset:'
XASSET_THUMBNAIL_TAIL_NAME = '.jpg'
STREAM_DATA_CHUNK_SIZE = 1024
import os
import logging
import StringIO
from urlparse import urlparse, urlunparse, parse_qsl
from urllib import urlencode
from opaque_keys.edx.locator import AssetLocator
from opaque_keys.edx.keys import CourseKey, AssetKey
from opaque_keys import InvalidKeyError
from xmodule.modulestore.exceptions import ItemNotFoundError
from xmodule.exceptions import NotFoundError
from PIL import Image
class StaticContent(object):
def __init__(self, loc, name, content_type, data, last_modified_at=None, thumbnail_location=None, import_path=None,
length=None, locked=False):
self.location = loc
self.name = name # a display string which can be edited, and thus not part of the location which needs to be fixed
self.content_type = content_type
self._data = data
self.length = length
self.last_modified_at = last_modified_at
self.thumbnail_location = thumbnail_location
# optional information about where this file was imported from. This is needed to support import/export
# cycles
self.import_path = import_path
self.locked = locked
@property
def is_thumbnail(self):
return self.location.category == 'thumbnail'
@staticmethod
def generate_thumbnail_name(original_name, dimensions=None):
"""
- original_name: Name of the asset (typically its location.name)
- dimensions: `None` or a tuple of (width, height) in pixels
"""
name_root, ext = os.path.splitext(original_name)
if not ext == XASSET_THUMBNAIL_TAIL_NAME:
name_root = name_root + ext.replace(u'.', u'-')
if dimensions:
width, height = dimensions # pylint: disable=unpacking-non-sequence
name_root += "-{}x{}".format(width, height)
return u"{name_root}{extension}".format(
name_root=name_root,
extension=XASSET_THUMBNAIL_TAIL_NAME,
)
@staticmethod
def compute_location(course_key, path, revision=None, is_thumbnail=False):
"""
Constructs a location object for static content.
- course_key: the course that this asset belongs to
- path: is the name of the static asset
- revision: is the object's revi | sion information
- is_thumbnail: is whether or not we want the thumbnail version of this
asset
"""
path = path.replace('/', '_')
return course_key.make_asset_key(
'asset' if not is_thumbnail else 'thumbnail',
AssetLocator.clean_keeping_underscores(path)
).for_branch(None)
def get_id(self):
return self.location
@property
def da | ta(self):
return self._data
ASSET_URL_RE = re.compile(r"""
/?c4x/
(?P<org>[^/]+)/
(?P<course>[^/]+)/
(?P<category>[^/]+)/
(?P<name>[^/]+)
""", re.VERBOSE | re.IGNORECASE)
@staticmethod
def is_c4x_path(path_string):
"""
Returns a boolean if a path is believed to be a c4x link based on the leading element
"""
return StaticContent.ASSET_URL_RE.match(path_string) is not None
@staticmethod
def get_static_path_from_location(location):
"""
This utility static method will take a location identifier and create a 'durable' /static/.. URL representation of it.
This link is 'durable' as it can maintain integrity across cloning of courseware across course-ids, e.g. reruns of
courses.
In the LMS/CMS, we have runtime link-rewriting, so at render time, this /static/... format will get translated into
the actual /c4x/... path which the client needs to reference static content
"""
if location is not None:
return u"/static/{name}".format(name=location.name)
else:
return None
@staticmethod
def get_base_url_path_for_course_assets(course_key):
if course_key is None:
return None
assert isinstance(course_key, CourseKey)
placeholder_id = uuid.uuid4().hex
# create a dummy asset location with a fake but unique name. strip off the name, and return it
url_path = StaticContent.serialize_asset_key_with_slash(
course_key.make_asset_key('asset', placeholder_id).for_branch(None)
)
return url_path.replace(placeholder_id, '')
@staticmethod
def get_location_from_path(path):
"""
Generate an AssetKey for the given path (old c4x/org/course/asset/name syntax)
"""
try:
return AssetKey.from_string(path)
except InvalidKeyError:
# TODO - re-address this once LMS-11198 is tackled.
if path.startswith('/'):
# try stripping off the leading slash and try again
return AssetKey.from_string(path[1:])
@staticmethod
def get_asset_key_from_path(course_key, path):
"""
Parses a path, extracting an asset key or creating one.
Args:
course_key: key to the course which owns this asset
path: the path to said content
Returns:
AssetKey: the asset key that represents the path
"""
# Clean up the path, removing any static prefix and any leading slash.
if path.startswith('/static/'):
path = path[len('/static/'):]
path = path.lstrip('/')
try:
return AssetKey.from_string(path)
except InvalidKeyError:
# If we couldn't parse the path, just let compute_location figure it out.
# It's most likely a path like /image.png or something.
return StaticContent.compute_location(course_key, path)
@staticmethod
def get_canonicalized_asset_path(course_key, path, base_url):
"""
Returns a fully-qualified path to a piece of static content.
If a static asset CDN is configured, this path will include it.
Otherwise, the path will simply be relative.
Args:
course_key: key to the course which owns this asset
path: the path to said content
Returns:
string: fully-qualified path to asset
"""
# Break down the input path.
_, _, relative_path, params, query_string, fragment = urlparse(path)
# Convert our path to an asset key if it isn't one already.
asset_key = StaticContent.get_asset_key_from_path(course_key, relative_path)
# Check the status of the asset to see if this can be served via CDN aka publicly.
serve_from_cdn = False
try:
content = AssetManager.find(asset_key, as_stream=True)
is_locked = getattr(content, "locked", True)
serve_from_cdn = not is_locked
except (ItemNotFoundError, NotFoundError):
# If we can't find the item, just treat it as if it's locked.
serve_from_cdn = False
# Update any query parameter values that have asset paths in them. This is for assets that
# require their own after-the-fact values, like a Flash file that needs the path of a config
# file passed to it e.g. /static/visualization.swf?configFile=/static/visualization.xml
query_params = parse_qsl(query_string)
updated_query_params = []
for query_name, query_value in query_params:
if query_value.startswith("/static/"):
new_query_value = StaticContent.get_canonicalized_asset_path(course_key, query_value, base_url)
updated_query_params.append((query_name, new_query_value))
else:
updated_query_params.append((query_name, query_value))
serialized_asset_key = StaticContent.serialize_asset_key_with_slash(asset_key)
base_url = base_url if serve_from_cdn else ''
return urlunparse((None, base_url, serialized_asset_key, params, urlencode(updated_qu |
ketor/z-vimrc | .vim/bundle/taghighlight/plugin/TagHighlight/module/config.py | Python | gpl-2.0 | 3,393 | 0.003831 | #!/usr/bin/env python
# Tag Highlighter:
# Author: A. S. Budden <abudden _at_ gmail _dot_ com>
# Copyright: Copyright (C) 2009-2013 A. S. Budden
# Permission is hereby granted to use and distribute this code,
# with or without modifications, provided that this copyright
# notice is copied with it. Like anything else that's free,
# the TagHighlight plugin is provided *as is* and comes with no
# warranty of any kind, either expressed or implied. By using
# this plugin, you agree that in no event will the copyright
# holder be liable for any damages resulting from the use
# of this software.
# ---------------------------------------------------------------------
import sys
import os
from optparse import Values
from .utilities import TagHighlightOptionDict
from .loaddata import LoadFile, LoadDataFile, SetLoadDataDirectory
from .debug import SetDebugLogFile, SetDebugLogLevel, Debug
config = TagHighlightOptionDict()
def SetDataDirectories():
global config
if hasattr(sys, 'frozen'):
# Compiled variant, executable should be in
# plugin/TagHighlight/Compiled/Win32, so data
# is in ../../data relative to executable
config['DataDirectory'] = os.path.abspath(
os.path.join(os.path.dirname(sys.executable),
'../../data'))
config['VersionInfoDir'] = os.path.abspath(os.path.dirname(sys.executable))
else:
# Script variant: this file in
# plugin/TagHighlight/module, so data is in
# ../data relative to this file
config['DataDirectory'] = os.path.abspath(
os.path.join(os.path.dirname(__file__),
'../data'))
config['VersionInfoDir'] = config['DataDirectory']
SetLoadDataDirectory(config['DataDirectory'])
if not os.path.exists(config['DataDirectory']):
raise IOError("Data directory doesn't exist, have you installed the main distribution?")
def LoadVersionInfo():
global config
data = LoadDataFile('release.txt')
config['Release'] = data['release']
try:
config['Version'] = LoadFile(os.path.join(config['VersionInfoDir'],'version_info.txt'))
except IOError:
config['Version'] = {
'clean': 'Unreleased',
'date | ': 'Unreleased',
'revision_id': 'Unreleased',
}
def SetInitialOptions(new_options, manual_options):
global config
for key in new_options:
config[key] = new_options[key]
if 'DebugLevel' in config:
SetDebugLogLevel(config['DebugLevel'])
if 'DebugFile' in config:
SetDebugLogFile(config['Debug | File'])
config['ManuallySetOptions'] = manual_options
def LoadLanguages():
global config
if 'LanguageHandler' in config:
return
from .languages import Languages
config['LanguageHandler'] = Languages(config)
full_language_list = config['LanguageHandler'].GetAllLanguages()
if len(config['Languages']) == 0:
# Include all languages
config['LanguageList'] = full_language_list
else:
config['LanguageList'] = [i for i in full_language_list if i in config['Languages']]
Debug("Languages:\n\t{0!r}\n\t{1!r}".format(full_language_list, config['LanguageList']), "Information")
SetDataDirectories()
LoadVersionInfo()
|
zentralopensource/zentral | zentral/contrib/simplemdm/models.py | Python | apache-2.0 | 3,296 | 0.002731 | import logging
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.urls import reverse
from zentral.utils.osx_package import get_standalone_package_builders
from .utils import delete_app, build_and_upload_app
logger = logging.getLogger("zentral.contrib.simplemdm.models")
class SimpleMDMInstance(models.Model):
business_unit = models.ForeignKey("inventory.BusinessUnit", on_delete=models.PROTECT)
api_key = models.TextField()
account_name = models.TextField(editable=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return "{} SimpleMDM instance".format(self.account_name)
def get_absolute_url(self):
return reverse("simplemdm:simplemdm_instance", args=(self.pk,))
class SimpleMDMApp(models.Model):
simplemdm_instance = models.ForeignKey(SimpleMDMInstance, on_delete=models.CASCADE)
name = models.CharField(max_length=256)
simplemdm_id = models.IntegerField('SimpleMDM ID')
builder = models.CharField(max_length=256)
enrollment_pk = models.PositiveIntegerField(null=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
def delete(self, *args, **kwargs):
enrollment = self.get_enrollment()
super().delete(*args, **kwargs)
if enrollment:
enrollment.delete()
def get_absolute_url(self):
return "{}#app_{}".format(self.simplemdm_instance.get_absolute_url(), self.pk)
def get_builder_class(self):
return get_standalone_package_builders()[self.builder]
def get_enrollment(self):
try:
enrollment_model = self.get_builder_class().form.Meta.model
return enrollment_model.objects.get(pk=self.enrollment_pk)
except (AttributeError, ObjectDoesNotExist):
pass
def enrollment_update_callback(self):
api_key = self.simplemdm_instance.api_key
name, simplemdm_id, error_msg = build_and_upload_app(api_key,
self.get_builder_class(),
self.get_enrollment())
if not error_msg:
if self.simplemdm_id:
delete_app(api_key, self.simplemdm_id)
self.name = name
self.simplemdm_id = simplemdm_id
self.save()
else:
logger.error("Could not replace the SimpleMDM app. %s", error_msg)
def get_description_for_enrollment(self):
return str(self.simplemdm_instance)
def serialize_for_event(self):
"""used for | the enrollment secret verification events, via the enrollment"""
instance = self.simplemdm_instance
meta_business_unit = instance.business_unit.meta_business_unit
return {"simplemdm_app": {"pk": self.pk,
"instance": {"pk": instance.pk,
"account_name": instance.account_name,
| "meta_business_unit": {"pk": meta_business_unit.pk,
"name": meta_business_unit.name}}}}
|
meisamhe/GPLshared | Programming/MPI — AMath 483 583, Spring 2013 1.0 documentation_files/matrix_search.py | Python | gpl-3.0 | 2,103 | 0 | import sys
import random
# @include
def matrix_search(A, x):
row, col = 0, len(A[0]) - 1 # Start from the top-right corner.
# Keeps searching while there are unclassified rows and columns.
while row < len(A) and col >= 0:
if A[row][col] == x:
return True
elif A[row][col] < x:
row += 1 # Eliminate this row.
else: # A[row][col] > x.
col -= 1 # Eliminate this column.
return False
# @exclude
def simple_test():
A = [[1]]
assert not matrix_search(A, 0)
ass | ert matrix_search(A, 1)
A = [[1, 5], [2, 6]]
assert no | t matrix_search(A, 0)
assert matrix_search(A, 1)
assert matrix_search(A, 2)
assert matrix_search(A, 5)
assert matrix_search(A, 6)
assert not matrix_search(A, 3)
assert not matrix_search(A, float('inf'))
A = [[2, 5], [2, 6]]
assert not matrix_search(A, 1)
assert matrix_search(A, 2)
A = [[1, 5, 7], [3, 10, 100], [3, 12, float('inf')]]
assert matrix_search(A, 1)
assert not matrix_search(A, 2)
assert not matrix_search(A, 4)
assert matrix_search(A, 3)
assert matrix_search(A, 10)
assert matrix_search(A, float('inf'))
assert matrix_search(A, 12)
# O(n^2) solution for verifying answer.
def brute_force_search(A, x):
for row in A:
for cell in row:
if cell == x:
return True
return False
def main():
simple_test()
for _ in range(10000):
if len(sys.argv) == 3:
n = int(sys.argv[1])
m = int(sys.argv[2])
else:
n = random.randint(1, 100)
m = random.randint(1, 100)
A = [[0] * m for i in range(n)]
A[0][0] = random.randrange(100)
for i in range(n):
for j in range(m):
up = 0 if i == 0 else A[i - 1][j]
left = 0 if j == 0 else A[i][j - 1]
A[i][j] = max(up, left) + random.randint(1, 20)
x = random.randrange(100)
assert brute_force_search(A, x) == matrix_search(A, x)
if __name__ == '__main__':
main()
|
pantsbuild/pex | pex/resolve/requirement_configuration.py | Python | apache-2.0 | 2,532 | 0.00079 | # Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import
from pex.fetcher import URLFetcher
from pex.network_configuration import NetworkConfiguration
from pex.requirements import Constraint, parse_requirement_file, parse_requirement_strings
from pex.typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing import Iterable, List, Optional
import attr # vendor:skip
from pex.requirements import ParsedRequirement
else:
from pex.third_party import attr
@attr.s(frozen=True)
class RequirementConfiguration(object):
requirements = attr.ib(default=None) # type: Optional[Iterable[str]]
requirement_files = attr.ib(default=None) # type: Optional[Iterable[str]]
constraint_files = attr.ib(default=None) # type: Optional[Iterable[str]]
def parse_requirements(self, network_configuration=None):
# type: (Optional[NetworkConfiguration]) -> Iterable[ParsedRequirement]
parsed_requirements = [] # type: List[ParsedRequirement]
if self.requirements:
parsed_requirements.extend(parse_requirement_strings(self.requiremen | ts))
if self.requirement_files:
fetcher = URLFetcher(network_configuration=network_configuration)
for requirement_file in self.requirement_files:
parsed_requirements.extend(
requirement_or_constraint
for requirement_or_constraint in parse_requirement_file(
requirement_file, is_constraints=False, fetcher=fetcher
)
| if not isinstance(requirement_or_constraint, Constraint)
)
return parsed_requirements
def parse_constraints(self, network_configuration=None):
# type: (Optional[NetworkConfiguration]) -> Iterable[Constraint]
parsed_constraints = [] # type: List[Constraint]
if self.constraint_files:
fetcher = URLFetcher(network_configuration=network_configuration)
for constraint_file in self.constraint_files:
parsed_constraints.extend(
requirement_or_constraint
for requirement_or_constraint in parse_requirement_file(
constraint_file, is_constraints=True, fetcher=fetcher
)
if isinstance(requirement_or_constraint, Constraint)
)
return parsed_constraints
|
Distrotech/notify-python | tests/test-xy.py | Python | lgpl-2.1 | 418 | 0.004785 | #!/usr/bin/env python
import pygtk
pygtk.require('2.0')
import pynotify
import sys
if __name__ == '__main__':
if not pynotify.init("XY"):
sys.exit(1)
n = pynotify.Notification( | "X, Y Test",
"This notification should poin | t to 150, 10")
n.set_hint("x", 150)
n.set_hint("y", 10)
if not n.show():
print "Failed to send notification"
sys.exit(1)
|
JohnRandom/django-aggregator | dasdocc/aggregator/tests/commands/TestUpdateFeeds.py | Python | bsd-3-clause | 786 | 0.002545 | from nose.tools import *
from nose.plugins.attrib import attr
from django.test import TestCase
from django.core.management import call_command as call
from das | docc.aggregator.tests.factories import FeedFactory, InvalidFeedFactory
from dasdocc.aggregator.models import Feed
class UpdateValidFeedsTests(TestCase):
def setUp(self):
self.feed = FeedFactory()
def teardown(self):
pass
def test_updating_valid_feeds_works(self):
assert_equals(Feed.objects.get().title, None)
call( | 'updatefeeds')
assert_equals(Feed.objects.get().title, u'c-base logbuch')
def test_updating_does_not_delete_valid_tests(self):
assert_equals(Feed.objects.count(), 1)
call('updatefeeds')
assert_equals(Feed.objects.count(), 1)
|
fairdk/fair-ubuntu-centre | installscripts/data/intranet/fairintranet/technicians/management/commands/install_site.py | Python | gpl-3.0 | 1,436 | 0.004875 | from __future__ import print_function
from __future__ import absol | ute_import
from __future__ import unicode_literals
import logging
import sys
|
from django.core.management.base import BaseCommand
from core import models
logger = logging.getLogger('fairintranet.technicians')
class Command(BaseCommand):
help = (
'Asks for computers, printers, etc...'
)
args = ''
def handle(self, *args, **options):
try:
page = models.HomePage.get_root_nodes()[0].get_children()[0] # @UndefinedVariable
except IndexError:
logger.error("No root page")
sys.exit(-1)
school_name = raw_input("Enter the name of school/institution (Name Of School): ")
school_name = school_name.strip()
site_name = "Intranet of " + school_name
page.title = site_name
page.save()
if models.ResourceUsage.objects.exists():
reset_stats = raw_input("Usage statistics exist. Do you want to reset? Say 'y' if this is a new deployment and the data has been copied from an existing deployment [y/N]: ")
if reset_stats.lower().strip() == 'y':
logger.info("Resetting statistics...")
models.ResourceUsage.objects.all().delete()
else:
logger.info("Keeping statistics")
logger.info("New site name set: {:s}".format(site_name))
|
18F/regulations-site | regulations/tests/diff_applier_tests.py | Python | cc0-1.0 | 8,525 | 0 | from unittest import TestCase
from regulations.generator.layers import diff_applier
from regulations.generator.layers import tree_builder
from regulations.generator.node_types import REGTEXT
from collections import deque
class DiffApplierTest(TestCase):
def test_create_applier(self):
diff = {'some': 'diff'}
da = diff_applier.DiffApplier(diff, None)
self.assertEquals(da.diff, diff)
def create_diff_applier(self):
diff = {'some': 'diff'}
da = diff_applier.DiffApplier(diff, None)
text = "abcd"
da.deconstruct_text(text)
return da
def test_deconstruct_text(self):
da = self.create_diff_applier()
self.assertTrue('oq' in da.__dict__)
deque_list = [
deque(['a']), deque(['b']),
deque(['c']), deque(['d'])]
self.assertEquals(da.oq, deque_list)
def test_insert_text(self):
da = self.create_diff_applier()
da.insert_text(1, 'AA')
deque_list = [
deque(['a']), deque(['<ins>AA</ins>', 'b']),
deque(['c']), deque(['d'])]
self.assertEquals(da.oq, deque_list)
def test_insert_text_at_end(self):
da = self.create_diff_applier()
da.insert_text(4, 'AA')
deque_list = [
deque(['a']), deque(['b']),
deque(['c']), deque(['d', '<ins>', 'AA', '</ins>'])]
self.assertEquals(da.oq, deque_list)
def test_delete_text(self):
da = self.create_diff_applier()
da.delete_text(0, 2)
deque_list = [
deque(['<del>', 'a']), deque(['b', '</del>']),
deque(['c']), deque(['d'])]
self.assertEquals(da.oq, deque_list)
def test_apply_diff(self):
diff = {'204': {'text': [('delete', 0, 2), ('insert', 4, 'AAB')],
'op': ''}}
da = diff_applier.DiffApplier(diff, None)
da.apply_diff('acbd', '204')
new_text = da.get_text()
self.assertEquals('<del>ac</del>bd<ins>AAB</ins>', new_text)
def test_apply_diff_title(self):
diff = {'204': {'title': [('delete', 0, 2), ('insert', 4, 'AAC')],
'text': [('delete', 0, 2), ('insert', 4, 'AAB')],
'op': ''}}
da = diff_applier.DiffApplier(diff, None)
da.apply_diff('acbd', '204', component='title')
new_text = da.get_text()
self.assertEquals('<del>ac</del>bd<ins>AAC</ins>', new_text)
def test_delete_all(self):
da = diff_applier.DiffApplier({}, None)
original = 'abcd'
deleted = da.delete_all(original)
self.assertEqual('<del>abcd</del>', deleted)
def build_tree(self):
child = {
'text': 'child text',
'children': [],
'label_id': '204-3',
'label': ['204', '3'],
'node_type': REGTEXT
}
tree = {
'text': 'parent text',
'children': [child],
'label_id': '204',
'label': ['204'],
'node_type': REGTEXT
}
return tree
def test_add_nodes_to_tree(self):
tree = self.build_tree()
new_node = {
'text': 'child text',
'children': [],
'label_id': '204-2',
'label': ['204', '2'],
'node_type': REGTEXT
}
da = diff_applier.DiffApplier({}, None)
adds = tree_builder.AddQueue()
adds.insert_all([('204-2', new_node)])
da.add_nodes_to_tree(tree, adds)
self.assertEqual(len(tree['children']), 2)
self.assertEqual(tree['children'][0], new_node)
def test_add_nodes_new_section(self):
tree = self.build_tree()
new_node = {
'text': 'new node text',
'children': [],
'label_id': '204-2',
'label': ['204', '2'],
'node_type': REGTEXT
}
new_node_child = {
'text': 'new node child text',
'children': [],
'label_id': '204-2-a',
'label': ['204', '2', 'a'],
'node_type': REGTEXT
}
da = diff_applier.DiffApplier({}, None)
adds = tree_builder.AddQueue()
adds.insert_all([('204-2-a', new_node_child), ('204-2', new_node)])
da.add_nodes_to_tree(tree, adds)
self.assertEqual(len(tree['children']), 2)
new_node['children'].append(new_node_child)
self.assertEqual(tree['children'][0], new_node)
def test_add_nodes_empty_tree(self):
tree = {}
new_node = {
'text': 'new node text',
'children': [],
'label_id': '204-2',
'label': ['204', '2'],
'node_type': REGTEXT
}
da = diff_applier.DiffApplier({}, None)
adds = tree_builder.AddQueue()
adds.insert_all([('204-2', new_node)])
da.add_nodes_to_tree(tree, adds)
def test_add_nodes_child_ops(self):
"""If we don't know the correct order of children, attempt to use data
from `child_ops`"""
def mk_node(section):
return {'label': ['100', section], 'node_type': 'regtext',
'children': []}
node_1, node_2 = mk_node('1'), mk_node('2')
node_2a, node_3 = mk_node('2a'), mk_node('3')
original = {'label': ['100'], 'node_type': 'regtext', 'children': [
node_1, node_2
]}
diff = {
'100': {
'op': diff_applier.DiffApplier.MODIFIED_OP,
'child_ops': [[diff_applier.DiffApplier.EQUAL, 0, 1],
[diff_applier.DiffApplier.DELETE, 1, 2],
[diff_applier.DiffApplier.INSERT, 1, ['100-2a']],
[diff_applier.DiffApplier.INSERT, 2, ['100-3']]]
},
'100-2': {'op': diff_applier.DiffApplier.DELETED_OP},
'100-2a': {
'op': diff_applier.DiffApplier.ADDED_OP,
'node': node_2a
},
'100-3': {
'op': diff_applier.DiffApplier.ADDED_OP,
'node': node_3
}
}
adds = tree_builder.AddQueue()
adds.insert_all([('100-2a', node_2a), ('100-3', node_3)])
da = diff_applier.DiffApplier(diff, None)
da.add_nodes_to_tree(original, adds)
self.assertEqual(original['child_labels'],
['100-1', '100-2', '100-2a', '100-3'])
def test_set_child_labels_reorder(self):
"""Nodes which have been _moved_ should be ordered in their final
resting position"""
node1 = {'label': ['1', '1'], 'node_type': 'regtext', 'children': []}
node2 = {'label': ['1', '2'], 'node_type': 'regtext', 'children': []}
root = {'label': ['1'], 'node_type': 'regtext',
'children': [node1, node2]}
diff = {'1': {
'op': diff_applier.DiffApplier.MODIFIED_OP,
'child_ops': [[diff_applier.DiffApplier.DELETE, 0, 2],
[diff_applier.DiffApplier.INSERT, 0, ['1-2', '1-1']]]
}}
da = diff_applier.DiffApplier(diff, None)
da.set_child_labels(root)
self.assertEqual(root['child_labels'], ['1-2', '1-1'])
def test_child_picking(self):
da = self.create_diff_applier()
da.label_requested = '204-3'
self.assertTrue(da.is_child_of_requested('204-3-a'))
self.assertFalse(da.is_child_of_requested('204-32'))
da.label_requested = '204-3-Interp'
self.assertTrue(da.is_child_of_requested('204-3-a-Interp'))
self.assertTrue(da.is_child_of_requested('204-3-Interp-1'))
self.assertFalse(da.is_child_ | of_requested('204-30-Interp'))
da.label_requested = '204-3-Interp-4'
self.assertFalse(da.is_child_of_requested('204-3-a-Interp'))
self.assertFalse(da.is_child_of_requested('204-3-Interp-1'))
self.assertTrue(da.is_child_of_requested('204-3-Interp-4-a'))
def test_tree_changes_new_section(self):
diff = {'9999-25': {'op': 'add | ed',
'node': {'text': 'Some Text',
|
hilgroth/fiware-IoTAgent-Cplusplus | tests/e2e_tests/component/iot_api/services/create/setup.py | Python | agpl-3.0 | 10,033 | 0.011562 | from lettuce import step, world
from iotqautils.gtwRest import Rest_Utils_SBC
from common.user_steps import UserSteps
from common.gw_configuration import IOT_SERVER_ROOT,CBROKER_HEADER,CBROKER_PATH_HEADER
api = Rest_Utils_SBC(server_root=IOT_SERVER_ROOT+'/iot')
user_steps = UserSteps()
@step('a Service with name "([^"]*)", path "([^"]*)", resource "([^"]*)" and apikey "([^"]*)" not created')
def service_not_created(step, service_name, service_path, resource, apikey):
if user_steps.service_created(service_name, service_path, resource):
print 'ERROR: El servicio {} ya existe'.format(service_name)
world.remember.setdefault(service_name, {})
if service_path == 'void':
service_path='/'
world.remember[service_name].setdefault(service_path, {})
world.remember[service_name][service_path].setdefault('resource', {})
world.remember[service_name][service_path]['resource'].setdefault(resource, {})
if not apikey:
apikey = ""
world.remember[service_name][service_path]['resource'][resource].setdefault(apikey)
@step('I create a service with name "([^"]*)", path "([^"]*)", resource "([^"]*)", apikey "([^"]*)", cbroker "([^"]*)", entity_type "([^"]*)" and token "([^"]*)"')
def create_service(step,srv_name,srv_path,resource,apikey,cbroker,entity_type,token):
world.typ1 = {}
world.typ2 = {}
world.srv_path = srv_path
world.resource = resource
world.apikey = apikey
world.cbroker = cbroker
world.entity_type = entity_type
world.token = token
req=user_steps.create_service_with_params(srv_name,srv_path,resource,apikey,cbroker,entity_type,token)
assert req.status_code == 201, 'ERROR: ' + req.text + "El servicio {} no se ha creado correctamente".format(srv_name)
print 'Se ha creado el servicio {}'.format(srv_name)
@step('I create a service with name "([^"]*)", path "([^"]*)", resource "([^"]*)", apikey "([^"]*)", cbroker "([^"]*)" and atributes "([^"]*)" and "([^"]*)", with names "([^"]*)" and "([^"]*)", types "([^"]*)" and "([^"]*)" and values "([^"]*)" and "([^"]*)"')
def create_service_with_attrs(step,srv_name,srv_path,resource,apikey,cbroker,typ1, typ2, name1, name2, type1, type2, value1, value2):
world.srv_path = srv_path
world.resource = resource
world.apikey = apikey
world.cbroker = cbroker
world.entity_type = {}
world.token = {}
attributes=[]
st_attributes=[]
world.typ1 = typ1
world.typ2 = typ2
world.name1 = name1
world.name2 = name2
world.type1 = type1
world.type2 = type2
world.value1 = value1
| world.value2 = value2
if typ1=='attr':
attributes=[
{
"name": name1,
"type": type1,
"object_id": value1
}
]
if typ2=='attr':
attribute={
"name": name2,
"type": type2,
"object_id": value2
}
attributes.append( | attribute)
if typ1=='st_att':
st_attributes=[
{
"name": name1,
"type": type1,
"value": value1
}
]
if typ2=='st_att':
st_attribute={
"name": name2,
"type": type2,
"value": value2
}
st_attributes.append(st_attribute)
req=user_steps.create_service_with_params(srv_name,srv_path,resource,apikey,cbroker,{},{},attributes,st_attributes)
assert req.status_code == 201, 'ERROR: ' + req.text + "El servicio {} no se ha creado correctamente".format(srv_name)
print 'Se ha creado el servicio {}'.format(srv_name)
@step('the Service with name "([^"]*)" and path "([^"]*)" is created')
def service_created(step, service_name, service_path):
attributes=0
st_attributes=0
headers = {}
params = {}
headers[CBROKER_HEADER] = str(service_name)
if service_path:
if not service_path == 'void':
headers[CBROKER_PATH_HEADER] = str(service_path)
else:
headers[CBROKER_PATH_HEADER] = '/'
if world.resource:
params['resource']= world.resource
req = api.get_service('', headers, params)
res = req.json()
assert res['count'] == 1, 'Error: 1 service expected, ' + str(res['count']) + ' received'
response = res['services'][0]
assert response['service'] == service_name, 'Expected Result: ' + service_name + '\nObtained Result: ' + response['service']
assert response['resource'] == world.resource, 'Expected Result: ' + world.resource + '\nObtained Result: ' + response['resource']
if world.srv_path:
if world.srv_path == 'void':
assert response['service_path'] == '/', 'Expected Result: ' + '/' + '\nObtained Result: ' + response['service_path']
else:
assert response['service_path'] == world.srv_path, 'Expected Result: ' + world.srv_path + '\nObtained Result: ' + response['service_path']
if world.apikey:
assert response['apikey'] == world.apikey, 'Expected Result: ' + world.apikey + '\nObtained Result: ' + response['apikey']
else:
assert response['apikey'] == "", 'Expected Result: NULL \nObtained Result: ' + response['apikey']
if world.cbroker:
assert response['cbroker'] == world.cbroker, 'Expected Result: ' + world.cbroker + '\nObtained Result: ' + response['cbroker']
else:
assert response['cbroker'] == "", 'Expected Result: NULL \nObtained Result: ' + response['cbroker']
if world.entity_type:
assert response['entity_type'] == world.entity_type, 'Expected Result: ' + world.entity_type + '\nObtained Result: ' + response['entity_type']
if world.token:
assert response['token'] == world.token, 'Expected Result: ' + world.token + '\nObtained Result: ' + response['token']
if world.typ1:
if world.typ1 == 'attr':
assert response['attributes'][0]['name'] == world.name1, 'Expected Result: ' + world.name1 + '\nObtained Result: ' + response['attributes'][0]['name']
assert response['attributes'][0]['type'] == world.type1, 'Expected Result: ' + world.type1 + '\nObtained Result: ' + response['attributes'][0]['type']
assert response['attributes'][0]['object_id'] == world.value1, 'Expected Result: ' + world.value1 + '\nObtained Result: ' + response['attributes'][0]['object_id']
attributes+=1
if world.typ1 == 'st_att':
assert response['static_attributes'][0]['name'] == world.name1, 'Expected Result: ' + world.name1 + '\nObtained Result: ' + response['static_attributes'][0]['name']
assert response['static_attributes'][0]['type'] == world.type1, 'Expected Result: ' + world.type1 + '\nObtained Result: ' + response['static_attributes'][0]['type']
assert response['static_attributes'][0]['value'] == world.value1, 'Expected Result: ' + world.value1 + '\nObtained Result: ' + response['static_attributes'][0]['value']
st_attributes+=1
if world.typ2:
if world.typ2 == 'attr':
assert response['attributes'][attributes]['name'] == world.name2, 'Expected Result: ' + world.name2 + '\nObtained Result: ' + response['attributes'][attributes]['name']
assert response['attributes'][attributes]['type'] == world.type2, 'Expected Result: ' + world.type2 + '\nObtained Result: ' + response['attributes'][attributes]['type']
assert response['attributes'][attributes]['object_id'] == world.value2, 'Expected Result: ' + world.value2 + '\nObtained Result: ' + response['attributes'][attributes]['object_id']
if world.typ2 == 'st_att':
assert response['static_attributes'][st_attributes]['name'] == world.name2, 'Expected Result: ' + world.name2 + '\nObtained Result: ' + response['static_attributes'][st_attributes]['name']
assert response['static_attributes'][st_attributes]['type'] == world.type2, 'Expected Result: ' + world.type2 + '\nObtained Result: ' + res |
dmccloskey/ddt_python | ddt_python/ddt_tile_html.py | Python | mit | 2,646 | 0.032905 | from .ddt_tile import ddt_tile
class ddt_tile_html(ddt_tile):
def make_parameters_form_01(self,
formparameters={},
):
'''Make htmlparameters
INPUT:
OUTPUT:
'''
#defaults:
htmlid='filtermenuform1';
htmltype='form_01';
formsubmitbuttonidtext={'id':'submit1','text':'submit'};
formresetbuttonidtext={'id':'reset1','text':'reset'};
formupdatebuttonidtext={'id':'update1','text':'update'};
if formparameters:
formparameters_O = formparameters;
else:
formparameters_O = {
'htmlid':htmlid,
'htmltype':htmltype,
| "formsubmitbuttonidtext":formsubmitbuttonidtext,
"formresetbuttonidtext":formresetbuttonidtext,
"formupdatebuttonidtext":formupdatebuttonidtext
};
self.make_htmlparameters(htmlparameters=formparameters_O);
def make_parameters_datalist_01(self,
datalistparameters={},
):
'''Make htmlparameters
| INPUT:
OUTPUT:
'''
#defaults
htmlid='datalist1';
htmltype='datalist_01';
datalist=[
{'value':'hclust','text':'by cluster'},
{'value':'probecontrast','text':'by row and column'},
{'value':'probe','text':'by row'},
{'value':'contrast','text':'by column'},
{'value':'custom','text':'by value'}];
if datalistparameters:
datalistparameters_O = datalistparameters;
else:
datalistparameters_O = {
'htmlid':htmlid,
'htmltype':htmltype,
'datalist':datalist
};
self.make_htmlparameters(htmlparameters=datalistparameters_O);
def make_parameters_href_02(self,
formparameters={},
alert=None,
url=None,
):
'''Make htmlparameters
INPUT:
OUTPUT:
'''
#defaults:
htmlid='formhref02';
htmltype='href_02';
formsubmitbuttonidtext={'id':'submithref1','text':'submit'};
htmlalert=alert;
hrefurl=url;
if formparameters:
formparameters_O = formparameters;
else:
formparameters_O = {
'htmlid':htmlid,
'htmltype':htmltype,
"formsubmitbuttonidtext":formsubmitbuttonidtext,
'hrefurl':hrefurl,
'htmlalert':htmlalert,
};
self.make_htmlparameters(htmlparameters=formparameters_O); |
lawrenceakka/SoCo | soco/core.py | Python | mit | 73,424 | 0 | # -*- coding: utf-8 -*-
# pylint: disable=fixme, protected-access
"""The core module contains the SoCo class that implements
the main entry to the SoCo functionality
"""
from __future__ import unicode_literals
import datetime
import logging
import re
import socket
from functools import wraps
import warnings
from soco.exceptions import SoCoUPnPException
import requests
from . import config
from .compat import UnicodeType
from .data_structures import (
DidlObject, DidlPlaylistContainer, DidlResource,
Queue, from_didl_string, to_didl_string
)
from .exceptions import SoCoSlaveException
from .groups import ZoneGroup
from .music_library import MusicLibrary
from .services import (
DeviceProperties, ContentDirectory, RenderingControl, AVTransport,
ZoneGroupTopology, AlarmClock, SystemProperties, MusicServices,
zone_group_state_shared_cache,
)
from .utils import (
really_utf8, camel_to_underscore, deprecated
)
from .xml import XML
_LOG = logging.getLogger(__name__)
class _ArgsSingleton(type):
"""A metaclass which permits only a single instance of each derived class
sharing the same `_class_group` class attribute to exist for any given set
of positional arguments.
Attempts to instantiate a second instance of a derived class, or another
class with the same `_class_group`, with the same args will return the
existing instance.
For example:
>>> class ArgsSingletonBase(object):
... __metaclass__ = _ArgsSingleton
...
>>> class First(ArgsSingletonBase):
... _class_group = "greeting"
... def __init__(self, param):
... pass
...
>>> class Second(ArgsSingletonBase):
... _class_group = "greeting"
... def __init__(self, param):
... pass
>>> assert First('hi') is First('hi')
>>> assert First('hi') is First('bye')
AssertionError
>>> assert First('hi') is Second('hi')
"""
_instances = {}
def __call__(cls, *args, **kwargs):
key = cls._class_group if hasattr(cls, '_class_group') else cls
if key not in cls._instances:
cls._instances[key] = {}
if args not in cls._instances[key]:
cls._instances[key][args] = super(_ArgsSingleton, cls).__call__(
*args, **kwargs)
return cls._instances[key][args]
class _SocoSingletonBase( # pylint: disable=too-few-public-methods,no-init
_ArgsSingleton(str('ArgsSingletonMeta'), (object,), {})):
"""The base class for the SoCo class.
Uses a Python 2 and 3 compatible method of declaring a metaclass. See, eg,
here: http://www.artima.com/weblogs/viewpost.jsp?thread=236234 and
here: http://mikewatkins.ca/2008/11/29/python-2-and-3-metaclasses/
"""
pass
def only_on_master(function):
"""Decorator that raises SoCoSlaveException on master call on slave."""
@wraps(function)
def inner_function(self, *args, **kwargs):
"""Master checking inner function."""
if not self.is_coordinator:
message = 'The method or property "{0}" can only be called/used '\
'on the coordinator in a group'.format(function.__name__)
raise SoCoSlaveException(message)
return function(self, *args, **kwargs)
return inner_function
# pylint: disable=R0904,too-many-instance-attributes
class SoCo(_SocoSingletonBase):
"""A simple class for controlling a Sonos speaker.
For any given set of arguments to __init__, only one instance of this class
may be created. Subsequent attempts to create an instance with the same
arguments will return the previously created instance. This means that all
SoCo instances created with the same ip address are in fact the *same* SoCo
instance, reflecting the real world position.
.. rubric:: Methods
.. autosummary::
play
play_uri
play_from_queue
pause
stop
seek
next
previous
switch_to_line_in
switch_to_tv
get_current_track_info
get_speaker_info
partymode
join
unjoin
get_queue
get_current_transport_info
add_uri_to_queue
add_to_queue
remove_from_queue
clear_queue
get_favorite_radio_shows
get_favorite_radio_stations
get_sonos_favorites
create_sonos_playlist
create_sonos_playlist_from_queue
remove_sonos_playlist
add_item_to_sonos_playlist
get_item_album_art_uri
set_sleep_timer
get_sleep_timer
.. rubric:: Properties
.. warning::
These properties are not generally cached and may obtain information
over the network, so may take longer than expected to set or return
a value. It may be a good idea for you to cache the value in your
own code.
.. autosummary::
uid
household_id
mute
volume
bass
treble
loudness
cross_fade
status_light
player_name
play_mode
queue_size
is_playing_tv
is_playing_radio
is_playing_line_in
"""
_class_group = 'SoCo'
# pylint: disable=super-on-old-class
def __init__(self, ip_address):
# Note: Creation of a SoCo instance should be as cheap and quick as
# possible. Do not make any network calls here
| super(SoCo, self).__init__()
# Check if ip_address is a valid IPv4 representation | .
# Sonos does not (yet) support IPv6
try:
socket.inet_aton(ip_address)
except socket.error:
raise ValueError("Not a valid IP address string")
#: The speaker's ip address
self.ip_address = ip_address
self.speaker_info = {} # Stores information about the current speaker
# The services which we use
# pylint: disable=invalid-name
self.avTransport = AVTransport(self)
self.contentDirectory = ContentDirectory(self)
self.deviceProperties = DeviceProperties(self)
self.renderingControl = RenderingControl(self)
self.zoneGroupTopology = ZoneGroupTopology(self)
self.alarmClock = AlarmClock(self)
self.systemProperties = SystemProperties(self)
self.musicServices = MusicServices(self)
self.music_library = MusicLibrary(self)
# Some private attributes
self._all_zones = set()
self._groups = set()
self._is_bridge = None
self._is_coordinator = False
self._player_name = None
self._uid = None
self._household_id = None
self._visible_zones = set()
self._zgs_cache = None
_LOG.debug("Created SoCo instance for ip: %s", ip_address)
def __str__(self):
return "<{0} object at ip {1}>".format(
self.__class__.__name__, self.ip_address)
def __repr__(self):
return '{0}("{1}")'.format(self.__class__.__name__, self.ip_address)
@property
def player_name(self):
"""The speaker's name.
A string.
"""
# We could get the name like this:
# result = self.deviceProperties.GetZoneAttributes()
# return result["CurrentZoneName"]
# but it is probably quicker to get it from the group topology
# and take advantage of any caching
self._parse_zone_group_state()
return self._player_name
@player_name.setter
def player_name(self, playername):
"""Set the speaker's name."""
self.deviceProperties.SetZoneAttributes([
('DesiredZoneName', playername),
('DesiredIcon', ''),
('DesiredConfiguration', '')
])
@property
def uid(self):
"""A unique identifier.
Looks like: ``'RINCON_000XXXXXXXXXX1400'``
"""
# Since this does not change over time (?) check whether we already
# know the answer. If so, there is no need to go further
if self._uid is not None:
return self._uid
# if not, we have to get it from the zone topology, which
# is probably quicker |
zhanghui9700/eonboard | eoncloud_web/biz/network/admin.py | Python | apache-2.0 | 487 | 0 | from django.contrib import admin
from biz.network.models import Network, Subnet, Router
class NetworkAdmin(admin.ModelAdmin):
list_display = ("id", "name", "is_default")
class SubnetAdmin(admin.ModelAdmin):
list_display = ("id", "name" | , "address", "ip_version")
class RouterAdmin(admin.ModelAdmin):
list_display = ("id", "name", "gateway")
admin.site.register(Network | , NetworkAdmin)
admin.site.register(Subnet, SubnetAdmin)
admin.site.register(Router, RouterAdmin)
|
swagner-de/irws_homeworks | word_embeddings/embedding.py | Python | mit | 1,203 | 0.003325 | import glob
import os
import numpy as np
def load_emebeddings(folder):
files = [filename for filename in glob.iglob(folder + '**', recursive=True) if not os.path.isdir(filename)]
w2v = {}
for file in files:
with open(file, "r", encoding='utf8') as lines:
for line in lines:
# based on http://nadbordrozd.github.io/blog/2016/05/20/text-classification-with-word2vec/
w2v[line.split()[0]] = line.split()[1:]
return w2v
# derive a vector by multiplying the tfidf with every line of the embeddingg vector
# then sum all embedding vectors together
# then divide by the sum of the length of all embedding vectors
def compute_embedding_vec(embeddings, doc_tfidf):
intersect = set(doc_tfidf.keys()).intersection(embeddings.keys())
res = []
divisor = 0
for term in intersect:
_tfidf = doc_tfidf[term]
divisor += _tfidf
emb_vec = embeddings[term]
| for emb in range(le | n(emb_vec)):
try:
res[emb] += _tfidf * float(emb_vec[emb])
except IndexError:
res.append(_tfidf * float(emb_vec[emb]))
for k in res:
k /= divisor
return res
|
cupcicm/bson | bson/codec.py | Python | bsd-3-clause | 10,379 | 0.030061 | #!/usr/bin/python -OOOO
# vim: set fileencoding=utf8 shiftwidth=4 tabstop=4 textwidth=80 foldmethod=marker :
# Copyright (c) 2010, Kou Man Tong. All rights reserved.
# For licensing, see LICENSE file included in the package.
"""
Base codec functions for bson.
"""
import struct
import cStringIO
import calendar, pytz
from datetime import datetime
import warnings
try:
from abc import ABCMeta, abstractmethod
except ImportError:
# If abc is not present (older versions of python), just define the ABCMeta
# class as a dummy class, we don't really need it anyway.
class ABCMeta(type):
pass
def abstractmethod(funcobj):
"""A decorator indicating abstract methods.
Requires that the metaclass is ABCMeta or derived from it. A
class that has a metaclass derived from ABCMeta cannot be
instantiated unless all of its abstract methods are overridden.
The abstract methods can be called using any of the normal
'super' call mechanisms.
Usage:
class C:
__metaclass__ = ABCMeta
@abstractmethod
def my_abstract_method(self, ...):
...
"""
funcobj.__isabstractmethod__ = True
return funcobj
# {{{ Error Classes
class MissingClassDefinition(ValueError):
def __init__(self, class_name):
super(MissingClassDefinition, self).__init__(
"No class definition for class %s" % (class_name,))
# }}}
# {{{ Warning Classes
class MissingTimezoneWarning(RuntimeWarning):
def __init__(self, *args):
args = list(args)
if len(args) < 1:
args.append("Input datetime object has no tzinfo, assuming UTC.")
super(MissingTimezoneWarning, self).__init__(*args)
# }}}
# {{{ Traversal Step
class TraversalStep(object):
def __init__(self, parent, key):
self.parent = parent
self.key = key
# }}}
# {{{ Custom Object Codec
class BSONCoding(object):
__metaclass__ = ABCMeta
@abstractmethod
def bson_encode(self):
pass
@abstractmethod
def bson_init(self, raw_values):
pass
classes = {}
def import_class(cls):
if not issubclass(cls, BSONCoding):
return
global classes
classes[cls.__name__] = cls
def import_classes(*args):
for cls in args:
import_class(cls)
def import_classes_from_modules(*args):
for module in args:
for item in module.__dict__:
if hasattr(item, "__new__") and hasattr(item, "__name__"):
import_class(item)
def encode_object(obj, traversal_stack, generator_func):
values = obj.bson_encode()
class_name = obj.__class__.__name__
values["$$__CLASS_NAME__$$"] = class_name
return encode_document(values, traversal_stack, obj, generator_func)
def encode_object_element(name, value, traversal_stack, generator_func):
return "\x03" + encode_cstring(name) + \
encode_object(value, traversal_stack,
generator_func = generator_func)
class _EmptyClass(object):
pass
def decode_object(raw_values):
global classes
class_name = raw_values["$$__CLASS_NAME__$$"]
cls = None
try:
cls = classes[class_name]
except KeyError, e:
raise MissingClassDefinition(class_name)
retval = _EmptyClass()
retval.__class__ = cls
alt_retval = retval.bson_init(raw_values)
return alt_retval or retval
# }}}
# {{{ Codec Logic
def encode_string(value):
value = value.encode("utf8")
length = len(value)
return struct.pack("<i%dsb" % (length,), length + 1, value, 0)
def decode_string(data, base):
length = struct.unpack("<i", data[base:base + 4])[0]
value = data[base + 4: base + 4 + length - 1]
value = value.decode("utf8")
return (base + 4 + length, value)
def encode_cstring(value):
if isinstance(value, unicode):
value = value.encode("utf8")
return value + "\x00"
def decode_cstring(data, base):
length = 0
max_length = len(data) - base
while length < max_length:
character = data[base + length]
length += 1
if character == "\x00":
break
return (base + length, data[base:base + length - 1].decode("utf8"))
def encode_binary(value):
length = len(value)
return struct.pack("<ib", length, 0) + value
def decode_binary(data, base):
length, binary_type = struct.unpack("<ib", data[base:base + 5])
return (base + 5 + length, data[base + 5:base + 5 + length])
def encode_double(value):
return struct.pack("<d", value)
def decode_double(data, base):
ret | urn (base + 8, struct.unpack("<d", data[base: base + 8])[0])
ELEMENT_TYPES = {
0x01 : "double",
0x02 : "string",
0x03 : "document",
0x04 : "array",
| 0x05 : "binary",
0x08 : "boolean",
0x09 : "UTCdatetime",
0x0A : "none",
0x10 : "int32",
0x12 : "int64"
}
def encode_double_element(name, value):
return "\x01" + encode_cstring(name) + encode_double(value)
def decode_double_element(data, base):
base, name = decode_cstring(data, base + 1)
base, value = decode_double(data, base)
return (base, name, value)
def encode_string_element(name, value):
return "\x02" + encode_cstring(name) + encode_string(value)
def decode_string_element(data, base):
base, name = decode_cstring(data, base + 1)
base, value = decode_string(data, base)
return (base, name, value)
def encode_value(name, value, buf, traversal_stack, generator_func):
if isinstance(value, BSONCoding):
buf.write(encode_object_element(name, value, traversal_stack,
generator_func))
elif isinstance(value, float):
buf.write(encode_double_element(name, value))
elif isinstance(value, unicode):
buf.write(encode_string_element(name, value))
elif isinstance(value, dict):
buf.write(encode_document_element(name, value,
traversal_stack, generator_func))
elif isinstance(value, list) or isinstance(value, tuple):
buf.write(encode_array_element(name, value,
traversal_stack, generator_func))
elif isinstance(value, str):
buf.write(encode_binary_element(name, value))
elif isinstance(value, bool):
buf.write(encode_boolean_element(name, value))
elif isinstance(value, datetime):
buf.write(encode_UTCdatetime_element(name, value))
elif value is None:
buf.write(encode_none_element(name, value))
elif isinstance(value, int):
if value < -0x80000000 or value > 0x7fffffff:
buf.write(encode_int64_element(name, value))
else:
buf.write(encode_int32_element(name, value))
elif isinstance(value, long):
buf.write(encode_int64_element(name, value))
def encode_document(obj, traversal_stack,
traversal_parent = None,
generator_func = None):
buf = cStringIO.StringIO()
key_iter = obj.iterkeys()
if generator_func is not None:
key_iter = generator_func(obj, traversal_stack)
for name in key_iter:
value = obj[name]
traversal_stack.append(TraversalStep(traversal_parent or obj, name))
encode_value(name, value, buf, traversal_stack, generator_func)
traversal_stack.pop()
e_list = buf.getvalue()
e_list_length = len(e_list)
return struct.pack("<i%dsb" % (e_list_length,), e_list_length + 4 + 1,
e_list, 0)
def encode_array(array, traversal_stack,
traversal_parent = None,
generator_func = None):
buf = cStringIO.StringIO()
for i in xrange(0, len(array)):
value = array[i]
traversal_stack.append(TraversalStep(traversal_parent or array, i))
encode_value(unicode(i), value, buf, traversal_stack, generator_func)
traversal_stack.pop()
e_list = buf.getvalue()
e_list_length = len(e_list)
return struct.pack("<i%dsb" % (e_list_length,), e_list_length + 4 + 1,
e_list, 0)
def decode_element(data, base):
element_type = struct.unpack("<b", data[base:base + 1])[0]
element_description = ELEMENT_TYPES[element_type]
decode_func = globals()["decode_" + element_description + "_element"]
return decode_func(data, base)
def decode_document(data, base):
length = struct.unpack("<i", data[base:base + 4])[0]
end_point = base + length
base += 4
retval = {}
while base < end_point - 1:
base, name, value = decode_element(data, base)
retval[name] = value
if "$$__CLASS_NAME__$$" in retval:
retval = decode_object(retval)
return (end_point, retval)
def encode_document_element(name, value, traversal_stack, generator_func):
return "\x03" + encode_cstring(name) + \
encode_document(value, traversal_stack,
generator_func = generator_func)
def decode_document_element(data, base):
base, name = decode_cstring(data, base + 1)
base, value = decode_document(data, base)
return (base, name, value)
def encode_array_element(name, value, traversa |
weiweihuanghuang/Glyphs-Scripts | Hinting/Delete Hints in Visible Layers.py | Python | apache-2.0 | 520 | 0.036538 | #MenuTitle: Delete Hints in Visible Layers
# -*- coding: utf-8 -*-
__doc__="""
Deletes all hints in active layers of selected glyphs.
"""
import GlyphsApp
Font = Glyphs.font
selectedLayers = Font.selectedLayers
print "Deleting hints | in active layer:"
def process( thisLayer ):
for x in reversed( range( len( thisLayer.hints ))):
del thisLayer.hints[x]
Font.disableUpdateInterface()
for thisLayer in selectedLayers:
print "Processing", thisLayer.parent.name
proces | s( thisLayer )
Font.enableUpdateInterface()
|
mdrohmann/txtemplates | tests/echo/conftest.py | Python | bsd-3-clause | 199 | 0 | server_module = 'txtemplates.echo'
backend_ | options = [{}]
backend_ids = ['default']
full_server_options = [({}, {})]
full_server_ids = ['default']
# vim: set | ft=python sw=4 et spell spelllang=en:
|
marrow/dsl | marrow/dsl/core/lines.py | Python | mit | 4,465 | 0.051064 | # encoding: utf-8
from __future__ import unicode_literals
from collections import deque
from .buffer import Buffer
from .compat import py2, str
from .line import Line
log = __import__('logging').getLogger(__name__)
def _pub(a):
return {i for i in a if i[0] != '_'}
class Lines(object):
"""An iterable set of named, indexed buffers containing lines, able to push lines back during iteration.
Access as a dictionary using string keys to access named buffers.
Attributes:
- `buffers`: A mapping of buffer name to buffer.
- `lines`: A deque of the buffers in order.
- `active`: A reference to the last manipulated buffer.
"""
__slots__ = ('buffers', 'lines', 'active')
def __init__(self, buffers, *args, **kw):
"""Construct a | new set of buffers for the given input, or an empty buffer."""
tags = kw.pop('tags', None)
self.buffers = {} # Named references to buffers.
self.lines = deque() # Indexed references to buffers.
if isinstance(buffers, str) | and args:
buffers = [(i, Buffer(())) for i in [buffers] + list(args)]
elif isinstance(buffers, str):
buffers = [('default', Buffer(buffers))]
elif isinstance(buffers, Lines):
self.buffers = buffers.buffers.copy()
self.lines.extend(buffers.lines)
buffers = ()
for name, buffer in buffers:
if isinstance(buffer, str):
buffer = Buffer(buffer)
self.buffers[name] = buffer
self.lines.append(buffer)
if tags:
for buffer in self.lines:
buffer.tag |= tags
if 'default' in kw and kw['default']:
self.active = self.buffers[kw['default']]
else:
self.active = self.lines[0] if self.lines else None
super(Lines, self).__init__()
def __len__(self):
"""Conform to Python API expectations for length retrieval."""
return self.count
def __repr__(self):
"""Produce a programmers' representation giving general information about buffer state."""
rev = {v: k for k, v in self.buffers.items()}
buffers = ', '.join((rev[buf] + '=' + repr(buf)) for buf in self.lines)
if buffers: buffers = ", " + buffers
return '{0.__class__.__name__}({0.count}{1}, active={2})'.format(
self, buffers, 'None' if self.active is None else rev[self.active])
def __iter__(self):
"""We conform to the Python iterator protocol, so we return ourselves here."""
return self
def __next__(self):
"""Python iterator protocol to retrieve the next line."""
return self.next()
def __str__(self):
"""Flatten the buffers back into a single newline-separated string."""
return "\n".join(str(i) for i in self)
if py2: # Python 2 compatibility glue.
__unicode__ = __str__
del __str__
def __contains__(self, name):
"""Does this group of lines contain the named buffer?"""
return name in self.buffers
def __getitem__(self, name):
"""Allow retrieval of named buffers through array subscript access."""
return self.buffers[name]
def __setitem__(self, name, value):
"""Allow assignment of named buffers through array subscript assignment."""
if not isinstance(value, Buffer):
value = Buffer(value)
self.buffers[name] = value
if value not in self.lines:
self.lines.append(value)
def __delitem__(self, name):
"""Allow removal of named buffers through array subscript deletion."""
if name not in self.buffers:
raise KeyError()
value = self[name]
del self.buffers[name]
try:
self.lines.remove(value)
except ValueError:
pass
@property
def count(self):
"""Retrieve the total number of lines stored in all buffers."""
return sum(len(i) for i in self.lines)
def next(self):
"""Retrieve and remove (pull) the first line in the next non-empty buffer or raise StopIteration."""
for lines in self.lines:
if lines: break
else:
raise StopIteration()
self.active = lines
return lines.next()
def pull(self):
"""Retrieve and remove (pull) the first line in the next non-empty buffer or return None."""
for lines in self.lines:
if lines: break
else:
return None
self.active = lines
return lines.pull()
def peek(self):
"""Retrieve the next line without removing it from its buffer, or None if there are no lines available."""
for lines in self.lines:
if lines: break
else:
return None
self.active = lines
return lines.peek()
def push(self, *lines):
self.active.push(*lines)
def append(self, *lines):
self.active.append(*lines)
|
PawarPawan/h2o-v3 | h2o-py/tests/testdir_algos/glm/pyunit_NOFEATURE_prostateGLM.py | Python | apache-2.0 | 956 | 0.032427 | import sys
sys.path.insert(1, "../../../")
import h2o
import pandas as pd
import statsmodels.api as sm
def prostate(ip,port):
# Log.info("Importing prostate.csv data...\n")
h2o_data = h2o.upload_file(path=h2o.locate("smalldata/logreg/prostate.csv"))
#prostate.summary()
sm_data = pd.read_csv(h2o.locate("smalldata/logreg/prostate.csv")).as_matrix()
sm_data_response = sm_data[:,1]
sm_data_features = sm_data[:,2:]
#Log.info(cat("B)H2O GLM (binomial) with parameters:\nX:", myX, "\nY:", myY, "\n"))
h2o_glm = h2o.glm(y=h2o_data[1], x=h2o_data[2:], family="binomial", n_folds=10, alpha=[0.5])
h2o_glm.show()
sm_glm | = sm.GLM(endog=sm_data_ | response, exog=sm_data_features, family=sm.families.Binomial()).fit()
assert abs(sm_glm.null_deviance - h2o_glm._model_json['output']['training_metrics']['null_deviance']) < 1e-5, "Expected null deviances to be the same"
if __name__ == "__main__":
h2o.run_test(sys.argv, prostate)
|
napalm-automation/napalm-yang | napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/bgp/global_/dynamic_neighbor_prefixes/__init__.py | Python | apache-2.0 | 15,976 | 0.001064 | # -*- coding: utf-8 -*-
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListType
from pyangbind.lib.yangtypes import YANGDynClass
from pyangbind.lib.yangtypes import ReferenceType
from pyangbind.lib.base import PybindBase
from collections import OrderedDict
from decimal import Decimal
from bitarray import bitarray
import six
# PY3 support of some PY2 keywords (needs improved)
if six.PY3:
import builtins as __builtin__
long = int
elif six.PY2:
import __builtin__
from . import dynamic_neighbor_prefix
class dynamic_neighbor_prefixes(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-network-instance - based on the path /network-instances/network-instance/protocols/protocol/bgp/global/dynamic-neighbor-prefixes. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: A list of IP prefixes from which the system should:
- Accept connections to the BGP daemon
- Dynamically configure a BGP neighbor corresponding to the
source address of the remote system, using the parameters
of the specified peer-group.
For such neighbors, an entry within the neighbor list should
be created, indicating that the peer was dynamically
configured, and referencing the peer-group from which the
configuration was derived.
"""
__slots__ = ("_path_helper", "_extmethods", "__dynamic_neighbor_prefix")
_yang_name = "dynamic-neighbor-prefixes"
_pybind_generated_by = "container"
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__dynamic_neighbor_prefix = YANGDynClass(
base=YANGListType(
"prefix",
dynamic_neighbor_prefix.dynamic_neighbor_prefix,
yang_name="dynamic-neighbor-prefix",
parent=self,
is_container="list",
user_ordered=False,
path_helper=self._path_helper,
yang_keys="prefix",
extensions=None,
),
is_container="list",
yang_name="dynamic-neighbor-prefix",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
extensions=None,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="list",
is_config=True,
)
load = kwargs.pop("load", None)
if args:
if len(args) > 1:
raise TypeError("cannot create a YANG container with >1 argument")
all_attr = True
for e in self._pyangbind_elements:
if not hasattr(args[0], e):
all_attr = False
break
if not all_attr:
raise ValueError("Supplied object did not have the correct attributes")
for e in self._pyangbind_elements:
nobj = getattr(args[0], e)
if nobj._changed() is False:
continue
setmethod = getattr(self, "_set_%s" % e)
if load is None:
setmethod(getattr(args[0], e))
else:
setmethod(getattr(args[0], e), load=load)
def _path(self):
if hasattr(self, "_parent"):
return self._parent._path() + [self._yang_name]
else:
return [
"network-instances",
"network-instance",
"protocols",
"protocol",
"bgp",
"global",
| "dynamic-neighbor-prefixes",
]
def _get_dynamic_neighbor_prefix(self):
"""
Getter method for dynamic_neighbor_prefix, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/global/dynamic_neighbor_prefixes/dynamic_neighbor_prefix (list)
YANG Description: An individual prefix from which dynamic neighbor
connections are allowed.
"""
return self.__dynamic_neighbor_prefix
def _set_dynamic_nei | ghbor_prefix(self, v, load=False):
"""
Setter method for dynamic_neighbor_prefix, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/global/dynamic_neighbor_prefixes/dynamic_neighbor_prefix (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_dynamic_neighbor_prefix is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_dynamic_neighbor_prefix() directly.
YANG Description: An individual prefix from which dynamic neighbor
connections are allowed.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(
v,
base=YANGListType(
"prefix",
dynamic_neighbor_prefix.dynamic_neighbor_prefix,
yang_name="dynamic-neighbor-prefix",
parent=self,
is_container="list",
user_ordered=False,
path_helper=self._path_helper,
yang_keys="prefix",
extensions=None,
),
is_container="list",
yang_name="dynamic-neighbor-prefix",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
extensions=None,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="list",
is_config=True,
)
except (TypeError, ValueError):
raise ValueError(
{
"error-string": """dynamic_neighbor_prefix must be of a type compatible with list""",
"defined-type": "list",
"generated-type": """YANGDynClass(base=YANGListType("prefix",dynamic_neighbor_prefix.dynamic_neighbor_prefix, yang_name="dynamic-neighbor-prefix", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='prefix', extensions=None), is_container='list', yang_name="dynamic-neighbor-prefix", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='list', is_config=True)""",
}
)
self.__dynamic_neighbor_prefix = t
if hasattr(self, "_set"):
self._set()
def _unset_dynamic_neighbor_prefix(self):
self.__dynamic_neighbor_prefix = YANGDynClass(
base=YANGListType(
"prefix",
dynamic_neighbor_prefix.dynamic_neighbor_prefix,
yang_name="dynamic-neighbor-prefix",
parent=self,
is_container="list",
user_ordered=False,
path_helper=self._path_helper,
yang_keys="prefix",
extensions=None,
),
is_container="list",
yang_name="dynamic-neighbor-prefix",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
extensions=None,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="list",
is_config=True,
)
dynamic_neighbor_prefix = __builtin__.property(
_get_dy |
GreenSteam/pep257 | src/pydocstyle/violations.py | Python | mit | 12,345 | 0.000081 | """Docstring violation definition."""
from collections import namedtuple
from functools import partial
from itertools import dropwhile
from typing import Any, Callable, Iterable, List, Optional
from .parser import Definition
from .utils import is_blank
__all__ = ('Error', 'ErrorRegistry', 'conventions')
ErrorParams = namedtuple('ErrorParams', ['code', 'short_desc', 'context'])
class Error:
"""Error in docstring style."""
# Options that define how errors are printed:
explain = False
source = False
def __init__(
self,
code: str,
short_desc: str,
context: str,
*parameters: Iterable[str],
) -> None:
"""Initialize the object.
`parameters` are specific to the created error.
"""
self.code = code
self.short_desc = short_desc
self.context = context
self.parameters = parameters
self.definition = None # type: Optional[Definition]
self.explanation = None # type: Optional[str]
def set_context(self, definition: Definition, explanation: str) -> None:
"""Set the source code context for this error."""
self.definition = definition
self.explanation = explanation
filename = property(lambda self: self.definition.module.name)
line = property(lambda self: self.definition.error_lineno)
@property
def message(self) -> str:
"""Return the message to print to the user."""
ret = f'{self.code}: {self.short_desc}'
if self.context is not None:
specific_error_msg = self.context.format(*self.parameters)
ret += f' ({specific_error_msg})'
return ret
@property
def lines(self) -> str:
"""Return the source code lines for this error."""
if self.definition is None:
return ''
source = ''
lines = self.definition.source.splitlines(keepends=True)
offset = self.definition.start # type: ignore
lines_stripped = list(
reversed(list(dropwhile(is_blank, reversed(lines))))
)
numbers_width = len(str(offset + len(lines_stripped)))
line_format = f'{{:{numbers_width}}}:{{}}'
for n, line in enumerate(lines_stripped):
if line:
line = ' ' + line
source += line_format.format(n + offset, line)
if n > 5:
source += ' ...\n'
break
return source
def __str__(self) -> str:
if self.explanation:
self.explanation = '\n'.join(
l for l in self.explanation.split('\n') if not is_blank(l)
)
template = '{filename}:{line} {definition}:\n {message}'
if self.source and self.explain:
template += '\n\n{explanation}\n\n{lines}\n'
elif self.source and not self.explain:
template += '\n\n{lines}\n'
elif self.explain and not self.source:
template += '\n\n{explanation}\n\n'
return template.format(
**{
name: getattr(self, name)
for name in [
'filename',
'line',
'definition',
'message',
'explanation',
'lines',
]
}
)
def __repr__(self) -> str:
return str(self)
def __lt__(self, other: 'Error') -> bool:
return (self.filename, self.line) < (other.filename, other.line)
class ErrorRegistry:
"""A registry of all error codes, divided to groups."""
groups = [] # type: ignore
class ErrorGroup:
"""A group of similarly themed errors."""
def __init__(self, prefix: str, name: str) -> None:
"""Initialize the object.
`Prefix` should be the common prefix for errors in this group,
e.g., "D1".
`name` is the name of the group (its subject).
"""
self.prefix = prefix
self.name = name
self.errors = [] # type: List[ErrorParams]
def create_error(
self,
error_code: str,
error_desc: str,
error_context: Optional[str] = None,
) -> Callable[[Iterable[str]], Error]:
"""Create an error, register it to this group and return it."""
# TODO: check prefix
error_params = ErrorParams(error_code, error_desc, error_context)
factory = partial(Error, *error_params)
self.errors.append(error_params)
return factory
@classmethod
def create_group(cls, prefix: str, name: str) -> ErrorGroup:
"""Create a new error group and return it."""
group = cls.ErrorGroup(prefix, name)
cls.groups.append(group)
return group
@classmethod
def get_error_codes(cls) -> Iterable[str]:
"""Yield all registered codes."""
for group in cls.groups:
for error in group.errors:
yield error.code
@classmethod
def to_rst(cls) -> str:
"""Output the registry as reStructuredText, for documentation."""
max_len = max(
len(error.short_desc)
for group in cls.groups
for error in group.errors
)
sep_line | = '+' + 6 * '-' + '+' + '-' * (max_len + 2) + '+\n'
blank_line = '|' + (max_len + 9) * ' ' + '|\n'
table = ''
for group in cls.groups:
table += sep_line
table += blank_line
| table += '|' + f'**{group.name}**'.center(max_len + 9) + '|\n'
table += blank_line
for error in group.errors:
table += sep_line
table += (
'|'
+ error.code.center(6)
+ '| '
+ error.short_desc.ljust(max_len + 1)
+ '|\n'
)
table += sep_line
return table
D1xx = ErrorRegistry.create_group('D1', 'Missing Docstrings')
D100 = D1xx.create_error(
'D100',
'Missing docstring in public module',
)
D101 = D1xx.create_error(
'D101',
'Missing docstring in public class',
)
D102 = D1xx.create_error(
'D102',
'Missing docstring in public method',
)
D103 = D1xx.create_error(
'D103',
'Missing docstring in public function',
)
D104 = D1xx.create_error(
'D104',
'Missing docstring in public package',
)
D105 = D1xx.create_error(
'D105',
'Missing docstring in magic method',
)
D106 = D1xx.create_error(
'D106',
'Missing docstring in public nested class',
)
D107 = D1xx.create_error(
'D107',
'Missing docstring in __init__',
)
D2xx = ErrorRegistry.create_group('D2', 'Whitespace Issues')
D200 = D2xx.create_error(
'D200',
'One-line docstring should fit on one line ' 'with quotes',
'found {0}',
)
D201 = D2xx.create_error(
'D201',
'No blank lines allowed before function docstring',
'found {0}',
)
D202 = D2xx.create_error(
'D202',
'No blank lines allowed after function docstring',
'found {0}',
)
D203 = D2xx.create_error(
'D203',
'1 blank line required before class docstring',
'found {0}',
)
D204 = D2xx.create_error(
'D204',
'1 blank line required after class docstring',
'found {0}',
)
D205 = D2xx.create_error(
'D205',
'1 blank line required between summary line and description',
'found {0}',
)
D206 = D2xx.create_error(
'D206',
'Docstring should be indented with spaces, not tabs',
)
D207 = D2xx.create_error(
'D207',
'Docstring is under-indented',
)
D208 = D2xx.create_error(
'D208',
'Docstring is over-indented',
)
D209 = D2xx.create_error(
'D209',
'Multi-line docstring closing quotes should be on a separate line',
)
D210 = D2xx.create_error(
'D210',
'No whitespaces allowed surrounding docstring text',
)
D211 = D2xx.create_error(
'D211',
'No blank lines allowed before class docstring',
'found {0}',
)
D212 = D2xx.create_error(
'D212',
'Multi-line docstring summary should start at the first li |
NewEvolution/django-rest | tutorial/settings.py | Python | mit | 3,277 | 0.001221 | """
Django settings for tutorial project.
Generated by 'django-admin startproject' u | sing Django 1.10.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/d | eployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'c0=1yf+w%u=5sgv$bnbvtg8e(3u*!4##_bal@s3ra!ll7o%(3j'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'rest_framework',
'snippets.apps.SnippetsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'tutorial.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'tutorial.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
# REST Famework
# http://www.django-rest-framework.org/api-guide/settings/
REST_FRAMEWORK = {
'PAGE_SIZE': 10
}
|
SF-Zhou/LeetCode.Solutions | solutions/multiply_strings.py | Python | mit | 194 | 0 | class Solution(object):
def multiply(self, num1, num2):
"""
| :type num1: str
:type num2: str
:rtype: str
"""
return str(int(num1) * int(num2) | )
|
JDQuackers/xbox-remote-power | xbox-remote-power.py | Python | mit | 2,719 | 0.00331 | import sys, socket, select, time
from optparse import OptionParser
XBOX_PORT = 5050
XBOX_PING = "dd00000a000000000000000400000002"
XBOX_POWER = "dd02001300000010"
help_text = "xbox-remote-power.py -a <ip address> -i <live id>"
py3 = sys.version_info[0] > 2
def main():
parser = OptionParser()
parser.add_option('-a', '--address', dest='ip_addr', help="IP Address of Xbox One", default='')
parser.add_option('-i', '--id', dest='live_id', help="Live ID of Xbox One", default='')
(opts, args) = parser.parse_args()
if not opts.ip_addr:
opts.ip_addr = user_input("Enter the IP address: ")
ping = False
if not opts.live_id:
print("No Live ID given, do you want to attempt to ping the Xbox for it?")
result = ""
while result not in ("y", "n"):
result = user_input("(y/n): ").lower()
if result == "y":
ping | = True
elif result == "n":
opts.live_id = user_input("Enter the Live ID: ")
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setblocking(0)
s.bind(("", 0))
s.connect((opts.ip_addr, XBOX_PORT))
if ping:
print("Attempting to ping | Xbox for Live ID...")
s.send(bytearray.fromhex(XBOX_PING))
ready = select.select([s], [], [], 5)
if ready[0]:
data = s.recv(1024)
opts.live_id = data[199:215]
else:
print("Failed to ping Xbox, please enter Live ID manually")
opts.live_id = user_input("Enter the Live ID: ")
if isinstance(opts.live_id, str):
live_id = opts.live_id.encode()
else:
live_id = opts.live_id
power_packet = bytearray.fromhex(XBOX_POWER) + live_id + b'\x00'
print("Sending power on packets to " + opts.ip_addr)
for i in range(0, 5):
s.send(power_packet)
time.sleep(1)
print("Xbox should turn on now")
s.send(bytearray.fromhex(XBOX_PING))
ready = select.select([s], [], [], 5)
if ready[0]:
data = s.recv(1024)
opts.live_id = data[199:215]
print("Ping successful!")
print("Live ID = " + live_id.decode("utf-8"))
print("")
print("******************************************")
print("* Xbox running - Streaming now possible! *")
print("******************************************")
print("")
else:
print("Failed to ping Xbox - please try again! :(")
print("")
s.close()
def user_input(text):
response = ""
while response == "":
if py3:
response = input(text)
else:
response = raw_input(text)
return response
if __name__ == "__main__":
main()
|
atodorov/blivet | tests/clearpart_test.py | Python | gpl-2.0 | 9,228 | 0.000759 | import unittest
import mock
import blivet
from pykickstart.constants import CLEARPART_TYPE_ALL, CLEARPART_TYPE_LINUX, CLEARPART_TYPE_NONE
from parted import PARTITION_NORMAL
from blivet.flags import flags
DEVICE_CLASSES = [
blivet.devices.DiskDevice,
blivet.devices.PartitionDevice
]
@unittest.skipUnless(not any(x.unavailable_type_dependencies() for x in DEVICE_CLASSES), "some unsupported device classes required for this test")
class ClearPartTestCase(unittest.TestCase):
def setUp(self):
flags.testing = True
def test_should_clear(self):
""" Test the Blivet.should_clear method. """
b = blivet.Blivet()
DiskDevice = blivet.devices.DiskDevice
PartitionDevice = blivet.devices.PartitionDevice
# sda is a disk with an existing disklabel containing two partitions
sda = DiskDevice("sda", size=100000, exists=True)
sda.format = blivet.formats.get_format("disklabel", device=sda.path,
exists=True)
sda.format._parted_disk = mock.Mock()
sda.format._parted_device = mock.Mock()
sda.format._parted_disk.configure_mock(partitions=[])
b.devicetree._add_device(sda)
# sda1 is a partition containing an existing ext4 filesystem
sda1 = PartitionDevice("sda1", size=500, exists=True,
parents=[sda])
sda1._parted_partition = mock.Mock(**{'type': PARTITION_NORMAL,
'getFlag.return_value': 0})
sda1.format = blivet.formats.get_format("ext4", mountpoint="/boot",
device=sda1.path,
exists=True)
b.devicetree._add_device(sda1)
# sda2 is a partition containing an existing vfat filesystem
sda2 = PartitionDevice("sda2", size=10000, exists=True,
parents=[sda])
sda2._parted_partition = mock.Mock(**{'type': PARTITION_NORMAL,
'getFlag.return_value': 0})
sda2.format = blivet.formats.get_format("vfat", mountpoint="/foo",
device=sda2.path,
exists=True)
b.devicetree._add_device(sda2)
# sdb is an unpartitioned disk containing an xfs filesystem
sdb = DiskDevice("sdb", size=100000, exists=True)
sdb.format = blivet.formats.get_format("xfs", device=sdb.path,
exists=True)
b.devicetree._add_device(sdb)
# sdc is an unformatted/uninitialized/empty disk
sdc = DiskDevice("sdc", size=100000, exists=True)
b.devicetree._add_device(sdc)
# sdd is a disk containing an existing disklabel with no partitions
sdd = DiskDevice("sdd", size=100000, exists=True)
sdd.format = blivet.formats.get_format("disklabel", device=sdd.path,
exists=True)
b.devicetree._add_device(sdd)
#
# clearpart type none
#
b.config.clear_part_type = CLEARPART_TYPE_NONE
self.assertFalse(b.should_clear(sda1),
msg="type none should not clear any partitions")
self.assertFalse(b.should_clear(sda2),
msg="type none should not clear any partitions")
b.config.initialize_disks = False
self.assertFalse(b.should_clear(sda),
msg="type none should not clear non-empty disks")
self.assertFalse(b.should_clear(sdb),
msg="type none should not clear formatting from " |
"unpartitioned disks")
self.assertFalse(b.should_clear(sdc),
msg="type none should not clear empty disk without "
"initlabel")
self.assertFalse(b.should_clear(sdd),
msg="type none should not clear empty partition table "
"without initlabel")
b.config.initialize_dis | ks = True
self.assertFalse(b.should_clear(sda),
msg="type none should not clear non-empty disks even "
"with initlabel")
self.assertFalse(b.should_clear(sdb),
msg="type non should not clear formatting from "
"unpartitioned disks even with initlabel")
self.assertTrue(b.should_clear(sdc),
msg="type none should clear empty disks when initlabel "
"is set")
self.assertTrue(b.should_clear(sdd),
msg="type none should clear empty partition table when "
"initlabel is set")
#
# clearpart type linux
#
b.config.clear_part_type = CLEARPART_TYPE_LINUX
self.assertTrue(b.should_clear(sda1),
msg="type linux should clear partitions containing "
"ext4 filesystems")
self.assertFalse(b.should_clear(sda2),
msg="type linux should not clear partitions "
"containing vfat filesystems")
b.config.initialize_disks = False
self.assertFalse(b.should_clear(sda),
msg="type linux should not clear non-empty disklabels")
self.assertTrue(b.should_clear(sdb),
msg="type linux should clear linux-native whole-disk "
"formatting regardless of initlabel setting")
self.assertFalse(b.should_clear(sdc),
msg="type linux should not clear unformatted disks "
"unless initlabel is set")
self.assertFalse(b.should_clear(sdd),
msg="type linux should not clear disks with empty "
"partition tables unless initlabel is set")
b.config.initialize_disks = True
self.assertFalse(b.should_clear(sda),
msg="type linux should not clear non-empty disklabels")
self.assertTrue(b.should_clear(sdb),
msg="type linux should clear linux-native whole-disk "
"formatting regardless of initlabel setting")
self.assertTrue(b.should_clear(sdc),
msg="type linux should clear unformatted disks when "
"initlabel is set")
self.assertTrue(b.should_clear(sdd),
msg="type linux should clear disks with empty "
"partition tables when initlabel is set")
sda1.protected = True
self.assertFalse(b.should_clear(sda1),
msg="protected devices should never be cleared")
self.assertFalse(b.should_clear(sda),
msg="disks containing protected devices should never "
"be cleared")
sda1.protected = False
#
# clearpart type all
#
b.config.clear_part_type = CLEARPART_TYPE_ALL
self.assertTrue(b.should_clear(sda1),
msg="type all should clear all partitions")
self.assertTrue(b.should_clear(sda2),
msg="type all should clear all partitions")
b.config.initialize_disks = False
self.assertTrue(b.should_clear(sda),
msg="type all should initialize all disks")
self.assertTrue(b.should_clear(sdb),
msg="type all should initialize all disks")
self.assertTrue(b.should_clear(sdc),
msg="type all should initialize all disks")
self.assertTrue(b.should_clear(sdd),
msg="type all should initialize all disks")
b.config.initialize_disks = True
self.assertTrue(b.should_clear(sda),
msg="type all should initialize all disks")
self.assertTrue(b.should_cle |
HybridF5/tempest_debug | tempest/lib/services/compute/limits_client.py | Python | apache-2.0 | 1,138 | 0 | # Copyright 2012 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.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, ei | ther express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_serialization import jsonutils as json
from tempest.lib.api_schema.response.compute.v2_1 import limits as schema
from tempest.lib.common import rest_client
from tempest.lib.services.compute import base_compute_client
class LimitsClient(base_compute_client.BaseComputeClient):
def s | how_limits(self):
resp, body = self.get("limits")
body = json.loads(body)
self.validate_response(schema.get_limit, resp, body)
return rest_client.ResponseBody(resp, body)
|
UstadMobile/exelearning-ustadmobile-work | twisted/persisted/styles.py | Python | gpl-2.0 | 27,358 | 0.007932 | # -*- test-case-name: twisted.test.test_persisted -*-
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Different styles of persisted objects.
"""
# System Imports
import types
import copy_reg
import copy
try:
import cStringIO as StringIO
except ImportError:
import StringIO
from exe import globals as G
from exe.engine.path import Path
# Use the eXe logger directly:
import logging
log = logging.getLogger(__name__)
try:
from new import instancemethod
except:
from org.python.core import PyMethod
instancemethod = PyMethod
oldModules = {}
## First, let's register support for some stuff that really ought to
## be registerable...
def pickleMethod(method):
'support function for copy_reg to pickle method refs'
return unpickleMethod, (method.im_func.__name__,
method.im_self,
method.im_class)
def unpickleMethod(im_name,
im_self,
im_class):
'support function for copy_reg to unpickle method refs'
try:
unbound = getattr(im_class,im_name)
if im_self is None:
return unbound
bound=instancemethod(unbound.im_func,
im_self,
im_class)
return bound
except AttributeError:
log.error("Method" + im_name + "not on class" + im_class)
assert im_self is not None,"No recourse: no instance to guess from."
# Attempt a common fix before bailing -- if classes have
# changed around since we pickled this method, we may still be
# able to get it by looking on the instance's current class.
unbound = getattr(im_self.__class__,im_name)
log.error("Attempting fixup with" + unbound)
if im_self is None:
return unbound
bound=instancemethod(unbound.im_func,
im_self,
im_self.__class__)
return bound
copy_reg.pickle(types.MethodType,
pickleMethod,
unpickleMethod)
def pickleModule(module):
'support function for copy_reg to pickle module refs'
return unpickleModule, (module.__name__,)
def unpickleModule(name):
'support function for copy_reg to unpickle module refs'
if oldModules.has_key(name):
log.info("Module has moved: " + name)
name = oldModules[name]
log.info(name)
return __import__(name,{},{},'x')
copy_reg.pickle(types.ModuleType,
pickleModule,
unpickleModule)
def pickleStringO(stringo):
'support function for copy_reg to pickle StringIO.OutputTypes'
return unpickleStringO, (stringo.getvalue(), stringo.tell())
def unpickleStringO(val, sek):
x = StringIO.StringIO()
x.write(val)
x.seek(sek)
return x
if hasattr(StringIO, 'OutputType'):
copy_reg.pickle(StringIO.OutputType,
pickleStringO,
unpickleStringO)
def pickleStringI(stringi):
return unpickleStringI, (stringi.getvalue(), stringi.tell())
def unpickleStringI(val, sek):
x = StringIO.StringIO(val)
x.seek(sek)
return x
if hasattr(StringIO, 'InputType'):
copy_reg.pickle(StringIO.InputType,
pickleStringI,
unpickleStringI)
class Ephemeral:
"""
This type of object is never persisted; if possible, even references to it
are eliminated.
"""
def __getstate__(self):
log.warn( "WARNING: serializing ephemeral " + self )
import gc
for r in gc.get_referrers(self):
log.warn( " referred to by " + (r,))
return None
def __setstate__(self, state):
log.warn( "WARNING: unserializing ephemeral " + self.__class__ )
self.__class__ = Ephemeral
versionedsToUpgrade = {}
upgraded = {}
def doUpgrade(newPackage=None, isMerge=False, preMergePackage=None):
global versionedsToUpgrade, upgraded
# prepare to save the maximum field ID seen upon load,
# so that it can be set AFTER load, when the Field class is available:
G.application.maxFieldId = 1
try:
# Two-pass system for merges, to be sure that no old/corrupt files
# cause any problems, since we don't actually have a rollback system:
if isMerge:
# just check all the objects, but don't actually change any | ,
# letting any exception stop this before the real requireUpgrade()
log.debug("doUpgrade performing a pre-Merge safety check.")
for versioned in versionedsToUpgrade.values():
requireUpgrade(versioned, new | Package,
isMerge, preMergePackage, mergeCheck=True)
log.debug("doUpgrade completed the pre-Merge safety check.")
for versioned in versionedsToUpgrade.values():
requireUpgrade(versioned, newPackage,
isMerge, preMergePackage, mergeCheck=False)
except Exception, exc:
# clear out any remaining upgrades before continuing:
versionedsToUpgrade = {}
upgraded = {}
raise
versionedsToUpgrade = {}
upgraded = {}
def requireUpgrade(obj, newPackage=None,
isMerge=False, preMergePackage=None, mergeCheck=False):
"""Require that a Versioned instance be upgraded completely first.
"""
objID = id(obj)
if objID in versionedsToUpgrade and objID not in upgraded:
if not mergeCheck:
upgraded[objID] = 1
obj.versionUpgrade(newPackage, isMerge, preMergePackage, mergeCheck)
return obj
from twisted.python import reflect
def _aybabtu(c):
l = []
for b in reflect.allYourBase(c, Versioned):
if b not in l and b is not Versioned:
l.append(b)
return l
class Versioned:
"""
This type of object is persisted with versioning information.
I have a single class attribute, the int persistenceVersion. After I am
unserialized (and styles.doUpgrade() is called), self.upgradeToVersionX()
will be called for each version upgrade I must undergo.
For example, if I serialize an instance of a Foo(Versioned) at version 4
and then unserialize it when the code is at version 9, the calls::
self.upgradeToVersion5()
self.upgradeToVersion6()
self.upgradeToVersion7()
self.upgradeToVersion8()
self.upgradeToVersion9()
will be made. If any of these methods are undefined, a warning message
will be printed.
"""
persistenceVersion = 0
persistenceForgets = ()
def __setstate__(self, state):
# Do NOT flag this object ToUpgrade if this setstate is called
# during a deepcopy during a package merge's copyToPackage().
# This is because the object has already been upgraded during its
# initial load, and does not need to be flagged for another upgrade:
if not G.application.persistNonPersistants:
versionedsToUpgrade[id(self)] = self
self.__dict__ = state
def __getstate__(self, dict=None):
"""Get state, adding a version number to it on its way out.
"""
dct = copy.copy(dict or self.__dict__)
bases = _aybabtu(self.__class__)
bases.reverse()
bases.append(self.__class__) # don't forget me!!
for base in bases:
if base.__dict__.has_key('persistenceForgets'):
for slot in base.persistenceForgets:
if dct.has_key(slot):
del dct[slot]
if base.__dict__.has_key('persistenceVersion'):
dct['%s.persistenceVersion' % reflect.qual(base)] = base.persistenceVersion
return dct
def versionUpgrade(self, newPackage=None,
isMerge=False, preMergePackage=None, mergeCheck=False):
"""(internal) Do a version upgrade.
"""
bases = _aybabtu(self.__class__)
# put the bases in order so superclasses' persistenceVersion methods
# will be called first.
bases.reverse()
bases.append(self.__class__) # don't forget me |
obi-two/Rebelion | data/scripts/templates/object/mobile/shared_dressed_commoner_old_human_male_02.py | Python | mit | 459 | 0.04793 | #### NO | TICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_dressed_commoner_old_human_male_02.iff"
result.attribute_template_id = 9
result.stfName("npc_name","human_base_male")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return re | sult |
sidzan/netforce | netforce_stock/netforce_stock/models/barcode_issue_line.py | Python | mit | 2,232 | 0.003584 | # Copyright (c) 2012-2015 Netforce Co. Ltd.
#
# Permission is hereby granted, free of charge, to any pers | on obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# co | pies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 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.
from netforce.model import Model, fields, get_model
class BarcodeIssueLine(Model):
_name = "barcode.issue.line"
_transient = True
_fields = {
"wizard_id": fields.Many2One("barcode.issue", "Wizard", required=True, on_delete="cascade"),
"product_id": fields.Many2One("product", "Product", required=True),
"qty": fields.Decimal("Qty", required=True),
"uom_id": fields.Many2One("uom", "UoM", required=True),
"qty2": fields.Decimal("Secondary Qty"),
"lot_id": fields.Many2One("stock.lot", "Lot / Serial Number"),
"container_from_id": fields.Many2One("stock.container", "From Container"),
"container_to_id": fields.Many2One("stock.container", "To Container"),
"location_from_id": fields.Many2One("stock.location", "From Location"),
"location_to_id": fields.Many2One("stock.location", "To Location"),
"related_id": fields.Reference([["sale.order", "Sales Order"], ["purchase.order", "Purchase Order"]], "Related To"),
"qty2": fields.Decimal("Qty2"),
"notes": fields.Text("Notes"),
}
BarcodeIssueLine.register()
|
fab13n/caracole | villes/migrations/0001_initial.py | Python | mit | 5,318 | 0.005641 | # Generated by Django 3.2 on 2021-08-25 20:55
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Ville',
fields=[
('id', models.IntegerField(db_column='ville_id', primary_key=True, serialize=False)),
('departement', models.CharField(blank=True, db_column='ville_departement', max_length=3, null=True)),
('slug', models.CharField(blank=True, db_column='ville_slug', max_length=255, null=True)),
('nom', models.CharField(blank=True, db_column='ville_nom', max_length=45, null=True)),
('nom_simple', models.CharField(blank=True, db_column='ville_nom_simple', max_length=45, null=True)),
('nom_reel', models.CharField(blank=True, db_column='ville_nom_reel', max_length=45, null=True)),
('nom_soundex', models.CharField(blank=True, db_column='ville_nom_soundex', max_length=20, null=True)),
('nom_metaphone', models.CharField(blank=True, db_column='ville_nom_metaphone', max_length=22, null=True)),
('code_postal', models.CharField(blank=True, db_column='ville_code_postal', max_length=255, null=True)),
('commune', models.CharField(blank=True, db_column='ville_commune', max_length=3, null=True)),
('code_commune', models.CharField(db_column='ville_code_commune', max_length=5)),
('arrondissement', models.IntegerField(blank=True, db_column='ville_arrondissement', null=True)),
('canton', models.CharField(blank | =True, db_column='ville_canton', max_length=4, null=True)),
('amdi', models.IntegerField(blank=True, db_column='ville_amdi', null=True)),
('population_2010', models.IntegerField(blank=True, db_column='ville_population_2010', null=True)),
('population_1999', models.IntegerField(blank=True, db_column='ville_population_1999', null=True)),
('population_2012', mod | els.IntegerField(blank=True, db_column='ville_population_2012', null=True)),
('densite_2010', models.IntegerField(blank=True, db_column='ville_densite_2010', null=True)),
('surface', models.FloatField(blank=True, db_column='ville_surface', null=True)),
('longitude_deg', models.FloatField(blank=True, db_column='ville_longitude_deg', null=True)),
('latitude_deg', models.FloatField(blank=True, db_column='ville_latitude_deg', null=True)),
('longitude_grd', models.CharField(blank=True, db_column='ville_longitude_grd', max_length=9, null=True)),
('latitude_grd', models.CharField(blank=True, db_column='ville_latitude_grd', max_length=8, null=True)),
('longitude_dms', models.CharField(blank=True, db_column='ville_longitude_dms', max_length=9, null=True)),
('latitude_dms', models.CharField(blank=True, db_column='ville_latitude_dms', max_length=8, null=True)),
('zmin', models.IntegerField(blank=True, db_column='ville_zmin', null=True)),
('zmax', models.IntegerField(blank=True, db_column='ville_zmax', null=True)),
],
options={
'db_table': 'villes_france_free',
},
),
migrations.AddIndex(
model_name='ville',
index=models.Index(fields=['departement'], name='departement_idx'),
),
migrations.AddIndex(
model_name='ville',
index=models.Index(fields=['slug'], name='slug_idx'),
),
migrations.AddIndex(
model_name='ville',
index=models.Index(fields=['nom'], name='nom_idx'),
),
migrations.AddIndex(
model_name='ville',
index=models.Index(fields=['nom_simple'], name='nom_simple_idx'),
),
migrations.AddIndex(
model_name='ville',
index=models.Index(fields=['nom_reel'], name='nom_reel_idx'),
),
migrations.AddIndex(
model_name='ville',
index=models.Index(fields=['nom_soundex'], name='nom_soundex_idx'),
),
migrations.AddIndex(
model_name='ville',
index=models.Index(fields=['nom_metaphone'], name='nom_metaphone_idx'),
),
migrations.AddIndex(
model_name='ville',
index=models.Index(fields=['code_postal'], name='code_postal_idx'),
),
migrations.AddIndex(
model_name='ville',
index=models.Index(fields=['commune'], name='commune_idx'),
),
migrations.AddIndex(
model_name='ville',
index=models.Index(fields=['code_commune'], name='code_commune_idx'),
),
migrations.AddIndex(
model_name='ville',
index=models.Index(fields=['arrondissement'], name='arrondissement_idx'),
),
migrations.AddIndex(
model_name='ville',
index=models.Index(fields=['canton'], name='canton_idx'),
),
migrations.AddIndex(
model_name='ville',
index=models.Index(fields=['amdi'], name='amdi_idx'),
),
]
|
webbhm/OpenAg_MVP_UI | MVP_UI/python/temp_chart.py | Python | mit | 966 | 0.012422 | # /usr/bin/env python
import pygal
import requests
import json
#Use a view in CouchDB to get the data
#use the first key for attribute type
#order descending so when limit the results will get the latest at the top
r = requests.get('http://127.0.0.1:5984/mvp_sensor_data/_design/doc/_view/attribute_value?startkey=["temperature",{}]&endkey=["temperature"]&descending=true&limit=60')
#print(r)
v_lst = [float(x['value']['value']) for x in r.json()['rows']]
#print(v_lst)
ts_lst = [x['value']['timestamp'] for x in r.json()['rows']]
#print(ts_lst)
line_chart = pygal.Line()
line_chart.title = 'Temperature'
line_chart.y_title="Degrees C"
line_chart.x_title="Timestamp (hover over to display date)"
#need to reverse order to go from earliest to latest
ts_lst.reverse | ()
line_chart.x_labels = ts_lst
#need to reverse order to go from earliest to latest
v_lst.reverse()
li | ne_chart.add('Air Temp', v_lst)
line_chart.render_to_file('/home/pi/MVP_UI/web/temp_chart.svg')
|
ministryofjustice/manchester_traffic_offences_pleas | apps/plea/views.py | Python | mit | 8,700 | 0.002069 | import datetime
import json
from brake.decorators import ratelimit
from django.utils.decorators import method_decorator
from django.utils.translation import get_language
from django.conf import settings
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import redirect
from django.views.generic import FormView
from django.template import RequestContext
import logging
logger = logging.getLogger(__name__)
from django.contrib.admin.views.decorators import staff_member_required
from apps.forms.stages import MultiStageForm
from apps.forms.views import StorageView
from make_a_plea.helpers import (
filter_cases_by_month,
get_supported_language_from_request,
parse_date_or_400,
staff_or_404,
)
from .models import Case, Court, CaseTracker
from .forms import CourtFinderForm
from .stages import (URNEntryStage,
AuthenticationStage,
NoticeTypeStage,
CaseStage,
YourDetailsStage,
CompanyDetailsStage,
PleaStage,
YourStatusStage,
YourEmploymentStage,
YourSelfEmploymentStage,
YourOutOfWorkBenefitsStage,
AboutYourIncomeStage,
YourBenefitsStage,
YourPensionCreditStage,
YourIncomeStage,
HardshipStage,
HouseholdExpensesStage,
OtherExpensesStage,
CompanyFinancesStage,
ReviewStage,
CompleteStage)
from .fields import ERROR_MESSAGES
class PleaOnlineForms(MultiStageForm):
url_name = "plea_form_step"
stage_classes = [URNEntryStage,
AuthenticationStage,
NoticeTypeStage,
CaseStage,
YourDetailsStage,
CompanyDetailsStage,
PleaStage,
YourStatusStage,
YourEmploymentStage,
YourSelfEmploymentStage,
YourOutOfWorkBenefitsStage,
AboutYourIncomeStage,
YourBenefitsStage,
YourPensionCreditStage,
YourIncomeStage,
HardshipStage,
HouseholdExpensesStage,
OtherExpensesStage,
CompanyFinancesStage,
ReviewStage,
CompleteStage]
def __init__(self, *args, **kwargs):
super(PleaOnlineForms, self).__init__(*args, **kwargs)
self._urn_invalid = False
def save(self, *args, **kwargs):
"""
Check that the URN has not already been used.
"""
saved_urn = self.all_data.get("case", {}).get("urn")
saved_first_name = self.all_data.get("your_details", {}).get("first_name")
saved_last_name = self.all_data.get("your_details", {}).get("last_name")
if all([
saved_urn,
saved_first_name,
saved_last_name,
not Case.objects.can_use_urn(saved_urn, saved_first_name, saved_last_name)
]):
self._urn_invalid = True
else:
return super(PleaOnlineForms, self).save(*args, **kwargs)
def render(self, request, request_context=None):
request_context = request_context if request_context else {}
if self._urn_invalid:
return redirect("urn_already_used")
return super(PleaOnlineForms, self).render(request)
class PleaOnlineViews(StorageView):
start = "enter_urn"
def __init__(self, *args, **kwargs):
super(PleaOnlineViews, self).__init__(*args, **kwargs)
self.index = None
self.storage = None
def dispatch(se | lf, request, *args, **kwargs):
# If the session has timed out, redirect to start page
if all([
not request.session.get("plea_data"),
kwargs.get("stage | ", self.start) != self.start,
]):
return HttpResponseRedirect("/")
# Store the index if we've got one
idx = kwargs.pop("index", None)
try:
self.index = int(idx)
except (ValueError, TypeError):
self.index = 0
# Load storage
self.storage = self.get_storage(request, "plea_data")
return super(PleaOnlineViews, self).dispatch(request, *args, **kwargs)
def get(self, request, stage=None):
if not stage:
stage = PleaOnlineForms.stage_classes[0].name
return HttpResponseRedirect(reverse_lazy("plea_form_step", args=(stage,)))
form = PleaOnlineForms(self.storage, stage, self.index)
case_redirect = form.load(RequestContext(request))
if case_redirect:
return case_redirect
form.process_messages(request)
if stage == "complete":
self.clear_storage(request, "plea_data")
return form.render(request)
@method_decorator(ratelimit(block=True, rate=settings.RATE_LIMIT))
def post(self, request, stage):
nxt = request.GET.get("next", None)
form = PleaOnlineForms(self.storage, stage, self.index)
form.save(request.POST, RequestContext(request), nxt)
if not form._urn_invalid:
form.process_messages(request)
request.session.modified = True
return form.render(request)
def render(self, request, request_context=None):
request_context = request_context if request_context else {}
return super(PleaOnlineViews, self).render(request)
class UrnAlreadyUsedView(StorageView):
template_name = "urn_used.html"
def post(self, request):
del request.session["plea_data"]
return redirect("plea_form_step", stage="case")
class CourtFinderView(FormView):
template_name = "court_finder.html"
form_class = CourtFinderForm
def form_valid(self, form):
try:
court = Court.objects.get_court_dx(form.cleaned_data["urn"])
except Court.DoesNotExist:
court = False
return self.render_to_response(
self.get_context_data(
form=form,
court=court,
submitted=True,
)
)
@staff_or_404
def stats(request):
"""
Generate usage statistics (optionally by language) and send via email
"""
filter_params = {
"sent": True,
"language": get_supported_language_from_request(request),
}
if "end_date" in request.GET:
end_date = parse_date_or_400(request.GET["end_date"])
else:
now = datetime.datetime.utcnow()
last_day_of_last_month = now - datetime.timedelta(days=now.day)
end_date = datetime.datetime(
last_day_of_last_month.year,
last_day_of_last_month.month,
last_day_of_last_month.day,
23, 59, 59)
filter_params["completed_on__lte"] = end_date
if "start_date" in request.GET:
start_date = parse_date_or_400(request.GET["start_date"])
else:
start_date = datetime.datetime(1970, 1, 1)
filter_params["completed_on__gte"] = start_date
journies = Case.objects.filter(**filter_params).order_by("completed_on")
count = journies.count()
journies_by_month = filter_cases_by_month(journies)
earliest_journey = journies[0] if journies else None
latest_journey = journies.reverse()[0] if journies else None
response = {
"summary": {
"language": filter_params["language"],
"total": count,
"start_date": start_date.isoformat(),
"end_date": end_date.isoformat(),
"earliest_journey": earliest_journey.completed_on.isoformat() if earliest_journey else None,
"latest_journey": latest_journey.completed_on.isoformat() if latest_journey else None,
"by_month": journies_by_month,
},
"latest_example": {
|
Mezgrman/TweetPony | setup.py | Python | agpl-3.0 | 1,186 | 0.029511 | #!/usr/bin/env python
# Copyright 2013-2015 Julian Metzler
"""
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, 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
GN | U Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from setuptools import setup, find_packages
metadata = {}
with open('tweetpony/metadata.py') as f:
exec(f.read(), metadata)
setup(
name = metadata['name'],
version = metadata['version'],
description = metadata['description'],
license = metadata['license'],
author = metadata['author'],
author_email = metadata['author_email'],
install_requires = metadata['requires'],
url = metadata['url'],
keywords = metadata['keywords'],
packages = find_packages(),
use_2to3 = True,
) |
lmazuel/azure-sdk-for-python | azure-mgmt-monitor/azure/mgmt/monitor/models/activity_log_alert_resource.py | Python | mit | 3,303 | 0.000606 | # 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 may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .resource import Resource
class ActivityLogAlertResource(Resource):
"""An activity log alert resource.
Variables are only populated by the server, and will be ignored when
sending a request.
All required parameters must be populated in order to send to Azure.
:ivar id: Azure resource Id
:vartype id: str
:ivar name: Azure resource name
:vartype name: str
:ivar type: Azure resource type
:vartype type: str
:param location: Required. Resource location
:type location: str
:param tags: Resource tags |
:type tags: dict[str, str]
:param scopes: Required. A list of resourceIds that will be used as
prefixes. The alert will only apply to activityLogs with resourceIds that
fall under one of these prefixes. This list must include at least one
item.
:type scopes: list[str]
:param enabled: Indicates whether this activity log alert is enabled. If
an activity log alert is not enabled, then none of its actions will be
activated. Default value: True .
| :type enabled: bool
:param condition: Required. The condition that will cause this alert to
activate.
:type condition: ~azure.mgmt.monitor.models.ActivityLogAlertAllOfCondition
:param actions: Required. The actions that will activate when the
condition is met.
:type actions: ~azure.mgmt.monitor.models.ActivityLogAlertActionList
:param description: A description of this activity log alert.
:type description: str
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'location': {'required': True},
'scopes': {'required': True},
'condition': {'required': True},
'actions': {'required': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'scopes': {'key': 'properties.scopes', 'type': '[str]'},
'enabled': {'key': 'properties.enabled', 'type': 'bool'},
'condition': {'key': 'properties.condition', 'type': 'ActivityLogAlertAllOfCondition'},
'actions': {'key': 'properties.actions', 'type': 'ActivityLogAlertActionList'},
'description': {'key': 'properties.description', 'type': 'str'},
}
def __init__(self, **kwargs):
super(ActivityLogAlertResource, self).__init__(**kwargs)
self.scopes = kwargs.get('scopes', None)
self.enabled = kwargs.get('enabled', True)
self.condition = kwargs.get('condition', None)
self.actions = kwargs.get('actions', None)
self.description = kwargs.get('description', None)
|
davidbgk/udata | udata/core/dataset/factories.py | Python | agpl-3.0 | 1,823 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import factory
from udata.factories import ModelFactory
from .models import Dataset, Resource, Checksum, CommunityResource, License
from udata.core.organization.factories import OrganizationFactory
fro | m udata.core.spatial.factories import SpatialCoverageFactory
class DatasetFactory(ModelFactory):
class Meta:
model = Dataset
title = factory.Faker('sentence')
description = factory.Faker('text')
frequency = 'unknown'
class Params:
geo = factory.Trait(
spatial=factory.SubFactory(SpatialCoverageFactory)
)
v | isible = factory.Trait(
resources=factory.LazyAttribute(lambda o: [ResourceFactory()])
)
org = factory.Trait(
organization=factory.SubFactory(OrganizationFactory),
)
class VisibleDatasetFactory(DatasetFactory):
@factory.lazy_attribute
def resources(self):
return [ResourceFactory()]
class ChecksumFactory(ModelFactory):
class Meta:
model = Checksum
type = 'sha1'
value = factory.Faker('sha1')
class BaseResourceFactory(ModelFactory):
title = factory.Faker('sentence')
description = factory.Faker('text')
filetype = 'file'
url = factory.Faker('url')
checksum = factory.SubFactory(ChecksumFactory)
mime = factory.Faker('mime_type', category='text')
filesize = factory.Faker('pyint')
class CommunityResourceFactory(BaseResourceFactory):
class Meta:
model = CommunityResource
class ResourceFactory(BaseResourceFactory):
class Meta:
model = Resource
class LicenseFactory(ModelFactory):
class Meta:
model = License
id = factory.Faker('unique_string')
title = factory.Faker('sentence')
url = factory.Faker('uri')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.