blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
616
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
112
| license_type
stringclasses 2
values | repo_name
stringlengths 5
115
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 777
values | visit_date
timestamp[us]date 2015-08-06 10:31:46
2023-09-06 10:44:38
| revision_date
timestamp[us]date 1970-01-01 02:38:32
2037-05-03 13:00:00
| committer_date
timestamp[us]date 1970-01-01 02:38:32
2023-09-06 01:08:06
| github_id
int64 4.92k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-04 01:52:49
2023-09-14 21:59:50
⌀ | gha_created_at
timestamp[us]date 2008-05-22 07:58:19
2023-08-21 12:35:19
⌀ | gha_language
stringclasses 149
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 3
10.2M
| extension
stringclasses 188
values | content
stringlengths 3
10.2M
| authors
listlengths 1
1
| author_id
stringlengths 1
132
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d345d8aabf75c5430dee2cf383acce3e60f7f9b0 | b85ee3f4d308a3e0022938379fbcac3186d789bc | /hanishbot.py | fb412df1ad3c1929b3f3174963a995c346d7dc27 | [
"MIT"
]
| permissive | waffle-iron/hanish | 7f007f8e13237dea85a2c654d811836f0896f3e0 | 472afcb70ffe92517412c4211e6d44b51117922f | refs/heads/master | 2021-01-20T14:39:59.114026 | 2017-05-08T15:32:25 | 2017-05-08T15:32:25 | 90,644,193 | 0 | 0 | null | 2017-05-08T15:32:24 | 2017-05-08T15:32:24 | null | UTF-8 | Python | false | false | 1,665 | py | #!/usr/bin/env python
# hanishbot
# Primary entry point and application runner for the Hanish bot.
#
# Author: Benjamin Bengfort <[email protected]>
# Created: Mon May 08 11:15:40 2017 -0400
#
# Copyright (C) 2016 Bengfort.com
# For license information, see LICENSE.txt
#
# ID: hanishbot.py [] [email protected] $
"""
Primary entry point and application runner for the Hanish bot.
"""
##########################################################################
## Imports
##########################################################################
import dotenv
import hanish
import argparse
##########################################################################
## Command Arguments
##########################################################################
LOAD_DOTENV = True
DESCRIPTION = "A slackbot that makes small talk about the weather."
VERSION = "hanishbot v{}".format(hanish.get_version())
EPILOG = "Please report bugs or issues to github.com/bbengfort/hanish"
##########################################################################
## Main Method
##########################################################################
if __name__ == '__main__':
# Load the environment from the .env file
if LOAD_DOTENV:
dotenv.load_dotenv(dotenv.find_dotenv())
# Create the command line argument parser
parser = argparse.ArgumentParser(
description=DESCRIPTION, version=VERSION, epilog=EPILOG,
)
# Parse the arguments and execute the command
args = parser.parse_args()
try:
print("stub implementation")
parser.exit(0)
except Exception as e:
parser.error(str(e))
| [
"[email protected]"
]
| |
1a9de8a30bb18f7229e11115f93570d7aae04915 | bb33e6be8316f35decbb2b81badf2b6dcf7df515 | /source/res/scripts/common/visual_script/balance.py | 7d8f549f7593d5fa9a6341d037304211641b92f3 | []
| no_license | StranikS-Scan/WorldOfTanks-Decompiled | 999c9567de38c32c760ab72c21c00ea7bc20990c | d2fe9c195825ececc728e87a02983908b7ea9199 | refs/heads/1.18 | 2023-08-25T17:39:27.718097 | 2022-09-22T06:49:44 | 2022-09-22T06:49:44 | 148,696,315 | 103 | 39 | null | 2022-09-14T17:50:03 | 2018-09-13T20:49:11 | Python | UTF-8 | Python | false | false | 8,334 | py | # Python bytecode 2.7 (decompiled from Python 2.7)
# Embedded file name: scripts/common/visual_script/balance.py
import BigWorld
import sys
from block import Meta, Block, InitParam, buildStrKeysValue, EDITOR_TYPE
from slot_types import SLOT_TYPE, arrayOf
from type import VScriptStruct, VScriptStructField
from visual_script.misc import errorVScript
import ResMgr
import constants
import nations
_IS_VSE_EDITOR = sys.executable.endswith('vscript_editor.exe') or sys.executable.endswith('vscript_validator.exe')
constants.IS_EDITOR = constants.IS_EDITOR and not _IS_VSE_EDITOR
import items.vehicles as iv
_dataSection = None
_gList = None
class VsePaths(object):
def __enter__(self):
if _IS_VSE_EDITOR:
self.prevArenaPath = constants.ARENA_TYPE_XML_PATH
self.prevItemDefPath = constants.ITEM_DEFS_PATH
self.prevTypeXMLType = iv._VEHICLE_TYPE_XML_PATH
constants.ARENA_TYPE_XML_PATH = '../../../res/wot/scripts/arena_defs/'
constants.ITEM_DEFS_PATH = '../../../res/wot/scripts/item_defs/'
iv._VEHICLE_TYPE_XML_PATH = constants.ITEM_DEFS_PATH + 'vehicles/'
def __exit__(self, exc_type, exc_val, exc_tb):
if _IS_VSE_EDITOR:
constants.ARENA_TYPE_XML_PATH = self.prevArenaPath
constants.ITEM_DEFS_PATH = self.prevItemDefPath
iv._VEHICLE_TYPE_XML_PATH = self.prevTypeXMLType
def cache():
if not iv.g_cache:
with VsePaths():
from items import init
init(False, None)
from items.vehicles import init
init(False, None)
return iv.g_cache
def getVehicleList(naton):
if not iv.g_list:
cache()
return iv.g_list(naton)
def eqDataSection(eqName):
global _dataSection
if not _dataSection:
if constants.IS_CELLAPP or constants.IS_CLIENT:
xmlPath = constants.ITEM_DEFS_PATH
else:
xmlPath = '../../../res/wot/scripts/item_defs/'
xmlPath += 'vehicles/common/equipments.xml'
_dataSection = ResMgr.openSection(xmlPath)
ds = ResMgr.DataSection(eqName)
ds.copy(_dataSection[eqName])
return ds
def getArtefact(name):
return cache().equipments()[cache().equipmentIDs()[name]]
class EquipmentMeta(Meta):
@classmethod
def blockColor(cls):
pass
@classmethod
def blockCategory(cls):
pass
@classmethod
def blockIcon(cls):
pass
class ConfigParamStruct(VScriptStruct):
name = VScriptStructField('name', SLOT_TYPE.STR)
value = VScriptStructField('value', SLOT_TYPE.STR)
def __repr__(self):
return 'ConfigParam(name = {}, value = {})'.format(self.name, self.value)
class ReloadClientPlan(Block, EquipmentMeta):
def __init__(self, *args, **kwargs):
super(ReloadClientPlan, self).__init__(*args, **kwargs)
self._inSlot = self._makeEventInputSlot('in', self._execute)
self._out = self._makeEventOutputSlot('out')
def _execute(self):
if constants.IS_CELLAPP:
def reloader(*args):
for avatar in BigWorld.entities.valuesOfType('Avatar', 0):
if avatar.isClientConnected:
self._writeLog('send reload to client {}'.format(avatar.id))
avatar.ownClient.showDevelopmentInfo(100, '')
BigWorld.addTimer(reloader, 1.0)
self._out.call()
class ResMgrSpy(object):
def __init__(self, block, params):
self.spyParams = params
self.__spyParamsPaths = []
self.__block = block
import sys
sys.settrace(None)
sys.settrace(self.traceCalls)
return
def stop(self):
import sys
sys.settrace(None)
return
def traceCalls(self, frame, event, arg):
self.__traceCalls(frame, event)
return self.traceCalls
def __traceCalls(self, frame, event):
if event != 'call':
return
co = frame.f_code
if not co.co_name.startswith('read'):
return
l = frame.f_locals
if 'section' not in l or 'subsectionName' not in l:
return
attr = self.__path(l['section']) + l['subsectionName']
self.spyParams.discard(attr)
def __path(self, section):
if section.name == 'script':
return ''
parent = section.parentSection()
return '' if not parent else self.__path(parent) + section.name + '/'
class IntCompDescrDecoder(Block, EquipmentMeta):
def __init__(self, *args, **kwargs):
super(IntCompDescrDecoder, self).__init__(*args, **kwargs)
self._intCDs = self._makeDataInputSlot('incCD', arrayOf(SLOT_TYPE.INT))
def captionText(self):
pass
def __parseCDs(self):
cache()
from items import vehicles, ITEM_TYPE_NAMES
err = ''
results = []
for intCD in self._intCDs.getValue():
try:
itemTypeID, nationID, vehID = vehicles.parseIntCompactDescr(intCD)
item = vehicles.getItemByCompactDescr(intCD)
except Exception as e:
err += '{}: {}\n'.format(intCD, e)
results.append(err)
continue
results.append('{} {} {}\n'.format(intCD, (nations.NAMES[nationID], ITEM_TYPE_NAMES[itemTypeID], vehID), item.name))
return (results, err)
def _execute(self):
pass
def validate(self):
results, err = self.__parseCDs()
for res in results:
self._writeLog(res)
return err
class EquipmentParams(Block, EquipmentMeta):
def __init__(self, *args, **kwargs):
super(EquipmentParams, self).__init__(*args, **kwargs)
self.eqName = self._getInitParams()
self._inSlot = self._makeEventInputSlot('in', self._execute)
self._params = self._makeDataInputSlot('Parameters', arrayOf('ConfigParamStruct'))
self._out = self._makeEventOutputSlot('out')
def captionText(self):
return self.eqName
@classmethod
def initParams(cls):
return [InitParam('EquipmentName', SLOT_TYPE.STR, buildStrKeysValue('large_repairkit_battle_royale', 'regenerationKit', 'arcade_minefield_battle_royale', 'healPoint', 'selfBuff', 'trappoint', 'afterburning_battle_royale', 'repairpoint', 'arcade_bomber_battle_royale', 'spawn_kamikaze', 'arcade_smoke_battle_royale_with_damage', 'berserker', 'fireCircle', 'adaptationHealthRestore', 'corrodingShot', 'clingBrander', 'thunderStrike', 'shotPassion'), EDITOR_TYPE.STR_KEY_SELECTOR)]
def _execute(self):
self._writeLog('_execute {}'.format(self._params.getValue()))
errString = self._processParams()
if errString:
return errorVScript(self, errString)
else:
if constants.IS_CELLAPP:
from items.vehicles import g_cache
import InfluenceZone
eqExtra = g_cache.commonConfig['extrasDict'].get(self.eqName)
if eqExtra:
eqExtra._readConfig(None, None)
self._out.call()
return
def validate(self):
return self._processParams()
def _processParams(self):
if not self._params.getValue():
return ''
else:
import sys
self._writeLog('_processParams {}'.format((self._params.getValue(), sys.executable)))
spy = None
try:
try:
equipment = getArtefact(self.eqName)
equipmentSection = eqDataSection(self.eqName)
section = equipmentSection['script']
for param in self._params.getValue():
if not param.name:
continue
section.writeString(param.name, param.value)
if _IS_VSE_EDITOR:
spy = ResMgrSpy(self, {param.name for param in self._params.getValue()})
equipment.init(None, equipmentSection)
except Exception as e:
return 'error {}'.format(e)
finally:
if spy:
spy.stop()
return 'Were not read {}'.format(spy.spyParams) if spy and spy.spyParams else ''
| [
"[email protected]"
]
| |
57e75f26ee80bfea08e6b5076b340fb659ece915 | f8ad6963bfc851657ea50c6a036cfad29cdd7f60 | /Books/GodOfPython/P00_OriginalSource/ch16/ThreadServer.py | dab8cdf02274a063c8c05da2430fcaa1f42a73b4 | []
| no_license | foru120/PythonRepository | e1ab0265c0f50ef2e9acdf7447237c913560692b | db6b6be0f9fb91b0a81a3b6a2ec5631daab10f98 | refs/heads/master | 2021-01-01T06:53:11.728109 | 2019-04-25T13:52:50 | 2019-04-25T13:52:50 | 97,541,222 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,101 | py | #ThreadServer.py
from socket import *
import threading #쓰레드를 사용하기 위해
sevip = '127.0.0.1'
sevport = 62581
address = (sevip, sevport)
sevsock = socket(AF_INET, SOCK_STREAM)
sevsock.bind(address)
sevsock.listen()
print("waiting for connection...")
clisock , cliaddr = sevsock.accept()
print("connection from {}".format(cliaddr))
print("If you want to leave chat, just type !quit\n")
#쓰레드에서 실행될 코드를 담은 함수를 정의
def receive():
global clisock
while True:
data = clisock.recv(1024)
print(data.decode("UTF-8"), " *from Client")
clisock.close()
thread_recv = threading.Thread(target = receive, args = ()) #쓰레드 생성
thread_recv.start() #쓰레드 시작
while True:
try:
data = input("")
except KeyboardInterrupt:
break
if data =='!quit' or '': #!quit를 입력하면 while루프를 끝낸다.
clisock.close()
break
clisock.send(bytes(data,"UTF-8"))
sevsock.close()
print("disconnected")
| [
"[email protected]"
]
| |
530f3e39a4f1874f054c822946fcc627683d1f44 | ee730a381ef8113efedc62541f576393180b8f3e | /study/exceltest.py | 11394000d715ae7256d135d624944609d047e5b1 | []
| no_license | happy789450/python | b17357232cfb004757b82cb880ddb5f208aec443 | 05de30bf82db6a93e93a93c5158a6d23a7fb2390 | refs/heads/master | 2023-04-11T10:33:26.340610 | 2021-04-24T05:52:56 | 2021-04-24T05:52:56 | 348,461,701 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 297 | py | import datetime
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws['A2'] = 1
# ws.append([1, 2, 3])
# ws.append([2, 2, 3])
# ws['A2'] = datetime.datetime.now()
# ws.append([datetime.datetime.now()])
# ws['A3'] = 666
# ws['A5'] = 'aaa'
wb.save("/home/rice/桌面/test/sample.xlsx") | [
"[email protected]"
]
| |
01713593bf73d9c8417c6c76a052d1b48e4e8f08 | e98e7b45d85273797cf9f15e92fbe685a05bde18 | /编码/0091.py | 225393e7141d14cd27e7bed8e70a2df295c04195 | []
| no_license | wangdexinpython/test | 8d29d30e099f64f831b51265db7092d520df253c | a047148409e31b8a8140f2c13b959aa54ec14d0d | refs/heads/master | 2020-09-11T05:10:49.041795 | 2019-12-31T07:47:41 | 2019-12-31T07:47:41 | 221,948,822 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 568 | py | import requests,re,json
headers={
"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"
}
url='https://www.haodf.com/doctor/DE4rO-XCoLUXxbXYw1mnSzFYx4.htm'
cons =requests.get(url,headers=headers).text
c1 = re.findall(r'<div id=\\"truncate_DoctorSpecialize\\" style=\\".*?;\\">(.*?)<\\/div>',cons)[0].replace(' ','').replace('\t','')
print(c1)
ss = c1.encode('utf-8').decode('unicode_escape').replace('\s','')
# sss =
# ss=json.loads(c1,encoding='unicode_escape')
print(ss)
| [
"[email protected]"
]
| |
f16d8f1b2e86dd7fffcf3273a996c0486b447faa | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02778/s067474820.py | b38cee78f97ea21981130f05b1cc01060e600e35 | []
| no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 70 | py | n = list(input())
for i in range(0, len(n)):
print("x", end = "") | [
"[email protected]"
]
| |
dd89d168fb1b3e6cf2a02d688e79033aa57ac251 | c3145ee041d4d3e0cf26ec260d9409da8e8b160a | /group/migrations/0072_auto_20160205_1921.py | 4aa657e8c05c547172be8601b807bad31b6bb549 | []
| no_license | jlundell-bot/library_website | 0b7cab541d3cf69dd97c7c8350e21315e9155798 | 59a5e48adf28ecbc43c7be145f9ec386b1066313 | refs/heads/master | 2021-06-21T14:16:57.542644 | 2017-08-18T15:51:44 | 2017-08-18T19:37:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,891 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-02-05 19:21
from __future__ import unicode_literals
import base.models
from django.db import migrations
import wagtail.wagtailcore.blocks
import wagtail.wagtailcore.fields
import wagtail.wagtaildocs.blocks
import wagtail.wagtailembeds.blocks
import wagtail.wagtailimages.blocks
class Migration(migrations.Migration):
dependencies = [
('group', '0071_auto_20160204_1828'),
]
operations = [
migrations.AlterField(
model_name='grouppage',
name='body',
field=wagtail.wagtailcore.fields.StreamField((('h2', wagtail.wagtailcore.blocks.CharBlock(classname='title', icon='title', template='base/blocks/h2.html')), ('h3', wagtail.wagtailcore.blocks.CharBlock(classname='title', icon='title', template='base/blocks/h3.html')), ('h4', wagtail.wagtailcore.blocks.CharBlock(classname='title', icon='title', template='base/blocks/h4.html')), ('h5', wagtail.wagtailcore.blocks.CharBlock(classname='title', icon='title', template='base/blocks/h5.html')), ('h6', wagtail.wagtailcore.blocks.CharBlock(classname='title', icon='title', template='base/blocks/h6.html')), ('paragraph', wagtail.wagtailcore.blocks.StructBlock((('paragraph', wagtail.wagtailcore.blocks.RichTextBlock()),))), ('image', wagtail.wagtailcore.blocks.StructBlock((('image', wagtail.wagtailimages.blocks.ImageChooserBlock()), ('title', wagtail.wagtailcore.blocks.CharBlock(required=False)), ('citation', wagtail.wagtailcore.blocks.CharBlock(required=False)), ('caption', wagtail.wagtailcore.blocks.TextBlock(required=False)), ('alt_text', wagtail.wagtailcore.blocks.CharBlock(required=False)), ('alignment', base.models.ImageFormatChoiceBlock()), ('source', wagtail.wagtailcore.blocks.CharBlock(required=False)), ('lightbox', wagtail.wagtailcore.blocks.BooleanBlock(default=False, required=False))), label='Image')), ('blockquote', wagtail.wagtailcore.blocks.StructBlock((('quote', wagtail.wagtailcore.blocks.TextBlock('quote title')), ('attribution', wagtail.wagtailcore.blocks.CharBlock(required=False))))), ('button', wagtail.wagtailcore.blocks.StructBlock((('button_type', wagtail.wagtailcore.blocks.ChoiceBlock(choices=[('btn-primary', 'Primary'), ('btn-default', 'Secondary'), ('btn-reserve', 'Reservation')], initial='btn-primary')), ('button_text', wagtail.wagtailcore.blocks.CharBlock(max_length=20)), ('link_external', wagtail.wagtailcore.blocks.URLBlock(required=False)), ('link_page', wagtail.wagtailcore.blocks.PageChooserBlock(required=False)), ('link_document', wagtail.wagtaildocs.blocks.DocumentChooserBlock(required=False))))), ('video', wagtail.wagtailembeds.blocks.EmbedBlock(icon='media')), ('code', wagtail.wagtailcore.blocks.StructBlock((('language', wagtail.wagtailcore.blocks.ChoiceBlock(choices=[('bash', 'Bash/Shell'), ('css', 'CSS'), ('html', 'HTML'), ('javascript', 'Javascript'), ('json', 'JSON'), ('ocaml', 'OCaml'), ('php5', 'PHP'), ('html+php', 'PHP/HTML'), ('python', 'Python'), ('scss', 'SCSS'), ('yaml', 'YAML')])), ('code', wagtail.wagtailcore.blocks.TextBlock())))), ('agenda_item', wagtail.wagtailcore.blocks.StructBlock((('start_time', wagtail.wagtailcore.blocks.TimeBlock(icon='time', required=False)), ('end_time', wagtail.wagtailcore.blocks.TimeBlock(icon='time', required=False)), ('session_title', wagtail.wagtailcore.blocks.CharBlock(help_text='Title of the session. Can be used as title of the talk in some situations.', icon='title', required=False)), ('event', wagtail.wagtailcore.blocks.ListBlock(wagtail.wagtailcore.blocks.StructBlock((('title', wagtail.wagtailcore.blocks.CharBlock(help_text='Talk title, workshop title, etc.', required=False)), ('presenters', wagtail.wagtailcore.blocks.CharBlock(help_text='Comma separated list of presenters (if more than one)', required=False)), ('room_number', wagtail.wagtailcore.blocks.CharBlock(required=False)), ('description', wagtail.wagtailcore.blocks.RichTextBlock(required=False)))), help_text='A talk or event with a title, presenter room number, and description', icon='edit', label=' '))), icon='date', template='base/blocks/agenda.html')))),
),
migrations.AlterField(
model_name='grouppage',
name='intro',
field=wagtail.wagtailcore.fields.StreamField((('h2', wagtail.wagtailcore.blocks.CharBlock(classname='title', icon='title', template='base/blocks/h2.html')), ('h3', wagtail.wagtailcore.blocks.CharBlock(classname='title', icon='title', template='base/blocks/h3.html')), ('h4', wagtail.wagtailcore.blocks.CharBlock(classname='title', icon='title', template='base/blocks/h4.html')), ('h5', wagtail.wagtailcore.blocks.CharBlock(classname='title', icon='title', template='base/blocks/h5.html')), ('h6', wagtail.wagtailcore.blocks.CharBlock(classname='title', icon='title', template='base/blocks/h6.html')), ('paragraph', wagtail.wagtailcore.blocks.StructBlock((('paragraph', wagtail.wagtailcore.blocks.RichTextBlock()),))), ('image', wagtail.wagtailcore.blocks.StructBlock((('image', wagtail.wagtailimages.blocks.ImageChooserBlock()), ('title', wagtail.wagtailcore.blocks.CharBlock(required=False)), ('citation', wagtail.wagtailcore.blocks.CharBlock(required=False)), ('caption', wagtail.wagtailcore.blocks.TextBlock(required=False)), ('alt_text', wagtail.wagtailcore.blocks.CharBlock(required=False)), ('alignment', base.models.ImageFormatChoiceBlock()), ('source', wagtail.wagtailcore.blocks.CharBlock(required=False)), ('lightbox', wagtail.wagtailcore.blocks.BooleanBlock(default=False, required=False))), label='Image')), ('blockquote', wagtail.wagtailcore.blocks.StructBlock((('quote', wagtail.wagtailcore.blocks.TextBlock('quote title')), ('attribution', wagtail.wagtailcore.blocks.CharBlock(required=False))))), ('button', wagtail.wagtailcore.blocks.StructBlock((('button_type', wagtail.wagtailcore.blocks.ChoiceBlock(choices=[('btn-primary', 'Primary'), ('btn-default', 'Secondary'), ('btn-reserve', 'Reservation')], initial='btn-primary')), ('button_text', wagtail.wagtailcore.blocks.CharBlock(max_length=20)), ('link_external', wagtail.wagtailcore.blocks.URLBlock(required=False)), ('link_page', wagtail.wagtailcore.blocks.PageChooserBlock(required=False)), ('link_document', wagtail.wagtaildocs.blocks.DocumentChooserBlock(required=False))))), ('video', wagtail.wagtailembeds.blocks.EmbedBlock(icon='media')), ('code', wagtail.wagtailcore.blocks.StructBlock((('language', wagtail.wagtailcore.blocks.ChoiceBlock(choices=[('bash', 'Bash/Shell'), ('css', 'CSS'), ('html', 'HTML'), ('javascript', 'Javascript'), ('json', 'JSON'), ('ocaml', 'OCaml'), ('php5', 'PHP'), ('html+php', 'PHP/HTML'), ('python', 'Python'), ('scss', 'SCSS'), ('yaml', 'YAML')])), ('code', wagtail.wagtailcore.blocks.TextBlock())))), ('agenda_item', wagtail.wagtailcore.blocks.StructBlock((('start_time', wagtail.wagtailcore.blocks.TimeBlock(icon='time', required=False)), ('end_time', wagtail.wagtailcore.blocks.TimeBlock(icon='time', required=False)), ('session_title', wagtail.wagtailcore.blocks.CharBlock(help_text='Title of the session. Can be used as title of the talk in some situations.', icon='title', required=False)), ('event', wagtail.wagtailcore.blocks.ListBlock(wagtail.wagtailcore.blocks.StructBlock((('title', wagtail.wagtailcore.blocks.CharBlock(help_text='Talk title, workshop title, etc.', required=False)), ('presenters', wagtail.wagtailcore.blocks.CharBlock(help_text='Comma separated list of presenters (if more than one)', required=False)), ('room_number', wagtail.wagtailcore.blocks.CharBlock(required=False)), ('description', wagtail.wagtailcore.blocks.RichTextBlock(required=False)))), help_text='A talk or event with a title, presenter room number, and description', icon='edit', label=' '))), icon='date', template='base/blocks/agenda.html'))), blank=True),
),
]
| [
"[email protected]"
]
| |
da1ea66272f627d41439ddc8369681fc1650cce4 | 6ac2c27121d965babbb4bcbc7c479c26bf60bdf5 | /tests/node/Inequality.py | 4eff81390322439b36c26cdc460d6162687b6a98 | [
"MIT"
]
| permissive | Gawaboumga/PyMatex | 5a2e18c3e17d3b76e814492f7e2ca63a57d720e9 | 3ccc0aa23211a064aa31a9b509b108cd606a4992 | refs/heads/master | 2020-03-28T01:40:32.341723 | 2018-12-20T13:49:12 | 2018-12-20T13:49:12 | 147,521,693 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 794 | py | from tests import BaseTest
from pymatex.node import *
class InequalityTests(BaseTest.BaseTest):
def test_read_simple_inequality(self):
ast = self.parse(r'\sum_{i < j} i')
i = Variable('i')
self.assertEqual(ast, InequalitySummation(Inequality(i, Variable('j'), '<'), None, i))
def test_read_simple_inequality_with_constant(self):
ast = self.parse(r'\sum_{0 < j} i')
i = Variable('i')
self.assertEqual(ast, InequalitySummation(Inequality(Constant('0'), Variable('j'), '<'), None, i))
def test_read_multi_inequality(self):
ast = self.parse(r'\sum_{0 < i \leq j} i')
i = Variable('i')
self.assertEqual(ast, InequalitySummation(Inequality(Inequality(Constant('0'), i, '<'), Variable('j'), '\\leq'), None, i))
| [
"[email protected]"
]
| |
a12389d70e412c4f3fcde17263755ac7d5be0efd | 0d279444c768d10a7ee6c6ec26323947e05cfd01 | /backend/delivery_user_profile/migrations/0001_initial.py | 7a1b9a3c600b8b9ce8ef57537def7a338ad0b4da | []
| no_license | crowdbotics-apps/listsaver-24496 | e3574e92b092360d724147c78586142e07e98b7a | d8636cee59504dac335bc035fc890f80631de3b5 | refs/heads/master | 2023-03-05T08:15:13.712454 | 2021-02-13T13:56:15 | 2021-02-13T13:56:15 | 338,584,064 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,595 | py | # Generated by Django 2.2.18 on 2021-02-13 13:54
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Profile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('photo', models.URLField()),
('timestamp_created', models.DateTimeField(auto_now_add=True)),
('last_updated', models.DateTimeField(auto_now=True)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='profile_user', to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='ContactInfo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('first_name', models.CharField(max_length=255)),
('last_name', models.CharField(max_length=255)),
('phone', models.CharField(max_length=20)),
('address', models.TextField()),
('is_default', models.BooleanField()),
('profile', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='contactinfo_profile', to='delivery_user_profile.Profile')),
],
),
]
| [
"[email protected]"
]
| |
44e44c6662496b3b74ca005acce2cc1e123d70e8 | 11f4852e9af2eeb5d238ddd7df9ccd713160a334 | /train.py | 0ee97b96ea9a28f250231624bba0f5cc8088e39b | []
| no_license | chw0806-github/nucleus_detection | d174f6c924213a0c09b7c6f1990873f8819251ff | a53b10965b2963922b7c266bb93ad4cbe2906db0 | refs/heads/master | 2021-04-08T16:26:47.884953 | 2018-05-02T04:06:43 | 2018-05-02T04:06:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,402 | py | #!/usr/bin/env python
# coding=utf-8
"""
python=3.5.2
"""
from data_input import read_train_data, read_test_data, prob_to_rles, mask_to_rle, resize, np
from model import get_unet, dice_coef
import pandas as pd
from post_process import post_processing
from skimage.io import imshow
import matplotlib.pyplot as plt
from keras.models import load_model
from keras.callbacks import TensorBoard, EarlyStopping, ModelCheckpoint
epochs = 50
model_name = 'model-0416-bn.h5'
# best_model_name = 'model-dsbowl2018-0416-best.h5'
# get train_data
train_img, train_mask = read_train_data()
# get test_data
test_img, test_img_sizes = read_test_data()
# get u_net model
u_net = get_unet()
# fit model on train_data
print("\n Training...")
tb = TensorBoard(log_dir='./logs', histogram_freq=0, write_graph=True, write_images=False, embeddings_freq=0, embeddings_layer_names=None, embeddings_metadata=None)
# early_stopper = EarlyStopping(patience=5, verbose=1)
# check_pointer = ModelCheckpoint(best_model_name, verbose=1, save_best_only=True)
u_net.fit(train_img, train_mask, batch_size=16, epochs=epochs, callbacks=[tb])
print("\n Saving")
u_net.save(model_name)
print("\n load model")
u_net = load_model(model_name, custom_objects={'dice_coef': dice_coef})
print("\n Predicting and Saving predict")
# Predict on test data
test_mask = u_net.predict(test_img, verbose=1)
np.save("test_img_bn_pred", test_mask)
| [
"[email protected]"
]
| |
63ef1df5231e708ee0376612469a1cf795a19d00 | 75dcb56e318688499bdab789262839e7f58bd4f6 | /Algorithms in Python Live Coding & Design Techniques/src/005_dynamic-programming/staircase/Staircase.py | 23c2f71d354f0cfe8b1116f091b4108956fea056 | []
| no_license | syurskyi/Algorithms_and_Data_Structure | 9a1f358577e51e89c862d0f93f373b7f20ddd261 | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | refs/heads/master | 2023-02-22T17:55:55.453535 | 2022-12-23T03:15:00 | 2022-12-23T03:15:00 | 226,243,987 | 4 | 1 | null | 2023-02-07T21:01:45 | 2019-12-06T04:14:10 | Jupyter Notebook | UTF-8 | Python | false | false | 835 | py | #Recursive Approach
def ways(n, k):
if n == 0:
return 1
if n < 0:
return 0
ans = 0
for i in range(1, k+1):
ans += ways(n-i, k)
return ans
#Dynamic Programming : Top Down Approach
def ways_top_down(n, k, dp):
if n == 0:
dp[n] = 1
return dp[n]
if n < 0:
return 0
if not dp[n] == -1:
return dp[n]
dp[n] = 0
for i in range(1, k+1):
dp[n] += ways_top_down(n-i, k, dp)
return dp[n]
#Dynamic Programming : Bottom Up Approach
def ways_bottom_up(n, k):
dp = [0] * (n+1)
dp[0] = 1
for step in range(1, n+1):
dp[step] = 0
for j in range(1, k+1):
if step - j >= 0:
dp[step] += dp[step - j]
return dp[n]
n = 4
steps = 3
dp = [-1]*(n+1)
print(ways_bottom_up(n, steps)) | [
"[email protected]"
]
| |
c4ef3f208080a7271ff8600a826de6f2388393d0 | 90419da201cd4948a27d3612f0b482c68026c96f | /sdk/python/pulumi_azure_nextgen/network/v20181201/get_application_gateway.py | e213a1af3669ea04428b90d095a580ee2bde2889 | [
"BSD-3-Clause",
"Apache-2.0"
]
| permissive | test-wiz-sec/pulumi-azure-nextgen | cd4bee5d70cb0d332c04f16bb54e17d016d2adaf | 20a695af0d020b34b0f1c336e1b69702755174cc | refs/heads/master | 2023-06-08T02:35:52.639773 | 2020-11-06T22:39:06 | 2020-11-06T22:39:06 | 312,993,761 | 0 | 0 | Apache-2.0 | 2023-06-02T06:47:28 | 2020-11-15T09:04:00 | null | UTF-8 | Python | false | false | 23,183 | py | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outputs
__all__ = [
'GetApplicationGatewayResult',
'AwaitableGetApplicationGatewayResult',
'get_application_gateway',
]
@pulumi.output_type
class GetApplicationGatewayResult:
"""
Application gateway resource
"""
def __init__(__self__, authentication_certificates=None, autoscale_configuration=None, backend_address_pools=None, backend_http_settings_collection=None, custom_error_configurations=None, enable_fips=None, enable_http2=None, etag=None, firewall_policy=None, frontend_ip_configurations=None, frontend_ports=None, gateway_ip_configurations=None, http_listeners=None, identity=None, location=None, name=None, operational_state=None, probes=None, provisioning_state=None, redirect_configurations=None, request_routing_rules=None, resource_guid=None, rewrite_rule_sets=None, sku=None, ssl_certificates=None, ssl_policy=None, tags=None, trusted_root_certificates=None, type=None, url_path_maps=None, web_application_firewall_configuration=None, zones=None):
if authentication_certificates and not isinstance(authentication_certificates, list):
raise TypeError("Expected argument 'authentication_certificates' to be a list")
pulumi.set(__self__, "authentication_certificates", authentication_certificates)
if autoscale_configuration and not isinstance(autoscale_configuration, dict):
raise TypeError("Expected argument 'autoscale_configuration' to be a dict")
pulumi.set(__self__, "autoscale_configuration", autoscale_configuration)
if backend_address_pools and not isinstance(backend_address_pools, list):
raise TypeError("Expected argument 'backend_address_pools' to be a list")
pulumi.set(__self__, "backend_address_pools", backend_address_pools)
if backend_http_settings_collection and not isinstance(backend_http_settings_collection, list):
raise TypeError("Expected argument 'backend_http_settings_collection' to be a list")
pulumi.set(__self__, "backend_http_settings_collection", backend_http_settings_collection)
if custom_error_configurations and not isinstance(custom_error_configurations, list):
raise TypeError("Expected argument 'custom_error_configurations' to be a list")
pulumi.set(__self__, "custom_error_configurations", custom_error_configurations)
if enable_fips and not isinstance(enable_fips, bool):
raise TypeError("Expected argument 'enable_fips' to be a bool")
pulumi.set(__self__, "enable_fips", enable_fips)
if enable_http2 and not isinstance(enable_http2, bool):
raise TypeError("Expected argument 'enable_http2' to be a bool")
pulumi.set(__self__, "enable_http2", enable_http2)
if etag and not isinstance(etag, str):
raise TypeError("Expected argument 'etag' to be a str")
pulumi.set(__self__, "etag", etag)
if firewall_policy and not isinstance(firewall_policy, dict):
raise TypeError("Expected argument 'firewall_policy' to be a dict")
pulumi.set(__self__, "firewall_policy", firewall_policy)
if frontend_ip_configurations and not isinstance(frontend_ip_configurations, list):
raise TypeError("Expected argument 'frontend_ip_configurations' to be a list")
pulumi.set(__self__, "frontend_ip_configurations", frontend_ip_configurations)
if frontend_ports and not isinstance(frontend_ports, list):
raise TypeError("Expected argument 'frontend_ports' to be a list")
pulumi.set(__self__, "frontend_ports", frontend_ports)
if gateway_ip_configurations and not isinstance(gateway_ip_configurations, list):
raise TypeError("Expected argument 'gateway_ip_configurations' to be a list")
pulumi.set(__self__, "gateway_ip_configurations", gateway_ip_configurations)
if http_listeners and not isinstance(http_listeners, list):
raise TypeError("Expected argument 'http_listeners' to be a list")
pulumi.set(__self__, "http_listeners", http_listeners)
if identity and not isinstance(identity, dict):
raise TypeError("Expected argument 'identity' to be a dict")
pulumi.set(__self__, "identity", identity)
if location and not isinstance(location, str):
raise TypeError("Expected argument 'location' to be a str")
pulumi.set(__self__, "location", location)
if name and not isinstance(name, str):
raise TypeError("Expected argument 'name' to be a str")
pulumi.set(__self__, "name", name)
if operational_state and not isinstance(operational_state, str):
raise TypeError("Expected argument 'operational_state' to be a str")
pulumi.set(__self__, "operational_state", operational_state)
if probes and not isinstance(probes, list):
raise TypeError("Expected argument 'probes' to be a list")
pulumi.set(__self__, "probes", probes)
if provisioning_state and not isinstance(provisioning_state, str):
raise TypeError("Expected argument 'provisioning_state' to be a str")
pulumi.set(__self__, "provisioning_state", provisioning_state)
if redirect_configurations and not isinstance(redirect_configurations, list):
raise TypeError("Expected argument 'redirect_configurations' to be a list")
pulumi.set(__self__, "redirect_configurations", redirect_configurations)
if request_routing_rules and not isinstance(request_routing_rules, list):
raise TypeError("Expected argument 'request_routing_rules' to be a list")
pulumi.set(__self__, "request_routing_rules", request_routing_rules)
if resource_guid and not isinstance(resource_guid, str):
raise TypeError("Expected argument 'resource_guid' to be a str")
pulumi.set(__self__, "resource_guid", resource_guid)
if rewrite_rule_sets and not isinstance(rewrite_rule_sets, list):
raise TypeError("Expected argument 'rewrite_rule_sets' to be a list")
pulumi.set(__self__, "rewrite_rule_sets", rewrite_rule_sets)
if sku and not isinstance(sku, dict):
raise TypeError("Expected argument 'sku' to be a dict")
pulumi.set(__self__, "sku", sku)
if ssl_certificates and not isinstance(ssl_certificates, list):
raise TypeError("Expected argument 'ssl_certificates' to be a list")
pulumi.set(__self__, "ssl_certificates", ssl_certificates)
if ssl_policy and not isinstance(ssl_policy, dict):
raise TypeError("Expected argument 'ssl_policy' to be a dict")
pulumi.set(__self__, "ssl_policy", ssl_policy)
if tags and not isinstance(tags, dict):
raise TypeError("Expected argument 'tags' to be a dict")
pulumi.set(__self__, "tags", tags)
if trusted_root_certificates and not isinstance(trusted_root_certificates, list):
raise TypeError("Expected argument 'trusted_root_certificates' to be a list")
pulumi.set(__self__, "trusted_root_certificates", trusted_root_certificates)
if type and not isinstance(type, str):
raise TypeError("Expected argument 'type' to be a str")
pulumi.set(__self__, "type", type)
if url_path_maps and not isinstance(url_path_maps, list):
raise TypeError("Expected argument 'url_path_maps' to be a list")
pulumi.set(__self__, "url_path_maps", url_path_maps)
if web_application_firewall_configuration and not isinstance(web_application_firewall_configuration, dict):
raise TypeError("Expected argument 'web_application_firewall_configuration' to be a dict")
pulumi.set(__self__, "web_application_firewall_configuration", web_application_firewall_configuration)
if zones and not isinstance(zones, list):
raise TypeError("Expected argument 'zones' to be a list")
pulumi.set(__self__, "zones", zones)
@property
@pulumi.getter(name="authenticationCertificates")
def authentication_certificates(self) -> Optional[Sequence['outputs.ApplicationGatewayAuthenticationCertificateResponse']]:
"""
Authentication certificates of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
"""
return pulumi.get(self, "authentication_certificates")
@property
@pulumi.getter(name="autoscaleConfiguration")
def autoscale_configuration(self) -> Optional['outputs.ApplicationGatewayAutoscaleConfigurationResponse']:
"""
Autoscale Configuration.
"""
return pulumi.get(self, "autoscale_configuration")
@property
@pulumi.getter(name="backendAddressPools")
def backend_address_pools(self) -> Optional[Sequence['outputs.ApplicationGatewayBackendAddressPoolResponse']]:
"""
Backend address pool of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
"""
return pulumi.get(self, "backend_address_pools")
@property
@pulumi.getter(name="backendHttpSettingsCollection")
def backend_http_settings_collection(self) -> Optional[Sequence['outputs.ApplicationGatewayBackendHttpSettingsResponse']]:
"""
Backend http settings of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
"""
return pulumi.get(self, "backend_http_settings_collection")
@property
@pulumi.getter(name="customErrorConfigurations")
def custom_error_configurations(self) -> Optional[Sequence['outputs.ApplicationGatewayCustomErrorResponse']]:
"""
Custom error configurations of the application gateway resource.
"""
return pulumi.get(self, "custom_error_configurations")
@property
@pulumi.getter(name="enableFips")
def enable_fips(self) -> Optional[bool]:
"""
Whether FIPS is enabled on the application gateway resource.
"""
return pulumi.get(self, "enable_fips")
@property
@pulumi.getter(name="enableHttp2")
def enable_http2(self) -> Optional[bool]:
"""
Whether HTTP2 is enabled on the application gateway resource.
"""
return pulumi.get(self, "enable_http2")
@property
@pulumi.getter
def etag(self) -> Optional[str]:
"""
A unique read-only string that changes whenever the resource is updated.
"""
return pulumi.get(self, "etag")
@property
@pulumi.getter(name="firewallPolicy")
def firewall_policy(self) -> Optional['outputs.SubResourceResponse']:
"""
Reference of the FirewallPolicy resource.
"""
return pulumi.get(self, "firewall_policy")
@property
@pulumi.getter(name="frontendIPConfigurations")
def frontend_ip_configurations(self) -> Optional[Sequence['outputs.ApplicationGatewayFrontendIPConfigurationResponse']]:
"""
Frontend IP addresses of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
"""
return pulumi.get(self, "frontend_ip_configurations")
@property
@pulumi.getter(name="frontendPorts")
def frontend_ports(self) -> Optional[Sequence['outputs.ApplicationGatewayFrontendPortResponse']]:
"""
Frontend ports of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
"""
return pulumi.get(self, "frontend_ports")
@property
@pulumi.getter(name="gatewayIPConfigurations")
def gateway_ip_configurations(self) -> Optional[Sequence['outputs.ApplicationGatewayIPConfigurationResponse']]:
"""
Subnets of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
"""
return pulumi.get(self, "gateway_ip_configurations")
@property
@pulumi.getter(name="httpListeners")
def http_listeners(self) -> Optional[Sequence['outputs.ApplicationGatewayHttpListenerResponse']]:
"""
Http listeners of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
"""
return pulumi.get(self, "http_listeners")
@property
@pulumi.getter
def identity(self) -> Optional['outputs.ManagedServiceIdentityResponse']:
"""
The identity of the application gateway, if configured.
"""
return pulumi.get(self, "identity")
@property
@pulumi.getter
def location(self) -> Optional[str]:
"""
Resource location.
"""
return pulumi.get(self, "location")
@property
@pulumi.getter
def name(self) -> str:
"""
Resource name.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="operationalState")
def operational_state(self) -> str:
"""
Operational state of the application gateway resource.
"""
return pulumi.get(self, "operational_state")
@property
@pulumi.getter
def probes(self) -> Optional[Sequence['outputs.ApplicationGatewayProbeResponse']]:
"""
Probes of the application gateway resource.
"""
return pulumi.get(self, "probes")
@property
@pulumi.getter(name="provisioningState")
def provisioning_state(self) -> Optional[str]:
"""
Provisioning state of the application gateway resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
"""
return pulumi.get(self, "provisioning_state")
@property
@pulumi.getter(name="redirectConfigurations")
def redirect_configurations(self) -> Optional[Sequence['outputs.ApplicationGatewayRedirectConfigurationResponse']]:
"""
Redirect configurations of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
"""
return pulumi.get(self, "redirect_configurations")
@property
@pulumi.getter(name="requestRoutingRules")
def request_routing_rules(self) -> Optional[Sequence['outputs.ApplicationGatewayRequestRoutingRuleResponse']]:
"""
Request routing rules of the application gateway resource.
"""
return pulumi.get(self, "request_routing_rules")
@property
@pulumi.getter(name="resourceGuid")
def resource_guid(self) -> Optional[str]:
"""
Resource GUID property of the application gateway resource.
"""
return pulumi.get(self, "resource_guid")
@property
@pulumi.getter(name="rewriteRuleSets")
def rewrite_rule_sets(self) -> Optional[Sequence['outputs.ApplicationGatewayRewriteRuleSetResponse']]:
"""
Rewrite rules for the application gateway resource.
"""
return pulumi.get(self, "rewrite_rule_sets")
@property
@pulumi.getter
def sku(self) -> Optional['outputs.ApplicationGatewaySkuResponse']:
"""
SKU of the application gateway resource.
"""
return pulumi.get(self, "sku")
@property
@pulumi.getter(name="sslCertificates")
def ssl_certificates(self) -> Optional[Sequence['outputs.ApplicationGatewaySslCertificateResponse']]:
"""
SSL certificates of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
"""
return pulumi.get(self, "ssl_certificates")
@property
@pulumi.getter(name="sslPolicy")
def ssl_policy(self) -> Optional['outputs.ApplicationGatewaySslPolicyResponse']:
"""
SSL policy of the application gateway resource.
"""
return pulumi.get(self, "ssl_policy")
@property
@pulumi.getter
def tags(self) -> Optional[Mapping[str, str]]:
"""
Resource tags.
"""
return pulumi.get(self, "tags")
@property
@pulumi.getter(name="trustedRootCertificates")
def trusted_root_certificates(self) -> Optional[Sequence['outputs.ApplicationGatewayTrustedRootCertificateResponse']]:
"""
Trusted Root certificates of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
"""
return pulumi.get(self, "trusted_root_certificates")
@property
@pulumi.getter
def type(self) -> str:
"""
Resource type.
"""
return pulumi.get(self, "type")
@property
@pulumi.getter(name="urlPathMaps")
def url_path_maps(self) -> Optional[Sequence['outputs.ApplicationGatewayUrlPathMapResponse']]:
"""
URL path map of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
"""
return pulumi.get(self, "url_path_maps")
@property
@pulumi.getter(name="webApplicationFirewallConfiguration")
def web_application_firewall_configuration(self) -> Optional['outputs.ApplicationGatewayWebApplicationFirewallConfigurationResponse']:
"""
Web application firewall configuration.
"""
return pulumi.get(self, "web_application_firewall_configuration")
@property
@pulumi.getter
def zones(self) -> Optional[Sequence[str]]:
"""
A list of availability zones denoting where the resource needs to come from.
"""
return pulumi.get(self, "zones")
class AwaitableGetApplicationGatewayResult(GetApplicationGatewayResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetApplicationGatewayResult(
authentication_certificates=self.authentication_certificates,
autoscale_configuration=self.autoscale_configuration,
backend_address_pools=self.backend_address_pools,
backend_http_settings_collection=self.backend_http_settings_collection,
custom_error_configurations=self.custom_error_configurations,
enable_fips=self.enable_fips,
enable_http2=self.enable_http2,
etag=self.etag,
firewall_policy=self.firewall_policy,
frontend_ip_configurations=self.frontend_ip_configurations,
frontend_ports=self.frontend_ports,
gateway_ip_configurations=self.gateway_ip_configurations,
http_listeners=self.http_listeners,
identity=self.identity,
location=self.location,
name=self.name,
operational_state=self.operational_state,
probes=self.probes,
provisioning_state=self.provisioning_state,
redirect_configurations=self.redirect_configurations,
request_routing_rules=self.request_routing_rules,
resource_guid=self.resource_guid,
rewrite_rule_sets=self.rewrite_rule_sets,
sku=self.sku,
ssl_certificates=self.ssl_certificates,
ssl_policy=self.ssl_policy,
tags=self.tags,
trusted_root_certificates=self.trusted_root_certificates,
type=self.type,
url_path_maps=self.url_path_maps,
web_application_firewall_configuration=self.web_application_firewall_configuration,
zones=self.zones)
def get_application_gateway(application_gateway_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetApplicationGatewayResult:
"""
Use this data source to access information about an existing resource.
:param str application_gateway_name: The name of the application gateway.
:param str resource_group_name: The name of the resource group.
"""
__args__ = dict()
__args__['applicationGatewayName'] = application_gateway_name
__args__['resourceGroupName'] = resource_group_name
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('azure-nextgen:network/v20181201:getApplicationGateway', __args__, opts=opts, typ=GetApplicationGatewayResult).value
return AwaitableGetApplicationGatewayResult(
authentication_certificates=__ret__.authentication_certificates,
autoscale_configuration=__ret__.autoscale_configuration,
backend_address_pools=__ret__.backend_address_pools,
backend_http_settings_collection=__ret__.backend_http_settings_collection,
custom_error_configurations=__ret__.custom_error_configurations,
enable_fips=__ret__.enable_fips,
enable_http2=__ret__.enable_http2,
etag=__ret__.etag,
firewall_policy=__ret__.firewall_policy,
frontend_ip_configurations=__ret__.frontend_ip_configurations,
frontend_ports=__ret__.frontend_ports,
gateway_ip_configurations=__ret__.gateway_ip_configurations,
http_listeners=__ret__.http_listeners,
identity=__ret__.identity,
location=__ret__.location,
name=__ret__.name,
operational_state=__ret__.operational_state,
probes=__ret__.probes,
provisioning_state=__ret__.provisioning_state,
redirect_configurations=__ret__.redirect_configurations,
request_routing_rules=__ret__.request_routing_rules,
resource_guid=__ret__.resource_guid,
rewrite_rule_sets=__ret__.rewrite_rule_sets,
sku=__ret__.sku,
ssl_certificates=__ret__.ssl_certificates,
ssl_policy=__ret__.ssl_policy,
tags=__ret__.tags,
trusted_root_certificates=__ret__.trusted_root_certificates,
type=__ret__.type,
url_path_maps=__ret__.url_path_maps,
web_application_firewall_configuration=__ret__.web_application_firewall_configuration,
zones=__ret__.zones)
| [
"[email protected]"
]
| |
de2a2f46c04b3533461e9d8caf3a4a4d4aa0077b | bca9c2fa3c4c3d06dd612280ce39090a9dfab9bd | /neekanee/job_scrapers/plugins/com/link/verivo.py | 42dac15cdc1dc889d2fb09f4ea617b24d30a63a9 | []
| no_license | thayton/neekanee | 0890dd5e5cf5bf855d4867ae02de6554291dc349 | f2b2a13e584469d982f7cc20b49a9b19fed8942d | refs/heads/master | 2021-03-27T11:10:07.633264 | 2018-07-13T14:19:30 | 2018-07-13T14:19:30 | 11,584,212 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,331 | py | import re, mechanize, urlparse
from neekanee.jobscrapers.jobscraper import JobScraper
from neekanee.htmlparse.soupify import soupify, get_all_text, get_mailto
from neekanee_solr.models import *
COMPANY = {
'name': 'Verivo',
'hq': 'Waltham, MA',
'home_page_url': 'http://www.verivo.com',
'jobs_page_url': 'http://www.verivo.com/about-us/careers/',
'empcnt': [51,200]
}
class VerivoJobScraper(JobScraper):
def __init__(self):
super(VerivoJobScraper, self).__init__(COMPANY)
def scrape_job_links(self, url):
jobs = []
self.br.open(url)
s = soupify(self.br.response().read())
x = {'title': 'Careers', 'href': self.company.jobs_page_url}
a = s.find('a', attrs=x)
x = {'class': 'children'}
u = a.findNext('ul', attrs=x)
r1 = re.compile(r'/about-us/careers/[a-z-]+/$')
r2 = re.compile(r'/careers/[a-z-]+/$')
for a in u.findAll('a', href=r1):
l = urlparse.urljoin(self.br.geturl(), a['href'])
self.br.open(l)
s = soupify(self.br.response().read())
x = {'class': 'list-posts-wrapper'}
d = s.find('div', attrs=x)
if not d:
continue
for a in d.findAll('a', href=r2):
s = soupify(self.br.response().read())
title = a.text.lower().strip()
if title.startswith('read more'):
continue
job = Job(company=self.company)
job.title = a.text
job.url = urlparse.urljoin(self.br.geturl(), a['href'])
job.location = self.company.location
jobs.append(job)
self.br.back()
return jobs
def scrape_jobs(self):
job_list = self.scrape_job_links(self.company.jobs_page_url)
self.prune_unlisted_jobs(job_list)
new_jobs = self.new_job_listings(job_list)
for job in new_jobs:
self.br.open(job.url)
s = soupify(self.br.response().read())
d = s.find('div', attrs={'class': 'site-content'})
job.desc = get_all_text(d)
job.save()
def get_scraper():
return VerivoJobScraper()
if __name__ == '__main__':
job_scraper = get_scraper()
job_scraper.scrape_jobs()
| [
"[email protected]"
]
| |
034dbf6920b0dea17131a2d0fe980a11803de766 | f3b233e5053e28fa95c549017bd75a30456eb50c | /ptp1b_input/L86/86-84_MD_NVT_rerun/set.py | 8869714c49649943cc15437ffa3f1f2ed05321c6 | []
| no_license | AnguseZhang/Input_TI | ddf2ed40ff1c0aa24eea3275b83d4d405b50b820 | 50ada0833890be9e261c967d00948f998313cb60 | refs/heads/master | 2021-05-25T15:02:38.858785 | 2020-02-18T16:57:04 | 2020-02-18T16:57:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,083 | py | import os
dir = '/mnt/scratch/songlin3/run/ptp1b/L86/MD/ti_one-step/86_84/'
filesdir = dir + 'files/'
temp_equiin = filesdir + 'temp_equi.in'
temp_prodin = filesdir + 'temp_prod.in'
temp_pbs = filesdir + 'temp.pbs'
lambd = [ 0.00922, 0.04794, 0.11505, 0.20634, 0.31608, 0.43738, 0.56262, 0.68392, 0.79366, 0.88495, 0.95206, 0.99078]
for j in lambd:
os.system("rm -r %6.5f" %(j))
os.system("mkdir %6.5f" %(j))
os.chdir("%6.5f" %(j))
os.system("rm *")
workdir = dir + "%6.5f" %(j) + '/'
#equiin
eqin = workdir + "%6.5f_equi.in" %(j)
os.system("cp %s %s" %(temp_equiin, eqin))
os.system("sed -i 's/XXX/%6.5f/g' %s" %(j, eqin))
#prodin
prodin = workdir + "%6.5f_prod.in" %(j)
os.system("cp %s %s" %(temp_prodin, prodin))
os.system("sed -i 's/XXX/%6.5f/g' %s" %(j, prodin))
#PBS
pbs = workdir + "%6.5f.pbs" %(j)
os.system("cp %s %s" %(temp_pbs, pbs))
os.system("sed -i 's/XXX/%6.5f/g' %s" %(j, pbs))
#top
os.system("cp ../86-84_merged.prmtop .")
os.system("cp ../0.5_equi_0.rst .")
#submit pbs
os.system("qsub %s" %(pbs))
os.chdir(dir)
| [
"[email protected]"
]
| |
7b15765d3b5355212d948031d49b1d902c481e39 | e70e8f9f5c1b20fe36feab42ad4c2c34fc094069 | /Python/Advanced OOP/Problems/09. Programmer.py | 19550c44940b74453ea18b29b992c9fbee136945 | [
"MIT"
]
| permissive | teodoramilcheva/softuni-software-engineering | 9247ca2032915d8614017a3762d3752b3e300f37 | 98dc9faa66f42570f6538fd7ef186d2bd1d39bff | refs/heads/main | 2023-03-29T15:55:54.451641 | 2021-04-09T18:46:32 | 2021-04-09T18:46:32 | 333,551,625 | 0 | 0 | null | 2021-04-09T18:46:32 | 2021-01-27T20:30:18 | Python | UTF-8 | Python | false | false | 1,422 | py | class Programmer:
def __init__(self, name: str, language: str, skills: int):
self.name = name
self.language = language
self.skills = skills
def watch_course(self, course_name, language, skills_earned):
if self.language == language:
self.skills += skills_earned
return f'{self.name} watched {course_name}'
else:
return f'{self.name} does not know {language}'
def change_language(self, new_language, skills_needed):
if self.skills >= skills_needed:
if self.language != new_language:
previous_language = self.language
self.language = new_language
return f'{self.name} switched from {previous_language} to {new_language}'
else:
return f'{self.name} already knows {self.language}'
else:
needed_skills = skills_needed - self.skills
return f'{self.name} needs {needed_skills} more skills'
programmer = Programmer("John", "Java", 50)
print(programmer.watch_course("Python Masterclass", "Python", 84))
print(programmer.change_language("Java", 30))
print(programmer.change_language("Python", 100))
print(programmer.watch_course("Java: zero to hero", "Java", 50))
print(programmer.change_language("Python", 100))
print(programmer.watch_course("Python Masterclass", "Python", 84))
| [
"[email protected]"
]
| |
62a4e59e5cf4f549503451c4da96a2cbd3ba2cc6 | c9ddbdb5678ba6e1c5c7e64adf2802ca16df778c | /cases/synthetic/tree-big-1250.py | eaf3a74df44747f713f3fcccbb707d453c97b4ab | []
| no_license | Virtlink/ccbench-chocopy | c3f7f6af6349aff6503196f727ef89f210a1eac8 | c7efae43bf32696ee2b2ee781bdfe4f7730dec3f | refs/heads/main | 2023-04-07T15:07:12.464038 | 2022-02-03T15:42:39 | 2022-02-03T15:42:39 | 451,969,776 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 23,299 | py | # Binary-search trees
class TreeNode(object):
value:int = 0
left:"TreeNode" = None
right:"TreeNode" = None
def insert(self:"TreeNode", x:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode(x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode(x)
return True
else:
return self.right.insert(x)
return False
def contains(self:"TreeNode", x:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
class TreeNode2(object):
value:int = 0
value2:int = 0
left:"TreeNode2" = None
left2:"TreeNode2" = None
right:"TreeNode2" = None
right2:"TreeNode2" = None
def insert(self:"TreeNode2", x:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode2(x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode2(x, x)
return True
else:
return self.right.insert(x)
return False
def insert2(self:"TreeNode2", x:int, x2:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode2(x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode2(x, x)
return True
else:
return self.right.insert(x)
return False
def contains(self:"TreeNode2", x:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
def contains2(self:"TreeNode2", x:int, x2:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
class TreeNode3(object):
value:int = 0
value2:int = 0
value3:int = 0
left:"TreeNode3" = None
left2:"TreeNode3" = None
left3:"TreeNode3" = None
right:"TreeNode3" = None
right2:"TreeNode3" = None
right3:"TreeNode3" = None
def insert(self:"TreeNode3", x:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode3(x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode3(x, x, x)
return True
else:
return self.right.insert(x)
return False
def insert2(self:"TreeNode3", x:int, x2:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode3(x, x, x)
return True
else:
return self.left.insert($Parameters)
elif x > self.value:
if self.right is None:
self.right = makeNode3(x, x, x)
return True
else:
return self.right.insert(x)
return False
def insert3(self:"TreeNode3", x:int, x2:int, x3:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode3(x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode3(x, x, x)
return True
else:
return self.right.insert(x)
return False
def contains(self:"TreeNode3", x:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
def contains2(self:"TreeNode3", x:int, x2:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
def contains3(self:"TreeNode3", x:int, x2:int, x3:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
class TreeNode4(object):
value:int = 0
value2:int = 0
value3:int = 0
value4:int = 0
left:"TreeNode4" = None
left2:"TreeNode4" = None
left3:"TreeNode4" = None
left4:"TreeNode4" = None
right:"TreeNode4" = None
right2:"TreeNode4" = None
right3:"TreeNode4" = None
right4:"TreeNode4" = None
def insert(self:"TreeNode4", x:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode4(x, x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode4(x, x, x, x)
return True
else:
return self.right.insert(x)
return False
def insert2(self:"TreeNode4", x:int, x2:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode4(x, x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode4(x, x, x, x)
return True
else:
return self.right.insert(x)
return False
def insert3(self:"TreeNode4", x:int, x2:int, x3:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode4(x, x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode4(x, x, x, x)
return True
else:
return self.right.insert(x)
return False
def insert4(self:"TreeNode4", x:int, x2:int, x3:int, x4:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode4(x, x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode4(x, x, x, x)
return True
else:
return self.right.insert(x)
return False
def contains(self:"TreeNode4", x:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
def contains2(self:"TreeNode4", x:int, x2:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
def contains3(self:"TreeNode4", x:int, x2:int, x3:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
def contains4(self:"TreeNode4", x:int, x2:int, x3:int, x4:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
class TreeNode5(object):
value:int = 0
value2:int = 0
value3:int = 0
value4:int = 0
value5:int = 0
left:"TreeNode5" = None
left2:"TreeNode5" = None
left3:"TreeNode5" = None
left4:"TreeNode5" = None
left5:"TreeNode5" = None
right:"TreeNode5" = None
right2:"TreeNode5" = None
right3:"TreeNode5" = None
right4:"TreeNode5" = None
right5:"TreeNode5" = None
def insert(self:"TreeNode5", x:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode5(x, x, x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode5(x, x, x, x, x)
return True
else:
return self.right.insert(x)
return False
def insert2(self:"TreeNode5", x:int, x2:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode5(x, x, x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode5(x, x, x, x, x)
return True
else:
return self.right.insert(x)
return False
def insert3(self:"TreeNode5", x:int, x2:int, x3:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode5(x, x, x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode5(x, x, x, x, x)
return True
else:
return self.right.insert(x)
return False
def insert4(self:"TreeNode5", x:int, x2:int, x3:int, x4:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode5(x, x, x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode5(x, x, x, x, x)
return True
else:
return self.right.insert(x)
return False
def insert5(self:"TreeNode5", x:int, x2:int, x3:int, x4:int, x5:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode5(x, x, x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode5(x, x, x, x, x)
return True
else:
return self.right.insert(x)
return False
def contains(self:"TreeNode5", x:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
def contains2(self:"TreeNode5", x:int, x2:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
def contains3(self:"TreeNode5", x:int, x2:int, x3:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
def contains4(self:"TreeNode5", x:int, x2:int, x3:int, x4:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
def contains5(self:"TreeNode5", x:int, x2:int, x3:int, x4:int, x5:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
class Tree(object):
root:TreeNode = None
size:int = 0
def insert(self:"Tree", x:int) -> object:
if self.root is None:
self.root = makeNode(x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def contains(self:"Tree", x:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
class Tree2(object):
root:TreeNode2 = None
root2:TreeNode2 = None
size:int = 0
size2:int = 0
def insert(self:"Tree2", x:int) -> object:
if self.root is None:
self.root = makeNode2(x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert2(self:"Tree2", x:int, x2:int) -> object:
if self.root is None:
self.root = makeNode2(x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def contains(self:"Tree2", x:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains2(self:"Tree2", x:int, x2:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
class Tree3(object):
root:TreeNode3 = None
root2:TreeNode3 = None
root3:TreeNode3 = None
size:int = 0
size2:int = 0
size3:int = 0
def insert(self:"Tree3", x:int) -> object:
if self.root is None:
self.root = makeNode3(x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert2(self:"Tree3", x:int, x2:int) -> object:
if self.root is None:
self.root = makeNode3(x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert3(self:"Tree3", x:int, x2:int, x3:int) -> object:
if self.root is None:
self.root = makeNode3(x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def contains(self:"Tree3", x:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains2(self:"Tree3", x:int, x2:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains3(self:"Tree3", x:int, x2:int, x3:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
class Tree4(object):
root:TreeNode4 = None
root2:TreeNode4 = None
root3:TreeNode4 = None
root4:TreeNode4 = None
size:int = 0
size2:int = 0
size3:int = 0
size4:int = 0
def insert(self:"Tree4", x:int) -> object:
if self.root is None:
self.root = makeNode4(x, x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert2(self:"Tree4", x:int, x2:int) -> object:
if self.root is None:
self.root = makeNode4(x, x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert3(self:"Tree4", x:int, x2:int, x3:int) -> object:
if self.root is None:
self.root = makeNode4(x, x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert4(self:"Tree4", x:int, x2:int, x3:int, x4:int) -> object:
if self.root is None:
self.root = makeNode4(x, x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def contains(self:"Tree4", x:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains2(self:"Tree4", x:int, x2:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains3(self:"Tree4", x:int, x2:int, x3:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains4(self:"Tree4", x:int, x2:int, x3:int, x4:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
class Tree5(object):
root:TreeNode5 = None
root2:TreeNode5 = None
root3:TreeNode5 = None
root4:TreeNode5 = None
root5:TreeNode5 = None
size:int = 0
size2:int = 0
size3:int = 0
size4:int = 0
size5:int = 0
def insert(self:"Tree5", x:int) -> object:
if self.root is None:
self.root = makeNode5(x, x, x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert2(self:"Tree5", x:int, x2:int) -> object:
if self.root is None:
self.root = makeNode5(x, x, x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert3(self:"Tree5", x:int, x2:int, x3:int) -> object:
if self.root is None:
self.root = makeNode5(x, x, x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert4(self:"Tree5", x:int, x2:int, x3:int, x4:int) -> object:
if self.root is None:
self.root = makeNode5(x, x, x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert5(self:"Tree5", x:int, x2:int, x3:int, x4:int, x5:int) -> object:
if self.root is None:
self.root = makeNode5(x, x, x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def contains(self:"Tree5", x:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains2(self:"Tree5", x:int, x2:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains3(self:"Tree5", x:int, x2:int, x3:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains4(self:"Tree5", x:int, x2:int, x3:int, x4:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains5(self:"Tree5", x:int, x2:int, x3:int, x4:int, x5:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def makeNode(x: int) -> TreeNode:
b:TreeNode = None
b = TreeNode()
b.value = x
return b
def makeNode2(x: int, x2: int) -> TreeNode2:
b:TreeNode2 = None
b2:TreeNode2 = None
b = TreeNode2()
b.value = x
return b
def makeNode3(x: int, x2: int, x3: int) -> TreeNode3:
b:TreeNode3 = None
b2:TreeNode3 = None
b3:TreeNode3 = None
b = TreeNode3()
b.value = x
return b
def makeNode4(x: int, x2: int, x3: int, x4: int) -> TreeNode4:
b:TreeNode4 = None
b2:TreeNode4 = None
b3:TreeNode4 = None
b4:TreeNode4 = None
b = TreeNode4()
b.value = x
return b
def makeNode5(x: int, x2: int, x3: int, x4: int, x5: int) -> TreeNode5:
b:TreeNode5 = None
b2:TreeNode5 = None
b3:TreeNode5 = None
b4:TreeNode5 = None
b5:TreeNode5 = None
b = TreeNode5()
b.value = x
return b
# Input parameters
n:int = 100
n2:int = 100
n3:int = 100
n4:int = 100
n5:int = 100
c:int = 4
c2:int = 4
c3:int = 4
c4:int = 4
c5:int = 4
# Data
t:Tree = None
t2:Tree = None
t3:Tree = None
t4:Tree = None
t5:Tree = None
i:int = 0
i2:int = 0
i3:int = 0
i4:int = 0
i5:int = 0
k:int = 37813
k2:int = 37813
k3:int = 37813
k4:int = 37813
k5:int = 37813
# Crunch
t = Tree()
while i < n:
t.insert(k)
k = (k * 37813) % 37831
if i % c != 0:
t.insert(i)
i = i + 1
print(t.size)
for i in [4, 8, 15, 16, 23, 42]:
if t.contains(i):
print(i)
| [
"[email protected]"
]
| |
9bb70d70f0b770a991f5cd4cae1d17455809d883 | 786de89be635eb21295070a6a3452f3a7fe6712c | /XtcExplorer/tags/V00-01-05/src/pyana_ipimb.py | 7ee053a8e5780fb49084fe992c18bc46ada427fb | []
| no_license | connectthefuture/psdmrepo | 85267cfe8d54564f99e17035efe931077c8f7a37 | f32870a987a7493e7bf0f0a5c1712a5a030ef199 | refs/heads/master | 2021-01-13T03:26:35.494026 | 2015-09-03T22:22:11 | 2015-09-03T22:22:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,555 | py | #
# ipimb.py: plot beamline data
#
#
import numpy as np
import matplotlib.pyplot as plt
from pypdsdata import xtc
from utilities import PyanaOptions
from utilities import IpimbData
# analysis class declaration
class pyana_ipimb ( object ) :
def __init__ ( self,
sources = None,
plot_every_n = "0",
accumulate_n = "0",
fignum = "1" ) :
"""
@param ipimb_addresses list of IPIMB addresses
@param plot_every_n Zero (don't plot until the end), or N (int, plot every N event)
@param accumulate_n Accumulate all (0) or reset the array every n shots
@param fignum matplotlib figure number
"""
# initialize data
opt = PyanaOptions()
self.sources = opt.getOptStrings(sources)
print "pyana_ipimb, %d sources: " % len(self.sources)
for source in self.sources :
print " ", source
self.plot_every_n = opt.getOptInteger(plot_every_n)
self.accumulate_n = opt.getOptInteger(accumulate_n)
self.mpl_num = opt.getOptInteger(fignum)
# other
self.n_shots = None
self.accu_start = None
# lists to fill numpy arrays
self.initlists()
def initlists(self):
self.fex_sum = {}
self.fex_channels = {}
self.fex_position = {}
self.raw_channels = {}
for source in self.sources :
self.fex_sum[source] = list()
self.fex_channels[source] = list()
self.fex_position[source] = list()
self.raw_channels[source] = list()
def resetlists(self):
self.accu_start = self.n_shots
for source in self.sources :
del self.fex_sum[source][:]
del self.fex_channels[source][:]
del self.fex_position[source][:]
del self.raw_channels[source][:]
def beginjob ( self, evt, env ) :
self.n_shots = 0
self.accu_start = 0
self.data = {}
for source in self.sources :
self.data[source] = IpimbData( source )
def event ( self, evt, env ) :
self.n_shots+=1
if evt.get('skip_event') :
return
# IPM diagnostics, for saturation and low count filtering
for source in self.sources :
# raw data
ipmRaw = evt.get(xtc.TypeId.Type.Id_IpimbData, source )
if ipmRaw :
channelVoltages = []
channelVoltages.append( ipmRaw.channel0Volts() )
channelVoltages.append( ipmRaw.channel1Volts() )
channelVoltages.append( ipmRaw.channel2Volts() )
channelVoltages.append( ipmRaw.channel3Volts() )
self.raw_channels[source].append( channelVoltages )
else :
print "pyana_ipimb: No IpimbData from %s found" % source
# feature-extracted data
ipmFex = evt.get(xtc.TypeId.Type.Id_IpmFex, source )
if ipmFex :
self.fex_sum[source].append( ipmFex.sum )
self.fex_channels[source].append( ipmFex.channel )
self.fex_position[source].append( [ipmFex.xpos, ipmFex.ypos] )
else :
print "pyana_ipimb: No IpmFex from %s found" % source
# ----------------- Plotting ---------------------
if self.plot_every_n != 0 and (self.n_shots%self.plot_every_n)==0 :
header = "DetInfo:IPIMB data shots %d-%d" % (self.accu_start, self.n_shots)
self.make_plots(title=header)
# convert dict to a list:
data_ipimb = []
for source in self.sources :
data_ipimb.append( self.data[source] )
# give the list to the event object
evt.put( data_ipimb, 'data_ipimb' )
# --------- Reset -------------
if self.accumulate_n!=0 and (self.n_shots%self.accumulate_n)==0 :
self.resetlists()
def endjob( self, evt, env ) :
# ----------------- Plotting ---------------------
header = "DetInfo:IPIMB data shots %d-%d" % (self.accu_start, self.n_shots)
self.make_plots(title=header)
# convert dict to a list:
data_ipimb = []
for source in self.sources :
data_ipimb.append( self.data[source] )
# give the list to the event object
evt.put( data_ipimb, 'data_ipimb' )
def make_plots(self, title = ""):
# -------- Begin: move this to beginJob
""" This part should move to begin job, but I can't get
it to update the plot in SlideShow mode when I don't recreate
the figure each time. Therefore plotting is slow...
"""
ncols = 3
nrows = len(self.sources)
height=3.5
if nrows * 3.5 > 12 : height = 12/nrows
width=height*1.3
fig = plt.figure(num=self.mpl_num, figsize=(width*ncols,height*nrows) )
fig.clf()
fig.subplots_adjust(wspace=0.45, hspace=0.45)
fig.suptitle(title)
self.ax = []
for i in range (0, 3*len(self.sources)):
self.ax.append( fig.add_subplot(nrows, ncols, i) )
# -------- End: move this to beginJob
i = 0
for source in self.sources :
xaxis = np.arange( self.accu_start, self.n_shots )
#xaxis = np.arange( 0, len(self.fex_channels[source]) )
#ax1 = fig.add_subplot(nrows, ncols, i)
#plt.axes(self.ax[i])
self.ax[i].clear()
plt.axes(self.ax[i])
array = np.float_(self.fex_sum[source])
#plt.hist(array, 60)
plt.plot(xaxis,array)
plt.title(source)
plt.ylabel('Sum of channels',horizontalalignment='left') # the other right
plt.xlabel('Shot number',horizontalalignment='left') # the other right
i+=1
self.data[source].fex_sum = array
#ax2 = fig.add_subplot(nrows, ncols, i)
self.ax[i].clear()
plt.axes(self.ax[i])
array = np.float_(self.fex_channels[source])
#plt.plot(xaxis, array[:,0],xaxis, array[:,1],xaxis, array[:,2],xaxis, array[:,3])
plt.hist(array[:,0], 60, histtype='stepfilled', color='r', label='Ch0')
plt.hist(array[:,1], 60, histtype='stepfilled', color='b', label='Ch1')
plt.hist(array[:,2], 60, histtype='stepfilled', color='y', label='Ch2')
plt.hist(array[:,3], 60, histtype='stepfilled', color='m', label='Ch3')
plt.title(source)
plt.xlabel('IPIMB Value',horizontalalignment='left') # the other right
leg = self.ax[i].legend()#('ch0','ch1','ch2','ch3'),'upper center')
i+=1
self.data[source].fex_channels = array
self.data[source].raw_channels = np.float_(self.raw_channels[source])
#ax3 = fig.add_subplot(nrows, ncols, i)
self.ax[i].clear()
plt.axes(self.ax[i])
array2 = np.float_(self.fex_position[source])
plt.scatter(array2[:,0],array2[:,1])
plt.title(source)
plt.xlabel('Beam position X',horizontalalignment='left')
plt.ylabel('Beam position Y',horizontalalignment='left')
i+=1
self.data[source].fex_position = array2
plt.draw()
| [
"[email protected]@b967ad99-d558-0410-b138-e0f6c56caec7"
]
| [email protected]@b967ad99-d558-0410-b138-e0f6c56caec7 |
09a018a907737d3860489bfb1e283fb3076ae253 | 5d0edf31b17c5375faf6126c1a7be8e79bfe2ab8 | /buildout-cache/eggs/plone.app.i18n-2.0.3-py2.7.egg/plone/app/i18n/locales/browser/selector.py | b1c3042a8d637678e18e64d7d376cfaf252eb48d | []
| no_license | renansfs/Plone_SP | 27cba32ebd9fc03dae3941ec23cf1bf0a7b6667a | 8a7bdbdb98c3f9fc1073c6061cd2d3a0ec80caf5 | refs/heads/master | 2021-01-15T15:32:43.138965 | 2016-08-24T15:30:19 | 2016-08-24T15:30:19 | 65,313,812 | 0 | 3 | null | null | null | null | UTF-8 | Python | false | false | 4,422 | py | from zope.interface import implements
from zope.viewlet.interfaces import IViewlet
from Products.CMFCore.utils import getToolByName
from Products.Five.browser import BrowserView
class LanguageSelector(BrowserView):
"""Language selector.
>>> ls = LanguageSelector(None, dict(), None, None)
>>> ls
<plone.app.i18n.locales.browser.selector.LanguageSelector object at ...>
>>> ls.update()
>>> ls.available()
False
>>> ls.languages()
[]
>>> ls.showFlags()
False
>>> class Tool(object):
... use_cookie_negotiation = False
... supported_langs = ['de', 'en', 'ar']
... always_show_selector = False
...
... def __init__(self, **kw):
... self.__dict__.update(kw)
...
... def getSupportedLanguages(self):
... return self.supported_langs
...
... def showFlags(self):
... return True
...
... def getAvailableLanguageInformation(self):
... return dict(en={'selected' : True}, de={'selected' : False},
... nl={'selected' : True}, ar={'selected': True})
...
... def getLanguageBindings(self):
... # en = selected by user, nl = default, [] = other options
... return ('en', 'nl', [])
...
... def showSelector(self):
... return bool(self.use_cookie_negotiation or self.always_show_selector)
>>> ls.tool = Tool()
>>> ls.available()
False
>>> ls.tool = Tool(use_cookie_negotiation=True)
>>> ls.available()
True
>>> ls.languages()
[{'code': 'en', 'selected': True}, {'code': 'ar', 'selected': False},
{'code': 'nl', 'selected': False}]
>>> ls.showFlags()
True
>>> ls.tool = Tool(use_cookie_negotiation=True)
>>> ls.available()
True
>>> ls.tool = Tool(always_show_selector=True)
>>> ls.available()
True
>>> from zope.interface import implements
>>> from OFS.interfaces import IItem
>>> class Dummy(object):
... implements(IItem)
... def getPortalObject(self):
... return self
... def absolute_url(self):
... return 'absolute url'
>>> context = Dummy()
>>> context.portal_url = Dummy()
>>> ls = LanguageSelector(context, dict(), None, None)
>>> ls.portal_url()
'absolute url'
"""
implements(IViewlet)
def __init__(self, context, request, view, manager):
super(LanguageSelector, self).__init__(context, request)
self.context = context
self.request = request
self.view = view
self.manager = manager
def update(self):
self.tool = getToolByName(self.context, 'portal_languages', None)
def available(self):
if self.tool is not None:
selector = self.tool.showSelector()
languages = len(self.tool.getSupportedLanguages()) > 1
return selector and languages
return False
def portal_url(self):
portal_tool = getToolByName(self.context, 'portal_url', None)
if portal_tool is not None:
return portal_tool.getPortalObject().absolute_url()
return None
def languages(self):
"""Returns list of languages."""
if self.tool is None:
return []
bound = self.tool.getLanguageBindings()
current = bound[0]
def merge(lang, info):
info["code"] = lang
if lang == current:
info['selected'] = True
else:
info['selected'] = False
return info
languages = [merge(lang, info) for (lang, info) in
self.tool.getAvailableLanguageInformation().items()
if info["selected"]]
# sort supported languages by index in portal_languages tool
supported_langs = self.tool.getSupportedLanguages()
def index(info):
try:
return supported_langs.index(info["code"])
except ValueError:
return len(supported_langs)
return sorted(languages, key=index)
def showFlags(self):
"""Do we use flags?."""
if self.tool is not None:
return self.tool.showFlags()
return False
| [
"[email protected]"
]
| |
a979b2457aa15f38669ab8f4705db11263d03091 | 2a171178942a19afe9891c2425dce208ae04348b | /kubernetes/test/test_runtime_raw_extension.py | cd032512be70fb92fa0bda986b64e64902f7a786 | [
"Apache-2.0"
]
| permissive | ouccema/client-python | ac3f1dee1c5ad8d82f15aeecb87a2f5f219ca4f4 | d7f33ec53e302e66674df581904a3c5b1fcf3945 | refs/heads/master | 2021-01-12T03:17:54.274888 | 2017-01-03T22:13:14 | 2017-01-03T22:13:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,460 | py | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.5.0-snapshot
Generated by: https://github.com/swagger-api/swagger-codegen.git
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.
"""
from __future__ import absolute_import
import os
import sys
import unittest
import kubernetes.client
from kubernetes.client.rest import ApiException
from kubernetes.client.models.runtime_raw_extension import RuntimeRawExtension
class TestRuntimeRawExtension(unittest.TestCase):
""" RuntimeRawExtension unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testRuntimeRawExtension(self):
"""
Test RuntimeRawExtension
"""
model = kubernetes.client.models.runtime_raw_extension.RuntimeRawExtension()
if __name__ == '__main__':
unittest.main()
| [
"[email protected]"
]
| |
544fc0b34f29d0d1c9f3ba62a97bca006fbb1688 | 98c6ea9c884152e8340605a706efefbea6170be5 | /examples/data/Assignment_1/srrmik001/question2.py | e69bea6d4cc917f38fed872b3bdcfe0cac9366f6 | []
| no_license | MrHamdulay/csc3-capstone | 479d659e1dcd28040e83ebd9e3374d0ccc0c6817 | 6f0fa0fa1555ceb1b0fb33f25e9694e68b6a53d2 | refs/heads/master | 2021-03-12T21:55:57.781339 | 2014-09-22T02:22:22 | 2014-09-22T02:22:22 | 22,372,174 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 369 | py | # Mikhaila Sorour
# 3 March 2014
# Program to check the validity of time
hours = eval(input("Enter the hours:\n"))
minutes = eval(input("Enter the minutes:\n"))
seconds = eval(input("Enter the seconds:\n"))
if (0 <= hours <= 24) and (0 <= minutes <= 59) and (0 <= seconds <= 59):
print("Your time is valid.")
else:
print ("Your time is invalid.")
| [
"[email protected]"
]
| |
9f9942f6f845c4509deedbae7579929c9e3bc703 | cff52d298fcbc8d386e73a47cfbebc9be18290ce | /kuterless/nice_to_meet_you/control.py | 27c923c5634f1997189e076391d8d59903636562 | []
| no_license | justminime/NeuroNet | b5c8c230133554ba5e9f971b956c64f6f1a62e79 | 683c3ffe53a9c4f5fd8c2b8c475e44febc859971 | refs/heads/master | 2023-08-08T00:34:49.475359 | 2018-12-18T22:03:30 | 2018-12-18T22:03:30 | 163,107,131 | 0 | 0 | null | 2023-09-06T06:59:37 | 2018-12-25T19:34:54 | Python | UTF-8 | Python | false | false | 2,525 | py | # -*- coding: utf-8 -*-
"""
This file contain the control services, used for all views
"""
#from coplay.models import UserProfile, Discussion, UserUpdate
from django.contrib.auth.models import User
from django.core.mail.message import EmailMessage
from django.core.urlresolvers import reverse
from django.template.base import Template
from django.template.context import Context
from django.template.loader import render_to_string
from django.utils import timezone
from rest_framework.authtoken.models import Token
from taggit.models import Tag
import kuterless.settings
#from gtts import gTTS
import pyqrcode
from kuterless.settings import SITE_URL, MEDIA_URL
def get_sound_to_play_name(acquaintance_id):
# return "media/message" + str(acquaintance_id)+".mp3"
num_of_messages = 8
return "media/audio_messages/default_message"+str(acquaintance_id % num_of_messages)+".mp3"
def get_buisness_card_name(buisness_card_id):
return "media/buisness_card" + str(buisness_card_id)+".vcf"
def get_buisness_qr_code_image_name(buisness_card_id):
return MEDIA_URL + "buisness_card_qr" + str(buisness_card_id)+".png"
def update_vcf_file(buisness_card_id,private_name = '',family_name = '', email = '', phone_number = '', url = ''):
serialized_vcard = ''
serialized_vcard += 'BEGIN:VCARD\r\n'#BEGIN:VCARD
serialized_vcard += 'VERSION:3.0\r\n'#VERSION:3.0
serialized_vcard += 'FN:'+ private_name + ' ' + family_name + '\r\n'#FN:Pname Fname
serialized_vcard += 'N:'+ family_name + ';' + private_name + ';;;\r\n'#N:Fname;Pname;;;
serialized_vcard += 'EMAIL;TYPE=INTERNET;TYPE=HOME:' + email + '\r\n'#EMAIL;TYPE=INTERNET;TYPE=HOME:[email protected]
serialized_vcard += 'TEL;TYPE=CELL:' + phone_number + '\r\n'#TEL;TYPE=CELL:0522947775
if url:
serialized_vcard += 'URL:'+ url + '\r\n'#URL:hp.com
serialized_vcard += 'END:VCARD\r\n'#END:VCARD
with open(get_buisness_card_name(buisness_card_id), "wb") as f:
f.write( serialized_vcard)
buisness_card_url = reverse('nice_to_meet_you:scan_card', kwargs={'pk': str(buisness_card_id)})
url = pyqrcode.create(SITE_URL + buisness_card_url)
with open(get_buisness_qr_code_image_name(buisness_card_id)[1:], 'wb') as fstream:
url.png(fstream, scale=5)
def update_sound_to_play_file(acquaintance_id, message):
return None
# tts_object = gTTS( text = message, lang='en', slow=False)
# tts_object.save(get_sound_to_play_name(acquaintance_id))
| [
"[email protected]"
]
| |
9eb2742835cce3707419ca4eba4a07b4310eb473 | 3780a5612c7a3c084f9106840e19e6fc07f135df | /prefect/migrations/0001_initial.py | 752252a6f24b65190d8976e2f377c0f62ab37ea6 | [
"MIT"
]
| permissive | dschien/energy-aggregator | 7a6f487db7a5fdbafc92152371ffedfc39f71f2e | 421638029c5066c3182e8c94424abf5a6b05c1ea | refs/heads/master | 2021-01-01T05:11:16.303483 | 2016-10-25T17:52:01 | 2016-10-25T17:52:01 | 71,920,880 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 973 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-07-21 16:27
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('ep', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='PrefectDeviceParameterConfiguration',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('power_consumption', models.DecimalField(decimal_places=2, max_digits=7)),
('line', models.CharField(max_length=2)),
('device', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='configuration', to='ep.Device')),
],
options={
'verbose_name': 'Prefect Device Configuration',
},
),
]
| [
"[email protected]"
]
| |
2e388c4a7d35230a2f16bf9b5800ce21de947eb3 | 42bf795f97efe36291590879dd1d2e146df1a4f0 | /User_details/decorators.py | 6a3e46c903d5138679b94eed874fc62faa36b601 | []
| no_license | sameesayeed007/tango-backend | b0e05fcdfe4b6c5f5a2cb501f6ef1e94da145811 | 05923a80ef4e464a5baa27102d678b1d8858f787 | refs/heads/master | 2022-12-30T18:57:52.180073 | 2020-10-25T09:08:35 | 2020-10-25T09:08:35 | 291,616,184 | 0 | 2 | null | 2020-10-05T05:48:05 | 2020-08-31T04:41:57 | Python | UTF-8 | Python | false | false | 1,099 | py | from django.http import HttpResponse
from django.shortcuts import redirect
def unauthenticated_user(view_func):
def wrapper_func(request, *args, **kwargs):
if request.user.is_authenticated:
return redirect('/')
else:
return view_func(request, *args, **kwargs)
return wrapper_func
def allowed_users(allowed_roles=[]):
def decorator(view_func):
def wrapper_func(request, *args, **kwargs):
group = None
if request.user.groups.exists():
group = request.user.groups.all()[0].name
if group in allowed_roles:
return view_func(request, *args, **kwargs)
else:
return HttpResponse('You are not authorized to view this page')
return wrapper_func
return decorator
def admin_only(view_func):
def wrapper_function(request, *args, **kwargs):
group = None
if request.user.groups.exists():
group = request.user.groups.all()[0].name
if group == 'user':
return redirect('user-page')
elif group == 'admin':
return view_func(request, *args, **kwargs)
elif group == 'supplier':
return view_func(request, *args, **kwargs)
return wrapper_function
| [
"[email protected]"
]
| |
814f5968de17f5952b71e28a3b6183bddd55a086 | 2e582bc42f104e93be85cf6abffd258a36a5ec15 | /1487A/arena.py | 6d266b328f22a0410a98405aa90b801f80cc2cba | []
| no_license | akantuni/Codeforces | d2f86f1dd156aef300e797117a9ef21927c8fef0 | 6901a982cbaf705fdb22e5f78999a5b82917bb23 | refs/heads/master | 2023-06-14T18:02:37.316810 | 2021-07-10T19:13:13 | 2021-07-10T19:13:13 | 289,826,328 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 295 | py | t = int(input())
for k in range(t):
n = int(input())
heroes = sorted(list(map(int, input().split())))
if len(set(heroes)) == 1:
print(0)
else:
for i, hero in enumerate(heroes):
if hero > heroes[0]:
print(n - i)
break
| [
"[email protected]"
]
| |
56bb4c3df12e4fd71898de232f1404e82a3cb36e | 54b31b705d88e21bc0b23aabe1df15ca13a07de2 | /bayespy/discrete_example.py | 680d647f49cdac991073a70d4427c783c026955a | [
"MIT",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unknown-license-reference",
"AFL-3.0",
"GPL-1.0-or-later",
"BSD-3-Clause",
"Apache-2.0"
]
| permissive | bayespy/bayespy | 307ef4c51d511e14d4693cce9929dda37124d11d | 5fe58f7160ebc3a9df7f9e96e50d2bd47837794a | refs/heads/develop | 2023-08-18T21:35:27.744022 | 2023-05-25T08:16:36 | 2023-05-25T08:16:36 | 5,568,322 | 655 | 164 | MIT | 2023-08-15T09:31:55 | 2012-08-27T08:10:20 | Python | UTF-8 | Python | false | false | 1,910 | py | # This example could be simplified a little bit by using Bernoulli instead of
# Categorical, but Categorical makes it possible to use more categories than
# just TRUE and FALSE.
import numpy as np
from bayespy.nodes import Categorical, Mixture
from bayespy.inference import VB
# NOTE: Python's built-in booleans don't work nicely for indexing, thus define
# own variables:
FALSE = 0
TRUE = 1
def _or(p_false, p_true):
"""
Build probability table for OR-operation of two parents
p_false: Probability table to use if both are FALSE
p_true: Probability table to use if one or both is TRUE
"""
return np.take([p_false, p_true], [[FALSE, TRUE], [TRUE, TRUE]], axis=0)
asia = Categorical([0.5, 0.5])
tuberculosis = Mixture(asia, Categorical, [[0.99, 0.01], [0.8, 0.2]])
smoking = Categorical([0.5, 0.5])
lung = Mixture(smoking, Categorical, [[0.98, 0.02], [0.25, 0.75]])
bronchitis = Mixture(smoking, Categorical, [[0.97, 0.03], [0.08, 0.92]])
xray = Mixture(tuberculosis, Mixture, lung, Categorical,
_or([0.96, 0.04], [0.115, 0.885]))
dyspnea = Mixture(bronchitis, Mixture, tuberculosis, Mixture, lung, Categorical,
[_or([0.6, 0.4], [0.18, 0.82]),
_or([0.11, 0.89], [0.04, 0.96])])
# Mark observations
tuberculosis.observe(TRUE)
smoking.observe(FALSE)
bronchitis.observe(TRUE) # not a "chance" observation as in the original example
# Run inference
Q = VB(dyspnea, xray, bronchitis, lung, smoking, tuberculosis, asia)
Q.update(repeat=100)
# Show results
print("P(asia):", asia.get_moments()[0][TRUE])
print("P(tuberculosis):", tuberculosis.get_moments()[0][TRUE])
print("P(smoking):", smoking.get_moments()[0][TRUE])
print("P(lung):", lung.get_moments()[0][TRUE])
print("P(bronchitis):", bronchitis.get_moments()[0][TRUE])
print("P(xray):", xray.get_moments()[0][TRUE])
print("P(dyspnea):", dyspnea.get_moments()[0][TRUE])
| [
"[email protected]"
]
| |
ccd652427fbc4bbf97ee89ec2711fe34015941be | de8310ef0914f45bb3a5bba3b089edbf45148867 | /ArraysAndStrings/URLify.py | 5d34eb4fa524336e0ebef88751ba27fbcebd1eac | []
| no_license | agbarker/Cracking-the-Coding-Interview-Python | f51a053ffe45bd89958f8b1e6eeb4db4c1ed6129 | 6358275b5f921d3c0203795d6951a6d3292333cf | refs/heads/master | 2020-03-20T11:46:10.750589 | 2018-06-15T00:10:15 | 2018-06-15T00:10:15 | 137,411,516 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 746 | py | """Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string."""
"""Replacement in place is not possible in python as strings are immutable. Much of the input is unecessary in python due to this constraint. I have eliminated the length variable input."""
def urlify(string):
"""Converts string with spaces to valid url.
>>> urlify('taco cat')
'taco%20cat'
>>> urlify('cat')
'cat'"""
tokens = string.split(" ")
i = 1
result = tokens[0]
while i in range(len(tokens)):
result = result + '%20' + tokens[i]
i += 1
return result
| [
"[email protected]"
]
| |
5cc67c74ecd44738a48c2a8a28aec26cb911ffc9 | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/otherforms/_laming.py | 7c430ecc3c5017417aea135fc105890846dec859 | [
"MIT"
]
| permissive | cash2one/xai | de7adad1758f50dd6786bf0111e71a903f039b64 | e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6 | refs/heads/master | 2021-01-19T12:33:54.964379 | 2017-01-28T02:00:50 | 2017-01-28T02:00:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 214 | py |
#calss header
class _LAMING():
def __init__(self,):
self.name = "LAMING"
self.definitions = lam
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.basic = ['lam']
| [
"[email protected]"
]
| |
ef38d0e49ad09bd73b645413d4327879867a7aba | 33b2f392afef9b5e83e177fd3f0ef5582051b97d | /source_code/version_v1.0.2/wx/lib/pubsub/core/arg1/publisher.py | 6dc684450d9987d3289544ec5b29c09da6a994a5 | []
| no_license | luke1987515/Compatibility_Get_Reprt | eb0edbc33afcd59fb1efcb53d7eee1658d2c3009 | 2707b9dec5ee8c0a0cc90b6a3d4682970b21a1cb | refs/heads/master | 2021-01-10T07:39:06.111371 | 2016-01-26T06:34:51 | 2016-01-26T06:34:51 | 48,530,211 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,448 | py | """
Mixin for publishing messages to a topic's listeners. This will be
mixed into topicobj.Topic so that a user can use a Topic object to
send a message to the topic's listeners via a publish() method.
:copyright: Copyright since 2006 by Oliver Schoenborn, all rights reserved.
:license: BSD, see LICENSE_BSD_Simple.txt for details.
"""
from .publisherbase import PublisherBase
class Publisher(PublisherBase):
"""
Publisher that allows old-style Message.data messages to be sent
to listeners. Listeners take one arg (required, unless there is an
*arg), but can have kwargs (since they have default values).
"""
def sendMessage(self, topicName, data=None):
"""Send message of type topicName to all subscribed listeners,
with message data. If topicName is a subtopic, listeners
of topics more general will also get the message.
Note that any listener that lets a raised exception escape will
interrupt the send operation, unless an exception handler was
specified via pub.setListenerExcHandler().
"""
topicMgr = self.getTopicMgr()
topicObj = topicMgr.getOrCreateTopic(topicName)
# don't care if topic not final: topicObj.getListeners()
# will return nothing if not final but notification will still work
topicObj.publish(data)
def getMsgProtocol(self):
return 'arg1'
| [
"[email protected]"
]
| |
8a40cb445ac8644a94ee38c4497b48ecbcd1922d | 47927ae79f1af279e186e76c85a77c962802262d | /number-of-provinces/number-of-provinces.py | 1097ed6272ba003b0e3a436057a685835f5cbba7 | []
| no_license | asheeshcric/leetcode | 810b53c05c44aecea70aaa333041edf9540dd532 | 8e651348b8aaff2c7bf2a09327b73ff23b6f613f | refs/heads/main | 2023-08-15T12:57:43.347469 | 2021-10-12T23:53:14 | 2021-10-12T23:53:14 | 346,944,371 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,260 | py | class Solution:
def findCircleNum(self, isConnected: List[List[int]]) -> int:
graph = self.buildGraph(isConnected)
print(graph)
def dfs(node):
stack = [node]
while stack:
node = stack.pop()
if node in visited:
continue
for neigh in graph[node]:
stack.append(neigh)
visited.add(node)
# Now find the number of connected components
components = 0
visited = set()
for node in graph:
if node not in visited:
dfs(node)
components += 1
return components
def buildGraph(self, isConnected):
graph = dict()
for node, connections in enumerate(isConnected):
graph[node] = set()
for other_node, connection in enumerate(connections):
if other_node == node:
continue
if connection == 1:
# This means the node is connected to the original node
graph[node].add(other_node)
return graph
| [
"[email protected]"
]
| |
83ed6309f274d9843de88fa5fc4f0f94a7a6375c | 050fc5ca698dfd7612dee42aa980fc7b5eee40a2 | /tests/plugin/web/sw_fastapi/test_fastapi.py | db79f769eae13f255d37f5ef2543a8f5eaccad9a | [
"Apache-2.0"
]
| permissive | apache/skywalking-python | 8ac6ce06630c519f9984a45e74c1fcc88cf5b9d6 | 1a360228c63cd246dd4c5dd8e1f09bdd5556ad7d | refs/heads/master | 2023-09-05T02:45:56.225937 | 2023-08-28T22:19:24 | 2023-08-28T22:19:24 | 261,456,329 | 178 | 122 | Apache-2.0 | 2023-08-28T22:19:26 | 2020-05-05T12:13:49 | Python | UTF-8 | Python | false | false | 1,383 | py | #
# 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.
#
from typing import Callable
import pytest
import requests
from skywalking.plugins.sw_fastapi import support_matrix
from tests.orchestrator import get_test_vector
from tests.plugin.base import TestPluginBase
@pytest.fixture
def prepare():
# type: () -> Callable
return lambda *_: requests.get('http://0.0.0.0:9090/users?test=test1&test=test2&test2=test2', timeout=5)
class TestPlugin(TestPluginBase):
@pytest.mark.parametrize('version', get_test_vector(lib_name='fastapi', support_matrix=support_matrix))
def test_plugin(self, docker_compose, version):
self.validate()
| [
"[email protected]"
]
| |
1c757ce5d3ece2fec1e9f67392d79f90b9cbe48d | 377420d718094a37da2e170718cecd80435d425a | /google/ads/googleads/v4/resources/types/keyword_plan_ad_group_keyword.py | 43255c2418b375282bce90bbdcbac956b32c4c27 | [
"Apache-2.0"
]
| permissive | sammillendo/google-ads-python | ed34e737748e91a0fc5716d21f8dec0a4ae088c1 | a39748521847e85138fca593f3be2681352ad024 | refs/heads/master | 2023-04-13T18:44:09.839378 | 2021-04-22T14:33:09 | 2021-04-22T14:33:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,104 | py | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, 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 proto # type: ignore
from google.ads.googleads.v4.enums.types import keyword_match_type
from google.protobuf import wrappers_pb2 as wrappers # type: ignore
__protobuf__ = proto.module(
package="google.ads.googleads.v4.resources",
marshal="google.ads.googleads.v4",
manifest={"KeywordPlanAdGroupKeyword",},
)
class KeywordPlanAdGroupKeyword(proto.Message):
r"""A Keyword Plan ad group keyword.
Max number of keyword plan keywords per plan: 10000.
Attributes:
resource_name (str):
Immutable. The resource name of the Keyword Plan ad group
keyword. KeywordPlanAdGroupKeyword resource names have the
form:
``customers/{customer_id}/keywordPlanAdGroupKeywords/{kp_ad_group_keyword_id}``
keyword_plan_ad_group (google.protobuf.wrappers_pb2.StringValue):
The Keyword Plan ad group to which this
keyword belongs.
id (google.protobuf.wrappers_pb2.Int64Value):
Output only. The ID of the Keyword Plan
keyword.
text (google.protobuf.wrappers_pb2.StringValue):
The keyword text.
match_type (google.ads.googleads.v4.enums.types.KeywordMatchTypeEnum.KeywordMatchType):
The keyword match type.
cpc_bid_micros (google.protobuf.wrappers_pb2.Int64Value):
A keyword level max cpc bid in micros (e.g.
$1 = 1mm). The currency is the same as the
account currency code. This will override any
CPC bid set at the keyword plan ad group level.
Not applicable for negative keywords. (negative
= true) This field is Optional.
negative (google.protobuf.wrappers_pb2.BoolValue):
Immutable. If true, the keyword is negative.
"""
resource_name = proto.Field(proto.STRING, number=1)
keyword_plan_ad_group = proto.Field(
proto.MESSAGE, number=2, message=wrappers.StringValue,
)
id = proto.Field(proto.MESSAGE, number=3, message=wrappers.Int64Value,)
text = proto.Field(proto.MESSAGE, number=4, message=wrappers.StringValue,)
match_type = proto.Field(
proto.ENUM,
number=5,
enum=keyword_match_type.KeywordMatchTypeEnum.KeywordMatchType,
)
cpc_bid_micros = proto.Field(
proto.MESSAGE, number=6, message=wrappers.Int64Value,
)
negative = proto.Field(proto.MESSAGE, number=7, message=wrappers.BoolValue,)
__all__ = tuple(sorted(__protobuf__.manifest))
| [
"[email protected]"
]
| |
5f81c65e80c83744abc3c5e164e1f0a9d2296682 | 786027545626c24486753351d6e19093b261cd7d | /ghidra9.2.1_pyi/ghidra/util/task/TaskMonitor.pyi | 6d492035c2c3080b8d5e526b272a37ac4ea8c71f | [
"MIT"
]
| permissive | kohnakagawa/ghidra_scripts | 51cede1874ef2b1fed901b802316449b4bf25661 | 5afed1234a7266c0624ec445133280993077c376 | refs/heads/main | 2023-03-25T08:25:16.842142 | 2021-03-18T13:31:40 | 2021-03-18T13:31:40 | 338,577,905 | 14 | 1 | null | null | null | null | UTF-8 | Python | false | false | 5,972 | pyi | import ghidra.util.task
import java.lang
class TaskMonitor(object):
"""
TaskMonitor provides an interface by means of which a
potentially long running task can show its progress and also check if the user
has cancelled the operation.
Operations that support a task monitor should periodically
check to see if the operation has been cancelled and abort. If possible, the
operation should also provide periodic progress information. If it can estimate a
percentage done, then it should use the setProgress(int) method,
otherwise it should just call the setMessage(String) method.
"""
DUMMY: ghidra.util.task.TaskMonitor = ghidra.util.task.StubTaskMonitor@167dbce
NO_PROGRESS_VALUE: int = -1
def addCancelledListener(self, listener: ghidra.util.task.CancelledListener) -> None:
"""
Add cancelled listener
@param listener the cancel listener
"""
...
def cancel(self) -> None:
"""
Cancel the task
"""
...
def checkCanceled(self) -> None:
"""
Check to see if this monitor has been canceled
@throws CancelledException if monitor has been cancelled
"""
...
def clearCanceled(self) -> None:
"""
Clear the cancellation so that this TaskMonitor may be reused
"""
...
def equals(self, __a0: object) -> bool: ...
def getClass(self) -> java.lang.Class: ...
def getMaximum(self) -> long:
"""
Returns the current maximum value for progress
@return the maximum progress value
"""
...
def getMessage(self) -> unicode:
"""
Gets the last set message of this monitor
@return the message
"""
...
def getProgress(self) -> long:
"""
Returns the current progress value or {@link #NO_PROGRESS_VALUE} if there is no value
set
@return the current progress value or {@link #NO_PROGRESS_VALUE} if there is no value
set
"""
...
def hashCode(self) -> int: ...
def incrementProgress(self, incrementAmount: long) -> None:
"""
A convenience method to increment the current progress by the given value
@param incrementAmount The amount by which to increment the progress
"""
...
def initialize(self, max: long) -> None:
"""
Initialized this TaskMonitor to the given max values. The current value of this monitor
will be set to zero.
@param max maximum value for progress
"""
...
def isCancelEnabled(self) -> bool:
"""
Returns true if cancel ability is enabled
@return true if cancel ability is enabled
"""
...
def isCancelled(self) -> bool:
"""
Returns true if the user has cancelled the operation
@return true if the user has cancelled the operation
"""
...
def isIndeterminate(self) -> bool:
"""
Returns true if this monitor shows no progress
@return true if this monitor shows no progress
"""
...
def notify(self) -> None: ...
def notifyAll(self) -> None: ...
def removeCancelledListener(self, listener: ghidra.util.task.CancelledListener) -> None:
"""
Remove cancelled listener
@param listener the cancel listener
"""
...
def setCancelEnabled(self, enable: bool) -> None:
"""
Set the enablement of the Cancel button
@param enable true means to enable the cancel button
"""
...
def setIndeterminate(self, indeterminate: bool) -> None:
"""
An indeterminate task monitor may choose to show an animation instead of updating progress
@param indeterminate true if indeterminate
"""
...
def setMaximum(self, max: long) -> None:
"""
Set the progress maximum value
<p><b>
Note: setting this value will reset the progress to be the max if the progress is currently
greater than the new new max value.</b>
@param max maximum value for progress
"""
...
def setMessage(self, message: unicode) -> None:
"""
Sets the message displayed on the task monitor
@param message the message to display
"""
...
def setProgress(self, value: long) -> None:
"""
Sets the current progress value
@param value progress value
"""
...
def setShowProgressValue(self, showProgressValue: bool) -> None:
"""
True (the default) signals to paint the progress information inside of the progress bar
@param showProgressValue true to paint the progress value; false to not
"""
...
def toString(self) -> unicode: ...
@overload
def wait(self) -> None: ...
@overload
def wait(self, __a0: long) -> None: ...
@overload
def wait(self, __a0: long, __a1: int) -> None: ...
@property
def cancelEnabled(self) -> bool: ...
@cancelEnabled.setter
def cancelEnabled(self, value: bool) -> None: ...
@property
def cancelled(self) -> bool: ...
@property
def indeterminate(self) -> bool: ...
@indeterminate.setter
def indeterminate(self, value: bool) -> None: ...
@property
def maximum(self) -> long: ...
@maximum.setter
def maximum(self, value: long) -> None: ...
@property
def message(self) -> unicode: ...
@message.setter
def message(self, value: unicode) -> None: ...
@property
def progress(self) -> long: ...
@progress.setter
def progress(self, value: long) -> None: ...
@property
def showProgressValue(self) -> None: ... # No getter available.
@showProgressValue.setter
def showProgressValue(self, value: bool) -> None: ...
| [
"[email protected]"
]
| |
4c776c689923c340b8f7275b6b5350139f3b45f6 | 551e1190a7b1da5694ecb812eecf0ed44a4025ee | /arrfill.py | 82c3f569559ae964387875be01c812b0b23528ff | []
| no_license | Destroyer4114/Python | 5dc3d85a31c7d1867e71f050bdc84209d08a945c | 82fbdc75f367cecb16166b2e03a0e6fc38da2c62 | refs/heads/main | 2023-08-11T19:01:09.588798 | 2021-10-09T11:13:12 | 2021-10-09T11:13:12 | 351,766,636 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 161 | py | for i in range(int(input())):
n,m= map(int(),input().split())
s= [0]*(n)
for j in range(m):
x,y= map(int,input().split())
| [
"[email protected]"
]
| |
dc109bca51260581e325a5a3ee31aad9bb8d3296 | 70fa6468c768d4ec9b4b14fc94fa785da557f1b5 | /lib/surface/ml_engine/operations/cancel.py | 889a587d266cce0d2d87ee0d2731e7bceb68bdb2 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
]
| permissive | kylewuolle/google-cloud-sdk | d43286ef646aec053ecd7eb58566ab2075e04e76 | 75f09ebe779e99fdc3fd13b48621fe12bfaa11aa | refs/heads/master | 2020-04-20T22:10:41.774132 | 2019-01-26T09:29:26 | 2019-01-26T09:29:26 | 169,131,028 | 0 | 0 | NOASSERTION | 2019-02-04T19:04:40 | 2019-02-04T18:58:36 | Python | UTF-8 | Python | false | false | 1,350 | py | # -*- coding: utf-8 -*- #
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""ml-engine operations cancel command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.ml_engine import operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.ml_engine import flags
from googlecloudsdk.command_lib.ml_engine import operations_util
def _AddCancelArgs(parser):
flags.OPERATION_NAME.AddToParser(parser)
class Cancel(base.SilentCommand):
"""Cancel a Cloud ML Engine operation."""
@staticmethod
def Args(parser):
_AddCancelArgs(parser)
def Run(self, args):
return operations_util.Cancel(operations.OperationsClient(),
args.operation)
| [
"[email protected]"
]
| |
0a62e91e6809dd26fae2e255a028678e38365747 | d08b0a2ea1365e96c2143a3076d6f1cfce178321 | /learnPython-master/Python基础代码/生成器-杨辉三角.py | 9ad701e82460579ee6166ff43b0e04f20832dd4f | []
| no_license | xueyes/py3_study | f64060e5dbfcbf11c8d61de8561ce90bbb4e3c19 | a7d83b58ef95806f061f375952db604afe98bc13 | refs/heads/master | 2022-12-11T05:56:03.540612 | 2019-05-06T13:07:55 | 2019-05-06T13:07:55 | 162,883,421 | 1 | 0 | null | 2022-12-08T02:28:21 | 2018-12-23T11:02:31 | HTML | UTF-8 | Python | false | false | 372 | py | def triangles():
g = [1]
while True:
yield g
g.append(0)
g = [g[i] + g[i - 1] for i in range(len(g))]
# 方法二
# def Triangles():
# L = [1]
# while True:
# yield L
# L = [1] + [L[i-1]+L[i] for i in range(len(L)) if i>0] + [1]
n = 0
for t in triangles():
print(t)
n = n + 1
if n == 10:
break
| [
"[email protected]"
]
| |
bf1a535305ed6702198c8e6f86a7e35fc5ee1d24 | 6a6984544a4782e131510a81ed32cc0c545ab89c | /src/trigger-sim/resources/test/InIceSMTTest.py | e76d9b6cc051e6da93843ab9522e021036a89dad | []
| no_license | wardVD/IceSimV05 | f342c035c900c0555fb301a501059c37057b5269 | 6ade23a2fd990694df4e81bed91f8d1fa1287d1f | refs/heads/master | 2020-11-27T21:41:05.707538 | 2016-09-02T09:45:50 | 2016-09-02T09:45:50 | 67,210,139 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 601 | py | #!/usr/bin/env python
from I3Tray import *
from icecube import icetray, dataclasses, dataio, trigger_sim
from os.path import expandvars
import sys
from icecube.trigger_sim.inice_test_modules import TestSource, TestModule
tray = I3Tray()
gcd_file = expandvars("$I3_TESTDATA/sim/GeoCalibDetectorStatus_2013.56429_V1.i3.gz")
tray.AddModule("I3InfiniteSource", prefix=gcd_file, stream=icetray.I3Frame.DAQ)
tray.AddModule(TestSource)
tray.AddModule("SimpleMajorityTrigger", TriggerConfigID = 1006)
tray.AddModule(TestModule, TriggerConfigID = 1006)
tray.Execute(100)
tray.Finish()
| [
"[email protected]"
]
| |
c5b6007281a9882a1ead24bdfd1c6c3bfc974164 | a110cda0dd755a0aeeccaa349de5b7c8f836f7d9 | /Dynamo_0.9.X/Material.ImportAllFromProject.py | 8ebeabec311a77bd8f881b36999e9aede5824adc | []
| no_license | ksobon/archi-lab | 26d93ef07e4f571e73a78bc40299edd3dc84c2a6 | 9a8a57eccca899ace78a998dc7698ff7754fae6b | refs/heads/master | 2021-01-15T09:37:06.045588 | 2020-06-03T15:55:46 | 2020-06-03T15:55:46 | 26,090,112 | 6 | 5 | null | 2020-02-09T04:24:41 | 2014-11-02T19:02:28 | Python | UTF-8 | Python | false | false | 1,885 | py | # Copyright(c) 2015, Konrad K Sobon
# @arch_laboratory, http://archi-lab.net
# Import Element wrapper extension methods
import clr
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.Elements)
# Import DocumentManager and TransactionManager
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
doc = DocumentManager.Instance.CurrentDBDocument
uiapp = DocumentManager.Instance.CurrentUIApplication
app = uiapp.Application
# Import RevitAPI
clr.AddReference("RevitAPI")
import Autodesk
from Autodesk.Revit.DB import *
import sys
pyt_path = r'C:\Program Files (x86)\IronPython 2.7\Lib'
sys.path.append(pyt_path)
#The inputs to this node will be stored as a list in the IN variable.
dataEnteringNode = IN
RunIt = IN[1]
class CustomCopyHandler(IDuplicateTypeNamesHandler):
def OnDuplicateTypeNamesFound(self, args):
return DuplicateTypeAction.UseDestinationTypes
try:
if RunIt:
TransactionManager.Instance.EnsureInTransaction(doc)
errorReport = None
fileDoc = app.OpenDocumentFile(IN[0])
filter = ElementClassFilter(Material)
allMat = FilteredElementCollector(fileDoc).WherePasses(filter).ToElementIds()
trans = Autodesk.Revit.DB.Transform.Identity
co = CopyPasteOptions()
co.SetDuplicateTypeNamesHandler(CustomCopyHandler())
newIds = ElementTransformUtils.CopyElements(fileDoc, allMat, doc, trans, co)
output = []
if newIds != None:
for i in newIds:
output.append(doc.GetElement(i).ToDSType(False))
TransactionManager.Instance.TransactionTaskDone()
else:
errorReport = "Set Run it to true!"
except:
# if error accurs anywhere in the process catch it
import traceback
errorReport = traceback.format_exc()
#Assign your output to the OUT variable
if errorReport == None:
OUT = output
else:
OUT = errorReport
| [
"[email protected]"
]
| |
63e88f32f327f0a4fdb1cdcaada92096e1338efc | b7fe089a067bdefd917af1c6b8f0701d33a3cf77 | /tests/networks/backbones/test_efficientnet.py | 230ffbbe1d834ecd3fc0f385fc495db1d46c43e4 | [
"MIT"
]
| permissive | Ares2013/coreml | 145a186a8e12f95d836118d30ba9d4e533862c03 | cd9f8c5f2e8cec8da6c5842dd235339b2e32be38 | refs/heads/master | 2022-12-04T18:02:01.590739 | 2020-08-19T08:41:12 | 2020-08-19T08:41:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,722 | py | """Tests coreml.networks.backbones.efficientnet"""
import torch
import torch.nn as nn
import unittest
from coreml.networks.backbones.efficientnet import EfficientNet
class EfficientNetTestCase(unittest.TestCase):
"""Class to check the EfficientNet backbone"""
def test_efficientnet_b0(self):
"""Test efficientnet_b0"""
net = EfficientNet('tf_efficientnet_b0', num_classes=2, in_channels=1)
dummy = torch.ones((128, 1, 96, 64))
out = net(dummy)
self.assertTrue(out.shape, (128, 2))
def test_efficientnet_b4(self):
"""Test efficientnet_b4"""
net = EfficientNet('tf_efficientnet_b4', num_classes=2, in_channels=1)
dummy = torch.ones((128, 1, 96, 64))
out = net(dummy)
self.assertTrue(out.shape, (128, 2))
def test_efficientnet_b5(self):
"""Test efficientnet_b5"""
net = EfficientNet('tf_efficientnet_b5', num_classes=2, in_channels=1)
dummy = torch.ones((128, 1, 96, 64))
out = net(dummy)
self.assertTrue(out.shape, (128, 2))
def test_efficientnet_b7(self):
"""Test efficientnet_b7"""
net = EfficientNet('tf_efficientnet_b7', num_classes=2, in_channels=1)
dummy = torch.ones((128, 1, 96, 64))
out = net(dummy)
self.assertTrue(out.shape, (128, 2))
def test_efficientnet_features(self):
"""Test efficientnet extract_features"""
net = EfficientNet(
'tf_efficientnet_b0', num_classes=2, in_channels=1,
return_features=True)
dummy = torch.ones((128, 1, 224, 224))
out = net(dummy)
self.assertTrue(out.shape, (128, 1280, 7, 7))
if __name__ == "__main__":
unittest.main()
| [
"[email protected]"
]
| |
8d6463e395c349d2b2e673b0ba78279a143e92dd | f77d7a92e64766c1aaa888e91fb0377f1acd37a4 | /docs/photons_docs/config/ext/photons_errors.py | 94f270010e4c9e3de934fa4dbcff7e81d8607203 | [
"MIT"
]
| permissive | geoff-nixon/photons-core | e531b3dd6f20e51138d0a38a680f140dc01f409b | cd4aaca33a79485fe5bb8fc26bdf35b7a7064e4b | refs/heads/master | 2020-05-04T09:04:49.753358 | 2019-03-31T05:10:36 | 2019-03-31T05:10:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,221 | py | from photons_app.errors import PhotonsAppError
from photons_app import errors
from docutils.parsers.rst import Directive
from docutils import statemachine
import pkg_resources
import os
class ShowPhotonsErrorsModulesDirective(Directive):
has_content = True
def run(self):
template = []
for name in dir(errors):
thing = getattr(errors, name)
if thing is PhotonsAppError:
continue
if isinstance(thing, type) and issubclass(thing, PhotonsAppError):
template.extend([
".. autoclass:: photons_app.errors.{0}".format(name)
, ""
, " {0}".format(thing.desc)
, ""]
)
source = self.state_machine.input_lines.source(self.lineno - self.state_machine.input_offset - 1)
tab_width = self.options.get('tab-width', self.state.document.settings.tab_width)
lines = statemachine.string2lines('\n'.join(template), tab_width, convert_whitespace=True)
self.state_machine.insert_input(lines, source)
return []
def setup(app):
app.add_directive('photons_errors', ShowPhotonsErrorsModulesDirective)
| [
"[email protected]"
]
| |
7cebc0b0c1b61ec9172d4a4251419db4bd840f91 | 34ef83114e02b173bd2d55eb53ad399e738a8e3c | /django/code_test/blogstandart_2_0v/manage.py | 3ac52e0cdbc0544c74845cd8841cf6383e548d6b | []
| no_license | vavilon/Python3 | e976a18eb301e4953696d1e3f4730ed890da015a | 8c79729747ce51d60ad685e6a2e58292954ed7eb | refs/heads/master | 2023-01-09T13:44:37.408601 | 2018-01-25T22:41:14 | 2018-01-25T22:41:14 | 100,892,055 | 0 | 1 | null | 2022-12-26T20:29:27 | 2017-08-20T22:23:06 | Python | UTF-8 | Python | false | false | 548 | py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "blogstandart_2_0.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
| [
"[email protected]"
]
| |
3fbf36c2307e8a12c7191f45d321926234a141d6 | a37e5bcf2b8d0d9175acfc9fda999debe3af2fb3 | /manage.py | d0d841b35c308da5cfb50860b837ca8db9c06dc9 | []
| no_license | hanifsarwary/ClothingSite | d882f1bbec8922aafaa1384c52036826cf55854f | fcaedb49b43aaf85788e570757507bcb10746fd6 | refs/heads/master | 2020-08-12T14:45:19.806795 | 2019-12-04T13:17:00 | 2019-12-04T13:17:00 | 214,785,483 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 632 | py | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'clothingSite.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
| [
"[email protected]"
]
| |
73e931ed29a6009dd135a7b63818fc5e41753f96 | 12b5584956797fcb0f48e7971bc074ae13a37489 | /pySpatialTools/Discretization/spatialdiscretizer.py | 9f9b8bcc40782a92b41a8a406d94185d9ab8291a | [
"MIT"
]
| permissive | tgquintela/pySpatialTools | a0ef5b032310aa1c140e805f4ee8c4a40fd2d10e | e028008f9750521bf7d311f7cd3323c88d621ea4 | refs/heads/master | 2020-05-21T22:09:08.858084 | 2017-02-10T11:18:41 | 2017-02-10T11:18:41 | 39,067,763 | 8 | 0 | null | null | null | null | UTF-8 | Python | false | false | 10,341 | py |
"""
Spatial Discretizor
-------------------
Module which contains the classes to 'discretize' a topological space.
When we talk about discretize we talk about creating a non-bijective
mathematical application between two topological spaces.
The main function of an spatial discretization class is the transformation of
the spatial information of one element in some topological space to the spatial
information in another topological space in which each tological elements
contains a group of topological elements of the previous topological space.
If the point do not belong to the space discretized, the function has to
return -1.
The clases also implement some useful functions related with this task.
Conventions
-----------
- Region_id as int, regionslocs as numpy.ndarray (even if it is an int)
TODO
----
- Complete irregular discretizer.
- Assign regions to points.
- Multiple regions
- nd-grid discretization
- Retrieve only populated regions. (Renumerate populated regions)
- Multiple discretization types aggregated
- Compute contiguity using correlation measure
"""
import numpy as np
import warnings
from utils import check_discretizors, check_flag_multi
class BaseSpatialDiscretizor:
"""
Spatial Discretizor object. This object performs a discretization of the
spatial domain and it is able to do:
- Assign a static predefined regions to each point.
- Retrieve neighbourhood defined by static regions.
This class acts as a base of all possible discretizers.
"""
def __len__(self):
"""Returns the number of regions or discretization units."""
return len(np.unique(self.regions_id))
def __getitem__(self, key):
"""Get the regions_id which match with the input."""
if type(key) == int:
return self.regions_id[key]
else:
return self.discretize(key)
def _initialization(self):
"""Function to initialize useful class parameters for discretizers."""
## Conditionals initialization
if 'limits' not in dir(self):
self.limits = None
if 'borders' not in dir(self):
self.borders = None
if 'regionlocs' not in dir(self):
self.regionlocs = None
if 'regions_id' not in dir(self):
self.regions_id = None
check_discretizors(self)
def retrieve_region(self, element_i, info_i, ifdistance=False):
"""Retrieve the region to which the points given belong to in this
discretization.
**warning** it is in format retriever to be used in that way if the
user consider in that way.
Parameters
----------
element_i: numpy.ndarray, shape(n, m) or shape (n,)
the point or points we want to retrieve their regions.
info_i: optional [ignored]
the special information in order to retrieve neighs and regions.
ifdistance: bool
True if we want the distance.
Returns
-------
region: numpy.ndarray or int
the region id of the given points.
See also
--------
pySpatialTools.BaseRetriever
"""
region = self.discretize(element_i)
return region
def retrieve_neigh(self, element_i, elements):
"""Retrieve the neighs given a point using this discretization. Could
be an internal retrieve if element_i is an index or an external
retrieve if element_i it is not a point in elements (element_i is a
coordinates).
Parameters
----------
element_i: numpy.ndarray
the point location for which we want its neighbours using the given
discretization.
elements: optional
the spatial information of the elements from which we want to get
the neighs of element_i.
Returns
-------
logi: numpy.ndarray boolean
the boolean array of which elements are neighs (are in the same
region) of element_i.
"""
region = self.discretize(element_i)
regions = self.discretize(elements)
logi = self.check_neighbors(region, regions)
return logi
def discretize(self, elements):
"""Discretize elements given their region_id.
Parameters
----------
elements: optional
the spatial information of the elements for which we want to obtain
their region given that discretization.
Returns
-------
regions: numpy.ndarray of int
the region_id of each elements for this discretization.
"""
regions = self._map_loc2regionid(elements)
return regions
def belong_region(self, elements, region_id=None):
"""Function to compute the belonging of some elements to the regions
selected.
Parameters
----------
elements: optional
the coordinates of the elements we want to check its belonging to
the selected region.
region_id: int or None
the region we want to check. If it is None we will check the whole
region defined by the discretization.
Returns
-------
boolean: bool
the belonging to the selected region.
"""
if region_id is None:
regions = self.discretize(elements)
boolean = np.logical_not(self.check_neighbors(regions, -1))
else:
regions = self.discretize(elements)
boolean = self.check_neighbors(regions, region_id)
return boolean
def get_contiguity(self, region_id=None, *params):
"""Get the whole contiguity or the contiguos regions of a given region.
Parameters
----------
region_id: int or None
the regions we want to get their contiguous regions. If it is None
it is retrieved the whole map of contiguity.
params: list or tuple
the instructions of which considerations we need to compute the
contiguity we want.
Returns
-------
contiguity: list or list of lists
the contiguous regions.
"""
contiguity = self._compute_contiguity_geom(region_id, *params)
return contiguity
def get_limits(self, region_id=None):
"""Function to compute the limits of the region.
Parameters
----------
region_id: numpy.ndarray or int
the regions id of the regions we want to get their limits. If it is
None it is retrieved the limits of the whole discretized space.
Returns
-------
limits: numpy.ndarray
the limits with an specific ordering.
"""
## Check limits function
def check_limits(limits):
try:
assert len(limits.shape) == 1
assert len(limits) == self.n_dim * 2
return True
except:
try:
assert len(limits.shape) == self.n_dim
assert limits.shape == tuple([2]*self.n_dim)
return True
except:
return False
## Compute limits
if region_id is None:
limits = self.limits
else:
limits = self._compute_limits(region_id)
## Check output
if not check_limits(limits):
raise TypeError("Incorrect computation of limits.")
return limits
def get_activated_regions(self, elements, geom=True):
"""Get the regions that have at least one of the elements input in
them.
Parameters
----------
elements: optional
the spatial information of the elements for which we want to obtain
their region given that discretization.
Returns
-------
regions: numpy.ndarray
the regions which have some elements in them.
"""
if self.multiple:
discretized = self.discretize(elements)
## for weighted
if type(discretized) == tuple:
discretized = discretized[0]
regions = []
for e in discretized:
regions += list(e)
regions = np.unique(regions)
else:
regions = np.unique(self.discretize(elements))
return regions
def check_neighbors(self, regions, region):
"""Check if the region is in each of the regions of pre-discretized
list of elements.
Parameters
----------
regions: int or numpy.ndarray
the regions id we want to check if there are similar to region.
region: list or numpy.array
the assignation of regions.
Returns
-------
logi: numpy.ndarray boolean
the boolean array of which have region coincidence (are in the same
region).
"""
## Check if there is flag multi
flag_multi = check_flag_multi(regions)
if self.multiple:
logi = self._check_neighbors_multiple(region, regions)
else:
msg = "Regions multi-assigned in a not multi-assign discretizor."
if flag_multi:
warnings.warn(msg)
logi = self._check_neighbors_multiple(region, regions)
else:
logi = self._check_neighbors_individual(region, regions)
return logi
###########################################################################
########################### Auxiliar functions ############################
###########################################################################
def _check_neighbors_individual(self, region, regions):
"""Check if there is equal regions in a uni-assigned regions. Returns
a boolean array."""
logi = regions == region
return logi
def _check_neighbors_multiple(self, region, regions):
"""Check if there is equal regions in a multi-assigned regions. Returns
a boolean array."""
N_r = len(regions)
logi = np.zeros(N_r).astype(bool)
for i in xrange(N_r):
logi[i] = region in regions[i]
return logi
| [
"[email protected]"
]
| |
fcf6fabcce314d18894e8c1469786cb596d838ca | ba3231b25c60b73ca504cd788efa40d92cf9c037 | /nitro-python-13.0.36/nssrc/com/citrix/netscaler/nitro/resource/config/cmp/cmpparameter.py | e51711ea6a777ffce61fcf0443e72fca53c4133c | [
"Apache-2.0",
"Python-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | zhuweigh/vpx13 | f6d559ae85341e56472e3592cbc67062dac34b93 | b36caa3729d3ca5515fa725f2d91aeaabdb2daa9 | refs/heads/master | 2020-07-04T22:15:16.595728 | 2019-09-20T00:19:56 | 2019-09-20T00:19:56 | 202,435,307 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 16,484 | py | #
# Copyright (c) 2008-2019 Citrix Systems, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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.
#
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception
from nssrc.com.citrix.netscaler.nitro.util.nitro_util import nitro_util
class cmpparameter(base_resource) :
""" Configuration for CMP parameter resource. """
def __init__(self) :
self._cmplevel = None
self._quantumsize = None
self._servercmp = None
self._heurexpiry = None
self._heurexpirythres = None
self._heurexpiryhistwt = None
self._minressize = None
self._cmpbypasspct = None
self._cmponpush = None
self._policytype = None
self._addvaryheader = None
self._varyheadervalue = None
self._externalcache = None
self._feature = None
@property
def cmplevel(self) :
r"""Specify a compression level. Available settings function as follows:
* Optimal - Corresponds to a gzip GZIP level of 5-7.
* Best speed - Corresponds to a gzip level of 1.
* Best compression - Corresponds to a gzip level of 9.<br/>Default value: optimal<br/>Possible values = optimal, bestspeed, bestcompression.
"""
try :
return self._cmplevel
except Exception as e:
raise e
@cmplevel.setter
def cmplevel(self, cmplevel) :
r"""Specify a compression level. Available settings function as follows:
* Optimal - Corresponds to a gzip GZIP level of 5-7.
* Best speed - Corresponds to a gzip level of 1.
* Best compression - Corresponds to a gzip level of 9.<br/>Default value: optimal<br/>Possible values = optimal, bestspeed, bestcompression
"""
try :
self._cmplevel = cmplevel
except Exception as e:
raise e
@property
def quantumsize(self) :
r"""Minimum quantum of data to be filled before compression begins.<br/>Default value: 57344<br/>Minimum length = 8<br/>Maximum length = 63488.
"""
try :
return self._quantumsize
except Exception as e:
raise e
@quantumsize.setter
def quantumsize(self, quantumsize) :
r"""Minimum quantum of data to be filled before compression begins.<br/>Default value: 57344<br/>Minimum length = 8<br/>Maximum length = 63488
"""
try :
self._quantumsize = quantumsize
except Exception as e:
raise e
@property
def servercmp(self) :
r"""Allow the server to send compressed data to the Citrix ADC. With the default setting, the Citrix ADC appliance handles all compression.<br/>Default value: ON<br/>Possible values = ON, OFF.
"""
try :
return self._servercmp
except Exception as e:
raise e
@servercmp.setter
def servercmp(self, servercmp) :
r"""Allow the server to send compressed data to the Citrix ADC. With the default setting, the Citrix ADC appliance handles all compression.<br/>Default value: ON<br/>Possible values = ON, OFF
"""
try :
self._servercmp = servercmp
except Exception as e:
raise e
@property
def heurexpiry(self) :
r"""Heuristic basefile expiry.<br/>Default value: OFF<br/>Possible values = ON, OFF.
"""
try :
return self._heurexpiry
except Exception as e:
raise e
@heurexpiry.setter
def heurexpiry(self, heurexpiry) :
r"""Heuristic basefile expiry.<br/>Default value: OFF<br/>Possible values = ON, OFF
"""
try :
self._heurexpiry = heurexpiry
except Exception as e:
raise e
@property
def heurexpirythres(self) :
r"""Threshold compression ratio for heuristic basefile expiry, multiplied by 100. For example, to set the threshold ratio to 1.25, specify 125.<br/>Default value: 100<br/>Minimum length = 1<br/>Maximum length = 1000.
"""
try :
return self._heurexpirythres
except Exception as e:
raise e
@heurexpirythres.setter
def heurexpirythres(self, heurexpirythres) :
r"""Threshold compression ratio for heuristic basefile expiry, multiplied by 100. For example, to set the threshold ratio to 1.25, specify 125.<br/>Default value: 100<br/>Minimum length = 1<br/>Maximum length = 1000
"""
try :
self._heurexpirythres = heurexpirythres
except Exception as e:
raise e
@property
def heurexpiryhistwt(self) :
r"""For heuristic basefile expiry, weightage to be given to historical delta compression ratio, specified as percentage. For example, to give 25% weightage to historical ratio (and therefore 75% weightage to the ratio for current delta compression transaction), specify 25.<br/>Default value: 50<br/>Minimum length = 1<br/>Maximum length = 100.
"""
try :
return self._heurexpiryhistwt
except Exception as e:
raise e
@heurexpiryhistwt.setter
def heurexpiryhistwt(self, heurexpiryhistwt) :
r"""For heuristic basefile expiry, weightage to be given to historical delta compression ratio, specified as percentage. For example, to give 25% weightage to historical ratio (and therefore 75% weightage to the ratio for current delta compression transaction), specify 25.<br/>Default value: 50<br/>Minimum length = 1<br/>Maximum length = 100
"""
try :
self._heurexpiryhistwt = heurexpiryhistwt
except Exception as e:
raise e
@property
def minressize(self) :
r"""Smallest response size, in bytes, to be compressed.
"""
try :
return self._minressize
except Exception as e:
raise e
@minressize.setter
def minressize(self, minressize) :
r"""Smallest response size, in bytes, to be compressed.
"""
try :
self._minressize = minressize
except Exception as e:
raise e
@property
def cmpbypasspct(self) :
r"""Citrix ADC CPU threshold after which compression is not performed. Range: 0 - 100.<br/>Default value: 100<br/>Maximum length = 100.
"""
try :
return self._cmpbypasspct
except Exception as e:
raise e
@cmpbypasspct.setter
def cmpbypasspct(self, cmpbypasspct) :
r"""Citrix ADC CPU threshold after which compression is not performed. Range: 0 - 100.<br/>Default value: 100<br/>Maximum length = 100
"""
try :
self._cmpbypasspct = cmpbypasspct
except Exception as e:
raise e
@property
def cmponpush(self) :
r"""Citrix ADC does not wait for the quantum to be filled before starting to compress data. Upon receipt of a packet with a PUSH flag, the appliance immediately begins compression of the accumulated packets.<br/>Default value: DISABLED<br/>Possible values = ENABLED, DISABLED.
"""
try :
return self._cmponpush
except Exception as e:
raise e
@cmponpush.setter
def cmponpush(self, cmponpush) :
r"""Citrix ADC does not wait for the quantum to be filled before starting to compress data. Upon receipt of a packet with a PUSH flag, the appliance immediately begins compression of the accumulated packets.<br/>Default value: DISABLED<br/>Possible values = ENABLED, DISABLED
"""
try :
self._cmponpush = cmponpush
except Exception as e:
raise e
@property
def policytype(self) :
r"""Type of policy. Available settings function as follows:
* Classic - Classic policies evaluate basic characteristics of traffic and other data. Deprecated.
* Advanced - Advanced policies (which have been renamed as default syntax policies) can perform the same type of evaluations as classic policies. They also enable you to analyze more data (for example, the body of an HTTP request) and to configure more operations in the policy rule (for example, transforming data in the body of a request into an HTTP header).<br/>Possible values = CLASSIC, ADVANCED.
"""
try :
return self._policytype
except Exception as e:
raise e
@policytype.setter
def policytype(self, policytype) :
r"""Type of policy. Available settings function as follows:
* Classic - Classic policies evaluate basic characteristics of traffic and other data. Deprecated.
* Advanced - Advanced policies (which have been renamed as default syntax policies) can perform the same type of evaluations as classic policies. They also enable you to analyze more data (for example, the body of an HTTP request) and to configure more operations in the policy rule (for example, transforming data in the body of a request into an HTTP header).<br/>Possible values = CLASSIC, ADVANCED
"""
try :
self._policytype = policytype
except Exception as e:
raise e
@property
def addvaryheader(self) :
r"""Control insertion of the Vary header in HTTP responses compressed by Citrix ADC. Intermediate caches store different versions of the response for different values of the headers present in the Vary response header.<br/>Default value: DISABLED<br/>Possible values = ENABLED, DISABLED.
"""
try :
return self._addvaryheader
except Exception as e:
raise e
@addvaryheader.setter
def addvaryheader(self, addvaryheader) :
r"""Control insertion of the Vary header in HTTP responses compressed by Citrix ADC. Intermediate caches store different versions of the response for different values of the headers present in the Vary response header.<br/>Default value: DISABLED<br/>Possible values = ENABLED, DISABLED
"""
try :
self._addvaryheader = addvaryheader
except Exception as e:
raise e
@property
def varyheadervalue(self) :
r"""The value of the HTTP Vary header for compressed responses. If this argument is not specified, a default value of "Accept-Encoding" will be used.<br/>Minimum length = 1.
"""
try :
return self._varyheadervalue
except Exception as e:
raise e
@varyheadervalue.setter
def varyheadervalue(self, varyheadervalue) :
r"""The value of the HTTP Vary header for compressed responses. If this argument is not specified, a default value of "Accept-Encoding" will be used.<br/>Minimum length = 1
"""
try :
self._varyheadervalue = varyheadervalue
except Exception as e:
raise e
@property
def externalcache(self) :
r"""Enable insertion of Cache-Control: private response directive to indicate response message is intended for a single user and must not be cached by a shared or proxy cache.<br/>Default value: NO<br/>Possible values = YES, NO.
"""
try :
return self._externalcache
except Exception as e:
raise e
@externalcache.setter
def externalcache(self, externalcache) :
r"""Enable insertion of Cache-Control: private response directive to indicate response message is intended for a single user and must not be cached by a shared or proxy cache.<br/>Default value: NO<br/>Possible values = YES, NO
"""
try :
self._externalcache = externalcache
except Exception as e:
raise e
@property
def feature(self) :
r"""The feature to be checked while applying this config.
"""
try :
return self._feature
except Exception as e:
raise e
@feature.setter
def feature(self, feature) :
r"""The feature to be checked while applying this config.
"""
try :
self._feature = feature
except Exception as e:
raise e
def _get_nitro_response(self, service, response) :
r""" converts nitro response into object and returns the object array in case of get request.
"""
try :
result = service.payload_formatter.string_to_resource(cmpparameter_response, response, self.__class__.__name__)
if(result.errorcode != 0) :
if (result.errorcode == 444) :
service.clear_session(self)
if result.severity :
if (result.severity == "ERROR") :
raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
else :
raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
return result.cmpparameter
except Exception as e :
raise e
def _get_object_name(self) :
r""" Returns the value of object identifier argument
"""
try :
return 0
except Exception as e :
raise e
@classmethod
def update(cls, client, resource) :
r""" Use this API to update cmpparameter.
"""
try :
if type(resource) is not list :
updateresource = cmpparameter()
updateresource.cmplevel = resource.cmplevel
updateresource.quantumsize = resource.quantumsize
updateresource.servercmp = resource.servercmp
updateresource.heurexpiry = resource.heurexpiry
updateresource.heurexpirythres = resource.heurexpirythres
updateresource.heurexpiryhistwt = resource.heurexpiryhistwt
updateresource.minressize = resource.minressize
updateresource.cmpbypasspct = resource.cmpbypasspct
updateresource.cmponpush = resource.cmponpush
updateresource.policytype = resource.policytype
updateresource.addvaryheader = resource.addvaryheader
updateresource.varyheadervalue = resource.varyheadervalue
updateresource.externalcache = resource.externalcache
updateresource.feature = resource.feature
return updateresource.update_resource(client)
except Exception as e :
raise e
@classmethod
def unset(cls, client, resource, args) :
r""" Use this API to unset the properties of cmpparameter resource.
Properties that need to be unset are specified in args array.
"""
try :
if type(resource) is not list :
unsetresource = cmpparameter()
return unsetresource.unset_resource(client, args)
except Exception as e :
raise e
@classmethod
def get(cls, client, name="", option_="") :
r""" Use this API to fetch all the cmpparameter resources that are configured on netscaler.
"""
try :
if not name :
obj = cmpparameter()
response = obj.get_resources(client, option_)
return response
except Exception as e :
raise e
class Servercmp:
ON = "ON"
OFF = "OFF"
class Policytype:
CLASSIC = "CLASSIC"
ADVANCED = "ADVANCED"
class Cmponpush:
ENABLED = "ENABLED"
DISABLED = "DISABLED"
class Feature:
WL = "WL"
WebLogging = "WebLogging"
SP = "SP"
SurgeProtection = "SurgeProtection"
LB = "LB"
LoadBalancing = "LoadBalancing"
CS = "CS"
ContentSwitching = "ContentSwitching"
CR = "CR"
CacheRedirection = "CacheRedirection"
SC = "SC"
SureConnect = "SureConnect"
CMP = "CMP"
CMPcntl = "CMPcntl"
CompressionControl = "CompressionControl"
PQ = "PQ"
PriorityQueuing = "PriorityQueuing"
HDOSP = "HDOSP"
HttpDoSProtection = "HttpDoSProtection"
SSLVPN = "SSLVPN"
AAA = "AAA"
GSLB = "GSLB"
GlobalServerLoadBalancing = "GlobalServerLoadBalancing"
SSL = "SSL"
SSLOffload = "SSLOffload"
SSLOffloading = "SSLOffloading"
CF = "CF"
ContentFiltering = "ContentFiltering"
IC = "IC"
IntegratedCaching = "IntegratedCaching"
OSPF = "OSPF"
OSPFRouting = "OSPFRouting"
RIP = "RIP"
RIPRouting = "RIPRouting"
BGP = "BGP"
BGPRouting = "BGPRouting"
REWRITE = "REWRITE"
IPv6PT = "IPv6PT"
IPv6protocoltranslation = "IPv6protocoltranslation"
AppFw = "AppFw"
ApplicationFirewall = "ApplicationFirewall"
RESPONDER = "RESPONDER"
HTMLInjection = "HTMLInjection"
push = "push"
NSPush = "NSPush"
NetScalerPush = "NetScalerPush"
AppFlow = "AppFlow"
CloudBridge = "CloudBridge"
ISIS = "ISIS"
ISISRouting = "ISISRouting"
CH = "CH"
CallHome = "CallHome"
AppQoE = "AppQoE"
ContentAccelerator = "ContentAccelerator"
SYSTEM = "SYSTEM"
RISE = "RISE"
FEO = "FEO"
LSN = "LSN"
LargeScaleNAT = "LargeScaleNAT"
RDPProxy = "RDPProxy"
Rep = "Rep"
Reputation = "Reputation"
URLFiltering = "URLFiltering"
VideoOptimization = "VideoOptimization"
ForwardProxy = "ForwardProxy"
SSLInterception = "SSLInterception"
AdaptiveTCP = "AdaptiveTCP"
CQA = "CQA"
CI = "CI"
ContentInspection = "ContentInspection"
class Externalcache:
YES = "YES"
NO = "NO"
class Addvaryheader:
ENABLED = "ENABLED"
DISABLED = "DISABLED"
class Cmplevel:
optimal = "optimal"
bestspeed = "bestspeed"
bestcompression = "bestcompression"
class Heurexpiry:
ON = "ON"
OFF = "OFF"
class cmpparameter_response(base_response) :
def __init__(self, length=1) :
self.cmpparameter = []
self.errorcode = 0
self.message = ""
self.severity = ""
self.sessionid = ""
self.cmpparameter = [cmpparameter() for _ in range(length)]
| [
"[email protected]"
]
| |
a6b5ab6e0082d3f1e3ba47450999a097a86f5258 | cee8fb161f0bd4aa4345b1ec9c269e43cc10c2dd | /rtamt/operation/arithmetic/dense_time/online/exp_operation.py | 54fad220102af8c5dda57df0aba9870f88bcf60c | [
"BSD-3-Clause"
]
| permissive | TomyYamy/rtamt | 172510fc2b26188b1d7ed6f6cfefc6830508c9a1 | a16db77b61028f774d81457ff22e666229a5432c | refs/heads/master | 2023-09-05T00:06:44.375841 | 2021-11-12T09:46:58 | 2021-11-12T09:46:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 484 | py | import math
from rtamt.operation.abstract_operation import AbstractOperation
class ExpOperation(AbstractOperation):
def __init__(self):
self.input = []
def update(self, input_list):
out = []
for in_sample in input_list:
out_time = in_sample[0]
out_value = math.exp(in_sample[1])
out.append([out_time, out_value])
return out
def update_final(self, *args, **kargs):
return self.update(args[0]) | [
"[email protected]"
]
| |
0a2080933765ad216e8ef34c423e5dfdc1bbd3ec | f07a42f652f46106dee4749277d41c302e2b7406 | /Data Set/bug-fixing-5/0dade18f43cf5c015773d461ccff478f156179b5-<get_module_docs>-fix.py | 6399b208333447abdd182b8d1999ac8a8e8cbaf6 | []
| no_license | wsgan001/PyFPattern | e0fe06341cc5d51b3ad0fe29b84098d140ed54d1 | cc347e32745f99c0cd95e79a18ddacc4574d7faa | refs/heads/main | 2023-08-25T23:48:26.112133 | 2021-10-23T14:11:22 | 2021-10-23T14:11:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,481 | py | def get_module_docs(self, path, contents):
'\n :type path: str\n :type contents: str\n :rtype: dict[str, any]\n '
module_doc_types = ['DOCUMENTATION', 'EXAMPLES', 'RETURN']
docs = {
}
def check_assignment(statement, doc_types=None):
'Check the given statement for a documentation assignment.'
for target in statement.targets:
if isinstance(target, ast.Tuple):
continue
if (doc_types and (target.id not in doc_types)):
continue
docs[target.id] = dict(yaml=statement.value.s, lineno=statement.lineno, end_lineno=(statement.lineno + len(statement.value.s.splitlines())))
module_ast = self.parse_module(path, contents)
if (not module_ast):
return {
}
if path.startswith('lib/ansible/modules/'):
for body_statement in module_ast.body:
if isinstance(body_statement, ast.Assign):
check_assignment(body_statement, module_doc_types)
elif path.startswith('lib/ansible/utils/module_docs_fragments/'):
for body_statement in module_ast.body:
if isinstance(body_statement, ast.ClassDef):
for class_statement in body_statement.body:
if isinstance(class_statement, ast.Assign):
check_assignment(class_statement)
else:
raise Exception(('unsupported path: %s' % path))
return docs | [
"[email protected]"
]
| |
8d6b6341d97bf4d6bd372ca55ec0b55bb54141f4 | 33aeee667b5d55dfc48c39a96583b1eccf04961a | /P3python_dev/Demo/order_demo.py | 005fc3ba980240b0df6bfebb9f7673f8853dc3f9 | []
| no_license | yangtingting123456/python-unittest-requests-htmlrunner | fc2cbec7f0b36e4aa1be905db0dcc34d32262e93 | 9f155cbf3fc25d68ba0420837d03b4d7ac71f2b6 | refs/heads/master | 2023-01-06T10:18:21.979337 | 2020-10-26T09:18:43 | 2020-10-26T09:18:43 | 307,299,936 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 215 | py | #手动在控制台输入五个数字
nums=input('请输入任意五个数字:')
print(type(nums))
num=nums.split(' ')
print(type(num))
num.sort()
print(num)
num_list=num.sort(reverse=True)
print('%s'%num_list)
| [
"[email protected]"
]
| |
efb63d86ca30c1448d7cb0cab52ccbbac460ef26 | 7ce8670cc2b63a01aa4fa08ff040dc2ea2304c04 | /ecommarce/migrations/0022_auto_20180926_0539.py | c3e042f2634dc3a6a8d79a19d4f3431c3ae2b8ce | []
| no_license | Shamsulhaq/sonomm | bca793f21fbbb698a498159fc592063751099cd2 | 0d1fed65bfcc8829b80c018ca460ce198869a21f | refs/heads/master | 2020-03-26T08:05:46.667063 | 2018-11-28T18:41:35 | 2018-11-28T18:41:35 | 138,379,757 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 455 | py | # Generated by Django 2.1.1 on 2018-09-26 05:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ecommarce', '0021_auto_20180926_0535'),
]
operations = [
migrations.AlterField(
model_name='productbasic',
name='regular_price',
field=models.DecimalField(blank=True, decimal_places=2, default=0, max_digits=9, null=True),
),
]
| [
"[email protected]"
]
| |
e0b024e5b79c1d5f42ef9a23a54590144441cd5c | d2024f10e641ab2f28a888d23071edc032299498 | /pacer/pacer.py | e0eca0bd7271916fc0daebeb3fbf4c3dc9da0b15 | []
| no_license | chen116/demo2018 | 6f2ae07150182b8e14a2eacbc57bdc79c03e6dee | d289545bcc30445be26e1381d5301d8f657d0c6e | refs/heads/master | 2021-04-27T13:11:44.742650 | 2018-07-14T14:38:37 | 2018-07-14T14:38:37 | 122,435,014 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 734 | py | import heartbeat
import host_guest_comm
import numpy as np
import time
window_size_hr=5
hb = heartbeat.Heartbeat(1024,window_size_hr,100,"vic.log",10,100)
monitoring_items = ["heart_rate","app_mode","frame_size","timeslice"]
comm = host_guest_comm.DomU(monitoring_items)
it = 1
matsize = 500
comm.write("app_mode", 4)
comm.write("frame_size", matsize)
for i in range(it*6):
# hb stuff
a= np.random.rand(matsize, matsize)
b= np.random.rand(matsize, matsize)
tn = time.time()
c= np.matmul(b,a.T)
print(time.time()-tn)
time.sleep(0.1)
hb.heartbeat_beat()
print(hb.get_instant_heartrate())
if i%window_size_hr==0:
comm.write("heart_rate", hb.get_window_heartrate())
comm.write("heart_rate", "done")
hb.heartbeat_finish() | [
"[email protected]"
]
| |
c5fc28a9aac563a1e87570944ad552bfb2e8010e | 6ea83cee7623e2b1d28bb79d0e97645327627b0c | /old_code_before_revision_where_processed_google_sheet_csv_data_and_image_conversion_etc/hennur/pdf_generation/sub_elements/image.py | 0a968642bfbf4c07c6528dd4d7de831eaa014877 | []
| no_license | santokalayil/Address_Directory_Generaation_-_ReportLab_Automation | 6358134211f621a54c2734971947d52e22cce30a | ed00103c41aa358d5b3256ad0bfd5c4467ac231b | refs/heads/main | 2023-07-19T01:22:49.959251 | 2021-08-21T18:19:00 | 2021-08-21T18:19:00 | 352,067,628 | 4 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,365 | py | from reportlab.lib import colors
from pdf_generation.page_settings import *
from reportlab.platypus import Image, Table
class family_image:
def __init__(self, img_path):
self.img_path = img_path
def generate(self):
# pct = 0.9
img_width = (320 * 0.35) # * pct
img_height = (249 * 0.35) # * pct
img = Image(filename=self.img_path, width=img_width, height=img_height, )
img_table = Table(
data=[[img]],
colWidths=img_width,
rowHeights=img_height,
style=[
# The two (0, 0) in each attribute represent the range
# # of table cells that the style applies to. Since there's only one cell at (0, 0),
# it's used for both start and end of the range
('ALIGN', (0, 0), (0, 0), 'LEFT'),
# ('BOX', (0, 0), (0, 0), 2, colors.HexColor('#eeeeee')),
# The fourth argument to this style attribute is the border width
('VALIGN', (0, 0), (0, 0), 'MIDDLE'),
("TOPPADDING", (0, 0), (-1, -1), 0),
("BOTTOMPADDING", (0, 0), (-1, -1), 0),
("LEFTPADDING", (0, 0), (-1, -1), 0),
("RIGHTPADDING", (0, 0), (-1, -1), 0),
]
)
return img_table
| [
"[email protected]"
]
| |
7e7f0b264959e12721da8946df1b7451fb442b0a | d41d18d3ea6edd2ec478b500386375a8693f1392 | /plotly/validators/histogram/marker/_showscale.py | 9ae878dd8c435f88b4a47da9bbee1a5d4207006c | [
"MIT"
]
| permissive | miladrux/plotly.py | 38921dd6618650d03be9891d6078e771ffccc99a | dbb79e43e2cc6c5762251537d24bad1dab930fff | refs/heads/master | 2020-03-27T01:46:57.497871 | 2018-08-20T22:37:38 | 2018-08-20T22:37:38 | 145,742,203 | 1 | 0 | MIT | 2018-08-22T17:37:07 | 2018-08-22T17:37:07 | null | UTF-8 | Python | false | false | 451 | py | import _plotly_utils.basevalidators
class ShowscaleValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(
self,
plotly_name='showscale',
parent_name='histogram.marker',
**kwargs
):
super(ShowscaleValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type='calc',
role='info',
**kwargs
)
| [
"[email protected]"
]
| |
38d7a85500b2bafd860e807a46b3baa9a9b67ed5 | 6250be4dcf519d0f0b152b10a641b2d12a35c53f | /모두의 파이썬/09B-walk2.py | d4d4e3deb14c67dd29c705c8b12e322122bfcb15 | []
| no_license | heechul90/study-python-basic-2 | babd01f6a7c2b1fbed4aa31030bb40128960a989 | 94780478e59dfc998baa6e3069ab2473c5df74db | refs/heads/master | 2022-10-27T14:44:00.688509 | 2022-10-24T10:55:33 | 2022-10-24T10:55:33 | 196,142,410 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 616 | py | # 마음대로 걷는 거북이2
import turtle as t
import random
t.shape("turtle") # ‘거북이’모양의 거북이 그래픽을 사용합니다.
t.speed(0)
for x in range(500): # 거북이를 500번 움직입니다.
a = random.randint(1, 360) # 1~360 사이의 아무 수나 골라 a에 저장합니다.
t.setheading(a) # a 각도로 거북이의 방향을 돌립니다.
b = random.randint(1,20) # 추가: 1~20 사이의 아무 수나 골라 b에 저장합니다.
t.forward(b) # 수정: 10을 b로 고칩니다.
| [
"[email protected]"
]
| |
897865636e0146212d66ac2daf1a4de0fd3a642f | c80dff81cfec241e6baac8d7211ac16a969d28a4 | /Fitting/gaussian.py | 138544e57dcef5f40cb42915f41608b1afe6e8d2 | []
| no_license | Silentsoul04/PythonCode | 0043354002b3117f7c2b69a52ca14e664f978576 | c7301fb7983edbe3492e7d78d531ba2f427d2f3e | refs/heads/master | 2023-01-27T14:26:07.609433 | 2020-12-11T20:23:48 | 2020-12-11T20:23:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,311 | py | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 7 17:30:06 2014
@author: rhf
- Gaussian distribution
- histogram
- fit of the histogram
- smooth of the plot
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy.interpolate import spline
# Define some test data which is close to Gaussian
data = np.random.normal(loc=0.0, scale=1.0, size=10000)
hist, bin_edges = np.histogram(data,bins=25, density=True)
bin_centres = (bin_edges[:-1] + bin_edges[1:])/2
# Define model function to be used to fit to the data above:
def gauss(x, *p):
A, mu, sigma = p
return A*np.exp(-(x-mu)**2/(2.*sigma**2))
# p0 is the initial guess for the fitting coefficients (A, mu and sigma above)
p0 = [1., 0., 1.]
coeff, var_matrix = curve_fit(gauss, bin_centres, hist, p0=p0)
# Get the fitted curve
hist_fit = gauss(bin_centres, *coeff)
plt.plot(bin_centres, hist,'bo', label='Test data')
plt.plot(bin_centres, hist_fit,'rx', label='Fitted data')
# smooth
xnew = np.linspace(bin_centres[0],bin_centres[-1],200)
hist_smooth = spline(bin_centres,hist_fit,xnew)
plt.plot(xnew,hist_smooth,'r-')
# Finally, lets get the fitting parameters, i.e. the mean and standard deviation:
print 'Fitted mean = ', coeff[1]
print 'Fitted standard deviation = ', coeff[2]
plt.show()
| [
"[email protected]"
]
| |
ec279913ecabe3eb11f4c1ffffd58e3d3b6a4f6c | 5f4e13201d4c5b7edc8dbbda289380682a187bec | /deps/numpy/doc/source/user/plot_face.py | 3945f448b1d1b817beec2a2713b6b514d2535f08 | [
"PSF-2.0",
"Apache-2.0",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"MIT"
]
| permissive | intellivoid/CoffeeHousePy | 92f4fb344de757837c3d3da05cb5513e90408039 | 57c453625239f28da88b88ddd0ae5f1ecdd4de3c | refs/heads/master | 2023-02-23T14:32:01.606630 | 2021-01-28T02:57:10 | 2021-01-28T02:57:10 | 324,419,067 | 0 | 2 | null | null | null | null | UTF-8 | Python | false | false | 95 | py | from scipy import misc
import matplotlib.pyplot as plt
img = misc.face()
plt.imshow(img)
| [
"[email protected]"
]
| |
bef4645a495593d7e79910acfbbbf98082fabfe9 | ec53949dafa4b6ad675d679b05ed7c83fef2c69a | /DataStructuresAndAlgo/InterviewQuestions/ValidateBST.py | 3108de4956d06bb38f0473cbf994c5b1572e2a3d | []
| no_license | tpotjj/Python | 9a5a20a53cd7a6ec14386c1db8ce155e0fc9ab8a | ca73c116ada4d05c0c565508163557744c86fc76 | refs/heads/master | 2023-07-11T16:37:10.039522 | 2021-08-14T11:17:55 | 2021-08-14T11:17:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 724 | py | class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def helper(node, minValue = float('-inf'), maxValue = float('inf')):
if not node:
return True
val = node.value
if val <= minValue or val >= maxValue:
return False
if not helper(node.right, val, maxValue):
return False
if not helper(node.left, minValue, val):
return False
return True
def isValidBST(root):
return helper(root)
root1 = TreeNode(2)
root1.left = TreeNode(1)
root1.right = TreeNode(4)
print(isValidBST(root1))
root2 = TreeNode(4)
root2.left = TreeNode(1)
root2.right = TreeNode(3)
print(isValidBST(root2)) | [
"[email protected]"
]
| |
275ea9d6de193ca4548a34d9ceea32848bf2ff43 | 25985aeeee54373d26a164e4cc6a014770e3ebf3 | /windows/w3af/w3af/core/data/dc/.svn/text-base/form.py.svn-base | 627f670c6050ac0f263a6142f22efd63e41306c8 | []
| no_license | sui84/tools | 4b750dae90940fbe3a226cba72dc071d8fb88b7c | 651cc08eb50199ce1044c684dbf714ea26df6432 | refs/heads/master | 2021-01-22T19:22:26.964580 | 2017-08-20T15:23:38 | 2017-08-20T15:23:38 | 100,774,276 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 13,411 | '''
form.py
Copyright 2006 Andres Riancho
This file is part of w3af, w3af.sourceforge.net .
w3af is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.
w3af 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 w3af; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
'''
import copy
import operator
import random
import core.controllers.outputManager as om
from core.data.dc.dataContainer import dataContainer
from core.data.parsers.encode_decode import urlencode
from core.data.parsers.urlParser import url_object
class form(dataContainer):
'''
This class represents a HTML form.
@author: Andres Riancho ( [email protected] )
'''
# Max
TOP_VARIANTS = 150
MAX_VARIANTS_TOTAL = 10**9
SEED = 1
def __init__(self, init_val=(), strict=False):
dataContainer.__init__(self)
# Internal variables
self._method = None
self._action = None
self._types = {}
self._files = []
self._selects = {}
self._submitMap = {}
# This is used for processing checkboxes
self._secret_value = "3_!21#47w@"
def getAction(self):
'''
@return: The form action.
'''
return self._action
def setAction(self, action):
'''
>>> f = form()
>>> f.setAction('http://www.google.com/')
Traceback (most recent call last):
...
ValueError: The action of a form must be of urlParser.url_object type.
>>> f = form()
>>> action = url_object('http://www.google.com/')
>>> f.setAction(action)
>>> f.getAction() == action
True
'''
if not isinstance(action, url_object):
raise ValueError('The action of a form must be of urlParser.url_object type.')
self._action = action
def getMethod(self):
'''
@return: The form method.
'''
return self._method
def setMethod(self, method):
self._method = method.upper()
def getFileVariables( self ):
return self._files
def _setVar(self, name, value):
'''
Auxiliary setter for name=value
'''
# added to support repeated parameter names
if name in self:
self[name].append(value)
else:
self[name] = [value, ]
def addFileInput( self, attrs ):
'''
Adds a file input to the form
@parameter attrs: attrs=[("class", "screen")]
'''
name = ''
for attr in attrs:
if attr[0] == 'name':
name = attr[1]
break
if not name:
for attr in attrs:
if attr[0] == 'id':
name = attr[1]
break
if name:
self._files.append( name )
self._setVar(name, '')
# TODO: This does not work if there are different parameters in a form
# with the same name, and different types
self._types[name] = 'file'
def __str__( self ):
'''
This method returns a string representation of the form Object.
>>> f = form()
>>> _ = f.addInput( [("type", "text") , ("name", "abc") , ("value", "123")] )
>>> str(f)
'abc=123'
>>> f = form()
>>> _ = f.addInput( [("type", "text") , ("name", "abc") , ("value", "123")] )
>>> _ = f.addInput( [("type", "text") , ("name", "def") , ("value", "000")] )
>>> str(f)
'abc=123&def=000'
@return: string representation of the form Object.
'''
tmp = self.copy()
for i in self._submitMap:
tmp[i] = self._submitMap[i]
#
# FIXME: hmmm I think that we are missing something here... what about
# self._select values. See FIXME below. Maybe we need another for?
#
return urlencode(tmp)
def addSubmit( self, name, value ):
'''
This is something I hadn't thought about !
<input type="submit" name="b0f" value="Submit Request">
'''
self._submitMap[name] = value
def addInput(self, attrs):
'''
Adds a input to the form
@parameter attrs: attrs=[("class", "screen")]
'''
'''
<INPUT type="text" name="email"><BR>
<INPUT type="radio" name="sex" value="Male"> Male<BR>
'''
# Set the default input type to text.
attr_type = 'text'
name = value = ''
# Try to get the name:
for attr in attrs:
if attr[0] == 'name':
name = attr[1]
if not name:
for attr in attrs:
if attr[0] == 'id':
name = attr[1]
if not name:
return (name, value)
# Find the attr_type
for attr in attrs:
if attr[0] == 'type':
attr_type = attr[1].lower()
# Find the default value
for attr in attrs:
if attr[0] == 'value':
value = attr[1]
if attr_type == 'submit':
self.addSubmit( name, value )
else:
self._setVar(name, value)
# Save the attr_type
self._types[name] = attr_type
#
# TODO May be create special internal method instead of using
# addInput()?
#
return (name, value)
def getType( self, name ):
return self._types[name]
def addCheckBox(self, attrs):
"""
Adds checkbox field
"""
name, value = self.addInput(attrs)
if not name:
return
if name not in self._selects:
self._selects[name] = []
if value not in self._selects[name]:
self._selects[name].append(value)
self._selects[name].append(self._secret_value)
self._types[name] = 'checkbox'
def addRadio(self, attrs):
"""
Adds radio field
"""
name, value = self.addInput(attrs)
if not name:
return
self._types[name] = 'radio'
if name not in self._selects:
self._selects[name] = []
#
# FIXME: how do you maintain the same value in self._selects[name]
# and in self[name] ?
#
if value not in self._selects[name]:
self._selects[name].append(value)
def addSelect(self, name, options):
"""
Adds one more select field with options
Options is list of options attrs (tuples)
"""
if not name:
return
self._selects[name] = []
self._types[name] = 'select'
value = ""
for option in options:
for attr in option:
if attr[0].lower() == "value":
value = attr[1]
self._selects[name].append(value)
self._setVar(name, value)
def getVariants(self, mode="tmb"):
"""
Returns all variants of form by mode:
"all" - all values
"tb" - only top and bottom values
"tmb" - top, middle and bottom values
"t" - top values
"b" - bottom values
"""
if mode not in ("all", "tb", "tmb", "t", "b"):
raise ValueError, "mode must be in ('all', 'tb', 'tmb', 't', 'b')"
yield self
# Nothing to do
if not self._selects:
return
secret_value = self._secret_value
sel_names = self._selects.keys()
matrix = self._selects.values()
# Build self variant based on `sample_path`
for sample_path in self._getSamplePaths(mode, matrix):
# Clone self
self_variant = copy.deepcopy(self)
for row_index, col_index in enumerate(sample_path):
sel_name = sel_names[row_index]
value = matrix[row_index][col_index]
if value != secret_value:
# FIXME: Needs to support repeated parameter names
self_variant[sel_name] = [value]
else:
# FIXME: Is it good solution to simply delete unwant to
# send checkboxes?
if self_variant.get(sel_name): # We might had removed it b4
del self_variant[sel_name]
yield self_variant
def _getSamplePaths(self, mode, matrix):
if mode in ["t", "tb"]:
yield [0] * len(matrix)
if mode in ["b", "tb"]:
yield [-1] * len(matrix)
# mode in ["tmb", "all"]
elif mode in ["tmb", "all"]:
variants_total = self._getVariantsCount(matrix, mode)
# Combinatoric explosion. We only want TOP_VARIANTS paths top.
# Create random sample. We ensure that random sample is unique
# matrix by using `SEED` in the random generation
if variants_total > self.TOP_VARIANTS:
# Inform user
om.out.information("w3af found an HTML form that has several checkbox, radio" \
" and select input tags inside. Testing all combinations of those values" \
" would take too much time, the framework will only test" \
" %s randomly distributed variants."
% self.TOP_VARIANTS)
# Init random object. Set our seed.
rand = random.Random()
rand.seed(self.SEED)
# xrange in python2 has the following issue:
# >>> xrange(10**10)
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# OverflowError: long int too large to convert to int
#
# Which was amazingly reported by one of our users
# http://sourceforge.net/apps/trac/w3af/ticket/161481
#
# Given that we want to test SOME of the combinations we're
# going to settle with a rand.sample from the first
# MAX_VARIANTS_TOTAL (=10**9) items (that works in python2)
#
# >>> xrange(10**9)
# xrange(1000000000)
# >>>
variants_total = min(variants_total, self.MAX_VARIANTS_TOTAL)
for path in rand.sample(xrange(variants_total),
self.TOP_VARIANTS):
yield self._decodePath(path, matrix)
# Less than TOP_VARIANTS elems in matrix
else:
# Compress matrix dimensions to (N x Mc) where 1 <= Mc <=3
if mode == "tmb":
for row, vector in enumerate(matrix):
# Create new 3-length vector
if len(vector) > 3:
new_vector = [vector[0]]
new_vector.append(vector[len(vector)/2])
new_vector.append(vector[-1])
matrix[row] = new_vector
# New variants total
variants_total = self._getVariantsCount(matrix, mode)
# Now get all paths!
for path in xrange(variants_total):
decoded_path = self._decodePath(path, matrix)
yield decoded_path
def _decodePath(self, path, matrix):
'''
Decode the integer `path` into a tuple of ints where the ith-elem
is the index to select from vector given by matrix[i].
Diego Buthay ([email protected]) made a significant contribution to
the used algorithm.
@param path: integer
@param matrix: list of lists
@return: Tuple of integers
'''
# Hack to make the algorithm work.
matrix.append([1])
get_count = lambda i: reduce(operator.mul, map(len, matrix[i+1:]))
remainder = path
decoded_path = []
for i in xrange(len(matrix)-1):
base = get_count(i)
decoded_path.append(remainder / base)
remainder = remainder % base
# Restore state, pop out [1]
matrix.pop()
return decoded_path
def _getVariantsCount(self, matrix, mode):
'''
@param matrix:
@param tmb:
'''
if mode in ["t", "b"]:
return 1
elif mode == "tb":
return 2
else:
len_fun = (lambda x: min(len(x), 3)) if mode == "tmb" else len
return reduce(operator.mul, map(len_fun, matrix))
| [
"[email protected]"
]
| ||
b7c8473a2b9909b147915912c1f9c97e8ef39cc3 | 9322c270beaf1019328bf14c836d167145d45946 | /raoteh/sampler/tests/test_sample_mcx.py | 9fdb9aec3922742c6a71357b1a15795a4acdb1aa | []
| no_license | argriffing/raoteh | 13d198665a7a3968aad8d41ddad12c08d36d57b4 | cdc9cce8fdad0a79dbd90dfcdec6feece8fc931f | refs/heads/master | 2021-01-22T19:41:25.828133 | 2014-03-10T22:25:48 | 2014-03-10T22:25:48 | 10,087,018 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 11,830 | py | """
Test functions that Markov chain trajectories on a tree.
In this module we consider only discrete-time discrete-space Markov chains.
"""
from __future__ import division, print_function, absolute_import
import numpy as np
import networkx as nx
from numpy.testing import (run_module_suite, TestCase,
assert_equal, assert_allclose, assert_, assert_raises,
decorators)
from raoteh.sampler import _util, _mc0, _mcx, _sample_mcx
class TestNodeStateSampler(TestCase):
def test_resample_states_short_path(self):
# Define a very sparse transition matrix as a path.
P = nx.DiGraph()
P.add_weighted_edges_from([
(0, 1, 1.0),
(1, 0, 0.5),
(1, 2, 0.5),
(2, 1, 0.5),
(2, 3, 0.5),
(3, 2, 1.0)])
# Define a very sparse tree as a path.
T = nx.Graph()
T.add_edges_from([
(0, 1),
(1, 2)])
# Two of the three vertices of the tree have known states.
# The intermediate state is unknown,
# No value of the intermediate state can possibly connect
# the states at the two endpoints of the path.
node_to_state = {0: 0, 2: 3}
for root in T:
node_to_pset = _mcx.get_node_to_pset(T, root,
node_to_state=node_to_state, P_default=P)
node_to_state_set = _mc0.get_node_to_set(T, root,
node_to_pset, P_default=P)
assert_raises(
_util.StructuralZeroProb,
_sample_mcx.resample_states,
T, root,
node_to_state, P_default=P)
# But if the path endpoints have states
# that allow the intermediate state to act as a bridge,
# then sampling is possible.
root_distn = {0: 0.25, 1: 0.25, 2: 0.25, 3: 0.25}
node_to_state = {0: 0, 2: 2}
for root in T:
observed = _sample_mcx.resample_states(
T, root,
node_to_state, root_distn=root_distn, P_default=P)
expected = {0: 0, 1: 1, 2: 2}
assert_equal(observed, expected)
# Similarly if the root has a different distribution
# and the endpoints are different but still bridgeable
# by a single intermediate transitional state.
root_distn = {0: 0.1, 1: 0.2, 2: 0.3, 3: 0.4}
node_to_state = {0: 3, 2: 1}
for root in T:
observed = _sample_mcx.resample_states(
T, root,
node_to_state, root_distn=root_distn, P_default=P)
expected = {0: 3, 1: 2, 2: 1}
assert_equal(observed, expected)
def test_resample_states_infeasible(self):
# Do not allow any transitions.
P = nx.DiGraph()
# Define a very sparse tree as a path.
T = nx.Graph()
T.add_edges_from([
(0, 1),
(1, 2)])
# Sampling is not possible.
# Check that the correct exception is raised.
root_distn = {0: 0.25, 1: 0.25, 2: 0.25, 3: 0.25}
node_to_state = {0: 0, 2: 2}
for root in T:
assert_raises(
_util.StructuralZeroProb,
_sample_mcx.resample_states,
T, root,
node_to_state, root_distn=root_distn, P_default=P)
def test_resample_states_separated_regions(self):
# This test includes multiple regions of nodes with unknown states,
# where the regions are separated from each other by nodes
# with known states.
# Define a very sparse transition matrix as a path.
P = nx.DiGraph()
P.add_weighted_edges_from([
(0, 1, 1.0),
(1, 0, 0.5),
(1, 2, 0.5),
(2, 1, 0.5),
(2, 3, 0.5),
(3, 2, 1.0)])
# Define a very sparse tree.
T = nx.Graph()
T.add_edges_from([
(0, 10),
(0, 20),
(0, 30),
(10, 11),
(20, 21),
(30, 31),
(31, 32)])
# Define the known states
root_distn = {0: 0.25, 1: 0.25, 2: 0.25, 3: 0.25}
node_to_state = {
0 : 0,
11 : 2,
21 : 2,
32 : 3}
# Check that the correct internal states are sampled,
# regardless of the root choice.
for root in T:
observed = _sample_mcx.resample_states(T, root,
node_to_state, root_distn=root_distn, P_default=P)
expected = {
0 : 0,
10 : 1,
11 : 2,
20 : 1,
21 : 2,
30 : 1,
31 : 2,
32 : 3}
assert_equal(observed, expected)
class TestEdgeStateSampler(TestCase):
def test_resample_edge_states_separated_regions(self):
# This test is analogous to the corresponding node state test.
# Define a very sparse transition matrix as a path.
# To avoid periodicity it allows self transitions.
P = nx.DiGraph()
P.add_weighted_edges_from([
(0, 0, 0.5),
(1, 1, 0.5),
(2, 2, 0.5),
(3, 3, 0.5),
(0, 1, 0.5),
(1, 0, 0.25),
(1, 2, 0.25),
(2, 1, 0.25),
(2, 3, 0.25),
(3, 2, 0.5)])
# Define a very sparse tree.
T = nx.Graph()
T.add_weighted_edges_from([
(0, 10, 1.0),
(0, 20, 1.0),
(0, 30, 1.0),
(10, 11, 2.0),
(11, 12, 2.0),
(12, 13, 2.0),
(13, 14, 2.0),
(14, 15, 2.0),
(15, 16, 2.0),
(20, 21, 1.0),
(21, 22, 1.0),
(30, 31, 1.0),
(31, 32, 1.0),
(32, 33, 1.0)])
# Define the known states
root_distn = {0: 0.25, 1: 0.25, 2: 0.25, 3: 0.25}
node_to_state = {
0 : 0,
16 : 0,
22 : 2,
33 : 3}
# Define the event nodes.
# These are the degree-two nodes for which the adjacent edges
# are allowed to differ from each other.
event_nodes = {10, 20, 21, 30, 31, 32}
non_event_nodes = set(T) - event_nodes
# Check that the correct internal states are sampled,
# regardless of the root choice.
for root in non_event_nodes:
# Sample the edges states.
T_aug = _sample_mcx.resample_edge_states(
T, root, event_nodes,
node_to_state=node_to_state, root_distn=root_distn,
P_default=P)
# The unweighted and weighted tree size should be unchanged.
assert_equal(T.size(), T_aug.size())
assert_allclose(
T.size(weight='weight'), T_aug.size(weight='weight'))
# The edges along the long path should all have state 0
# because this path does not include any event nodes.
long_path_nodes = (10, 11, 12, 13, 14, 15, 16)
long_path_edges = zip(long_path_nodes[:-1], long_path_nodes[1:])
for a, b in long_path_edges:
assert_equal(T_aug[a][b]['state'], 0)
# Check the edge states along the short branch.
assert_equal(T_aug[0][20]['state'], 0)
assert_equal(T_aug[20][21]['state'], 1)
assert_equal(T_aug[21][22]['state'], 2)
# Check the edge states along the medium length branch.
assert_equal(T_aug[0][30]['state'], 0)
assert_equal(T_aug[30][31]['state'], 1)
assert_equal(T_aug[31][32]['state'], 2)
assert_equal(T_aug[32][33]['state'], 3)
def test_resample_edge_states_unknown_degree_three(self):
# This test uses a more complicated transition matrix.
# This transition matrix is on a 4x4 grid.
P = _mc0.get_example_transition_matrix()
# Define a very sparse tree.
T = nx.Graph()
T.add_weighted_edges_from([
# first branch
(0, 10, 1.0),
(10, 11, 1.0),
(11, 12, 1.0),
# second branch
(0, 20, 2.0),
(20, 21, 2.0),
(21, 22, 2.0),
# third branch
(0, 30, 1.0),
(30, 31, 1.0),
(31, 32, 1.0),
])
# Define the known states
node_to_state = {
12 : 11,
22 : 24,
32 : 42}
# Define the event nodes.
# These are the degree-two nodes for which the adjacent edges
# are allowed to differ from each other.
event_nodes = {10, 11, 20, 21, 30, 31}
non_event_nodes = set(T) - event_nodes
# Sample the edges states.
# Try all non-event nodes as roots.
for root in non_event_nodes:
# Sample the edges states.
T_aug = _sample_mcx.resample_edge_states(
T, root, event_nodes,
node_to_state=node_to_state, root_distn=None,
P_default=P)
# The unweighted and weighted tree size should be unchanged.
assert_equal(T.size(), T_aug.size())
assert_allclose(
T.size(weight='weight'),
T_aug.size(weight='weight'))
# The origin node must have state 22.
assert_equal(T_aug[0][10]['state'], 22)
assert_equal(T_aug[0][20]['state'], 22)
assert_equal(T_aug[0][30]['state'], 22)
class TestFeasibleStateSampler(TestCase):
def test_get_feasible_history(self):
# This transition matrix is on a 4x4 grid.
P = _mc0.get_example_transition_matrix()
# Define a very sparse tree.
T = nx.Graph()
T.add_weighted_edges_from([
(0, 12, 1.0),
(0, 23, 2.0),
(0, 33, 1.0),
])
# Define the known states
node_to_state = {
12 : 11,
23 : 14,
33 : 41}
# Define a root at a node with a known state,
# so that we can avoid specifying a distribution at the root.
root = 12
T_aug = _sample_mcx.get_feasible_history(T, node_to_state,
root=root, P_default=P)
# The unweighted and weighted tree size should be unchanged.
assert_allclose(
T.size(weight='weight'), T_aug.size(weight='weight'))
# Check that for each node in the initial tree,
# all adjacent edges in the augmented tree have the same state.
# Furthermore if the state of the node in the initial tree is known,
# check that the adjacent edges share this known state.
for a in T:
states = set()
for b in T_aug.neighbors(a):
states.add(T_aug[a][b]['state'])
assert_equal(len(states), 1)
state = _util.get_first_element(states)
if a in node_to_state:
assert_equal(node_to_state[a], state)
# Check that every adjacent edge pair is a valid transition.
successors = nx.dfs_successors(T_aug, root)
for a, b in nx.bfs_edges(T_aug, root):
if b in successors:
for c in successors[b]:
ab = T_aug[a][b]['state']
bc = T_aug[b][c]['state']
assert_(ab in P)
assert_(bc in P[ab])
assert_(P[ab][bc]['weight'] > 0)
if __name__ == '__main__':
run_module_suite()
| [
"[email protected]"
]
| |
68d13a2a50ef4b39ae111b75a765b6bc473dd10c | 2c4efe2ce49a900c68348f50e71802994c84900a | /braindecode/braindecode/venv1/Lib/site-packages/numba/cuda/tests/cudapy/test_forall.py | f6d600d8bb11534ddaaad7b10be0bc1287032cde | [
"BSD-3-Clause",
"BSD-2-Clause"
]
| permissive | sisi2/Masterthesis | b508632526e82b23c2efb34729141bfdae078fa0 | 7ce17644af47db4ad62764ed062840a10afe714d | refs/heads/master | 2022-11-19T15:21:28.272824 | 2018-08-13T15:02:20 | 2018-08-13T15:02:20 | 131,345,102 | 2 | 1 | null | 2022-11-15T14:08:07 | 2018-04-27T21:09:21 | Python | UTF-8 | Python | false | false | 1,123 | py | from __future__ import print_function, absolute_import
import numpy as np
from numba import cuda
import numba.unittest_support as unittest
from numba.cuda.testing import skip_on_cudasim, SerialMixin
@skip_on_cudasim('forall API unsupported in the simulator')
class TestForAll(SerialMixin, unittest.TestCase):
def test_forall_1(self):
@cuda.jit
def foo(x):
i = cuda.grid(1)
if i < x.size:
x[i] += 1
arr = np.arange(11)
orig = arr.copy()
foo.forall(arr.size)(arr)
self.assertTrue(np.all(arr == orig + 1))
def test_forall_2(self):
@cuda.jit("void(float32, float32[:], float32[:])")
def bar(a, x, y):
i = cuda.grid(1)
if i < x.size:
y[i] = a * x[i] + y[i]
x = np.arange(13, dtype=np.float32)
y = np.arange(13, dtype=np.float32)
oldy = y.copy()
a = 1.234
bar.forall(y.size)(a, x, y)
self.assertTrue(np.all(y == (a * x + oldy)))
if __name__ == '__main__':
unittest.main()
| [
"[email protected]"
]
| |
52ae38711097f2236ddfae0e9e374633a596c0bd | a64b8fc6c9e81d433878009249fe9c9a109a602c | /core/confdb/syntax/meta/interfaces.py | a55f214f6c750f612e2563ff8dd20d85ccb8d42d | [
"BSD-3-Clause"
]
| permissive | ewwwcha/noc | d1de6fe1d556e0f14a0dd31c600844cf43c96728 | aba08dc328296bb0e8e181c2ac9a766e1ec2a0bb | refs/heads/master | 2020-07-29T10:10:30.862660 | 2019-09-20T07:54:52 | 2019-09-20T07:54:52 | 209,755,887 | 1 | 0 | NOASSERTION | 2019-09-20T09:36:22 | 2019-09-20T09:36:22 | null | UTF-8 | Python | false | false | 5,016 | py | # -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# ConfDB interfaces X meta syntax
# ----------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------
# Python modules
from __future__ import absolute_import
# NOC modules
from ..defs import DEF
from ..patterns import ANY, INTEGER
INTERFACES_META_SYNTAX = DEF(
"meta",
[
DEF(
"profile",
[
DEF(
"id",
[DEF(ANY, name="id", required=True, gen="make_interfaces_meta_profile_id")],
),
DEF(
"name",
[DEF(ANY, name="name", required=True, gen="make_interfaces_meta_profile_name")],
),
],
),
DEF(
"link",
[
DEF(
ANY,
[
DEF(
"object",
[
DEF(
"id",
[
DEF(
ANY,
name="object_id",
required=True,
gen="make_interfaces_meta_link_object_id",
)
],
),
DEF(
"name",
[
DEF(
ANY,
name="object_name",
required=True,
gen="make_interfaces_meta_link_object_name",
)
],
),
DEF(
"profile",
[
DEF(
"id",
[
DEF(
ANY,
name="id",
required=True,
gen="make_interfaces_meta_link_object_profile_id",
)
],
),
DEF(
"name",
[
DEF(
ANY,
name="name",
required=True,
gen="make_interfaces_meta_link_object_profile_name",
)
],
),
DEF(
"level",
[
DEF(
INTEGER,
name="level",
required=True,
gen="make_interfaces_meta_link_object_profile_level",
)
],
),
],
),
],
),
DEF(
"interface",
[
DEF(
ANY,
name="remote_interface",
required=True,
multi=True,
gen="make_interfaces_meta_link_interface",
)
],
),
],
name="link",
multi=True,
)
],
),
],
)
| [
"[email protected]"
]
| |
1dc9756617bc7606a3e5f69b72ea4f6279f1e493 | 43b36890c037da0f8a1ee4c6f03349c5e70b6333 | /modules/ieee/doc/next.py | c6c4b76a779cc42c762ff8aae6a23a7b615c2e7c | [
"BSL-1.0"
]
| permissive | msuchard/nt2 | 3a07decd8d184e3067452bc7f075e392c7bacc03 | 082d79abd069f4c356bfe10fd113de024f90a5f8 | refs/heads/master | 2021-01-18T12:29:32.075028 | 2011-11-15T23:18:23 | 2011-11-15T23:19:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,330 | py | [ ## this file was manually modified by jt
{
'functor' : {
'arity' : '1',
'call_types' : [],
'ret_arity' : '0',
'rturn' : {
'default' : 'T',
},
'simd_types' : ['real_'],
'type_defs' : [],
'types' : ['real_', 'unsigned_int_', 'signed_int_'],
},
'info' : 'manually modified',
'unit' : {
'global_header' : {
'first_stamp' : 'modified by jt the 04/12/2010',
'included' : ['#include <nt2/include/functions/successor.hpp>', '#include <nt2/include/constants/eps_related.hpp>'],
'no_ulp' : 'True',
'notes' : [],
'stamp' : 'modified by jt the 12/12/2010',
},
'ranges' : {
'real_' : [['T(-10)', 'T(10)']],
'signed_int_' : [['-100', '100']],
'unsigned_int_' : [['0', '100']],
},
'specific_values' : {
'default' : {
},
'real_' : {
'nt2::Inf<T>()' : 'nt2::Inf<r_t>()',
'nt2::Minf<T>()' : 'nt2::Valmin<r_t>()',
'nt2::Mone<T>()' : 'nt2::Mone<r_t>()+nt2::Eps<r_t>()/2',
'nt2::Nan<T>()' : 'nt2::Nan<r_t>()',
'nt2::One<T>()' : 'nt2::One<r_t>()+nt2::Eps<r_t>()',
'nt2::Zero<T>()' : 'nt2::Zero<r_t>()+nt2::Mindenormal<T>()',
'nt2::Valmax<T>()' : 'nt2::Inf<r_t>()',
},
'signed_int_' : {
'nt2::Valmax<T>()' : 'nt2::Valmax<r_t>()',
'nt2::Mone<T>()' : 'nt2::Zero<r_t>()',
'nt2::One<T>()' : 'nt2::Two<r_t>()',
'nt2::Zero<T>()' : 'nt2::One<r_t>()',
},
'unsigned_int_' : {
'nt2::Valmax<T>()' : 'nt2::Valmax<r_t>()',
'nt2::One<T>()' : 'nt2::Two<r_t>()',
'nt2::Zero<T>()' : 'nt2::One<r_t>()',
},
},
'verif_test' : {
'property_call' : {
'default' : ['nt2::next(a0)'],
},
'property_value' : {
'default' : ['nt2::successor(a0)'],
},
'ulp_thresh' : '0',
},
},
'version' : '0.1',
},
]
| [
"[email protected]"
]
| |
d8b7625ba76b77d1482fe1ee3866c6c8f7ec0a41 | 3d6a348d703bcef1ff0b11f340a9b63f4ffec534 | /app/__init__.py | 200cd3e2f574bb9f57b349ec8c5a9a9a836cde1a | []
| no_license | Boomatang/Clue | 717fed577c15203e8a86de2da96650d46170cc03 | 1b397b815d20c87bf1a0935f6c3f0502ceaddf6e | refs/heads/master | 2021-05-09T10:48:04.036476 | 2019-09-02T17:41:37 | 2019-09-02T17:41:37 | 118,974,799 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,870 | py | from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from app.utils import logger
from config import config
from flask_login import LoginManager
from flask_mail import Mail
bootstrap = Bootstrap()
db = SQLAlchemy()
mail = Mail()
login_manager = LoginManager()
login_manager.session_protection = "strong"
login_manager.login_view = "auth.login"
@logger.catch()
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bootstrap.init_app(app)
db.init_app(app)
mail.init_app(app)
login_manager.init_app(app)
# if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
# from flask_sslify import SSLify
# sslify = SSLify(app)
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
from .user import user as user_blueprint
app.register_blueprint(user_blueprint)
from .cutlist import cutlist as cutlist_blueprint
app.register_blueprint(cutlist_blueprint)
from .tools import tools as tools_blueprint
app.register_blueprint(tools_blueprint)
from .librarys import library as library_blueprint
app.register_blueprint(library_blueprint, url_prefix="/materials")
from .BOM import BOM as BOM_blueprint
app.register_blueprint(BOM_blueprint)
from .api import api as api_blueprint
app.register_blueprint(api_blueprint, url_prefix="/api/v1")
from .cert import cert as cert_blueprint
app.register_blueprint(cert_blueprint, url_prefix="/cert")
from .project import project as project_blueprint
app.register_blueprint(project_blueprint, url_prefix="/project")
from .auth import auth as main_blueprint
app.register_blueprint(main_blueprint, url_prefix="/auth")
return app
| [
"[email protected]"
]
| |
629a0a7c039064ace700531452345db4a512f867 | f654f5f07dd8109c0ee31ba89dd4804e6b288343 | /src/test/config/sections/brain/test_oob.py | bde9b4d6a7293565166e49830fe171d49a3fb640 | [
"MIT"
]
| permissive | sprinteroz/program-y | 3d1f5f28e4f3be770705d4bef15410b8b78f19da | 454c6bde225dce7c3fb01c549d46249248caf7b5 | refs/heads/master | 2021-01-19T16:05:25.636700 | 2017-08-22T03:56:33 | 2017-08-22T03:56:33 | 100,986,551 | 1 | 0 | null | 2017-08-21T19:43:43 | 2017-08-21T19:43:43 | null | UTF-8 | Python | false | false | 1,628 | py | import unittest
from programy.config.file.yaml_file import YamlConfigurationFile
from programy.config.sections.brain.oob import BrainOOBConfiguration
from programy.config.sections.client.console import ConsoleConfiguration
class BrainOOBConfigurationTests(unittest.TestCase):
def test_oob_with_data(self):
yaml = YamlConfigurationFile()
self.assertIsNotNone(yaml)
yaml.load_from_text("""
brain:
oobs:
default:
classname: programy.utils.oob.default.DefaultOutOfBandProcessor
""", ConsoleConfiguration(), ".")
brain_config = yaml.get_section("brain")
self.assertIsNotNone(brain_config)
oobs_config = yaml.get_section("oobs", brain_config)
self.assertIsNotNone(oobs_config)
oob_config = BrainOOBConfiguration("default")
oob_config.load_config_section(yaml, oobs_config, ".")
self.assertEqual("programy.utils.oob.default.DefaultOutOfBandProcessor", oob_config.classname)
def test_default_without_data(self):
yaml = YamlConfigurationFile()
self.assertIsNotNone(yaml)
yaml.load_from_text("""
brain:
oobs:
default:
""", ConsoleConfiguration(), ".")
brain_config = yaml.get_section("brain")
self.assertIsNotNone(brain_config)
oobs_config = yaml.get_section("oobs", brain_config)
self.assertIsNotNone(oobs_config)
oob_config = BrainOOBConfiguration("default")
oob_config.load_config_section(yaml, oobs_config, ".")
self.assertIsNone(oob_config.classname)
| [
"[email protected]"
]
| |
15364f7c33c0d232d41563d89fefbb13af61eba3 | bd9f8187b7821b2e6ffd949386b791f264a7ccab | /adam.py | 8ac53ebe61738f4f6d795a3b2d41cf4a933fbc85 | []
| no_license | LeonKennedy/qkids | 353786666536a745d6ecdc75b70be0ff988580a3 | d7c8bdea4d6ccd257750e05fb113d2f39622ff0e | refs/heads/master | 2020-03-17T13:41:32.466438 | 2018-11-25T12:25:21 | 2018-11-25T12:25:21 | 133,641,201 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,496 | py | #!/usr/bin/env python
#-*- coding: utf-8 -*-
# @Filename: adma.py
# @Author: olenji - [email protected]
# @Description: COO 所需数据
# @Create: 2018-11-25 19:00:56
# @Last Modified: 2018-11-25 19:00:56
#
from LocalDatabase import get_schedule_connection, get_product_connection
import pandas as pd
import pdb
class M1:
def get_users(self):
conn = get_product_connection()
sql = "select user_id, first_large_buy_at from users where vip = 1 and first_large_buy_at > '2016-01-01' and deleted_at is null"
df = pd.read_sql(sql, conn, index_col = 'user_id')
df['count'] = 0
self._df = df
def count_consume(self):
conn = get_schedule_connection()
sql = "select student_id, created_at from student_appointments \
where status = 3 and deleted_at is null and created_at > \
'2016-01-01'"
with conn.cursor() as cur:
cur.execute(sql)
while cur.rownumber < cur.rowcount:
student, date = cur.fetchone()
if student in self._df.index:
a = date - self._df.loc[student, 'first_large_buy_at']
if a.days < 365:
self._df.loc[student,'count'] += 1
if cur.rownumber % 10000 == 0:
print(date)
self._df.to_csv('user_comsume.csv')
if __name__ == "__main__":
m = M1()
m.get_users()
m.count_consume()
| [
"[email protected]"
]
| |
fd801218ea84ab029a1a97a8ee592cf3140712b6 | 54f352a242a8ad6ff5516703e91da61e08d9a9e6 | /Source Codes/CodeJamData/16/31/0.py | b3e9c53ea22fc72878d34f6b44630978001fd602 | []
| no_license | Kawser-nerd/CLCDSA | 5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb | aee32551795763b54acb26856ab239370cac4e75 | refs/heads/master | 2022-02-09T11:08:56.588303 | 2022-01-26T18:53:40 | 2022-01-26T18:53:40 | 211,783,197 | 23 | 9 | null | null | null | null | UTF-8 | Python | false | false | 698 | py | from sys import stdin
def getint():
return int(stdin.readline())
def getints():
return tuple(int(z) for z in stdin.readline().split())
for cn in xrange(1,1 + getint()):
n = getint()
ps = getints()
m1 = max((ps[i],i) for i in xrange(n))[1]
m2 = max((ps[i],i) for i in xrange(n) if i != m1)[1]
plan = []
for k in xrange(ps[m1]-ps[m2]):
plan.append([m1])
for j in xrange(n):
if j != m1 and j != m2:
for z in xrange(ps[j]):
plan.append([j])
for j in xrange(ps[m2]):
plan.append([m1,m2])
print "Case #{}: {}".format(cn, " ".join("".join(chr(65+i) for i in step) for step in plan))
| [
"[email protected]"
]
| |
98201188154bbccad11c7feb8172dedeb36eaaed | e6cb78ce3575334a8dbc871371c04572ba47f20f | /0x01-python-if_else_loops_functions/101-remove_char_at.py | faf681782e69b2a646f204769c4488356fad4753 | []
| no_license | SoniaChevli/holbertonschool-higher_level_programming | c781903157136a550b151cac7975ac54015f4e45 | 0c210f6d18781bfe10fb8c87da7cc7177e58f46e | refs/heads/master | 2020-03-09T13:07:48.416175 | 2018-09-07T18:09:16 | 2018-09-07T18:09:16 | 128,802,668 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 155 | py | #!/usr/bin/python3
def remove_char_at(str, n):
copy = ''
for x in range(len(str)):
if (x != n):
copy += str[x]
return copy
| [
"[email protected]"
]
| |
60096a85f40d711369a08c7b1b86636e2e7a41d9 | 13a66c5a9ff2490ee747a22dc6d264d7d5899278 | /scripts/app_client.py | 8a9b78ee34fb69a119e5d89e237e33ea6132f9da | []
| no_license | sandhyazdodiya/pure_django_api_vs_drf | 4b39e7974eb23baad3609c148b7983ed9b91e39d | 4d59f5072bad988a20b6185e8e0672dbf7179109 | refs/heads/main | 2023-02-05T10:49:22.088156 | 2020-12-31T12:42:01 | 2020-12-31T12:42:01 | 322,474,346 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 646 | py | import requests
import json
import MySQLdb
BASE_URL = "http://127.0.0.1:8000/"
ENDPOINT = "api/updates/"
def get_list():
r = requests.get(BASE_URL+ENDPOINT) # Get list
print(r.status_code)
data = r.json()
for obj in data:
if obj['id'] ==1:
r2 = requests.get(BASE_URL+ENDPOINT+str(obj["id"])) # get one data
print(r2.json())
return r.json()
def create_update():
new_data ={
"user" :1,
"content" : "Some new Update"
}
r = requests.delete(BASE_URL+ENDPOINT, data=new_data)
print(r.status_code)
return r.text
print(create_update())
# print(get_list()) | [
"[email protected]"
]
| |
52570feb3048b5c5e20cd6026b9a9669abff56ca | c7066d3b72a54665d81de1d77d7bdcfd0ece7b42 | /python/ccxt/blockchaincom.py | c6025ce785fbb002fa10e340dd3033cc8ddfc862 | [
"MIT"
]
| permissive | blair/ccxt | cf09b7a604586c230e8cea2b6e4dbf6c3c3497ea | 3a6bd4efb78d01391f9a4ea43ec228b75ca24695 | refs/heads/master | 2023-09-03T21:09:44.447194 | 2023-08-26T19:01:14 | 2023-08-26T19:01:14 | 126,121,401 | 0 | 2 | MIT | 2018-03-21T04:02:57 | 2018-03-21T04:02:56 | null | UTF-8 | Python | false | false | 48,945 | py | # -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.base.exchange import Exchange
from ccxt.abstract.blockchaincom import ImplicitAPI
from ccxt.base.types import OrderSide
from ccxt.base.types import OrderType
from typing import Optional
from typing import List
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import ArgumentsRequired
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import OrderNotFound
from ccxt.base.errors import AuthenticationError
from ccxt.base.decimal_to_precision import TICK_SIZE
from ccxt.base.precise import Precise
class blockchaincom(Exchange, ImplicitAPI):
def describe(self):
return self.deep_extend(super(blockchaincom, self).describe(), {
'id': 'blockchaincom',
'secret': None,
'name': 'Blockchain.com',
'countries': ['LX'],
'rateLimit': 500, # prev 1000
'version': 'v3',
'pro': True,
'has': {
'CORS': False,
'spot': True,
'margin': None, # on exchange but not implemented in CCXT
'swap': False,
'future': False,
'option': False,
'cancelAllOrders': True,
'cancelOrder': True,
'createOrder': True,
'createStopLimitOrder': True,
'createStopMarketOrder': True,
'createStopOrder': True,
'fetchBalance': True,
'fetchCanceledOrders': True,
'fetchClosedOrders': True,
'fetchDeposit': True,
'fetchDepositAddress': True,
'fetchDeposits': True,
'fetchFundingHistory': False,
'fetchFundingRate': False,
'fetchFundingRateHistory': False,
'fetchFundingRates': False,
'fetchIndexOHLCV': False,
'fetchL2OrderBook': True,
'fetchL3OrderBook': True,
'fetchLedger': False,
'fetchMarginMode': False,
'fetchMarkets': True,
'fetchMarkOHLCV': False,
'fetchMyTrades': True,
'fetchOHLCV': False,
'fetchOpenInterestHistory': False,
'fetchOpenOrders': True,
'fetchOrder': True,
'fetchOrderBook': True,
'fetchPositionMode': False,
'fetchPremiumIndexOHLCV': False,
'fetchTicker': True,
'fetchTickers': True,
'fetchTrades': False,
'fetchTradingFee': False,
'fetchTradingFees': True,
'fetchTransfer': False,
'fetchTransfers': False,
'fetchWithdrawal': True,
'fetchWithdrawals': True,
'fetchWithdrawalWhitelist': True, # fetches exchange specific benficiary-ids needed for withdrawals
'transfer': False,
'withdraw': True,
},
'timeframes': None,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/147515585-1296e91b-7398-45e5-9d32-f6121538533f.jpeg',
'test': {
'public': 'https://testnet-api.delta.exchange',
'private': 'https://testnet-api.delta.exchange',
},
'api': {
'public': 'https://api.blockchain.com/v3/exchange',
'private': 'https://api.blockchain.com/v3/exchange',
},
'www': 'https://blockchain.com',
'doc': [
'https://api.blockchain.com/v3',
],
'fees': 'https://exchange.blockchain.com/fees',
},
'api': {
'public': {
'get': {
'tickers': 1, # fetchTickers
'tickers/{symbol}': 1, # fetchTicker
'symbols': 1, # fetchMarkets
'symbols/{symbol}': 1, # fetchMarket
'l2/{symbol}': 1, # fetchL2OrderBook
'l3/{symbol}': 1, # fetchL3OrderBook
},
},
'private': {
'get': {
'fees': 1, # fetchFees
'orders': 1, # fetchOpenOrders, fetchClosedOrders
'orders/{orderId}': 1, # fetchOrder(id)
'trades': 1,
'fills': 1, # fetchMyTrades
'deposits': 1, # fetchDeposits
'deposits/{depositId}': 1, # fetchDeposit
'accounts': 1, # fetchBalance
'accounts/{account}/{currency}': 1,
'whitelist': 1, # fetchWithdrawalWhitelist
'whitelist/{currency}': 1, # fetchWithdrawalWhitelistByCurrency
'withdrawals': 1, # fetchWithdrawalWhitelist
'withdrawals/{withdrawalId}': 1, # fetchWithdrawalById
},
'post': {
'orders': 1, # createOrder
'deposits/{currency}': 1, # fetchDepositAddress by currency(only crypto supported)
'withdrawals': 1, # withdraw
},
'delete': {
'orders': 1, # cancelOrders
'orders/{orderId}': 1, # cancelOrder
},
},
},
'fees': {
'trading': {
'feeSide': 'get',
'tierBased': True,
'percentage': True,
'tiers': {
'taker': [
[self.parse_number('0'), self.parse_number('0.004')],
[self.parse_number('10000'), self.parse_number('0.0022')],
[self.parse_number('50000'), self.parse_number('0.002')],
[self.parse_number('100000'), self.parse_number('0.0018')],
[self.parse_number('500000'), self.parse_number('0.0018')],
[self.parse_number('1000000'), self.parse_number('0.0018')],
[self.parse_number('2500000'), self.parse_number('0.0018')],
[self.parse_number('5000000'), self.parse_number('0.0016')],
[self.parse_number('25000000'), self.parse_number('0.0014')],
[self.parse_number('100000000'), self.parse_number('0.0011')],
[self.parse_number('500000000'), self.parse_number('0.0008')],
[self.parse_number('1000000000'), self.parse_number('0.0006')],
],
'maker': [
[self.parse_number('0'), self.parse_number('0.002')],
[self.parse_number('10000'), self.parse_number('0.0012')],
[self.parse_number('50000'), self.parse_number('0.001')],
[self.parse_number('100000'), self.parse_number('0.0008')],
[self.parse_number('500000'), self.parse_number('0.0007000000000000001')],
[self.parse_number('1000000'), self.parse_number('0.0006')],
[self.parse_number('2500000'), self.parse_number('0.0005')],
[self.parse_number('5000000'), self.parse_number('0.0004')],
[self.parse_number('25000000'), self.parse_number('0.0003')],
[self.parse_number('100000000'), self.parse_number('0.0002')],
[self.parse_number('500000000'), self.parse_number('0.0001')],
[self.parse_number('1000000000'), self.parse_number('0')],
],
},
},
},
'requiredCredentials': {
'apiKey': False,
'secret': True,
},
'options': {
'networks': {
'ERC20': 'ETH',
'TRC20': 'TRX',
'ALGO': 'ALGO',
'ADA': 'ADA',
'AR': 'AR',
'ATOM': 'ATOM',
'AVAXC': 'AVAX',
'BCH': 'BCH',
'BSV': 'BSV',
'BTC': 'BTC',
# 'BEP20': 'BNB', # todo
'DCR': 'DCR',
'DESO': 'DESO',
'DASH': 'DASH',
'CELO': 'CELO',
'CHZ': 'CHZ',
'MATIC': 'MATIC',
'SOL': 'SOL',
'DOGE': 'DOGE',
'DOT': 'DOT',
'EOS': 'EOS',
'ETC': 'ETC',
'FIL': 'FIL',
'KAVA': 'KAVA',
'LTC': 'LTC',
'IOTA': 'MIOTA',
'NEAR': 'NEAR',
'STX': 'STX',
'XLM': 'XLM',
'XMR': 'XMR',
'XRP': 'XRP',
'XTZ': 'XTZ',
'ZEC': 'ZEC',
'ZIL': 'ZIL',
# 'THETA': 'THETA', # todo: possible TFUEL THETA FUEL is also same, but API might have a mistake
# todo: uncomment below after consensus
# 'MOBILECOIN': 'MOB',
# 'KIN': 'KIN',
# 'DIGITALGOLD': 'DGLD',
},
},
'precisionMode': TICK_SIZE,
'exceptions': {
'exact': {
'401': AuthenticationError,
'404': OrderNotFound,
},
'broad': {},
},
})
def fetch_markets(self, params={}):
"""
retrieves data on all markets for blockchaincom
:param dict [params]: extra parameters specific to the exchange api endpoint
:returns dict[]: an array of objects representing market data
"""
#
# "USDC-GBP": {
# "base_currency": "USDC",
# "base_currency_scale": 6,
# "counter_currency": "GBP",
# "counter_currency_scale": 2,
# "min_price_increment": 10000,
# "min_price_increment_scale": 8,
# "min_order_size": 500000000,
# "min_order_size_scale": 8,
# "max_order_size": 0,
# "max_order_size_scale": 8,
# "lot_size": 10000,
# "lot_size_scale": 8,
# "status": "open",
# "id": 68,
# "auction_price": 0,
# "auction_size": 0,
# "auction_time": "",
# "imbalance": 0
# }
#
markets = self.publicGetSymbols(params)
marketIds = list(markets.keys())
result = []
for i in range(0, len(marketIds)):
marketId = marketIds[i]
market = self.safe_value(markets, marketId)
baseId = self.safe_string(market, 'base_currency')
quoteId = self.safe_string(market, 'counter_currency')
base = self.safe_currency_code(baseId)
quote = self.safe_currency_code(quoteId)
numericId = self.safe_number(market, 'id')
active = None
marketState = self.safe_string(market, 'status')
if marketState == 'open':
active = True
else:
active = False
# price precision
minPriceIncrementString = self.safe_string(market, 'min_price_increment')
minPriceIncrementScaleString = self.safe_string(market, 'min_price_increment_scale')
minPriceScalePrecisionString = self.parse_precision(minPriceIncrementScaleString)
pricePrecisionString = Precise.string_mul(minPriceIncrementString, minPriceScalePrecisionString)
# amount precision
lotSizeString = self.safe_string(market, 'lot_size')
lotSizeScaleString = self.safe_string(market, 'lot_size_scale')
lotSizeScalePrecisionString = self.parse_precision(lotSizeScaleString)
amountPrecisionString = Precise.string_mul(lotSizeString, lotSizeScalePrecisionString)
# minimum order size
minOrderSizeString = self.safe_string(market, 'min_order_size')
minOrderSizeScaleString = self.safe_string(market, 'min_order_size_scale')
minOrderSizeScalePrecisionString = self.parse_precision(minOrderSizeScaleString)
minOrderSizePreciseString = Precise.string_mul(minOrderSizeString, minOrderSizeScalePrecisionString)
minOrderSize = self.parse_number(minOrderSizePreciseString)
# maximum order size
maxOrderSize = None
maxOrderSize = self.safe_string(market, 'max_order_size')
if maxOrderSize != '0':
maxOrderSizeScaleString = self.safe_string(market, 'max_order_size_scale')
maxOrderSizeScalePrecisionString = self.parse_precision(maxOrderSizeScaleString)
maxOrderSizeString = Precise.string_mul(maxOrderSize, maxOrderSizeScalePrecisionString)
maxOrderSize = self.parse_number(maxOrderSizeString)
else:
maxOrderSize = None
result.append({
'info': market,
'id': marketId,
'numericId': numericId,
'symbol': base + '/' + quote,
'base': base,
'quote': quote,
'settle': None,
'baseId': baseId,
'quoteId': quoteId,
'settleId': None,
'type': 'spot',
'spot': True,
'margin': False,
'swap': False,
'future': False,
'option': False,
'active': active,
'contract': False,
'linear': None,
'inverse': None,
'contractSize': None,
'expiry': None,
'expiryDatetime': None,
'strike': None,
'optionType': None,
'precision': {
'amount': self.parse_number(amountPrecisionString),
'price': self.parse_number(pricePrecisionString),
},
'limits': {
'leverage': {
'min': None,
'max': None,
},
'amount': {
'min': minOrderSize,
'max': maxOrderSize,
},
'price': {
'min': None,
'max': None,
},
'cost': {
'min': None,
'max': None,
},
},
})
return result
def fetch_order_book(self, symbol: str, limit: Optional[int] = None, params={}):
"""
fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
:param str symbol: unified symbol of the market to fetch the order book for
:param int [limit]: the maximum amount of order book entries to return
:param dict [params]: extra parameters specific to the blockchaincom api endpoint
:returns dict: A dictionary of `order book structures <https://github.com/ccxt/ccxt/wiki/Manual#order-book-structure>` indexed by market symbols
"""
return self.fetch_l3_order_book(symbol, limit, params)
def fetch_l3_order_book(self, symbol: str, limit: Optional[int] = None, params={}):
"""
fetches level 3 information on open orders with bid(buy) and ask(sell) prices, volumes and other data
:param str symbol: unified market symbol
:param int [limit]: max number of orders to return, default is None
:param dict [params]: extra parameters specific to the blockchaincom api endpoint
:returns dict: an `order book structure <https://github.com/ccxt/ccxt/wiki/Manual#order-book-structure>`
"""
self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
}
if limit is not None:
request['depth'] = limit
response = self.publicGetL3Symbol(self.extend(request, params))
return self.parse_order_book(response, market['symbol'], None, 'bids', 'asks', 'px', 'qty')
def fetch_l2_order_book(self, symbol: str, limit: Optional[int] = None, params={}):
self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
}
if limit is not None:
request['depth'] = limit
response = self.publicGetL2Symbol(self.extend(request, params))
return self.parse_order_book(response, market['symbol'], None, 'bids', 'asks', 'px', 'qty')
def parse_ticker(self, ticker, market=None):
#
# {
# "symbol": "BTC-USD",
# "price_24h": 47791.86,
# "volume_24h": 362.88635738,
# "last_trade_price": 47587.75
# }
#
marketId = self.safe_string(ticker, 'symbol')
symbol = self.safe_symbol(marketId, market, '-')
last = self.safe_string(ticker, 'last_trade_price')
baseVolume = self.safe_string(ticker, 'volume_24h')
open = self.safe_string(ticker, 'price_24h')
return self.safe_ticker({
'symbol': symbol,
'timestamp': None,
'datetime': None,
'high': None,
'low': None,
'bid': None,
'bidVolume': None,
'ask': None,
'askVolume': None,
'vwap': None,
'open': open,
'close': None,
'last': last,
'previousClose': None,
'change': None,
'percentage': None,
'average': None,
'baseVolume': baseVolume,
'quoteVolume': None,
'info': ticker,
}, market)
def fetch_ticker(self, symbol: str, params={}):
"""
fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
:param str symbol: unified symbol of the market to fetch the ticker for
:param dict [params]: extra parameters specific to the blockchaincom api endpoint
:returns dict: a `ticker structure <https://github.com/ccxt/ccxt/wiki/Manual#ticker-structure>`
"""
self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
}
response = self.publicGetTickersSymbol(self.extend(request, params))
return self.parse_ticker(response, market)
def fetch_tickers(self, symbols: Optional[List[str]] = None, params={}):
"""
fetches price tickers for multiple markets, statistical calculations with the information calculated over the past 24 hours each market
:param str[]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
:param dict [params]: extra parameters specific to the blockchaincom api endpoint
:returns dict: a dictionary of `ticker structures <https://github.com/ccxt/ccxt/wiki/Manual#ticker-structure>`
"""
self.load_markets()
tickers = self.publicGetTickers(params)
return self.parse_tickers(tickers, symbols)
def parse_order_state(self, state):
states = {
'OPEN': 'open',
'REJECTED': 'rejected',
'FILLED': 'closed',
'CANCELED': 'canceled',
'PART_FILLED': 'open',
'EXPIRED': 'expired',
}
return self.safe_string(states, state, state)
def parse_order(self, order, market=None):
#
# {
# clOrdId: '00001',
# ordType: 'MARKET',
# ordStatus: 'FILLED',
# side: 'BUY',
# symbol: 'USDC-USDT',
# exOrdId: '281775861306290',
# price: null,
# text: 'Fill',
# lastShares: '30.0',
# lastPx: '0.9999',
# leavesQty: '0.0',
# cumQty: '30.0',
# avgPx: '0.9999',
# timestamp: '1633940339619'
# }
#
clientOrderId = self.safe_string(order, 'clOrdId')
type = self.safe_string_lower(order, 'ordType')
statusId = self.safe_string(order, 'ordStatus')
state = self.parse_order_state(statusId)
side = self.safe_string_lower(order, 'side')
marketId = self.safe_string(order, 'symbol')
symbol = self.safe_symbol(marketId, market, '-')
exchangeOrderId = self.safe_string(order, 'exOrdId')
price = self.safe_string(order, 'price') if (type != 'market') else None
average = self.safe_number(order, 'avgPx')
timestamp = self.safe_integer(order, 'timestamp')
datetime = self.iso8601(timestamp)
filled = self.safe_string(order, 'cumQty')
remaining = self.safe_string(order, 'leavesQty')
result = self.safe_order({
'id': exchangeOrderId,
'clientOrderId': clientOrderId,
'datetime': datetime,
'timestamp': timestamp,
'lastTradeTimestamp': None,
'status': state,
'symbol': symbol,
'type': type,
'timeInForce': None,
'side': side,
'price': price,
'average': average,
'amount': None,
'filled': filled,
'remaining': remaining,
'cost': None,
'trades': [],
'fees': {},
'info': order,
})
return result
def create_order(self, symbol: str, type: OrderType, side: OrderSide, amount, price=None, params={}):
"""
create a trade order
:param str symbol: unified symbol of the market to create an order in
:param str type: 'market' or 'limit'
:param str side: 'buy' or 'sell'
:param float amount: how much of currency you want to trade in units of base currency
:param float [price]: the price at which the order is to be fullfilled, in units of the quote currency, ignored in market orders
:param dict [params]: extra parameters specific to the blockchaincom api endpoint
:returns dict: an `order structure <https://github.com/ccxt/ccxt/wiki/Manual#order-structure>`
"""
self.load_markets()
market = self.market(symbol)
orderType = self.safe_string(params, 'ordType', type)
uppercaseOrderType = orderType.upper()
clientOrderId = self.safe_string_2(params, 'clientOrderId', 'clOrdId', self.uuid16())
params = self.omit(params, ['ordType', 'clientOrderId', 'clOrdId'])
request = {
# 'stopPx' : limit price
# 'timeInForce' : "GTC" for Good Till Cancel, "IOC" for Immediate or Cancel, "FOK" for Fill or Kill, "GTD" Good Till Date
# 'expireDate' : expiry date in the format YYYYMMDD
# 'minQty' : The minimum quantity required for an IOC fill
'ordType': uppercaseOrderType,
'symbol': market['id'],
'side': side.upper(),
'orderQty': self.amount_to_precision(symbol, amount),
'clOrdId': clientOrderId,
}
stopPrice = self.safe_value_2(params, 'stopPx', 'stopPrice')
params = self.omit(params, ['stopPx', 'stopPrice'])
if uppercaseOrderType == 'STOP' or uppercaseOrderType == 'STOPLIMIT':
if stopPrice is None:
raise ArgumentsRequired(self.id + ' createOrder() requires a stopPx or stopPrice param for a ' + uppercaseOrderType + ' order')
if stopPrice is not None:
if uppercaseOrderType == 'MARKET':
request['ordType'] = 'STOP'
elif uppercaseOrderType == 'LIMIT':
request['ordType'] = 'STOPLIMIT'
priceRequired = False
stopPriceRequired = False
if request['ordType'] == 'LIMIT' or request['ordType'] == 'STOPLIMIT':
priceRequired = True
if request['ordType'] == 'STOP' or request['ordType'] == 'STOPLIMIT':
stopPriceRequired = True
if priceRequired:
request['price'] = self.price_to_precision(symbol, price)
if stopPriceRequired:
request['stopPx'] = self.price_to_precision(symbol, stopPrice)
response = self.privatePostOrders(self.extend(request, params))
return self.parse_order(response, market)
def cancel_order(self, id: str, symbol: Optional[str] = None, params={}):
"""
cancels an open order
:param str id: order id
:param str symbol: unified symbol of the market the order was made in
:param dict [params]: extra parameters specific to the blockchaincom api endpoint
:returns dict: An `order structure <https://github.com/ccxt/ccxt/wiki/Manual#order-structure>`
"""
request = {
'orderId': id,
}
response = self.privateDeleteOrdersOrderId(self.extend(request, params))
return {
'id': id,
'info': response,
}
def cancel_all_orders(self, symbol: Optional[str] = None, params={}):
"""
cancel all open orders
:param str symbol: unified market symbol of the market to cancel orders in, all markets are used if None, default is None
:param dict [params]: extra parameters specific to the blockchaincom api endpoint
:returns dict: an list of `order structures <https://github.com/ccxt/ccxt/wiki/Manual#order-structure>`
"""
# cancels all open orders if no symbol specified
# cancels all open orders of specified symbol, if symbol is specified
self.load_markets()
request = {
# 'symbol': marketId,
}
if symbol is not None:
marketId = self.market_id(symbol)
request['symbol'] = marketId
response = self.privateDeleteOrders(self.extend(request, params))
return {
'symbol': symbol,
'info': response,
}
def fetch_trading_fees(self, params={}):
"""
fetch the trading fees for multiple markets
:param dict [params]: extra parameters specific to the blockchaincom api endpoint
:returns dict: a dictionary of `fee structures <https://github.com/ccxt/ccxt/wiki/Manual#fee-structure>` indexed by market symbols
"""
self.load_markets()
response = self.privateGetFees(params)
#
# {
# makerRate: "0.002",
# takerRate: "0.004",
# volumeInUSD: "0.0"
# }
#
makerFee = self.safe_number(response, 'makerRate')
takerFee = self.safe_number(response, 'takerRate')
result = {}
for i in range(0, len(self.symbols)):
symbol = self.symbols[i]
result[symbol] = {
'info': response,
'symbol': symbol,
'maker': makerFee,
'taker': takerFee,
}
return result
def fetch_canceled_orders(self, symbol: Optional[str] = None, since: Optional[int] = None, limit: Optional[int] = None, params={}):
"""
fetches information on multiple canceled orders made by the user
:param str symbol: unified market symbol of the market orders were made in
:param int [since]: timestamp in ms of the earliest order, default is None
:param int [limit]: max number of orders to return, default is None
:param dict [params]: extra parameters specific to the blockchaincom api endpoint
:returns dict: a list of `order structures <https://github.com/ccxt/ccxt/wiki/Manual#order-structure>`
"""
state = 'CANCELED'
return self.fetch_orders_by_state(state, symbol, since, limit, params)
def fetch_closed_orders(self, symbol: Optional[str] = None, since: Optional[int] = None, limit: Optional[int] = None, params={}):
"""
fetches information on multiple closed orders made by the user
:param str symbol: unified market symbol of the market orders were made in
:param int [since]: the earliest time in ms to fetch orders for
:param int [limit]: the maximum number of orde structures to retrieve
:param dict [params]: extra parameters specific to the blockchaincom api endpoint
:returns Order[]: a list of `order structures <https://github.com/ccxt/ccxt/wiki/Manual#order-structure>`
"""
state = 'FILLED'
return self.fetch_orders_by_state(state, symbol, since, limit, params)
def fetch_open_orders(self, symbol: Optional[str] = None, since: Optional[int] = None, limit: Optional[int] = None, params={}):
"""
fetch all unfilled currently open orders
:param str symbol: unified market symbol
:param int [since]: the earliest time in ms to fetch open orders for
:param int [limit]: the maximum number of open orders structures to retrieve
:param dict [params]: extra parameters specific to the blockchaincom api endpoint
:returns Order[]: a list of `order structures <https://github.com/ccxt/ccxt/wiki/Manual#order-structure>`
"""
state = 'OPEN'
return self.fetch_orders_by_state(state, symbol, since, limit, params)
def fetch_orders_by_state(self, state, symbol: Optional[str] = None, since: Optional[int] = None, limit: Optional[int] = None, params={}):
self.load_markets()
request = {
# 'to': unix epoch ms
# 'from': unix epoch ms
'status': state,
'limit': 100,
}
market = None
if symbol is not None:
market = self.market(symbol)
request['symbol'] = market['id']
response = self.privateGetOrders(self.extend(request, params))
return self.parse_orders(response, market, since, limit)
def parse_trade(self, trade, market=None):
#
# {
# "exOrdId":281685751028507,
# "tradeId":281685434947633,
# "execId":8847494003,
# "side":"BUY",
# "symbol":"AAVE-USDT",
# "price":405.34,
# "qty":0.1,
# "fee":0.162136,
# "timestamp":1634559249687
# }
#
orderId = self.safe_string(trade, 'exOrdId')
tradeId = self.safe_string(trade, 'tradeId')
side = self.safe_string(trade, 'side').lower()
marketId = self.safe_string(trade, 'symbol')
priceString = self.safe_string(trade, 'price')
amountString = self.safe_string(trade, 'qty')
timestamp = self.safe_integer(trade, 'timestamp')
datetime = self.iso8601(timestamp)
market = self.safe_market(marketId, market, '-')
symbol = market['symbol']
fee = None
feeCostString = self.safe_string(trade, 'fee')
if feeCostString is not None:
feeCurrency = market['quote']
fee = {'cost': feeCostString, 'currency': feeCurrency}
return self.safe_trade({
'id': tradeId,
'timestamp': timestamp,
'datetime': datetime,
'symbol': symbol,
'order': orderId,
'type': None,
'side': side,
'takerOrMaker': None,
'price': priceString,
'amount': amountString,
'cost': None,
'fee': fee,
'info': trade,
}, market)
def fetch_my_trades(self, symbol: Optional[str] = None, since: Optional[int] = None, limit: Optional[int] = None, params={}):
"""
fetch all trades made by the user
:param str symbol: unified market symbol
:param int [since]: the earliest time in ms to fetch trades for
:param int [limit]: the maximum number of trades structures to retrieve
:param dict [params]: extra parameters specific to the blockchaincom api endpoint
:returns Trade[]: a list of `trade structures <https://github.com/ccxt/ccxt/wiki/Manual#trade-structure>`
"""
self.load_markets()
request = {}
if limit is not None:
request['limit'] = limit
market = None
if symbol is not None:
request['symbol'] = self.market_id(symbol)
market = self.market(symbol)
trades = self.privateGetFills(self.extend(request, params))
return self.parse_trades(trades, market, since, limit, params) # need to define
def fetch_deposit_address(self, code: str, params={}):
"""
fetch the deposit address for a currency associated with self account
:param str code: unified currency code
:param dict [params]: extra parameters specific to the blockchaincom api endpoint
:returns dict: an `address structure <https://github.com/ccxt/ccxt/wiki/Manual#address-structure>`
"""
self.load_markets()
currency = self.currency(code)
request = {
'currency': currency['id'],
}
response = self.privatePostDepositsCurrency(self.extend(request, params))
rawAddress = self.safe_string(response, 'address')
tag = None
address = None
if rawAddress is not None:
# if a tag or memo is used it is separated by a colon in the 'address' value
address, tag = rawAddress.split(':')
result = {'info': response}
result['currency'] = currency['code']
result['address'] = address
if tag is not None:
result['tag'] = tag
return result
def parse_transaction_state(self, state):
states = {
'COMPLETED': 'ok', #
'REJECTED': 'failed',
'PENDING': 'pending',
'FAILED': 'failed',
'REFUNDED': 'refunded',
}
return self.safe_string(states, state, state)
def parse_transaction(self, transaction, currency=None):
#
# deposit
#
# {
# "depositId":"748e9180-be0d-4a80-e175-0156150efc95",
# "amount":0.009,
# "currency":"ETH",
# "address":"0xEC6B5929D454C8D9546d4221ace969E1810Fa92c",
# "state":"COMPLETED",
# "txHash":"582114562140e51a80b481c2dfebaf62b4ab9769b8ff54820bb67e34d4a3ab0c",
# "timestamp":1633697196241
# }
#
# withdrawal
#
# {
# "amount":30.0,
# "currency":"USDT",
# "beneficiary":"cab00d11-6e7f-46b7-b453-2e8ef6f101fa", # blockchain specific id
# "withdrawalId":"99df5ef7-eab6-4033-be49-312930fbd1ea",
# "fee":34.005078,
# "state":"COMPLETED",
# "timestamp":1634218452549
# }
#
type = None
id = None
amount = self.safe_number(transaction, 'amount')
timestamp = self.safe_integer(transaction, 'timestamp')
currencyId = self.safe_string(transaction, 'currency')
code = self.safe_currency_code(currencyId, currency)
state = self.safe_string(transaction, 'state')
if 'depositId' in transaction:
type = 'deposit'
id = self.safe_string(transaction, 'depositId')
elif 'withdrawalId' in transaction:
type = 'withdrawal'
id = self.safe_string(transaction, 'withdrawalId')
feeCost = self.safe_number(transaction, 'fee') if (type == 'withdrawal') else None
fee = None
if feeCost is not None:
fee = {'currency': code, 'cost': feeCost}
address = self.safe_string(transaction, 'address')
txid = self.safe_string(transaction, 'txhash')
result = {
'info': transaction,
'id': id,
'txid': txid,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'network': None,
'addressFrom': None,
'address': address,
'addressTo': address,
'tagFrom': None,
'tag': None,
'tagTo': None,
'type': type,
'amount': amount,
'currency': code,
'status': self.parse_transaction_state(state), # 'status': 'pending', # 'ok', 'failed', 'canceled', string
'updated': None,
'comment': None,
'fee': fee,
}
return result
def fetch_withdrawal_whitelist(self, params={}):
"""
fetch the list of withdrawal addresses on the whitelist
:param dict [params]: extra parameters specific to the blockchaincom api endpoint
:returns dict: dictionary with keys beneficiaryId, name, currency
"""
self.load_markets()
response = self.privateGetWhitelist()
result = []
for i in range(0, len(response)):
entry = response[i]
result.append({
'beneficiaryId': self.safe_string(entry, 'whitelistId'),
'name': self.safe_string(entry, 'name'),
'currency': self.safe_string(entry, 'currency'),
'info': entry,
})
return result
def fetch_withdrawal_whitelist_by_currency(self, code: str, params={}):
self.load_markets()
currency = self.currency(code)
request = {
'currency': currency['id'],
}
response = self.privateGetWhitelistCurrency(self.extend(request, params))
result = []
for i in range(0, len(response)):
entry = response[i]
result.append({
'beneficiaryId': self.safe_string(entry, 'whitelistId'),
'name': self.safe_string(entry, 'name'),
'currency': self.safe_string(entry, 'currency'),
'info': entry,
})
return result
def withdraw(self, code: str, amount, address, tag=None, params={}):
"""
make a withdrawal
:param str code: unified currency code
:param float amount: the amount to withdraw
:param str address: the address to withdraw to
:param str tag:
:param dict [params]: extra parameters specific to the blockchaincom api endpoint
:returns dict: a `transaction structure <https://github.com/ccxt/ccxt/wiki/Manual#transaction-structure>`
"""
self.load_markets()
currency = self.currency(code)
request = {
'amount': amount,
'currency': currency['id'],
'beneficiary': address,
'sendMax': False,
}
response = self.privatePostWithdrawals(self.extend(request, params))
#
# {
# amount: "30.0",
# currency: "USDT",
# beneficiary: "adcd43fb-9ba6-41f7-8c0d-7013482cb88f",
# withdrawalId: "99df5ef7-eab6-4033-be49-312930fbd1ea",
# fee: "34.005078",
# state: "PENDING",
# timestamp: "1634218452595"
# },
#
return self.parse_transaction(response, currency)
def fetch_withdrawals(self, code: Optional[str] = None, since: Optional[int] = None, limit: Optional[int] = None, params={}):
"""
fetch all withdrawals made from an account
:param str code: unified currency code
:param int [since]: the earliest time in ms to fetch withdrawals for
:param int [limit]: the maximum number of withdrawals structures to retrieve
:param dict [params]: extra parameters specific to the blockchaincom api endpoint
:returns dict[]: a list of `transaction structures <https://github.com/ccxt/ccxt/wiki/Manual#transaction-structure>`
"""
self.load_markets()
request = {
# 'from' : integer timestamp in ms
# 'to' : integer timestamp in ms
}
if since is not None:
request['from'] = since
currency = None
if code is not None:
currency = self.currency(code)
response = self.privateGetWithdrawals(self.extend(request, params))
return self.parse_transactions(response, currency, since, limit)
def fetch_withdrawal(self, id: str, code: Optional[str] = None, params={}):
"""
fetch data on a currency withdrawal via the withdrawal id
:param str id: withdrawal id
:param str code: not used by blockchaincom.fetchWithdrawal
:param dict [params]: extra parameters specific to the blockchaincom api endpoint
:returns dict: a `transaction structure <https://github.com/ccxt/ccxt/wiki/Manual#transaction-structure>`
"""
self.load_markets()
request = {
'withdrawalId': id,
}
response = self.privateGetWithdrawalsWithdrawalId(self.extend(request, params))
return self.parse_transaction(response)
def fetch_deposits(self, code: Optional[str] = None, since: Optional[int] = None, limit: Optional[int] = None, params={}):
"""
fetch all deposits made to an account
:param str code: unified currency code
:param int [since]: the earliest time in ms to fetch deposits for
:param int [limit]: the maximum number of deposits structures to retrieve
:param dict [params]: extra parameters specific to the blockchaincom api endpoint
:returns dict[]: a list of `transaction structures <https://github.com/ccxt/ccxt/wiki/Manual#transaction-structure>`
"""
self.load_markets()
request = {
# 'from' : integer timestamp in ms
# 'to' : integer timestap in ms
}
if since is not None:
request['from'] = since
currency = None
if code is not None:
currency = self.currency(code)
response = self.privateGetDeposits(self.extend(request, params))
return self.parse_transactions(response, currency, since, limit)
def fetch_deposit(self, id: str, code: Optional[str] = None, params={}):
"""
fetch information on a deposit
:param str id: deposit id
:param str code: not used by blockchaincom fetchDeposit()
:param dict [params]: extra parameters specific to the blockchaincom api endpoint
:returns dict: a `transaction structure <https://github.com/ccxt/ccxt/wiki/Manual#transaction-structure>`
"""
self.load_markets()
depositId = self.safe_string(params, 'depositId', id)
request = {
'depositId': depositId,
}
deposit = self.privateGetDepositsDepositId(self.extend(request, params))
return self.parse_transaction(deposit)
def fetch_balance(self, params={}):
"""
query for balance and get the amount of funds available for trading or funds locked in orders
:param dict [params]: extra parameters specific to the blockchaincom api endpoint
:returns dict: a `balance structure <https://docs.ccxt.com/en/latest/manual.html?#balance-structure>`
"""
self.load_markets()
accountName = self.safe_string(params, 'account', 'primary')
params = self.omit(params, 'account')
request = {
'account': accountName,
}
response = self.privateGetAccounts(self.extend(request, params))
#
# {
# "primary": [
# {
# "currency":"ETH",
# "balance":0.009,
# "available":0.009,
# "balance_local":30.82869,
# "available_local":30.82869,
# "rate":3425.41
# },
# ...
# ]
# }
#
balances = self.safe_value(response, accountName)
if balances is None:
raise ExchangeError(self.id + ' fetchBalance() could not find the "' + accountName + '" account')
result = {'info': response}
for i in range(0, len(balances)):
entry = balances[i]
currencyId = self.safe_string(entry, 'currency')
code = self.safe_currency_code(currencyId)
account = self.account()
account['free'] = self.safe_string(entry, 'available')
account['total'] = self.safe_string(entry, 'balance')
result[code] = account
return self.safe_balance(result)
def fetch_order(self, id: str, symbol: Optional[str] = None, params={}):
"""
fetches information on an order made by the user
:param str symbol: not used by blockchaincom fetchOrder
:param dict [params]: extra parameters specific to the blockchaincom api endpoint
:returns dict: An `order structure <https://github.com/ccxt/ccxt/wiki/Manual#order-structure>`
"""
# note: only works with exchange-order-id
# does not work with clientOrderId
self.load_markets()
request = {
'orderId': id,
}
response = self.privateGetOrdersOrderId(self.extend(request, params))
#
# {
# "exOrdId": 11111111,
# "clOrdId": "ABC",
# "ordType": "MARKET",
# "ordStatus": "FILLED",
# "side": "BUY",
# "price": 0.12345,
# "text": "string",
# "symbol": "BTC-USD",
# "lastShares": 0.5678,
# "lastPx": 3500.12,
# "leavesQty": 10,
# "cumQty": 0.123345,
# "avgPx": 345.33,
# "timestamp": 1592830770594
# }
#
return self.parse_order(response)
def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
requestPath = '/' + self.implode_params(path, params)
url = self.urls['api'][api] + requestPath
query = self.omit(params, self.extract_params(path))
if api == 'public':
if query:
url += '?' + self.urlencode(query)
elif api == 'private':
self.check_required_credentials()
headers = {
'X-API-Token': self.secret,
}
if (method == 'GET'):
if query:
url += '?' + self.urlencode(query)
else:
body = self.json(query)
headers['Content-Type'] = 'application/json'
return {'url': url, 'method': method, 'body': body, 'headers': headers}
def handle_errors(self, code, reason, url, method, headers, body, response, requestHeaders, requestBody):
# {"timestamp":"2021-10-21T15:13:58.837+00:00","status":404,"error":"Not Found","message":"","path":"/orders/505050"
if response is None:
return None
text = self.safe_string(response, 'text')
if text is not None: # if trade currency account is empty returns 200 with rejected order
if text == 'Insufficient Balance':
raise InsufficientFunds(self.id + ' ' + body)
errorCode = self.safe_string(response, 'status')
errorMessage = self.safe_string(response, 'error')
if code is not None:
feedback = self.id + ' ' + self.json(response)
self.throw_exactly_matched_exception(self.exceptions['exact'], errorCode, feedback)
self.throw_broadly_matched_exception(self.exceptions['broad'], errorMessage, feedback)
return None
| [
"[email protected]"
]
| |
8d653e447ccd1bbc5219799f747b89e50269d731 | b988ae0baa8c6a8098fadbe96a8a4ba7a0016f36 | /social/backends/live.py | 2884438fbc0955e10b4cfc8bc8c723ec050ee504 | [
"Python-2.0",
"BSD-3-Clause",
"BSD-2-Clause"
]
| permissive | stephenmcd/python-social-auth | 6cedefa282975ce6043632f8272c527cc738abdd | f70500ad966887a793ea17ed7b794e5526f828f1 | refs/heads/master | 2021-01-21T08:51:52.779136 | 2013-12-03T10:28:38 | 2013-12-03T10:28:38 | 14,885,186 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,257 | py | """
Live OAuth2 backend, docs at:
http://psa.matiasaguirre.net/docs/backends/live.html
"""
from social.backends.oauth import BaseOAuth2
class LiveOAuth2(BaseOAuth2):
name = 'live'
AUTHORIZATION_URL = 'https://login.live.com/oauth20_authorize.srf'
ACCESS_TOKEN_URL = 'https://login.live.com/oauth20_token.srf'
ACCESS_TOKEN_METHOD = 'POST'
SCOPE_SEPARATOR = ','
DEFAULT_SCOPE = ['wl.basic', 'wl.emails']
EXTRA_DATA = [
('id', 'id'),
('access_token', 'access_token'),
('reset_token', 'reset_token'),
('expires', 'expires'),
('email', 'email'),
('first_name', 'first_name'),
('last_name', 'last_name'),
]
def get_user_details(self, response):
"""Return user details from Live Connect account"""
return {'username': response.get('name'),
'email': response.get('emails', {}).get('account', ''),
'first_name': response.get('first_name'),
'last_name': response.get('last_name')}
def user_data(self, access_token, *args, **kwargs):
"""Loads user data from service"""
return self.get_json('https://apis.live.net/v5.0/me', params={
'access_token': access_token
})
| [
"[email protected]"
]
| |
2631a8e662e432ab59e792b069be027fbf8dd507 | d41d18d3ea6edd2ec478b500386375a8693f1392 | /plotly/validators/bar/_constraintext.py | 930b959ee4bb09faf0e0d0634c33bccb98c98747 | [
"MIT"
]
| permissive | miladrux/plotly.py | 38921dd6618650d03be9891d6078e771ffccc99a | dbb79e43e2cc6c5762251537d24bad1dab930fff | refs/heads/master | 2020-03-27T01:46:57.497871 | 2018-08-20T22:37:38 | 2018-08-20T22:37:38 | 145,742,203 | 1 | 0 | MIT | 2018-08-22T17:37:07 | 2018-08-22T17:37:07 | null | UTF-8 | Python | false | false | 487 | py | import _plotly_utils.basevalidators
class ConstraintextValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self, plotly_name='constraintext', parent_name='bar', **kwargs
):
super(ConstraintextValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type='calc',
role='info',
values=['inside', 'outside', 'both', 'none'],
**kwargs
)
| [
"[email protected]"
]
| |
b9ceed3c8c034db5703e61e8a45a35719069f193 | 60d5ea4f007d49768d250ef394003f554003e4d0 | /python/Backtracking/051.N-Queens.py | ee7c4ab3c9a52e343f670af51f54f6fa41acebf8 | []
| no_license | EvanJamesMG/Leetcode | dd7771beb119ea1250dbb3b147a09053298cd63b | fa638c7fda3802e9f4e0751a2c4c084edf09a441 | refs/heads/master | 2021-01-10T17:11:10.896393 | 2017-12-01T16:04:44 | 2017-12-01T16:04:44 | 46,968,756 | 5 | 1 | null | null | null | null | UTF-8 | Python | false | false | 4,899 | py | /*
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
*/
#python 版本
'''
这类型问题统称为递归回溯问题,也可以叫做对决策树的深度优先搜索(dfs)。
N皇后问题有个技巧的关键在于棋盘的表示方法,这里使用一个数组就可以表达了。
比如board=[1, 3, 0, 2],这是4皇后问题的一个解,意思是:在第0行,皇后放在第1列;在第1行,皇后放在第3列;在第2行,皇后放在第0列;
在第3行,皇后放在第2列。这道题提供一个递归解法,下道题使用非递归。check函数用来检查在第k行,皇后是否可以放置在第j列。
'''
class Solution:
# @return a list of lists of string
def solveNQueens(self, n):
def check(k, j): # check if the kth queen can be put in column j!
for i in range(k):
if board[i]==j or abs(k-i)==abs(board[i]-j):
return False
return True
def dfs(depth, valuelist):
if depth==n: res.append(valuelist); return
for i in range(n):
if check(depth,i):
board[depth]=i
s='.'*n
dfs(depth+1, valuelist+[s[:i]+'Q'+s[i+1:]])
board=[-1 for i in range(n)]
res=[]
dfs(0,[])
return res
#Java 版本
'''
我们把这一题分成几个小问题
1. 传统的dfs递归
2. 验证放置Queen的地方是否合法
3. 输出Board结果
这么做的好处就是,一开始,我们不用建立一个庞大的Board,我们选用一个数组对应Board里面的每一行,数组每一个值对应这一行放置Queen的列号
比如: int[ ] {3,1,4,2} 代表放置的地点分别为[1,3], [2,1], [3,4], [4,2] 这么一来,我们用很简单的用数组表示了整个Board,
而且在isValid函数里判断的时候会非常简洁,而且把输出Board单独隔离了出来
dfs的循环是指这一行里,从第一列到最后一列放置的所有可能,如果放置的地点通过isValid验证,通过cur+1进入下一行进行递归,如果没通过验证,试下一个位置,如果所有位置都不Valid,跳回上一层
采用int[ ]的好处是,每一次我们只需改变一个数字就相当于改变了棋子的放置位置
isValid函数,首先int[ ]代表行,这样就避免了每一行出现重复的Queen (因为你不可能在一个int里面放2个值)这样简化了验证 接下来我们只需验证列和对角线
验证列的时候,要验证这一行之前的行有没有重复的(注意是验证之前的喔)
验证对角线,根据对角线性质,长 = 宽 那么我们不难写出 Math.abs(loc[i] - loc[cur]) == (cur - i)
最后loc[]里面记录的是解的信息(如果有解)我们把它转换成String, 输出Board即可
'''
'''
public class Solution
{
public ArrayList<String[]> solveNQueens(int n)
{
ArrayList<String[]> res = new ArrayList<String[]>();
int[] loc = new int[n]; //记录皇后处于哪一列,列数组
dfs(res,loc,0,n);
return res;
}
public void dfs(ArrayList<String[]> res, int[] loc, int cur, int n)
{
if(cur==n)
printboard(res,loc,n);
else
{
for(int i=0;i<n;i++)
{
loc[cur] = i;
if(isValid(loc,cur))
dfs(res,loc,cur+1,n);
}
}
}
public boolean isValid(int[] loc, int cur)
{
for(int i=0;i<cur;i++)//只需要保证与那些已经就位的皇后不冲突即可
{
if(loc[i]==loc[cur]||Math.abs(loc[i]-loc[cur])==(cur-i)) //验证对角线,根据对角线性质,长 = 宽
return false; // 那么我们不难写出 Math.abs(loc[i] - loc[cur]) == (cur - i)
}
return true;
}
public void printboard(ArrayList<String[]> res, int[] loc, int n)
{
String[] ans = new String[n];
for(int i=0;i<n;i++)
{
String row = new String();
for(int j=0;j<n;j++)
{
if(j==loc[i]) row += "Q";
else row += ".";
}
ans[i] = row;
}
res.add(ans);
}
}
'''
| [
"[email protected]"
]
| |
f1e6748a0efe1c156093e43c420f7c16862573db | 8aa1b94626402c0c614128d6061edb771dad05cf | /stu02/999test_user.py | 5b48e67c1eaea2db5b122eaee9ffccbb00699acd | []
| no_license | netfj/Project_Stu02 | 31e76c1b656ee74c54cae2185821dec7ccf50401 | afc1b26b7c586fd6979ab574c7d357a6b9ef4d29 | refs/heads/master | 2023-03-13T22:24:40.364167 | 2021-02-23T09:53:31 | 2021-02-23T09:53:31 | 341,506,093 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 98 | py |
a=[(1,2,3),('a','b','c')]
print(a)
print(a[0])
print(a[1][1])
for n in range(1,10):
print(n) | [
"[email protected]"
]
| |
52c28d99fae8462a3d39a4e713d71da4f32ba11a | f66a33f8cdd8286320da730be67c89ee00d83d8d | /src/mem/cache/compressors/Compressors.py | c8f82c55a1103c907425e48f1f0b631de7b162f6 | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license",
"LGPL-2.0-or-later",
"MIT"
]
| permissive | H2020-COSSIM/cgem5 | 0d5812632757e6146f7852c9bf4abe4e9628296a | 1222cc0c5618875e048f288e998187c236508a64 | refs/heads/main | 2023-05-13T14:08:01.665322 | 2023-05-08T08:39:50 | 2023-05-08T08:39:50 | 468,039,890 | 3 | 2 | BSD-3-Clause | 2022-10-12T14:29:33 | 2022-03-09T18:05:40 | C++ | UTF-8 | Python | false | false | 12,027 | py | # Copyright (c) 2018-2020 Inria
# 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 copyright holders 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
# OWNER 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.
from m5.params import *
from m5.proxy import *
from m5.SimObject import *
from m5.objects.IndexingPolicies import *
from m5.objects.ReplacementPolicies import *
class BaseCacheCompressor(SimObject):
type = "BaseCacheCompressor"
abstract = True
cxx_class = "gem5::compression::Base"
cxx_header = "mem/cache/compressors/base.hh"
block_size = Param.Int(Parent.cache_line_size, "Block size in bytes")
chunk_size_bits = Param.Unsigned(
32, "Size of a parsing data chunk (in bits)"
)
size_threshold_percentage = Param.Percent(
50,
"Minimum percentage of the block size, a compressed block must "
"achieve to be stored in compressed format",
)
comp_chunks_per_cycle = Param.Unsigned(
1, "Number of chunks that can be compressed in parallel per cycle."
)
comp_extra_latency = Param.Cycles(
1,
"Number of extra cycles required "
"to finish compression (e.g., due to shifting and packaging).",
)
decomp_chunks_per_cycle = Param.Unsigned(
1, "Number of chunks that can be decompressed in parallel per cycle."
)
decomp_extra_latency = Param.Cycles(
1,
"Number of extra cycles required "
"to finish decompression (e.g., due to shifting and packaging).",
)
class BaseDictionaryCompressor(BaseCacheCompressor):
type = "BaseDictionaryCompressor"
abstract = True
cxx_class = "gem5::compression::BaseDictionaryCompressor"
cxx_header = "mem/cache/compressors/dictionary_compressor.hh"
dictionary_size = Param.Int(
Parent.cache_line_size, "Number of dictionary entries"
)
class Base64Delta8(BaseDictionaryCompressor):
type = "Base64Delta8"
cxx_class = "gem5::compression::Base64Delta8"
cxx_header = "mem/cache/compressors/base_delta.hh"
chunk_size_bits = 64
# Base-delta compressors achieve 1-cycle latencies
comp_chunks_per_cycle = 8 * Self.block_size / Self.chunk_size_bits
comp_extra_latency = 0
decomp_chunks_per_cycle = 8 * Self.block_size / Self.chunk_size_bits
decomp_extra_latency = 0
class Base64Delta16(BaseDictionaryCompressor):
type = "Base64Delta16"
cxx_class = "gem5::compression::Base64Delta16"
cxx_header = "mem/cache/compressors/base_delta.hh"
chunk_size_bits = 64
# Base-delta compressors achieve 1-cycle latencies
comp_chunks_per_cycle = 8 * Self.block_size / Self.chunk_size_bits
comp_extra_latency = 0
decomp_chunks_per_cycle = 8 * Self.block_size / Self.chunk_size_bits
decomp_extra_latency = 0
class Base64Delta32(BaseDictionaryCompressor):
type = "Base64Delta32"
cxx_class = "gem5::compression::Base64Delta32"
cxx_header = "mem/cache/compressors/base_delta.hh"
chunk_size_bits = 64
# Base-delta compressors achieve 1-cycle latencies
comp_chunks_per_cycle = 8 * Self.block_size / Self.chunk_size_bits
comp_extra_latency = 0
decomp_chunks_per_cycle = 8 * Self.block_size / Self.chunk_size_bits
decomp_extra_latency = 0
class Base32Delta8(BaseDictionaryCompressor):
type = "Base32Delta8"
cxx_class = "gem5::compression::Base32Delta8"
cxx_header = "mem/cache/compressors/base_delta.hh"
chunk_size_bits = 32
# Base-delta compressors achieve 1-cycle latencies
comp_chunks_per_cycle = 8 * Self.block_size / Self.chunk_size_bits
comp_extra_latency = 0
decomp_chunks_per_cycle = 8 * Self.block_size / Self.chunk_size_bits
decomp_extra_latency = 0
class Base32Delta16(BaseDictionaryCompressor):
type = "Base32Delta16"
cxx_class = "gem5::compression::Base32Delta16"
cxx_header = "mem/cache/compressors/base_delta.hh"
chunk_size_bits = 32
# Base-delta compressors achieve 1-cycle latencies
comp_chunks_per_cycle = 8 * Self.block_size / Self.chunk_size_bits
comp_extra_latency = 0
decomp_chunks_per_cycle = 8 * Self.block_size / Self.chunk_size_bits
decomp_extra_latency = 0
class Base16Delta8(BaseDictionaryCompressor):
type = "Base16Delta8"
cxx_class = "gem5::compression::Base16Delta8"
cxx_header = "mem/cache/compressors/base_delta.hh"
chunk_size_bits = 16
# Base-delta compressors achieve 1-cycle latencies
comp_chunks_per_cycle = 8 * Self.block_size / Self.chunk_size_bits
comp_extra_latency = 0
decomp_chunks_per_cycle = 8 * Self.block_size / Self.chunk_size_bits
decomp_extra_latency = 0
class CPack(BaseDictionaryCompressor):
type = "CPack"
cxx_class = "gem5::compression::CPack"
cxx_header = "mem/cache/compressors/cpack.hh"
comp_chunks_per_cycle = 2
# Accounts for pattern matching, length generation, packaging and shifting
comp_extra_latency = 5
decomp_chunks_per_cycle = 2
decomp_extra_latency = 1
class FPC(BaseDictionaryCompressor):
type = "FPC"
cxx_class = "gem5::compression::FPC"
cxx_header = "mem/cache/compressors/fpc.hh"
comp_chunks_per_cycle = 8
comp_extra_latency = 1
decomp_chunks_per_cycle = 4
decomp_extra_latency = 1
# Dummy dictionary size, since FPC has no dictionary
dictionary_size = 1
zero_run_bits = Param.Int(3, "Number of bits of the zero run bit field")
class FPCD(BaseDictionaryCompressor):
type = "FPCD"
cxx_class = "gem5::compression::FPCD"
cxx_header = "mem/cache/compressors/fpcd.hh"
# Accounts for checking all patterns, selecting patterns, and shifting
# The original claim of a decompression latency of 2 cycles would likely
# generate an unrealistically complex circuit
comp_chunks_per_cycle = 4
comp_extra_latency = 1
decomp_chunks_per_cycle = 4
decomp_extra_latency = 0
dictionary_size = 2
class FrequentValuesCompressor(BaseCacheCompressor):
type = "FrequentValuesCompressor"
cxx_class = "gem5::compression::FrequentValues"
cxx_header = "mem/cache/compressors/frequent_values.hh"
chunk_size_bits = 32
code_generation_ticks = Param.Unsigned(
10000,
"Number of elapsed "
"ticks until the samples are analyzed and their codes are generated.",
)
# @todo The width of a counter width is determined by the maximum
# number of times a given value appears in the cache - i.e.,
# log2(cache_size/chunk_size_bits))".
counter_bits = Param.Unsigned(18, "Number of bits per frequency counter.")
max_code_length = Param.Unsigned(
18,
"Maximum number of bits in a "
"codeword. If 0, table indices are not encoded.",
)
num_samples = Param.Unsigned(
100000,
"Number of samples that must be "
"taken before compression is effectively used.",
)
check_saturation = Param.Bool(
False,
"Whether the counters should be " "manipulated in case of saturation.",
)
vft_assoc = Param.Int(16, "Associativity of the VFT.")
vft_entries = Param.MemorySize("1024", "Number of entries of the VFT.")
vft_indexing_policy = Param.BaseIndexingPolicy(
SetAssociative(
entry_size=1, assoc=Parent.vft_assoc, size=Parent.vft_entries
),
"Indexing policy of the VFT.",
)
vft_replacement_policy = Param.BaseReplacementPolicy(
LFURP(), "Replacement policy of the VFT."
)
comp_chunks_per_cycle = 1
comp_extra_latency = 1
decomp_chunks_per_cycle = 1
decomp_extra_latency = 0
class MultiCompressor(BaseCacheCompressor):
type = "MultiCompressor"
cxx_class = "gem5::compression::Multi"
cxx_header = "mem/cache/compressors/multi.hh"
# Dummy default compressor list. This might not be an optimal choice,
# since these compressors have many overlapping patterns
compressors = VectorParam.BaseCacheCompressor(
[CPack(), FPCD()], "Array of compressors"
)
encoding_in_tags = Param.Bool(
False,
"If set the bits to inform which "
"sub-compressor compressed some data are added to its corresponding "
"tag entry.",
)
# Use the sub-compressors' latencies
comp_chunks_per_cycle = 0
decomp_chunks_per_cycle = 0
# Assume extra 1 cycle to select the results of the winning sub-compressor
comp_extra_latency = 1
# Multi-compressors may need a couple of extra cycles to the select
# which sub-compressor should be used to decompress the data
decomp_extra_latency = 1
class PerfectCompressor(BaseCacheCompressor):
type = "PerfectCompressor"
cxx_class = "gem5::compression::Perfect"
cxx_header = "mem/cache/compressors/perfect.hh"
chunk_size_bits = 64
max_compression_ratio = Param.Int("Maximum compression ratio allowed")
# In a perfect world compression and decompression happen in 1 cycle
comp_chunks_per_cycle = 8 * Self.block_size / Self.chunk_size_bits
comp_extra_latency = 0
decomp_chunks_per_cycle = 8 * Self.block_size / Self.chunk_size_bits
decomp_extra_latency = 0
class RepeatedQwordsCompressor(BaseDictionaryCompressor):
type = "RepeatedQwordsCompressor"
cxx_class = "gem5::compression::RepeatedQwords"
cxx_header = "mem/cache/compressors/repeated_qwords.hh"
chunk_size_bits = 64
# Assume 1-cycle latencies
comp_chunks_per_cycle = 8 * Self.block_size / Self.chunk_size_bits
comp_extra_latency = 0
decomp_chunks_per_cycle = 8 * Self.block_size / Self.chunk_size_bits
decomp_extra_latency = 0
class ZeroCompressor(BaseDictionaryCompressor):
type = "ZeroCompressor"
cxx_class = "gem5::compression::Zero"
cxx_header = "mem/cache/compressors/zero.hh"
chunk_size_bits = 64
# Assume 1-cycle latencies
comp_chunks_per_cycle = 8 * Self.block_size / Self.chunk_size_bits
comp_extra_latency = 0
decomp_chunks_per_cycle = 8 * Self.block_size / Self.chunk_size_bits
decomp_extra_latency = 0
class BDI(MultiCompressor):
compressors = [
ZeroCompressor(size_threshold_percentage=99),
RepeatedQwordsCompressor(size_threshold_percentage=99),
Base64Delta8(size_threshold_percentage=99),
Base64Delta16(size_threshold_percentage=99),
Base64Delta32(size_threshold_percentage=99),
Base32Delta8(size_threshold_percentage=99),
Base32Delta16(size_threshold_percentage=99),
Base16Delta8(size_threshold_percentage=99),
]
# By default assume that the encoding is stored in the tags, and is
# retrieved and decoded while (and ends before) the data is being read.
decomp_extra_latency = 0
encoding_in_tags = True
| [
"[email protected]"
]
| |
9c24ec6281f68a5650163c101e90e9fc247a1dcf | 33edba95f6313b2f5003d5973a37ac1e5988442f | /src/users/SConstruct | 9b1f195bae06f126f6515df699eb7be726cced63 | []
| no_license | faustus123/bdxReco | 25a8883eb23f8bb6ee7f76050141fcc5ca8add79 | c173906d248146df3279347d7ff8f60211b8b601 | refs/heads/master | 2020-12-24T12:40:05.523304 | 2016-02-03T16:07:52 | 2016-02-03T16:07:52 | 51,010,837 | 0 | 0 | null | 2016-02-03T16:07:53 | 2016-02-03T15:56:13 | C++ | UTF-8 | Python | false | false | 565 | from utils import *
Import('env')
users_names = getSubdirs('./')
for user in users_names :
plugins = getSubdirs(str(user))
for plugin in plugins:
print bcolors.OKGREEN,"Found plugin ",plugin," for user ",user,bcolors.ENDC
#We do not want to increment "at libitum" CPPPATH
tmp_cpppath=env['CPPPATH'];
dir = str(user)+'/'+str(plugin)
user_plugin_src = Glob(dir+'/*.cc');
env.Append(CPPPATH=dir)
env.SharedLibrary(source=user_plugin_src,target='#/lib/users/'+user+'_'+plugin,SHLIBPREFIX='',SHLIBSUFFIX='.so')
env.Replace(CPPPATH = tmp_cpppath) | [
"[email protected]"
]
| ||
80c552dd0deb638466da67214246f640e2852f73 | 1d7eec692553afc411ec1e7325634f71a2aed291 | /backend/core/apps.py | 348e92f897b24984f69c0822f7848e13ccd76b1e | []
| no_license | Andy-Nkumane/Tilde | a41a2a65b3901b92263ae94d527de403f59a5caf | 80de97edaf99f4831ca8cb989b93e3be5e09fdd6 | refs/heads/develop | 2023-05-09T10:02:41.240517 | 2021-05-28T09:20:51 | 2021-05-28T09:20:51 | 299,501,586 | 0 | 0 | null | 2020-10-25T22:37:30 | 2020-09-29T04:10:48 | Python | UTF-8 | Python | false | false | 164 | py | from django.apps import AppConfig
class CoreConfig(AppConfig):
name = "core"
def ready(self):
# register the signals
import core.signals
| [
"[email protected]"
]
| |
f2bcfcdc6a9c0b10038cca469bc8f6212aecafae | b9008dc6326b30de1a16ba01a1f3143aa248f7c3 | /python/chapter3/ex01_2.py | 9f32e9fe384e913b4a49ee7bf387fcba2200d019 | []
| no_license | wonjongah/multicampus_IoT | ce219f8b9875aa7738ef952a8702d818a571610e | 765a5cd7df09a869a4074d8eafce69f1d6cfda4a | refs/heads/master | 2023-02-13T12:30:19.924691 | 2021-01-08T10:17:42 | 2021-01-08T10:17:42 | 292,800,307 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 33 | py | a = 1 +2j
b = 3 + 4j
print(a + b) | [
"[email protected]"
]
| |
5c0cb0db96cc9683da39a17d57d2fd157c236521 | 050be63ad4e88890954756fd1a06f93a7993f732 | /backend/lizz_jun18_mob4_dev_6256/wsgi.py | f43e047ac58a377ae0ced3d71b1e6d9d63b0bcea | []
| no_license | crowdbotics-apps/lizz-jun18-mob4-dev-6256 | 46cb7ed037b5e223b151e799db3aa2891257f407 | 4a889dc560f2d463e437978d665d0b00a7b4c87f | refs/heads/master | 2022-11-04T23:40:05.810141 | 2020-06-19T00:15:09 | 2020-06-19T00:15:09 | 273,366,024 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 425 | py | """
WSGI config for lizz_jun18_mob4_dev_6256 project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lizz_jun18_mob4_dev_6256.settings')
application = get_wsgi_application()
| [
"[email protected]"
]
| |
5e5660b444534e5fe95cc65a0a2a1bd41e5b8386 | b56eaf7a603cbb850be11dbbed2c33b954dedbcb | /ctools/pysc2/lib/actions.py | ddc7344914ebcf1ebfcea0f19aa4ebb4fc78515f | [
"Apache-2.0"
]
| permissive | LFhase/DI-star | 2887d9c5dd8bfaa629e0171504b05ac70fdc356f | 09d507c412235a2f0cf9c0b3485ec9ed15fb6421 | refs/heads/main | 2023-06-20T20:05:01.378611 | 2021-07-09T16:26:18 | 2021-07-09T16:26:18 | 384,499,311 | 1 | 0 | Apache-2.0 | 2021-07-09T16:50:29 | 2021-07-09T16:50:28 | null | UTF-8 | Python | false | false | 113,849 | py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Define the static list of types and actions for SC2."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import numbers
import enum
import numpy
import six
from ctools.pysc2.lib import point
from s2clientprotocol import spatial_pb2 as sc_spatial
from s2clientprotocol import ui_pb2 as sc_ui
class ActionSpace(enum.Enum):
FEATURES = 1 # Act in feature layer pixel space with FUNCTIONS below.
RGB = 2 # Act in RGB pixel space with FUNCTIONS below.
RAW = 3 # Act with unit tags with RAW_FUNCTIONS below.
def spatial(action, action_space):
"""Choose the action space for the action proto."""
if action_space == ActionSpace.FEATURES:
return action.action_feature_layer
elif action_space == ActionSpace.RGB:
return action.action_render
else:
raise ValueError("Unexpected value for action_space: %s" % action_space)
def no_op(action, action_space):
del action, action_space
def move_camera(action, action_space, minimap):
"""Move the camera."""
minimap.assign_to(spatial(action, action_space).camera_move.center_minimap)
def select_point(action, action_space, select_point_act, screen):
"""Select a unit at a point."""
select = spatial(action, action_space).unit_selection_point
screen.assign_to(select.selection_screen_coord)
select.type = select_point_act
def select_rect(action, action_space, select_add, screen, screen2):
"""Select units within a rectangle."""
select = spatial(action, action_space).unit_selection_rect
out_rect = select.selection_screen_coord.add()
screen_rect = point.Rect(screen, screen2)
screen_rect.tl.assign_to(out_rect.p0)
screen_rect.br.assign_to(out_rect.p1)
select.selection_add = bool(select_add)
def select_idle_worker(action, action_space, select_worker):
"""Select an idle worker."""
del action_space
action.action_ui.select_idle_worker.type = select_worker
def select_army(action, action_space, select_add):
"""Select the entire army."""
del action_space
action.action_ui.select_army.selection_add = select_add
def select_warp_gates(action, action_space, select_add):
"""Select all warp gates."""
del action_space
action.action_ui.select_warp_gates.selection_add = select_add
def select_larva(action, action_space):
"""Select all larva."""
del action_space
action.action_ui.select_larva.SetInParent() # Adds the empty proto field.
def select_unit(action, action_space, select_unit_act, select_unit_id):
"""Select a specific unit from the multi-unit selection."""
del action_space
select = action.action_ui.multi_panel
select.type = select_unit_act
select.unit_index = select_unit_id
def control_group(action, action_space, control_group_act, control_group_id):
"""Act on a control group, selecting, setting, etc."""
del action_space
select = action.action_ui.control_group
select.action = control_group_act
select.control_group_index = control_group_id
def unload(action, action_space, unload_id):
"""Unload a unit from a transport/bunker/nydus/etc."""
del action_space
action.action_ui.cargo_panel.unit_index = unload_id
def build_queue(action, action_space, build_queue_id):
"""Cancel a unit in the build queue."""
del action_space
action.action_ui.production_panel.unit_index = build_queue_id
def cmd_quick(action, action_space, ability_id, queued):
"""Do a quick command like 'Stop' or 'Stim'."""
action_cmd = spatial(action, action_space).unit_command
action_cmd.ability_id = ability_id
action_cmd.queue_command = queued
def cmd_screen(action, action_space, ability_id, queued, screen):
"""Do a command that needs a point on the screen."""
action_cmd = spatial(action, action_space).unit_command
action_cmd.ability_id = ability_id
action_cmd.queue_command = queued
screen.assign_to(action_cmd.target_screen_coord)
def cmd_minimap(action, action_space, ability_id, queued, minimap):
"""Do a command that needs a point on the minimap."""
action_cmd = spatial(action, action_space).unit_command
action_cmd.ability_id = ability_id
action_cmd.queue_command = queued
minimap.assign_to(action_cmd.target_minimap_coord)
def autocast(action, action_space, ability_id):
"""Toggle autocast."""
del action_space
action.action_ui.toggle_autocast.ability_id = ability_id
def raw_no_op(action):
del action
def raw_move_camera(action, world):
"""Move the camera."""
action_cmd = action.action_raw.camera_move
world.assign_to(action_cmd.center_world_space)
def raw_cmd(action, ability_id, queued, unit_tags):
"""Do a raw command to another unit."""
action_cmd = action.action_raw.unit_command
action_cmd.ability_id = ability_id
action_cmd.queue_command = queued
if not isinstance(unit_tags, (tuple, list)):
unit_tags = [unit_tags]
action_cmd.unit_tags.extend(unit_tags)
def raw_cmd_pt(action, ability_id, queued, unit_tags, world):
"""Do a raw command to another unit towards a point."""
action_cmd = action.action_raw.unit_command
action_cmd.ability_id = ability_id
action_cmd.queue_command = queued
if not isinstance(unit_tags, (tuple, list)):
unit_tags = [unit_tags]
action_cmd.unit_tags.extend(unit_tags)
world.assign_to(action_cmd.target_world_space_pos)
def raw_cmd_unit(action, ability_id, queued, unit_tags,
target_unit_tag):
"""Do a raw command to another unit towards a unit."""
action_cmd = action.action_raw.unit_command
action_cmd.ability_id = ability_id
action_cmd.queue_command = queued
if not isinstance(unit_tags, (tuple, list)):
unit_tags = [unit_tags]
action_cmd.unit_tags.extend(unit_tags)
action_cmd.target_unit_tag = target_unit_tag
def raw_autocast(action, ability_id, unit_tags):
"""Toggle autocast."""
action_cmd = action.action_raw.toggle_autocast
action_cmd.ability_id = ability_id
if not isinstance(unit_tags, (tuple, list)):
unit_tags = [unit_tags]
action_cmd.unit_tags.extend(unit_tags)
def numpy_to_python(val):
"""Convert numpy types to their corresponding python types."""
if isinstance(val, (int, float)):
return val
if isinstance(val, six.string_types):
return val
if (isinstance(val, numpy.number) or
isinstance(val, numpy.ndarray) and not val.shape): # numpy.array(1)
return val.item()
if isinstance(val, (list, tuple, numpy.ndarray)):
return [numpy_to_python(v) for v in val]
raise ValueError("Unknown value. Type: %s, repr: %s" % (type(val), repr(val)))
class ArgumentType(collections.namedtuple(
"ArgumentType", ["id", "name", "sizes", "fn", "values", "count"])):
"""Represents a single argument type.
Attributes:
id: The argument id. This is unique.
name: The name of the argument, also unique.
sizes: The max+1 of each of the dimensions this argument takes.
fn: The function to convert the list of integers into something more
meaningful to be set in the protos to send to the game.
values: An enum representing the values this argument type could hold. None
if this isn't an enum argument type.
count: Number of valid values. Only useful for unit_tags.
"""
__slots__ = ()
def __str__(self):
return "%s/%s %s" % (self.id, self.name, list(self.sizes))
def __reduce__(self):
return self.__class__, tuple(self)
@classmethod
def enum(cls, options, values):
"""Create an ArgumentType where you choose one of a set of known values."""
names, real = zip(*options)
del names # unused
def factory(i, name):
return cls(i, name, (len(real),), lambda a: real[a[0]], values, None)
return factory
@classmethod
def scalar(cls, value):
"""Create an ArgumentType with a single scalar in range(value)."""
return lambda i, name: cls(i, name, (value,), lambda a: a[0], None, None)
@classmethod
def point(cls): # No range because it's unknown at this time.
"""Create an ArgumentType that is represented by a point.Point."""
def factory(i, name):
return cls(i, name, (0, 0), lambda a: point.Point(*a).floor(), None, None)
return factory
@classmethod
def spec(cls, id_, name, sizes):
"""Create an ArgumentType to be used in ValidActions."""
return cls(id_, name, sizes, None, None, None)
@classmethod
def unit_tags(cls, count, size):
"""Create an ArgumentType with a list of unbounded ints."""
def clean(arg):
arg = numpy_to_python(arg)
if isinstance(arg, list) and len(arg) == 1 and isinstance(arg[0], list):
arg = arg[0] # Support [[list, of, tags]].
return arg[:count]
return lambda i, name: cls(i, name, (size,), clean, None, count)
class Arguments(collections.namedtuple("Arguments", [
"screen", "minimap", "screen2", "queued", "control_group_act",
"control_group_id", "select_point_act", "select_add", "select_unit_act",
"select_unit_id", "select_worker", "build_queue_id", "unload_id"])):
"""The full list of argument types.
Take a look at TYPES and FUNCTION_TYPES for more details.
Attributes:
screen: A point on the screen.
minimap: A point on the minimap.
screen2: The second point for a rectangle. This is needed so that no
function takes the same type twice.
queued: Whether the action should be done immediately or after all other
actions queued for this unit.
control_group_act: What to do with the control group.
control_group_id: Which control group to do it with.
select_point_act: What to do with the unit at the point.
select_add: Whether to add the unit to the selection or replace it.
select_unit_act: What to do when selecting a unit by id.
select_unit_id: Which unit to select by id.
select_worker: What to do when selecting a worker.
build_queue_id: Which build queue index to target.
unload_id: Which unit to target in a transport/nydus/command center.
"""
__slots__ = ()
@classmethod
def types(cls, **kwargs):
"""Create an Arguments of the possible Types."""
named = {name: factory(Arguments._fields.index(name), name)
for name, factory in six.iteritems(kwargs)}
return cls(**named)
def __reduce__(self):
return self.__class__, tuple(self)
class RawArguments(collections.namedtuple("RawArguments", [
"world", "queued", "unit_tags", "target_unit_tag"])):
"""The full list of argument types.
Take a look at TYPES and FUNCTION_TYPES for more details.
Attributes:
world: A point in world coordinates
queued: Whether the action should be done immediately or after all other
actions queued for this unit.
unit_tags: Which units should execute this action.
target_unit_tag: The target unit of this action.
"""
__slots__ = ()
@classmethod
def types(cls, **kwargs):
"""Create an Arguments of the possible Types."""
named = {name: factory(RawArguments._fields.index(name), name)
for name, factory in six.iteritems(kwargs)}
return cls(**named)
def __reduce__(self):
return self.__class__, tuple(self)
def _define_position_based_enum(name, options):
return enum.IntEnum(
name, {opt_name: i for i, (opt_name, _) in enumerate(options)})
QUEUED_OPTIONS = [
("now", False),
("queued", True),
]
Queued = _define_position_based_enum( # pylint: disable=invalid-name
"Queued", QUEUED_OPTIONS)
CONTROL_GROUP_ACT_OPTIONS = [
("recall", sc_ui.ActionControlGroup.Recall),
("set", sc_ui.ActionControlGroup.Set),
("append", sc_ui.ActionControlGroup.Append),
("set_and_steal", sc_ui.ActionControlGroup.SetAndSteal),
("append_and_steal", sc_ui.ActionControlGroup.AppendAndSteal),
]
ControlGroupAct = _define_position_based_enum( # pylint: disable=invalid-name
"ControlGroupAct", CONTROL_GROUP_ACT_OPTIONS)
SELECT_POINT_ACT_OPTIONS = [
("select", sc_spatial.ActionSpatialUnitSelectionPoint.Select),
("toggle", sc_spatial.ActionSpatialUnitSelectionPoint.Toggle),
("select_all_type", sc_spatial.ActionSpatialUnitSelectionPoint.AllType),
("add_all_type", sc_spatial.ActionSpatialUnitSelectionPoint.AddAllType),
]
SelectPointAct = _define_position_based_enum( # pylint: disable=invalid-name
"SelectPointAct", SELECT_POINT_ACT_OPTIONS)
SELECT_ADD_OPTIONS = [
("select", False),
("add", True),
]
SelectAdd = _define_position_based_enum( # pylint: disable=invalid-name
"SelectAdd", SELECT_ADD_OPTIONS)
SELECT_UNIT_ACT_OPTIONS = [
("select", sc_ui.ActionMultiPanel.SingleSelect),
("deselect", sc_ui.ActionMultiPanel.DeselectUnit),
("select_all_type", sc_ui.ActionMultiPanel.SelectAllOfType),
("deselect_all_type", sc_ui.ActionMultiPanel.DeselectAllOfType),
]
SelectUnitAct = _define_position_based_enum( # pylint: disable=invalid-name
"SelectUnitAct", SELECT_UNIT_ACT_OPTIONS)
SELECT_WORKER_OPTIONS = [
("select", sc_ui.ActionSelectIdleWorker.Set),
("add", sc_ui.ActionSelectIdleWorker.Add),
("select_all", sc_ui.ActionSelectIdleWorker.All),
("add_all", sc_ui.ActionSelectIdleWorker.AddAll),
]
SelectWorker = _define_position_based_enum( # pylint: disable=invalid-name
"SelectWorker", SELECT_WORKER_OPTIONS)
# The list of known types.
TYPES = Arguments.types(
screen=ArgumentType.point(),
minimap=ArgumentType.point(),
screen2=ArgumentType.point(),
queued=ArgumentType.enum(QUEUED_OPTIONS, Queued),
control_group_act=ArgumentType.enum(
CONTROL_GROUP_ACT_OPTIONS, ControlGroupAct),
control_group_id=ArgumentType.scalar(10),
select_point_act=ArgumentType.enum(
SELECT_POINT_ACT_OPTIONS, SelectPointAct),
select_add=ArgumentType.enum(SELECT_ADD_OPTIONS, SelectAdd),
select_unit_act=ArgumentType.enum(SELECT_UNIT_ACT_OPTIONS, SelectUnitAct),
select_unit_id=ArgumentType.scalar(500), # Depends on current selection.
select_worker=ArgumentType.enum(SELECT_WORKER_OPTIONS, SelectWorker),
build_queue_id=ArgumentType.scalar(10), # Depends on current build queue.
unload_id=ArgumentType.scalar(500), # Depends on the current loaded units.
)
RAW_TYPES = RawArguments.types(
world=ArgumentType.point(),
queued=ArgumentType.enum(QUEUED_OPTIONS, Queued),
unit_tags=ArgumentType.unit_tags(512, 512),
# target_unit_tag=ArgumentType.unit_tags(1, 512), # GG error
target_unit_tag=ArgumentType.scalar(512), # GG error
)
# Which argument types do each function need?
FUNCTION_TYPES = {
no_op: [],
move_camera: [TYPES.minimap],
select_point: [TYPES.select_point_act, TYPES.screen],
select_rect: [TYPES.select_add, TYPES.screen, TYPES.screen2],
select_unit: [TYPES.select_unit_act, TYPES.select_unit_id],
control_group: [TYPES.control_group_act, TYPES.control_group_id],
select_idle_worker: [TYPES.select_worker],
select_army: [TYPES.select_add],
select_warp_gates: [TYPES.select_add],
select_larva: [],
unload: [TYPES.unload_id],
build_queue: [TYPES.build_queue_id],
cmd_quick: [TYPES.queued],
cmd_screen: [TYPES.queued, TYPES.screen],
cmd_minimap: [TYPES.queued, TYPES.minimap],
autocast: [],
raw_no_op: [],
raw_cmd: [RAW_TYPES.queued, RAW_TYPES.unit_tags],
raw_cmd_pt: [RAW_TYPES.queued, RAW_TYPES.unit_tags, RAW_TYPES.world],
raw_cmd_unit: [RAW_TYPES.queued, RAW_TYPES.unit_tags,
RAW_TYPES.target_unit_tag],
raw_move_camera: [RAW_TYPES.world],
raw_autocast: [RAW_TYPES.unit_tags],
}
# Which ones need an ability?
ABILITY_FUNCTIONS = {cmd_quick, cmd_screen, cmd_minimap, autocast}
RAW_ABILITY_FUNCTIONS = {raw_cmd, raw_cmd_pt, raw_cmd_unit, raw_autocast}
# Which ones require a point?
POINT_REQUIRED_FUNCS = {
False: {cmd_quick, autocast},
True: {cmd_screen, cmd_minimap, autocast}}
always = lambda _: True
class Function(collections.namedtuple(
"Function", ["id", "name", "ability_id", "general_id", "function_type",
"args", "avail_fn", "raw"])):
"""Represents a function action.
Attributes:
id: The function id, which is what the agent will use.
name: The name of the function. Should be unique.
ability_id: The ability id to pass to sc2.
general_id: 0 for normal abilities, and the ability_id of another ability if
it can be represented by a more general action.
function_type: One of the functions in FUNCTION_TYPES for how to construct
the sc2 action proto out of python types.
args: A list of the types of args passed to function_type.
avail_fn: For non-abilities, this function returns whether the function is
valid.
raw: Whether the function is raw or not.
"""
__slots__ = ()
@classmethod
def ui_func(cls, id_, name, function_type, avail_fn=always):
"""Define a function representing a ui action."""
return cls(id_, name, 0, 0, function_type, FUNCTION_TYPES[function_type],
avail_fn, False)
@classmethod
def ability(cls, id_, name, function_type, ability_id, general_id=0):
"""Define a function represented as a game ability."""
assert function_type in ABILITY_FUNCTIONS
return cls(id_, name, ability_id, general_id, function_type,
FUNCTION_TYPES[function_type], None, False)
@classmethod
def raw_ability(cls, id_, name, function_type, ability_id, general_id=0,
avail_fn=always):
"""Define a function represented as a game ability."""
assert function_type in RAW_ABILITY_FUNCTIONS
return cls(id_, name, ability_id, general_id, function_type,
FUNCTION_TYPES[function_type], avail_fn, True)
@classmethod
def raw_ui_func(cls, id_, name, function_type, avail_fn=always):
"""Define a function representing a ui action."""
return cls(id_, name, 0, 0, function_type, FUNCTION_TYPES[function_type],
avail_fn, True)
@classmethod
def spec(cls, id_, name, args):
"""Create a Function to be used in ValidActions."""
return cls(id_, name, None, None, None, args, None, False)
def __hash__(self): # So it can go in a set().
return self.id
def __str__(self):
return self.str()
def __call__(self, *args):
"""A convenient way to create a FunctionCall from this Function."""
return FunctionCall.init_with_validation(self.id, args, raw=self.raw)
def __reduce__(self):
return self.__class__, tuple(self)
def str(self, space=False):
"""String version. Set space=True to line them all up nicely."""
return "%s/%s (%s)" % (str(int(self.id)).rjust(space and 4),
self.name.ljust(space and 50),
"; ".join(str(a) for a in self.args))
class Functions(object):
"""Represents the full set of functions.
Can't use namedtuple since python3 has a limit of 255 function arguments, so
build something similar.
"""
def __init__(self, functions):
functions = sorted(functions, key=lambda f: f.id)
self._func_list = functions
self._func_dict = {f.name: f for f in functions}
if len(self._func_dict) != len(self._func_list):
raise ValueError("Function names must be unique.")
def __getattr__(self, name):
return self._func_dict[name]
def __getitem__(self, key):
if isinstance(key, numbers.Integral):
return self._func_list[key]
return self._func_dict[key]
def __getstate__(self):
# Support pickling, which otherwise conflicts with __getattr__.
return self._func_list
def __setstate__(self, functions):
# Support pickling, which otherwise conflicts with __getattr__.
self.__init__(functions)
def __iter__(self):
return iter(self._func_list)
def __len__(self):
return len(self._func_list)
def __eq__(self, other):
return self._func_list == other._func_list # pylint: disable=protected-access
# The semantic meaning of these actions can mainly be found by searching:
# http://liquipedia.net/starcraft2/ or http://starcraft.wikia.com/ .
# pylint: disable=line-too-long
_FUNCTIONS = [
Function.ui_func(0, "no_op", no_op),
Function.ui_func(1, "move_camera", move_camera),
Function.ui_func(2, "select_point", select_point),
Function.ui_func(3, "select_rect", select_rect),
Function.ui_func(4, "select_control_group", control_group),
Function.ui_func(5, "select_unit", select_unit,
lambda obs: obs.ui_data.HasField("multi")),
Function.ui_func(6, "select_idle_worker", select_idle_worker,
lambda obs: obs.player_common.idle_worker_count > 0),
Function.ui_func(7, "select_army", select_army,
lambda obs: obs.player_common.army_count > 0),
Function.ui_func(8, "select_warp_gates", select_warp_gates,
lambda obs: obs.player_common.warp_gate_count > 0),
Function.ui_func(9, "select_larva", select_larva,
lambda obs: obs.player_common.larva_count > 0),
Function.ui_func(10, "unload", unload,
lambda obs: obs.ui_data.HasField("cargo")),
Function.ui_func(11, "build_queue", build_queue,
lambda obs: obs.ui_data.HasField("production")),
# Everything below here is generated with gen_actions.py
Function.ability(12, "Attack_screen", cmd_screen, 3674),
Function.ability(13, "Attack_minimap", cmd_minimap, 3674),
Function.ability(14, "Attack_Attack_screen", cmd_screen, 23, 3674),
Function.ability(15, "Attack_Attack_minimap", cmd_minimap, 23, 3674),
Function.ability(16, "Attack_AttackBuilding_screen", cmd_screen, 2048, 3674),
Function.ability(17, "Attack_AttackBuilding_minimap", cmd_minimap, 2048, 3674),
Function.ability(555, "Attack_Battlecruiser_screen", cmd_screen, 3771, 3674),
Function.ability(556, "Attack_Battlecruiser_minimap", cmd_minimap, 3771, 3674),
Function.ability(18, "Attack_Redirect_screen", cmd_screen, 1682, 3674),
Function.ability(19, "Scan_Move_screen", cmd_screen, 19, 3674),
Function.ability(20, "Scan_Move_minimap", cmd_minimap, 19, 3674),
Function.ability(21, "Behavior_BuildingAttackOff_quick", cmd_quick, 2082),
Function.ability(22, "Behavior_BuildingAttackOn_quick", cmd_quick, 2081),
Function.ability(23, "Behavior_CloakOff_quick", cmd_quick, 3677),
Function.ability(24, "Behavior_CloakOff_Banshee_quick", cmd_quick, 393, 3677),
Function.ability(25, "Behavior_CloakOff_Ghost_quick", cmd_quick, 383, 3677),
Function.ability(26, "Behavior_CloakOn_quick", cmd_quick, 3676),
Function.ability(27, "Behavior_CloakOn_Banshee_quick", cmd_quick, 392, 3676),
Function.ability(28, "Behavior_CloakOn_Ghost_quick", cmd_quick, 382, 3676),
Function.ability(29, "Behavior_GenerateCreepOff_quick", cmd_quick, 1693),
Function.ability(30, "Behavior_GenerateCreepOn_quick", cmd_quick, 1692),
Function.ability(31, "Behavior_HoldFireOff_quick", cmd_quick, 3689),
Function.ability(32, "Behavior_HoldFireOff_Ghost_quick", cmd_quick, 38, 3689),
Function.ability(33, "Behavior_HoldFireOff_Lurker_quick", cmd_quick, 2552, 3689),
Function.ability(34, "Behavior_HoldFireOn_quick", cmd_quick, 3688),
Function.ability(35, "Behavior_HoldFireOn_Ghost_quick", cmd_quick, 36, 3688),
Function.ability(36, "Behavior_HoldFireOn_Lurker_quick", cmd_quick, 2550, 3688),
Function.ability(37, "Behavior_PulsarBeamOff_quick", cmd_quick, 2376),
Function.ability(38, "Behavior_PulsarBeamOn_quick", cmd_quick, 2375),
Function.ability(39, "Build_Armory_screen", cmd_screen, 331),
Function.ability(40, "Build_Assimilator_screen", cmd_screen, 882),
Function.ability(41, "Build_BanelingNest_screen", cmd_screen, 1162),
Function.ability(42, "Build_Barracks_screen", cmd_screen, 321),
Function.ability(43, "Build_Bunker_screen", cmd_screen, 324),
Function.ability(44, "Build_CommandCenter_screen", cmd_screen, 318),
Function.ability(45, "Build_CreepTumor_screen", cmd_screen, 3691),
Function.ability(46, "Build_CreepTumor_Queen_screen", cmd_screen, 1694, 3691),
Function.ability(47, "Build_CreepTumor_Tumor_screen", cmd_screen, 1733, 3691),
Function.ability(48, "Build_CyberneticsCore_screen", cmd_screen, 894),
Function.ability(49, "Build_DarkShrine_screen", cmd_screen, 891),
Function.ability(50, "Build_EngineeringBay_screen", cmd_screen, 322),
Function.ability(51, "Build_EvolutionChamber_screen", cmd_screen, 1156),
Function.ability(52, "Build_Extractor_screen", cmd_screen, 1154),
Function.ability(53, "Build_Factory_screen", cmd_screen, 328),
Function.ability(54, "Build_FleetBeacon_screen", cmd_screen, 885),
Function.ability(55, "Build_Forge_screen", cmd_screen, 884),
Function.ability(56, "Build_FusionCore_screen", cmd_screen, 333),
Function.ability(57, "Build_Gateway_screen", cmd_screen, 883),
Function.ability(58, "Build_GhostAcademy_screen", cmd_screen, 327),
Function.ability(59, "Build_Hatchery_screen", cmd_screen, 1152),
Function.ability(60, "Build_HydraliskDen_screen", cmd_screen, 1157),
Function.ability(61, "Build_InfestationPit_screen", cmd_screen, 1160),
Function.ability(62, "Build_Interceptors_quick", cmd_quick, 1042),
Function.ability(63, "Build_Interceptors_autocast", autocast, 1042),
Function.ability(524, "Build_LurkerDen_screen", cmd_screen, 1163),
Function.ability(64, "Build_MissileTurret_screen", cmd_screen, 323),
Function.ability(65, "Build_Nexus_screen", cmd_screen, 880),
Function.ability(66, "Build_Nuke_quick", cmd_quick, 710),
Function.ability(67, "Build_NydusNetwork_screen", cmd_screen, 1161),
Function.ability(68, "Build_NydusWorm_screen", cmd_screen, 1768),
Function.ability(69, "Build_PhotonCannon_screen", cmd_screen, 887),
Function.ability(70, "Build_Pylon_screen", cmd_screen, 881),
Function.ability(71, "Build_Reactor_quick", cmd_quick, 3683),
Function.ability(72, "Build_Reactor_screen", cmd_screen, 3683),
Function.ability(73, "Build_Reactor_Barracks_quick", cmd_quick, 422, 3683),
Function.ability(74, "Build_Reactor_Barracks_screen", cmd_screen, 422, 3683),
Function.ability(75, "Build_Reactor_Factory_quick", cmd_quick, 455, 3683),
Function.ability(76, "Build_Reactor_Factory_screen", cmd_screen, 455, 3683),
Function.ability(77, "Build_Reactor_Starport_quick", cmd_quick, 488, 3683),
Function.ability(78, "Build_Reactor_Starport_screen", cmd_screen, 488, 3683),
Function.ability(79, "Build_Refinery_screen", cmd_screen, 320),
Function.ability(80, "Build_RoachWarren_screen", cmd_screen, 1165),
Function.ability(81, "Build_RoboticsBay_screen", cmd_screen, 892),
Function.ability(82, "Build_RoboticsFacility_screen", cmd_screen, 893),
Function.ability(83, "Build_SensorTower_screen", cmd_screen, 326),
Function.ability(525, "Build_ShieldBattery_screen", cmd_screen, 895),
Function.ability(84, "Build_SpawningPool_screen", cmd_screen, 1155),
Function.ability(85, "Build_SpineCrawler_screen", cmd_screen, 1166),
Function.ability(86, "Build_Spire_screen", cmd_screen, 1158),
Function.ability(87, "Build_SporeCrawler_screen", cmd_screen, 1167),
Function.ability(88, "Build_Stargate_screen", cmd_screen, 889),
Function.ability(89, "Build_Starport_screen", cmd_screen, 329),
Function.ability(90, "Build_StasisTrap_screen", cmd_screen, 2505),
Function.ability(91, "Build_SupplyDepot_screen", cmd_screen, 319),
Function.ability(92, "Build_TechLab_quick", cmd_quick, 3682),
Function.ability(93, "Build_TechLab_screen", cmd_screen, 3682),
Function.ability(94, "Build_TechLab_Barracks_quick", cmd_quick, 421, 3682),
Function.ability(95, "Build_TechLab_Barracks_screen", cmd_screen, 421, 3682),
Function.ability(96, "Build_TechLab_Factory_quick", cmd_quick, 454, 3682),
Function.ability(97, "Build_TechLab_Factory_screen", cmd_screen, 454, 3682),
Function.ability(98, "Build_TechLab_Starport_quick", cmd_quick, 487, 3682),
Function.ability(99, "Build_TechLab_Starport_screen", cmd_screen, 487, 3682),
Function.ability(100, "Build_TemplarArchive_screen", cmd_screen, 890),
Function.ability(101, "Build_TwilightCouncil_screen", cmd_screen, 886),
Function.ability(102, "Build_UltraliskCavern_screen", cmd_screen, 1159),
Function.ability(103, "BurrowDown_quick", cmd_quick, 3661),
Function.ability(104, "BurrowDown_Baneling_quick", cmd_quick, 1374, 3661),
Function.ability(105, "BurrowDown_Drone_quick", cmd_quick, 1378, 3661),
Function.ability(106, "BurrowDown_Hydralisk_quick", cmd_quick, 1382, 3661),
Function.ability(107, "BurrowDown_Infestor_quick", cmd_quick, 1444, 3661),
Function.ability(108, "BurrowDown_InfestorTerran_quick", cmd_quick, 1394, 3661),
Function.ability(109, "BurrowDown_Lurker_quick", cmd_quick, 2108, 3661),
Function.ability(110, "BurrowDown_Queen_quick", cmd_quick, 1433, 3661),
Function.ability(111, "BurrowDown_Ravager_quick", cmd_quick, 2340, 3661),
Function.ability(112, "BurrowDown_Roach_quick", cmd_quick, 1386, 3661),
Function.ability(113, "BurrowDown_SwarmHost_quick", cmd_quick, 2014, 3661),
Function.ability(114, "BurrowDown_Ultralisk_quick", cmd_quick, 1512, 3661),
Function.ability(115, "BurrowDown_WidowMine_quick", cmd_quick, 2095, 3661),
Function.ability(116, "BurrowDown_Zergling_quick", cmd_quick, 1390, 3661),
Function.ability(117, "BurrowUp_quick", cmd_quick, 3662),
Function.ability(118, "BurrowUp_autocast", autocast, 3662),
Function.ability(119, "BurrowUp_Baneling_quick", cmd_quick, 1376, 3662),
Function.ability(120, "BurrowUp_Baneling_autocast", autocast, 1376, 3662),
Function.ability(121, "BurrowUp_Drone_quick", cmd_quick, 1380, 3662),
Function.ability(122, "BurrowUp_Hydralisk_quick", cmd_quick, 1384, 3662),
Function.ability(123, "BurrowUp_Hydralisk_autocast", autocast, 1384, 3662),
Function.ability(124, "BurrowUp_Infestor_quick", cmd_quick, 1446, 3662),
Function.ability(125, "BurrowUp_InfestorTerran_quick", cmd_quick, 1396, 3662),
Function.ability(126, "BurrowUp_InfestorTerran_autocast", autocast, 1396, 3662),
Function.ability(127, "BurrowUp_Lurker_quick", cmd_quick, 2110, 3662),
Function.ability(128, "BurrowUp_Queen_quick", cmd_quick, 1435, 3662),
Function.ability(129, "BurrowUp_Queen_autocast", autocast, 1435, 3662),
Function.ability(130, "BurrowUp_Ravager_quick", cmd_quick, 2342, 3662),
Function.ability(131, "BurrowUp_Ravager_autocast", autocast, 2342, 3662),
Function.ability(132, "BurrowUp_Roach_quick", cmd_quick, 1388, 3662),
Function.ability(133, "BurrowUp_Roach_autocast", autocast, 1388, 3662),
Function.ability(134, "BurrowUp_SwarmHost_quick", cmd_quick, 2016, 3662),
Function.ability(135, "BurrowUp_Ultralisk_quick", cmd_quick, 1514, 3662),
Function.ability(136, "BurrowUp_Ultralisk_autocast", autocast, 1514, 3662),
Function.ability(137, "BurrowUp_WidowMine_quick", cmd_quick, 2097, 3662),
Function.ability(138, "BurrowUp_Zergling_quick", cmd_quick, 1392, 3662),
Function.ability(139, "BurrowUp_Zergling_autocast", autocast, 1392, 3662),
Function.ability(140, "Cancel_quick", cmd_quick, 3659),
Function.ability(141, "Cancel_AdeptPhaseShift_quick", cmd_quick, 2594, 3659),
Function.ability(142, "Cancel_AdeptShadePhaseShift_quick", cmd_quick, 2596, 3659),
Function.ability(143, "Cancel_BarracksAddOn_quick", cmd_quick, 451, 3659),
Function.ability(144, "Cancel_BuildInProgress_quick", cmd_quick, 314, 3659),
Function.ability(145, "Cancel_CreepTumor_quick", cmd_quick, 1763, 3659),
Function.ability(146, "Cancel_FactoryAddOn_quick", cmd_quick, 484, 3659),
Function.ability(147, "Cancel_GravitonBeam_quick", cmd_quick, 174, 3659),
Function.ability(148, "Cancel_LockOn_quick", cmd_quick, 2354, 3659),
Function.ability(149, "Cancel_MorphBroodlord_quick", cmd_quick, 1373, 3659),
Function.ability(150, "Cancel_MorphGreaterSpire_quick", cmd_quick, 1221, 3659),
Function.ability(151, "Cancel_MorphHive_quick", cmd_quick, 1219, 3659),
Function.ability(152, "Cancel_MorphLair_quick", cmd_quick, 1217, 3659),
Function.ability(153, "Cancel_MorphLurker_quick", cmd_quick, 2333, 3659),
Function.ability(154, "Cancel_MorphLurkerDen_quick", cmd_quick, 2113, 3659),
Function.ability(155, "Cancel_MorphMothership_quick", cmd_quick, 1848, 3659),
Function.ability(156, "Cancel_MorphOrbital_quick", cmd_quick, 1517, 3659),
Function.ability(157, "Cancel_MorphOverlordTransport_quick", cmd_quick, 2709, 3659),
Function.ability(158, "Cancel_MorphOverseer_quick", cmd_quick, 1449, 3659),
Function.ability(159, "Cancel_MorphPlanetaryFortress_quick", cmd_quick, 1451, 3659),
Function.ability(160, "Cancel_MorphRavager_quick", cmd_quick, 2331, 3659),
Function.ability(161, "Cancel_MorphThorExplosiveMode_quick", cmd_quick, 2365, 3659),
Function.ability(162, "Cancel_NeuralParasite_quick", cmd_quick, 250, 3659),
Function.ability(163, "Cancel_Nuke_quick", cmd_quick, 1623, 3659),
Function.ability(164, "Cancel_SpineCrawlerRoot_quick", cmd_quick, 1730, 3659),
Function.ability(165, "Cancel_SporeCrawlerRoot_quick", cmd_quick, 1732, 3659),
Function.ability(166, "Cancel_StarportAddOn_quick", cmd_quick, 517, 3659),
Function.ability(167, "Cancel_StasisTrap_quick", cmd_quick, 2535, 3659),
Function.ability(546, "Cancel_VoidRayPrismaticAlignment_quick", cmd_quick, 3707, 3659),
Function.ability(168, "Cancel_Last_quick", cmd_quick, 3671),
Function.ability(169, "Cancel_HangarQueue5_quick", cmd_quick, 1038, 3671),
Function.ability(170, "Cancel_Queue1_quick", cmd_quick, 304, 3671),
Function.ability(171, "Cancel_Queue5_quick", cmd_quick, 306, 3671),
Function.ability(172, "Cancel_QueueAddOn_quick", cmd_quick, 312, 3671),
Function.ability(173, "Cancel_QueueCancelToSelection_quick", cmd_quick, 308, 3671),
Function.ability(174, "Cancel_QueuePassive_quick", cmd_quick, 1831, 3671),
Function.ability(175, "Cancel_QueuePassiveCancelToSelection_quick", cmd_quick, 1833, 3671),
Function.ability(176, "Effect_Abduct_screen", cmd_screen, 2067),
Function.ability(177, "Effect_AdeptPhaseShift_screen", cmd_screen, 2544),
Function.ability(547, "Effect_AdeptPhaseShift_minimap", cmd_minimap, 2544),
Function.ability(526, "Effect_AntiArmorMissile_screen", cmd_screen, 3753),
Function.ability(178, "Effect_AutoTurret_screen", cmd_screen, 1764),
Function.ability(179, "Effect_BlindingCloud_screen", cmd_screen, 2063),
Function.ability(180, "Effect_Blink_screen", cmd_screen, 3687),
Function.ability(543, "Effect_Blink_minimap", cmd_minimap, 3687),
Function.ability(181, "Effect_Blink_Stalker_screen", cmd_screen, 1442, 3687),
Function.ability(544, "Effect_Blink_Stalker_minimap", cmd_minimap, 1442, 3687),
Function.ability(182, "Effect_ShadowStride_screen", cmd_screen, 2700, 3687),
Function.ability(545, "Effect_ShadowStride_minimap", cmd_minimap, 2700, 3687),
Function.ability(183, "Effect_CalldownMULE_screen", cmd_screen, 171),
Function.ability(184, "Effect_CausticSpray_screen", cmd_screen, 2324),
Function.ability(185, "Effect_Charge_screen", cmd_screen, 1819),
Function.ability(186, "Effect_Charge_autocast", autocast, 1819),
Function.ability(187, "Effect_ChronoBoost_screen", cmd_screen, 261),
Function.ability(527, "Effect_ChronoBoostEnergyCost_screen", cmd_screen, 3755),
Function.ability(188, "Effect_Contaminate_screen", cmd_screen, 1825),
Function.ability(189, "Effect_CorrosiveBile_screen", cmd_screen, 2338),
Function.ability(190, "Effect_EMP_screen", cmd_screen, 1628),
Function.ability(191, "Effect_Explode_quick", cmd_quick, 42),
Function.ability(192, "Effect_Feedback_screen", cmd_screen, 140),
Function.ability(193, "Effect_ForceField_screen", cmd_screen, 1526),
Function.ability(194, "Effect_FungalGrowth_screen", cmd_screen, 74),
Function.ability(195, "Effect_GhostSnipe_screen", cmd_screen, 2714),
Function.ability(196, "Effect_GravitonBeam_screen", cmd_screen, 173),
Function.ability(197, "Effect_GuardianShield_quick", cmd_quick, 76),
Function.ability(198, "Effect_Heal_screen", cmd_screen, 386),
Function.ability(199, "Effect_Heal_autocast", autocast, 386),
Function.ability(200, "Effect_HunterSeekerMissile_screen", cmd_screen, 169),
Function.ability(201, "Effect_ImmortalBarrier_quick", cmd_quick, 2328),
Function.ability(202, "Effect_ImmortalBarrier_autocast", autocast, 2328),
Function.ability(203, "Effect_InfestedTerrans_screen", cmd_screen, 247),
Function.ability(204, "Effect_InjectLarva_screen", cmd_screen, 251),
Function.ability(528, "Effect_InterferenceMatrix_screen", cmd_screen, 3747),
Function.ability(205, "Effect_KD8Charge_screen", cmd_screen, 2588),
Function.ability(206, "Effect_LockOn_screen", cmd_screen, 2350),
Function.ability(557, "Effect_LockOn_autocast", autocast, 2350),
Function.ability(207, "Effect_LocustSwoop_screen", cmd_screen, 2387),
Function.ability(208, "Effect_MassRecall_screen", cmd_screen, 3686),
Function.ability(209, "Effect_MassRecall_Mothership_screen", cmd_screen, 2368, 3686),
Function.ability(210, "Effect_MassRecall_MothershipCore_screen", cmd_screen, 1974, 3686),
Function.ability(529, "Effect_MassRecall_Nexus_screen", cmd_screen, 3757, 3686),
Function.ability(548, "Effect_MassRecall_StrategicRecall_screen", cmd_screen, 142, 3686),
Function.ability(211, "Effect_MedivacIgniteAfterburners_quick", cmd_quick, 2116),
Function.ability(212, "Effect_NeuralParasite_screen", cmd_screen, 249),
Function.ability(213, "Effect_NukeCalldown_screen", cmd_screen, 1622),
Function.ability(214, "Effect_OracleRevelation_screen", cmd_screen, 2146),
Function.ability(215, "Effect_ParasiticBomb_screen", cmd_screen, 2542),
Function.ability(216, "Effect_PhotonOvercharge_screen", cmd_screen, 2162),
Function.ability(217, "Effect_PointDefenseDrone_screen", cmd_screen, 144),
Function.ability(218, "Effect_PsiStorm_screen", cmd_screen, 1036),
Function.ability(219, "Effect_PurificationNova_screen", cmd_screen, 2346),
Function.ability(220, "Effect_Repair_screen", cmd_screen, 3685),
Function.ability(221, "Effect_Repair_autocast", autocast, 3685),
Function.ability(222, "Effect_Repair_Mule_screen", cmd_screen, 78, 3685),
Function.ability(223, "Effect_Repair_Mule_autocast", autocast, 78, 3685),
Function.ability(530, "Effect_Repair_RepairDrone_screen", cmd_screen, 3751, 3685),
Function.ability(531, "Effect_Repair_RepairDrone_autocast", autocast, 3751, 3685),
Function.ability(224, "Effect_Repair_SCV_screen", cmd_screen, 316, 3685),
Function.ability(225, "Effect_Repair_SCV_autocast", autocast, 316, 3685),
Function.ability(532, "Effect_RepairDrone_screen", cmd_screen, 3749),
Function.ability(533, "Effect_Restore_screen", cmd_screen, 3765),
Function.ability(534, "Effect_Restore_autocast", autocast, 3765),
Function.ability(226, "Effect_Salvage_quick", cmd_quick, 32),
Function.ability(227, "Effect_Scan_screen", cmd_screen, 399),
Function.ability(542, "Effect_Scan_minimap", cmd_minimap, 399),
Function.ability(228, "Effect_SpawnChangeling_quick", cmd_quick, 181),
Function.ability(229, "Effect_SpawnLocusts_screen", cmd_screen, 2704),
Function.ability(230, "Effect_Spray_screen", cmd_screen, 3684),
Function.ability(231, "Effect_Spray_Protoss_screen", cmd_screen, 30, 3684),
Function.ability(232, "Effect_Spray_Terran_screen", cmd_screen, 26, 3684),
Function.ability(233, "Effect_Spray_Zerg_screen", cmd_screen, 28, 3684),
Function.ability(549, "Effect_Spray_minimap", cmd_minimap, 3684),
Function.ability(550, "Effect_Spray_Protoss_minimap", cmd_minimap, 30, 3684),
Function.ability(551, "Effect_Spray_Terran_minimap", cmd_minimap, 26, 3684),
Function.ability(552, "Effect_Spray_Zerg_minimap", cmd_minimap, 28, 3684),
Function.ability(234, "Effect_Stim_quick", cmd_quick, 3675),
Function.ability(235, "Effect_Stim_Marauder_quick", cmd_quick, 253, 3675),
Function.ability(236, "Effect_Stim_Marauder_Redirect_quick", cmd_quick, 1684, 3675),
Function.ability(237, "Effect_Stim_Marine_quick", cmd_quick, 380, 3675),
Function.ability(238, "Effect_Stim_Marine_Redirect_quick", cmd_quick, 1683, 3675),
Function.ability(239, "Effect_SupplyDrop_screen", cmd_screen, 255),
Function.ability(240, "Effect_TacticalJump_screen", cmd_screen, 2358),
Function.ability(553, "Effect_TacticalJump_minimap", cmd_minimap, 2358),
Function.ability(241, "Effect_TimeWarp_screen", cmd_screen, 2244),
Function.ability(242, "Effect_Transfusion_screen", cmd_screen, 1664),
Function.ability(243, "Effect_ViperConsume_screen", cmd_screen, 2073),
Function.ability(244, "Effect_VoidRayPrismaticAlignment_quick", cmd_quick, 2393),
Function.ability(245, "Effect_WidowMineAttack_screen", cmd_screen, 2099),
Function.ability(246, "Effect_WidowMineAttack_autocast", autocast, 2099),
Function.ability(247, "Effect_YamatoGun_screen", cmd_screen, 401),
Function.ability(248, "Hallucination_Adept_quick", cmd_quick, 2391),
Function.ability(249, "Hallucination_Archon_quick", cmd_quick, 146),
Function.ability(250, "Hallucination_Colossus_quick", cmd_quick, 148),
Function.ability(251, "Hallucination_Disruptor_quick", cmd_quick, 2389),
Function.ability(252, "Hallucination_HighTemplar_quick", cmd_quick, 150),
Function.ability(253, "Hallucination_Immortal_quick", cmd_quick, 152),
Function.ability(254, "Hallucination_Oracle_quick", cmd_quick, 2114),
Function.ability(255, "Hallucination_Phoenix_quick", cmd_quick, 154),
Function.ability(256, "Hallucination_Probe_quick", cmd_quick, 156),
Function.ability(257, "Hallucination_Stalker_quick", cmd_quick, 158),
Function.ability(258, "Hallucination_VoidRay_quick", cmd_quick, 160),
Function.ability(259, "Hallucination_WarpPrism_quick", cmd_quick, 162),
Function.ability(260, "Hallucination_Zealot_quick", cmd_quick, 164),
Function.ability(261, "Halt_quick", cmd_quick, 3660),
Function.ability(262, "Halt_Building_quick", cmd_quick, 315, 3660),
Function.ability(263, "Halt_TerranBuild_quick", cmd_quick, 348, 3660),
Function.ability(264, "Harvest_Gather_screen", cmd_screen, 3666),
Function.ability(265, "Harvest_Gather_Drone_screen", cmd_screen, 1183, 3666),
Function.ability(266, "Harvest_Gather_Mule_screen", cmd_screen, 166, 3666),
Function.ability(267, "Harvest_Gather_Probe_screen", cmd_screen, 298, 3666),
Function.ability(268, "Harvest_Gather_SCV_screen", cmd_screen, 295, 3666),
Function.ability(269, "Harvest_Return_quick", cmd_quick, 3667),
Function.ability(270, "Harvest_Return_Drone_quick", cmd_quick, 1184, 3667),
Function.ability(271, "Harvest_Return_Mule_quick", cmd_quick, 167, 3667),
Function.ability(272, "Harvest_Return_Probe_quick", cmd_quick, 299, 3667),
Function.ability(273, "Harvest_Return_SCV_quick", cmd_quick, 296, 3667),
Function.ability(274, "HoldPosition_quick", cmd_quick, 3793),
Function.ability(558, "HoldPosition_Battlecruiser_quick", cmd_quick, 3778, 3793),
Function.ability(559, "HoldPosition_Hold_quick", cmd_quick, 18, 3793),
Function.ability(275, "Land_screen", cmd_screen, 3678),
Function.ability(276, "Land_Barracks_screen", cmd_screen, 554, 3678),
Function.ability(277, "Land_CommandCenter_screen", cmd_screen, 419, 3678),
Function.ability(278, "Land_Factory_screen", cmd_screen, 520, 3678),
Function.ability(279, "Land_OrbitalCommand_screen", cmd_screen, 1524, 3678),
Function.ability(280, "Land_Starport_screen", cmd_screen, 522, 3678),
Function.ability(281, "Lift_quick", cmd_quick, 3679),
Function.ability(282, "Lift_Barracks_quick", cmd_quick, 452, 3679),
Function.ability(283, "Lift_CommandCenter_quick", cmd_quick, 417, 3679),
Function.ability(284, "Lift_Factory_quick", cmd_quick, 485, 3679),
Function.ability(285, "Lift_OrbitalCommand_quick", cmd_quick, 1522, 3679),
Function.ability(286, "Lift_Starport_quick", cmd_quick, 518, 3679),
Function.ability(287, "Load_screen", cmd_screen, 3668),
Function.ability(288, "Load_Bunker_screen", cmd_screen, 407, 3668),
Function.ability(289, "Load_Medivac_screen", cmd_screen, 394, 3668),
Function.ability(290, "Load_NydusNetwork_screen", cmd_screen, 1437, 3668),
Function.ability(291, "Load_NydusWorm_screen", cmd_screen, 2370, 3668),
Function.ability(292, "Load_Overlord_screen", cmd_screen, 1406, 3668),
Function.ability(293, "Load_WarpPrism_screen", cmd_screen, 911, 3668),
Function.ability(294, "LoadAll_quick", cmd_quick, 3663),
Function.ability(295, "LoadAll_CommandCenter_quick", cmd_quick, 416, 3663),
Function.ability(296, "Morph_Archon_quick", cmd_quick, 1766),
Function.ability(297, "Morph_BroodLord_quick", cmd_quick, 1372),
Function.ability(298, "Morph_Gateway_quick", cmd_quick, 1520),
Function.ability(299, "Morph_GreaterSpire_quick", cmd_quick, 1220),
Function.ability(300, "Morph_Hellbat_quick", cmd_quick, 1998),
Function.ability(301, "Morph_Hellion_quick", cmd_quick, 1978),
Function.ability(302, "Morph_Hive_quick", cmd_quick, 1218),
Function.ability(303, "Morph_Lair_quick", cmd_quick, 1216),
Function.ability(304, "Morph_LiberatorAAMode_quick", cmd_quick, 2560),
Function.ability(305, "Morph_LiberatorAGMode_screen", cmd_screen, 2558),
Function.ability(554, "Morph_LiberatorAGMode_minimap", cmd_minimap, 2558),
Function.ability(306, "Morph_Lurker_quick", cmd_quick, 2332),
Function.ability(307, "Morph_LurkerDen_quick", cmd_quick, 2112),
Function.ability(308, "Morph_Mothership_quick", cmd_quick, 1847),
Function.ability(535, "Morph_ObserverMode_quick", cmd_quick, 3739),
Function.ability(309, "Morph_OrbitalCommand_quick", cmd_quick, 1516),
Function.ability(310, "Morph_OverlordTransport_quick", cmd_quick, 2708),
Function.ability(311, "Morph_Overseer_quick", cmd_quick, 1448),
Function.ability(536, "Morph_OverseerMode_quick", cmd_quick, 3745),
Function.ability(537, "Morph_OversightMode_quick", cmd_quick, 3743),
Function.ability(312, "Morph_PlanetaryFortress_quick", cmd_quick, 1450),
Function.ability(313, "Morph_Ravager_quick", cmd_quick, 2330),
Function.ability(314, "Morph_Root_screen", cmd_screen, 3680),
Function.ability(315, "Morph_SpineCrawlerRoot_screen", cmd_screen, 1729, 3680),
Function.ability(316, "Morph_SporeCrawlerRoot_screen", cmd_screen, 1731, 3680),
Function.ability(317, "Morph_SiegeMode_quick", cmd_quick, 388),
Function.ability(318, "Morph_SupplyDepot_Lower_quick", cmd_quick, 556),
Function.ability(319, "Morph_SupplyDepot_Raise_quick", cmd_quick, 558),
Function.ability(538, "Morph_SurveillanceMode_quick", cmd_quick, 3741),
Function.ability(320, "Morph_ThorExplosiveMode_quick", cmd_quick, 2364),
Function.ability(321, "Morph_ThorHighImpactMode_quick", cmd_quick, 2362),
Function.ability(322, "Morph_Unsiege_quick", cmd_quick, 390),
Function.ability(323, "Morph_Uproot_quick", cmd_quick, 3681),
Function.ability(324, "Morph_SpineCrawlerUproot_quick", cmd_quick, 1725, 3681),
Function.ability(325, "Morph_SporeCrawlerUproot_quick", cmd_quick, 1727, 3681),
Function.ability(326, "Morph_VikingAssaultMode_quick", cmd_quick, 403),
Function.ability(327, "Morph_VikingFighterMode_quick", cmd_quick, 405),
Function.ability(328, "Morph_WarpGate_quick", cmd_quick, 1518),
Function.ability(560, "Morph_WarpGate_autocast", autocast, 1518),
Function.ability(329, "Morph_WarpPrismPhasingMode_quick", cmd_quick, 1528),
Function.ability(330, "Morph_WarpPrismTransportMode_quick", cmd_quick, 1530),
Function.ability(331, "Move_screen", cmd_screen, 3794),
Function.ability(332, "Move_minimap", cmd_minimap, 3794),
Function.ability(561, "Move_Battlecruiser_screen", cmd_screen, 3776, 3794),
Function.ability(562, "Move_Battlecruiser_minimap", cmd_minimap, 3776, 3794),
Function.ability(563, "Move_Move_screen", cmd_screen, 16, 3794),
Function.ability(564, "Move_Move_minimap", cmd_minimap, 16, 3794),
Function.ability(333, "Patrol_screen", cmd_screen, 3795),
Function.ability(334, "Patrol_minimap", cmd_minimap, 3795),
Function.ability(565, "Patrol_Battlecruiser_screen", cmd_screen, 3777, 3795),
Function.ability(566, "Patrol_Battlecruiser_minimap", cmd_minimap, 3777, 3795),
Function.ability(567, "Patrol_Patrol_screen", cmd_screen, 17, 3795),
Function.ability(568, "Patrol_Patrol_minimap", cmd_minimap, 17, 3795),
Function.ability(335, "Rally_Units_screen", cmd_screen, 3673),
Function.ability(336, "Rally_Units_minimap", cmd_minimap, 3673),
Function.ability(337, "Rally_Building_screen", cmd_screen, 195, 3673),
Function.ability(338, "Rally_Building_minimap", cmd_minimap, 195, 3673),
Function.ability(339, "Rally_Hatchery_Units_screen", cmd_screen, 211, 3673),
Function.ability(340, "Rally_Hatchery_Units_minimap", cmd_minimap, 211, 3673),
Function.ability(341, "Rally_Morphing_Unit_screen", cmd_screen, 199, 3673),
Function.ability(342, "Rally_Morphing_Unit_minimap", cmd_minimap, 199, 3673),
Function.ability(343, "Rally_Workers_screen", cmd_screen, 3690),
Function.ability(344, "Rally_Workers_minimap", cmd_minimap, 3690),
Function.ability(345, "Rally_CommandCenter_screen", cmd_screen, 203, 3690),
Function.ability(346, "Rally_CommandCenter_minimap", cmd_minimap, 203, 3690),
Function.ability(347, "Rally_Hatchery_Workers_screen", cmd_screen, 212, 3690),
Function.ability(348, "Rally_Hatchery_Workers_minimap", cmd_minimap, 212, 3690),
Function.ability(349, "Rally_Nexus_screen", cmd_screen, 207, 3690),
Function.ability(350, "Rally_Nexus_minimap", cmd_minimap, 207, 3690),
Function.ability(539, "Research_AdaptiveTalons_quick", cmd_quick, 3709),
Function.ability(351, "Research_AdeptResonatingGlaives_quick", cmd_quick, 1594),
Function.ability(352, "Research_AdvancedBallistics_quick", cmd_quick, 805),
Function.ability(569, "Research_AnabolicSynthesis_quick", cmd_quick, 263),
Function.ability(353, "Research_BansheeCloakingField_quick", cmd_quick, 790),
Function.ability(354, "Research_BansheeHyperflightRotors_quick", cmd_quick, 799),
Function.ability(355, "Research_BattlecruiserWeaponRefit_quick", cmd_quick, 1532),
Function.ability(356, "Research_Blink_quick", cmd_quick, 1593),
Function.ability(357, "Research_Burrow_quick", cmd_quick, 1225),
Function.ability(358, "Research_CentrifugalHooks_quick", cmd_quick, 1482),
Function.ability(359, "Research_Charge_quick", cmd_quick, 1592),
Function.ability(360, "Research_ChitinousPlating_quick", cmd_quick, 265),
Function.ability(361, "Research_CombatShield_quick", cmd_quick, 731),
Function.ability(362, "Research_ConcussiveShells_quick", cmd_quick, 732),
Function.ability(570, "Research_CycloneLockOnDamage_quick", cmd_quick, 769),
Function.ability(540, "Research_CycloneRapidFireLaunchers_quick", cmd_quick, 768),
Function.ability(363, "Research_DrillingClaws_quick", cmd_quick, 764),
Function.ability(572, "Research_EnhancedShockwaves_quick", cmd_quick, 822),
Function.ability(364, "Research_ExtendedThermalLance_quick", cmd_quick, 1097),
Function.ability(365, "Research_GlialRegeneration_quick", cmd_quick, 216),
Function.ability(366, "Research_GraviticBooster_quick", cmd_quick, 1093),
Function.ability(367, "Research_GraviticDrive_quick", cmd_quick, 1094),
Function.ability(368, "Research_GroovedSpines_quick", cmd_quick, 1282),
Function.ability(369, "Research_HiSecAutoTracking_quick", cmd_quick, 650),
Function.ability(370, "Research_HighCapacityFuelTanks_quick", cmd_quick, 804),
Function.ability(371, "Research_InfernalPreigniter_quick", cmd_quick, 761),
Function.ability(372, "Research_InterceptorGravitonCatapult_quick", cmd_quick, 44),
Function.ability(374, "Research_MuscularAugments_quick", cmd_quick, 1283),
Function.ability(375, "Research_NeosteelFrame_quick", cmd_quick, 655),
Function.ability(376, "Research_NeuralParasite_quick", cmd_quick, 1455),
Function.ability(377, "Research_PathogenGlands_quick", cmd_quick, 1454),
Function.ability(378, "Research_PersonalCloaking_quick", cmd_quick, 820),
Function.ability(379, "Research_PhoenixAnionPulseCrystals_quick", cmd_quick, 46),
Function.ability(380, "Research_PneumatizedCarapace_quick", cmd_quick, 1223),
Function.ability(381, "Research_ProtossAirArmor_quick", cmd_quick, 3692),
Function.ability(382, "Research_ProtossAirArmorLevel1_quick", cmd_quick, 1565, 3692),
Function.ability(383, "Research_ProtossAirArmorLevel2_quick", cmd_quick, 1566, 3692),
Function.ability(384, "Research_ProtossAirArmorLevel3_quick", cmd_quick, 1567, 3692),
Function.ability(385, "Research_ProtossAirWeapons_quick", cmd_quick, 3693),
Function.ability(386, "Research_ProtossAirWeaponsLevel1_quick", cmd_quick, 1562, 3693),
Function.ability(387, "Research_ProtossAirWeaponsLevel2_quick", cmd_quick, 1563, 3693),
Function.ability(388, "Research_ProtossAirWeaponsLevel3_quick", cmd_quick, 1564, 3693),
Function.ability(389, "Research_ProtossGroundArmor_quick", cmd_quick, 3694),
Function.ability(390, "Research_ProtossGroundArmorLevel1_quick", cmd_quick, 1065, 3694),
Function.ability(391, "Research_ProtossGroundArmorLevel2_quick", cmd_quick, 1066, 3694),
Function.ability(392, "Research_ProtossGroundArmorLevel3_quick", cmd_quick, 1067, 3694),
Function.ability(393, "Research_ProtossGroundWeapons_quick", cmd_quick, 3695),
Function.ability(394, "Research_ProtossGroundWeaponsLevel1_quick", cmd_quick, 1062, 3695),
Function.ability(395, "Research_ProtossGroundWeaponsLevel2_quick", cmd_quick, 1063, 3695),
Function.ability(396, "Research_ProtossGroundWeaponsLevel3_quick", cmd_quick, 1064, 3695),
Function.ability(397, "Research_ProtossShields_quick", cmd_quick, 3696),
Function.ability(398, "Research_ProtossShieldsLevel1_quick", cmd_quick, 1068, 3696),
Function.ability(399, "Research_ProtossShieldsLevel2_quick", cmd_quick, 1069, 3696),
Function.ability(400, "Research_ProtossShieldsLevel3_quick", cmd_quick, 1070, 3696),
Function.ability(401, "Research_PsiStorm_quick", cmd_quick, 1126),
Function.ability(402, "Research_RavenCorvidReactor_quick", cmd_quick, 793),
Function.ability(403, "Research_RavenRecalibratedExplosives_quick", cmd_quick, 803),
Function.ability(404, "Research_ShadowStrike_quick", cmd_quick, 2720),
Function.ability(373, "Research_SmartServos_quick", cmd_quick, 766),
Function.ability(405, "Research_Stimpack_quick", cmd_quick, 730),
Function.ability(406, "Research_TerranInfantryArmor_quick", cmd_quick, 3697),
Function.ability(407, "Research_TerranInfantryArmorLevel1_quick", cmd_quick, 656, 3697),
Function.ability(408, "Research_TerranInfantryArmorLevel2_quick", cmd_quick, 657, 3697),
Function.ability(409, "Research_TerranInfantryArmorLevel3_quick", cmd_quick, 658, 3697),
Function.ability(410, "Research_TerranInfantryWeapons_quick", cmd_quick, 3698),
Function.ability(411, "Research_TerranInfantryWeaponsLevel1_quick", cmd_quick, 652, 3698),
Function.ability(412, "Research_TerranInfantryWeaponsLevel2_quick", cmd_quick, 653, 3698),
Function.ability(413, "Research_TerranInfantryWeaponsLevel3_quick", cmd_quick, 654, 3698),
Function.ability(414, "Research_TerranShipWeapons_quick", cmd_quick, 3699),
Function.ability(415, "Research_TerranShipWeaponsLevel1_quick", cmd_quick, 861, 3699),
Function.ability(416, "Research_TerranShipWeaponsLevel2_quick", cmd_quick, 862, 3699),
Function.ability(417, "Research_TerranShipWeaponsLevel3_quick", cmd_quick, 863, 3699),
Function.ability(418, "Research_TerranStructureArmorUpgrade_quick", cmd_quick, 651),
Function.ability(419, "Research_TerranVehicleAndShipPlating_quick", cmd_quick, 3700),
Function.ability(420, "Research_TerranVehicleAndShipPlatingLevel1_quick", cmd_quick, 864, 3700),
Function.ability(421, "Research_TerranVehicleAndShipPlatingLevel2_quick", cmd_quick, 865, 3700),
Function.ability(422, "Research_TerranVehicleAndShipPlatingLevel3_quick", cmd_quick, 866, 3700),
Function.ability(423, "Research_TerranVehicleWeapons_quick", cmd_quick, 3701),
Function.ability(424, "Research_TerranVehicleWeaponsLevel1_quick", cmd_quick, 855, 3701),
Function.ability(425, "Research_TerranVehicleWeaponsLevel2_quick", cmd_quick, 856, 3701),
Function.ability(426, "Research_TerranVehicleWeaponsLevel3_quick", cmd_quick, 857, 3701),
Function.ability(427, "Research_TunnelingClaws_quick", cmd_quick, 217),
Function.ability(428, "Research_WarpGate_quick", cmd_quick, 1568),
Function.ability(429, "Research_ZergFlyerArmor_quick", cmd_quick, 3702),
Function.ability(430, "Research_ZergFlyerArmorLevel1_quick", cmd_quick, 1315, 3702),
Function.ability(431, "Research_ZergFlyerArmorLevel2_quick", cmd_quick, 1316, 3702),
Function.ability(432, "Research_ZergFlyerArmorLevel3_quick", cmd_quick, 1317, 3702),
Function.ability(433, "Research_ZergFlyerAttack_quick", cmd_quick, 3703),
Function.ability(434, "Research_ZergFlyerAttackLevel1_quick", cmd_quick, 1312, 3703),
Function.ability(435, "Research_ZergFlyerAttackLevel2_quick", cmd_quick, 1313, 3703),
Function.ability(436, "Research_ZergFlyerAttackLevel3_quick", cmd_quick, 1314, 3703),
Function.ability(437, "Research_ZergGroundArmor_quick", cmd_quick, 3704),
Function.ability(438, "Research_ZergGroundArmorLevel1_quick", cmd_quick, 1189, 3704),
Function.ability(439, "Research_ZergGroundArmorLevel2_quick", cmd_quick, 1190, 3704),
Function.ability(440, "Research_ZergGroundArmorLevel3_quick", cmd_quick, 1191, 3704),
Function.ability(441, "Research_ZergMeleeWeapons_quick", cmd_quick, 3705),
Function.ability(442, "Research_ZergMeleeWeaponsLevel1_quick", cmd_quick, 1186, 3705),
Function.ability(443, "Research_ZergMeleeWeaponsLevel2_quick", cmd_quick, 1187, 3705),
Function.ability(444, "Research_ZergMeleeWeaponsLevel3_quick", cmd_quick, 1188, 3705),
Function.ability(445, "Research_ZergMissileWeapons_quick", cmd_quick, 3706),
Function.ability(446, "Research_ZergMissileWeaponsLevel1_quick", cmd_quick, 1192, 3706),
Function.ability(447, "Research_ZergMissileWeaponsLevel2_quick", cmd_quick, 1193, 3706),
Function.ability(448, "Research_ZergMissileWeaponsLevel3_quick", cmd_quick, 1194, 3706),
Function.ability(449, "Research_ZerglingAdrenalGlands_quick", cmd_quick, 1252),
Function.ability(450, "Research_ZerglingMetabolicBoost_quick", cmd_quick, 1253),
Function.ability(451, "Smart_screen", cmd_screen, 1),
Function.ability(452, "Smart_minimap", cmd_minimap, 1),
Function.ability(453, "Stop_quick", cmd_quick, 3665),
Function.ability(571, "Stop_Battlecruiser_quick", cmd_quick, 3783, 3665),
Function.ability(454, "Stop_Building_quick", cmd_quick, 2057, 3665),
Function.ability(455, "Stop_Redirect_quick", cmd_quick, 1691, 3665),
Function.ability(456, "Stop_Stop_quick", cmd_quick, 4, 3665),
Function.ability(457, "Train_Adept_quick", cmd_quick, 922),
Function.ability(458, "Train_Baneling_quick", cmd_quick, 80),
Function.ability(459, "Train_Banshee_quick", cmd_quick, 621),
Function.ability(460, "Train_Battlecruiser_quick", cmd_quick, 623),
Function.ability(461, "Train_Carrier_quick", cmd_quick, 948),
Function.ability(462, "Train_Colossus_quick", cmd_quick, 978),
Function.ability(463, "Train_Corruptor_quick", cmd_quick, 1353),
Function.ability(464, "Train_Cyclone_quick", cmd_quick, 597),
Function.ability(465, "Train_DarkTemplar_quick", cmd_quick, 920),
Function.ability(466, "Train_Disruptor_quick", cmd_quick, 994),
Function.ability(467, "Train_Drone_quick", cmd_quick, 1342),
Function.ability(468, "Train_Ghost_quick", cmd_quick, 562),
Function.ability(469, "Train_Hellbat_quick", cmd_quick, 596),
Function.ability(470, "Train_Hellion_quick", cmd_quick, 595),
Function.ability(471, "Train_HighTemplar_quick", cmd_quick, 919),
Function.ability(472, "Train_Hydralisk_quick", cmd_quick, 1345),
Function.ability(473, "Train_Immortal_quick", cmd_quick, 979),
Function.ability(474, "Train_Infestor_quick", cmd_quick, 1352),
Function.ability(475, "Train_Liberator_quick", cmd_quick, 626),
Function.ability(476, "Train_Marauder_quick", cmd_quick, 563),
Function.ability(477, "Train_Marine_quick", cmd_quick, 560),
Function.ability(478, "Train_Medivac_quick", cmd_quick, 620),
Function.ability(541, "Train_Mothership_quick", cmd_quick, 110),
Function.ability(479, "Train_MothershipCore_quick", cmd_quick, 1853),
Function.ability(480, "Train_Mutalisk_quick", cmd_quick, 1346),
Function.ability(481, "Train_Observer_quick", cmd_quick, 977),
Function.ability(482, "Train_Oracle_quick", cmd_quick, 954),
Function.ability(483, "Train_Overlord_quick", cmd_quick, 1344),
Function.ability(484, "Train_Phoenix_quick", cmd_quick, 946),
Function.ability(485, "Train_Probe_quick", cmd_quick, 1006),
Function.ability(486, "Train_Queen_quick", cmd_quick, 1632),
Function.ability(487, "Train_Raven_quick", cmd_quick, 622),
Function.ability(488, "Train_Reaper_quick", cmd_quick, 561),
Function.ability(489, "Train_Roach_quick", cmd_quick, 1351),
Function.ability(490, "Train_SCV_quick", cmd_quick, 524),
Function.ability(491, "Train_Sentry_quick", cmd_quick, 921),
Function.ability(492, "Train_SiegeTank_quick", cmd_quick, 591),
Function.ability(493, "Train_Stalker_quick", cmd_quick, 917),
Function.ability(494, "Train_SwarmHost_quick", cmd_quick, 1356),
Function.ability(495, "Train_Tempest_quick", cmd_quick, 955),
Function.ability(496, "Train_Thor_quick", cmd_quick, 594),
Function.ability(497, "Train_Ultralisk_quick", cmd_quick, 1348),
Function.ability(498, "Train_VikingFighter_quick", cmd_quick, 624),
Function.ability(499, "Train_Viper_quick", cmd_quick, 1354),
Function.ability(500, "Train_VoidRay_quick", cmd_quick, 950),
Function.ability(501, "Train_WarpPrism_quick", cmd_quick, 976),
Function.ability(502, "Train_WidowMine_quick", cmd_quick, 614),
Function.ability(503, "Train_Zealot_quick", cmd_quick, 916),
Function.ability(504, "Train_Zergling_quick", cmd_quick, 1343),
Function.ability(505, "TrainWarp_Adept_screen", cmd_screen, 1419),
Function.ability(506, "TrainWarp_DarkTemplar_screen", cmd_screen, 1417),
Function.ability(507, "TrainWarp_HighTemplar_screen", cmd_screen, 1416),
Function.ability(508, "TrainWarp_Sentry_screen", cmd_screen, 1418),
Function.ability(509, "TrainWarp_Stalker_screen", cmd_screen, 1414),
Function.ability(510, "TrainWarp_Zealot_screen", cmd_screen, 1413),
Function.ability(511, "UnloadAll_quick", cmd_quick, 3664),
Function.ability(512, "UnloadAll_Bunker_quick", cmd_quick, 408, 3664),
Function.ability(513, "UnloadAll_CommandCenter_quick", cmd_quick, 413, 3664),
Function.ability(514, "UnloadAll_NydusNetwork_quick", cmd_quick, 1438, 3664),
Function.ability(515, "UnloadAll_NydusWorm_quick", cmd_quick, 2371, 3664),
Function.ability(516, "UnloadAllAt_screen", cmd_screen, 3669),
Function.ability(517, "UnloadAllAt_minimap", cmd_minimap, 3669),
Function.ability(518, "UnloadAllAt_Medivac_screen", cmd_screen, 396, 3669),
Function.ability(519, "UnloadAllAt_Medivac_minimap", cmd_minimap, 396, 3669),
Function.ability(520, "UnloadAllAt_Overlord_screen", cmd_screen, 1408, 3669),
Function.ability(521, "UnloadAllAt_Overlord_minimap", cmd_minimap, 1408, 3669),
Function.ability(522, "UnloadAllAt_WarpPrism_screen", cmd_screen, 913, 3669),
Function.ability(523, "UnloadAllAt_WarpPrism_minimap", cmd_minimap, 913, 3669),
]
# pylint: enable=line-too-long
# Create an IntEnum of the function names/ids so that printing the id will
# show something useful.
_Functions = enum.IntEnum( # pylint: disable=invalid-name
"_Functions", {f.name: f.id for f in _FUNCTIONS})
_FUNCTIONS = [f._replace(id=_Functions(f.id)) for f in _FUNCTIONS]
FUNCTIONS = Functions(_FUNCTIONS)
# Some indexes to support features.py and action conversion.
ABILITY_IDS = collections.defaultdict(set) # {ability_id: {funcs}}
for _func in FUNCTIONS:
if _func.ability_id >= 0:
ABILITY_IDS[_func.ability_id].add(_func)
ABILITY_IDS = {k: frozenset(v) for k, v in six.iteritems(ABILITY_IDS)}
FUNCTIONS_AVAILABLE = {f.id: f for f in FUNCTIONS if f.avail_fn}
# pylint: disable=line-too-long
_RAW_FUNCTIONS = [
Function.raw_ui_func(0, "no_op", raw_no_op),
Function.raw_ui_func(168, "raw_move_camera", raw_move_camera),
Function.raw_ability(2, "Attack_pt", raw_cmd_pt, 3674),
Function.raw_ability(3, "Attack_unit", raw_cmd_unit, 3674),
Function.raw_ability(4, "Attack_Attack_pt", raw_cmd_pt, 23, 3674),
Function.raw_ability(6, "Attack_AttackBuilding_pt", raw_cmd_pt, 2048, 3674),
Function.raw_ability(5, "Attack_Attack_unit", raw_cmd_unit, 23, 3674),
Function.raw_ability(7, "Attack_AttackBuilding_unit", raw_cmd_unit, 2048, 3674),
Function.raw_ability(539, "Attack_Battlecruiser_pt", raw_cmd_pt, 3771, 3674),
Function.raw_ability(540, "Attack_Battlecruiser_unit", raw_cmd_unit, 3771, 3674),
Function.raw_ability(8, "Attack_Redirect_pt", raw_cmd_pt, 1682, 3674),
Function.raw_ability(9, "Attack_Redirect_unit", raw_cmd_unit, 1682, 3674),
Function.raw_ability(88, "Behavior_BuildingAttackOff_quick", raw_cmd, 2082), # wrong / baneling
Function.raw_ability(87, "Behavior_BuildingAttackOn_quick", raw_cmd, 2081), # wrong / baneling
Function.raw_ability(169, "Behavior_CloakOff_quick", raw_cmd, 3677),
Function.raw_ability(170, "Behavior_CloakOff_Banshee_quick", raw_cmd, 393, 3677),
Function.raw_ability(171, "Behavior_CloakOff_Ghost_quick", raw_cmd, 383, 3677),
Function.raw_ability(172, "Behavior_CloakOn_quick", raw_cmd, 3676),
Function.raw_ability(173, "Behavior_CloakOn_Banshee_quick", raw_cmd, 392, 3676),
Function.raw_ability(174, "Behavior_CloakOn_Ghost_quick", raw_cmd, 382, 3676),
Function.raw_ability(175, "Behavior_GenerateCreepOff_quick", raw_cmd, 1693),
Function.raw_ability(176, "Behavior_GenerateCreepOn_quick", raw_cmd, 1692),
Function.raw_ability(178, "Behavior_HoldFireOff_Ghost_quick", raw_cmd, 38, 3689),
Function.raw_ability(179, "Behavior_HoldFireOff_Lurker_quick", raw_cmd, 2552, 3689),
Function.raw_ability(177, "Behavior_HoldFireOff_quick", raw_cmd, 3689),
Function.raw_ability(181, "Behavior_HoldFireOn_Ghost_quick", raw_cmd, 36, 3688),
Function.raw_ability(182, "Behavior_HoldFireOn_Lurker_quick", raw_cmd, 2550, 3688),
Function.raw_ability(180, "Behavior_HoldFireOn_quick", raw_cmd, 3688),
Function.raw_ability(158, "Behavior_PulsarBeamOff_quick", raw_cmd, 2376),
Function.raw_ability(159, "Behavior_PulsarBeamOn_quick", raw_cmd, 2375),
Function.raw_ability(183, "Build_Armory_pt", raw_cmd_pt, 331),
Function.raw_ability(36, "Build_Assimilator_unit", raw_cmd_unit, 882),
Function.raw_ability(184, "Build_BanelingNest_pt", raw_cmd_pt, 1162),
Function.raw_ability(185, "Build_Barracks_pt", raw_cmd_pt, 321),
Function.raw_ability(186, "Build_Bunker_pt", raw_cmd_pt, 324),
Function.raw_ability(187, "Build_CommandCenter_pt", raw_cmd_pt, 318),
Function.raw_ability(188, "Build_CreepTumor_pt", raw_cmd_pt, 3691),
Function.raw_ability(189, "Build_CreepTumor_Queen_pt", raw_cmd_pt, 1694, 3691),
Function.raw_ability(190, "Build_CreepTumor_Tumor_pt", raw_cmd_pt, 1733, 3691),
Function.raw_ability(47, "Build_CyberneticsCore_pt", raw_cmd_pt, 894),
Function.raw_ability(44, "Build_DarkShrine_pt", raw_cmd_pt, 891),
Function.raw_ability(191, "Build_EngineeringBay_pt", raw_cmd_pt, 322),
Function.raw_ability(192, "Build_EvolutionChamber_pt", raw_cmd_pt, 1156),
Function.raw_ability(193, "Build_Extractor_unit", raw_cmd_unit, 1154),
Function.raw_ability(194, "Build_Factory_pt", raw_cmd_pt, 328),
Function.raw_ability(39, "Build_FleetBeacon_pt", raw_cmd_pt, 885),
Function.raw_ability(38, "Build_Forge_pt", raw_cmd_pt, 884),
Function.raw_ability(195, "Build_FusionCore_pt", raw_cmd_pt, 333),
Function.raw_ability(37, "Build_Gateway_pt", raw_cmd_pt, 883),
Function.raw_ability(196, "Build_GhostAcademy_pt", raw_cmd_pt, 327),
Function.raw_ability(197, "Build_Hatchery_pt", raw_cmd_pt, 1152),
Function.raw_ability(198, "Build_HydraliskDen_pt", raw_cmd_pt, 1157),
Function.raw_ability(199, "Build_InfestationPit_pt", raw_cmd_pt, 1160),
Function.raw_ability(200, "Build_Interceptors_autocast", raw_autocast, 1042),
Function.raw_ability(66, "Build_Interceptors_quick", raw_cmd, 1042),
Function.raw_ability(201, "Build_LurkerDen_pt", raw_cmd_pt, 1163),
Function.raw_ability(202, "Build_MissileTurret_pt", raw_cmd_pt, 323),
Function.raw_ability(34, "Build_Nexus_pt", raw_cmd_pt, 880),
Function.raw_ability(203, "Build_Nuke_quick", raw_cmd, 710),
Function.raw_ability(204, "Build_NydusNetwork_pt", raw_cmd_pt, 1161),
Function.raw_ability(205, "Build_NydusWorm_pt", raw_cmd_pt, 1768),
Function.raw_ability(41, "Build_PhotonCannon_pt", raw_cmd_pt, 887),
Function.raw_ability(35, "Build_Pylon_pt", raw_cmd_pt, 881),
Function.raw_ability(207, "Build_Reactor_pt", raw_cmd_pt, 3683),
Function.raw_ability(206, "Build_Reactor_quick", raw_cmd, 3683),
Function.raw_ability(209, "Build_Reactor_Barracks_pt", raw_cmd_pt, 422, 3683),
Function.raw_ability(208, "Build_Reactor_Barracks_quick", raw_cmd, 422, 3683),
Function.raw_ability(211, "Build_Reactor_Factory_pt", raw_cmd_pt, 455, 3683),
Function.raw_ability(210, "Build_Reactor_Factory_quick", raw_cmd, 455, 3683),
Function.raw_ability(213, "Build_Reactor_Starport_pt", raw_cmd_pt, 488, 3683),
Function.raw_ability(212, "Build_Reactor_Starport_quick", raw_cmd, 488, 3683),
Function.raw_ability(214, "Build_Refinery_pt", raw_cmd_unit, 320),
Function.raw_ability(215, "Build_RoachWarren_pt", raw_cmd_pt, 1165),
Function.raw_ability(45, "Build_RoboticsBay_pt", raw_cmd_pt, 892),
Function.raw_ability(46, "Build_RoboticsFacility_pt", raw_cmd_pt, 893),
Function.raw_ability(216, "Build_SensorTower_pt", raw_cmd_pt, 326),
Function.raw_ability(48, "Build_ShieldBattery_pt", raw_cmd_pt, 895),
Function.raw_ability(217, "Build_SpawningPool_pt", raw_cmd_pt, 1155),
Function.raw_ability(218, "Build_SpineCrawler_pt", raw_cmd_pt, 1166),
Function.raw_ability(219, "Build_Spire_pt", raw_cmd_pt, 1158),
Function.raw_ability(220, "Build_SporeCrawler_pt", raw_cmd_pt, 1167),
Function.raw_ability(42, "Build_Stargate_pt", raw_cmd_pt, 889),
Function.raw_ability(221, "Build_Starport_pt", raw_cmd_pt, 329),
Function.raw_ability(95, "Build_StasisTrap_pt", raw_cmd_pt, 2505),
Function.raw_ability(222, "Build_SupplyDepot_pt", raw_cmd_pt, 319),
Function.raw_ability(224, "Build_TechLab_pt", raw_cmd_pt, 3682),
Function.raw_ability(223, "Build_TechLab_quick", raw_cmd, 3682),
Function.raw_ability(226, "Build_TechLab_Barracks_pt", raw_cmd_pt, 421, 3682),
Function.raw_ability(225, "Build_TechLab_Barracks_quick", raw_cmd, 421, 3682),
Function.raw_ability(228, "Build_TechLab_Factory_pt", raw_cmd_pt, 454, 3682),
Function.raw_ability(227, "Build_TechLab_Factory_quick", raw_cmd, 454, 3682),
Function.raw_ability(230, "Build_TechLab_Starport_pt", raw_cmd_pt, 487, 3682),
Function.raw_ability(229, "Build_TechLab_Starport_quick", raw_cmd, 487, 3682),
Function.raw_ability(43, "Build_TemplarArchive_pt", raw_cmd_pt, 890),
Function.raw_ability(40, "Build_TwilightCouncil_pt", raw_cmd_pt, 886),
Function.raw_ability(231, "Build_UltraliskCavern_pt", raw_cmd_pt, 1159),
Function.raw_ability(232, "BurrowDown_quick", raw_cmd, 3661),
Function.raw_ability(233, "BurrowDown_Baneling_quick", raw_cmd, 1374, 3661),
Function.raw_ability(234, "BurrowDown_Drone_quick", raw_cmd, 1378, 3661),
Function.raw_ability(235, "BurrowDown_Hydralisk_quick", raw_cmd, 1382, 3661),
Function.raw_ability(236, "BurrowDown_Infestor_quick", raw_cmd, 1444, 3661),
Function.raw_ability(237, "BurrowDown_InfestorTerran_quick", raw_cmd, 1394, 3661),
Function.raw_ability(238, "BurrowDown_Lurker_quick", raw_cmd, 2108, 3661),
Function.raw_ability(239, "BurrowDown_Queen_quick", raw_cmd, 1433, 3661),
Function.raw_ability(240, "BurrowDown_Ravager_quick", raw_cmd, 2340, 3661),
Function.raw_ability(241, "BurrowDown_Roach_quick", raw_cmd, 1386, 3661),
Function.raw_ability(242, "BurrowDown_SwarmHost_quick", raw_cmd, 2014, 3661),
Function.raw_ability(243, "BurrowDown_Ultralisk_quick", raw_cmd, 1512, 3661),
Function.raw_ability(244, "BurrowDown_WidowMine_quick", raw_cmd, 2095, 3661),
Function.raw_ability(245, "BurrowDown_Zergling_quick", raw_cmd, 1390, 3661),
Function.raw_ability(247, "BurrowUp_autocast", raw_autocast, 3662),
Function.raw_ability(246, "BurrowUp_quick", raw_cmd, 3662),
Function.raw_ability(249, "BurrowUp_Baneling_autocast", raw_autocast, 1376, 3662),
Function.raw_ability(248, "BurrowUp_Baneling_quick", raw_cmd, 1376, 3662),
Function.raw_ability(250, "BurrowUp_Drone_quick", raw_cmd, 1380, 3662),
Function.raw_ability(252, "BurrowUp_Hydralisk_autocast", raw_autocast, 1384, 3662),
Function.raw_ability(251, "BurrowUp_Hydralisk_quick", raw_cmd, 1384, 3662),
Function.raw_ability(253, "BurrowUp_Infestor_quick", raw_cmd, 1446, 3662),
Function.raw_ability(255, "BurrowUp_InfestorTerran_autocast", raw_autocast, 1396, 3662),
Function.raw_ability(254, "BurrowUp_InfestorTerran_quick", raw_cmd, 1396, 3662),
Function.raw_ability(256, "BurrowUp_Lurker_quick", raw_cmd, 2110, 3662),
Function.raw_ability(258, "BurrowUp_Queen_autocast", raw_autocast, 1435, 3662),
Function.raw_ability(257, "BurrowUp_Queen_quick", raw_cmd, 1435, 3662),
Function.raw_ability(260, "BurrowUp_Ravager_autocast", raw_autocast, 2342, 3662),
Function.raw_ability(259, "BurrowUp_Ravager_quick", raw_cmd, 2342, 3662),
Function.raw_ability(262, "BurrowUp_Roach_autocast", raw_autocast, 1388, 3662),
Function.raw_ability(261, "BurrowUp_Roach_quick", raw_cmd, 1388, 3662),
Function.raw_ability(263, "BurrowUp_SwarmHost_quick", raw_cmd, 2016, 3662),
Function.raw_ability(265, "BurrowUp_Ultralisk_autocast", raw_autocast, 1514, 3662),
Function.raw_ability(264, "BurrowUp_Ultralisk_quick", raw_cmd, 1514, 3662),
Function.raw_ability(266, "BurrowUp_WidowMine_quick", raw_cmd, 2097, 3662),
Function.raw_ability(268, "BurrowUp_Zergling_autocast", raw_autocast, 1392, 3662),
Function.raw_ability(267, "BurrowUp_Zergling_quick", raw_cmd, 1392, 3662),
Function.raw_ability(98, "Cancel_quick", raw_cmd, 3659),
Function.raw_ability(123, "Cancel_AdeptPhaseShift_quick", raw_cmd, 2594, 3659),
Function.raw_ability(124, "Cancel_AdeptShadePhaseShift_quick", raw_cmd, 2596, 3659),
Function.raw_ability(269, "Cancel_BarracksAddOn_quick", raw_cmd, 451, 3659),
Function.raw_ability(125, "Cancel_BuildInProgress_quick", raw_cmd, 314, 3659),
Function.raw_ability(270, "Cancel_CreepTumor_quick", raw_cmd, 1763, 3659),
Function.raw_ability(271, "Cancel_FactoryAddOn_quick", raw_cmd, 484, 3659),
Function.raw_ability(126, "Cancel_GravitonBeam_quick", raw_cmd, 174, 3659),
Function.raw_ability(272, "Cancel_HangarQueue5_quick", raw_cmd, 1038, 3671),
Function.raw_ability(129, "Cancel_Last_quick", raw_cmd, 3671),
Function.raw_ability(273, "Cancel_LockOn_quick", raw_cmd, 2354, 3659),
Function.raw_ability(274, "Cancel_MorphBroodlord_quick", raw_cmd, 1373, 3659),
Function.raw_ability(275, "Cancel_MorphGreaterSpire_quick", raw_cmd, 1221, 3659),
Function.raw_ability(276, "Cancel_MorphHive_quick", raw_cmd, 1219, 3659),
Function.raw_ability(277, "Cancel_MorphLair_quick", raw_cmd, 1217, 3659),
Function.raw_ability(279, "Cancel_MorphLurkerDen_quick", raw_cmd, 2113, 3659),
Function.raw_ability(278, "Cancel_MorphLurker_quick", raw_cmd, 2333, 3659),
Function.raw_ability(280, "Cancel_MorphMothership_quick", raw_cmd, 1848, 3659),
Function.raw_ability(281, "Cancel_MorphOrbital_quick", raw_cmd, 1517, 3659),
Function.raw_ability(282, "Cancel_MorphOverlordTransport_quick", raw_cmd, 2709, 3659),
Function.raw_ability(283, "Cancel_MorphOverseer_quick", raw_cmd, 1449, 3659),
Function.raw_ability(284, "Cancel_MorphPlanetaryFortress_quick", raw_cmd, 1451, 3659),
Function.raw_ability(285, "Cancel_MorphRavager_quick", raw_cmd, 2331, 3659),
Function.raw_ability(286, "Cancel_MorphThorExplosiveMode_quick", raw_cmd, 2365, 3659),
Function.raw_ability(287, "Cancel_NeuralParasite_quick", raw_cmd, 250, 3659),
Function.raw_ability(288, "Cancel_Nuke_quick", raw_cmd, 1623, 3659),
Function.raw_ability(130, "Cancel_Queue1_quick", raw_cmd, 304, 3671),
Function.raw_ability(131, "Cancel_Queue5_quick", raw_cmd, 306, 3671),
Function.raw_ability(289, "Cancel_QueueAddOn_quick", raw_cmd, 312, 3671),
Function.raw_ability(132, "Cancel_QueueCancelToSelection_quick", raw_cmd, 308, 3671),
Function.raw_ability(134, "Cancel_QueuePassiveCancelToSelection_quick", raw_cmd, 1833, 3671),
Function.raw_ability(133, "Cancel_QueuePassive_quick", raw_cmd, 1831, 3671),
Function.raw_ability(290, "Cancel_SpineCrawlerRoot_quick", raw_cmd, 1730, 3659),
Function.raw_ability(291, "Cancel_SporeCrawlerRoot_quick", raw_cmd, 1732, 3659),
Function.raw_ability(292, "Cancel_StarportAddOn_quick", raw_cmd, 517, 3659),
Function.raw_ability(127, "Cancel_StasisTrap_quick", raw_cmd, 2535, 3659),
Function.raw_ability(128, "Cancel_VoidRayPrismaticAlignment_quick", raw_cmd, 3707, 3659),
Function.raw_ability(293, "Effect_Abduct_unit", raw_cmd_unit, 2067),
Function.raw_ability(96, "Effect_AdeptPhaseShift_pt", raw_cmd_pt, 2544),
Function.raw_ability(294, "Effect_AntiArmorMissile_unit", raw_cmd_unit, 3753),
Function.raw_ability(295, "Effect_AutoTurret_pt", raw_cmd_pt, 1764),
Function.raw_ability(296, "Effect_BlindingCloud_pt", raw_cmd_pt, 2063),
Function.raw_ability(111, "Effect_Blink_pt", raw_cmd_pt, 3687),
Function.raw_ability(135, "Effect_Blink_Stalker_pt", raw_cmd_pt, 1442, 3687),
Function.raw_ability(112, "Effect_Blink_unit", raw_cmd_unit, 3687), # wrong/unit
Function.raw_ability(297, "Effect_CalldownMULE_pt", raw_cmd_pt, 171),
Function.raw_ability(298, "Effect_CalldownMULE_unit", raw_cmd_unit, 171),
Function.raw_ability(299, "Effect_CausticSpray_unit", raw_cmd_unit, 2324),
Function.raw_ability(302, "Effect_Charge_autocast", raw_autocast, 1819),
Function.raw_ability(300, "Effect_Charge_pt", raw_cmd_pt, 1819),
Function.raw_ability(301, "Effect_Charge_unit", raw_cmd_unit, 1819),
Function.raw_ability(122, "Effect_ChronoBoostEnergyCost_unit", raw_cmd_unit, 3755), # new 4.0?
Function.raw_ability(33, "Effect_ChronoBoost_unit", raw_cmd_unit, 261), # wrong / old?
Function.raw_ability(303, "Effect_Contaminate_unit", raw_cmd_unit, 1825),
Function.raw_ability(304, "Effect_CorrosiveBile_pt", raw_cmd_pt, 2338),
Function.raw_ability(305, "Effect_EMP_pt", raw_cmd_pt, 1628),
Function.raw_ability(306, "Effect_EMP_unit", raw_cmd_unit, 1628),
Function.raw_ability(307, "Effect_Explode_quick", raw_cmd, 42),
Function.raw_ability(157, "Effect_Feedback_unit", raw_cmd_unit, 140),
Function.raw_ability(79, "Effect_ForceField_pt", raw_cmd_pt, 1526),
Function.raw_ability(308, "Effect_FungalGrowth_pt", raw_cmd_pt, 74),
Function.raw_ability(309, "Effect_FungalGrowth_unit", raw_cmd_unit, 74),
Function.raw_ability(310, "Effect_GhostSnipe_unit", raw_cmd_unit, 2714),
Function.raw_ability(32, "Effect_GravitonBeam_unit", raw_cmd_unit, 173),
Function.raw_ability(20, "Effect_GuardianShield_quick", raw_cmd, 76),
Function.raw_ability(312, "Effect_Heal_autocast", raw_autocast, 386),
Function.raw_ability(311, "Effect_Heal_unit", raw_cmd_unit, 386),
Function.raw_ability(313, "Effect_ImmortalBarrier_autocast", raw_autocast, 2328),
Function.raw_ability(91, "Effect_ImmortalBarrier_quick", raw_cmd, 2328),
Function.raw_ability(314, "Effect_InfestedTerrans_pt", raw_cmd_pt, 247),
Function.raw_ability(315, "Effect_InjectLarva_unit", raw_cmd_unit, 251),
Function.raw_ability(316, "Effect_InterferenceMatrix_unit", raw_cmd_unit, 3747),
Function.raw_ability(317, "Effect_KD8Charge_pt", raw_cmd_pt, 2588),
Function.raw_ability(538, "Effect_KD8Charge_unit", raw_cmd_unit, 2588),
Function.raw_ability(318, "Effect_LockOn_unit", raw_cmd_unit, 2350),
Function.raw_ability(541, "Effect_LockOn_autocast", raw_autocast, 2350),
Function.raw_ability(319, "Effect_LocustSwoop_pt", raw_cmd_pt, 2387),
Function.raw_ability(110, "Effect_MassRecall_pt", raw_cmd_pt, 3686),
Function.raw_ability(136, "Effect_MassRecall_Mothership_pt", raw_cmd_pt, 2368, 3686),
Function.raw_ability(162, "Effect_MassRecall_Nexus_pt", raw_cmd_pt, 3757, 3686),
Function.raw_ability(137, "Effect_MassRecall_StrategicRecall_pt", raw_cmd_pt, 142, 3686),
Function.raw_ability(320, "Effect_MedivacIgniteAfterburners_quick", raw_cmd, 2116),
Function.raw_ability(321, "Effect_NeuralParasite_unit", raw_cmd_unit, 249),
Function.raw_ability(322, "Effect_NukeCalldown_pt", raw_cmd_pt, 1622),
Function.raw_ability(90, "Effect_OracleRevelation_pt", raw_cmd_pt, 2146),
Function.raw_ability(323, "Effect_ParasiticBomb_unit", raw_cmd_unit, 2542),
Function.raw_ability(65, "Effect_PsiStorm_pt", raw_cmd_pt, 1036),
Function.raw_ability(167, "Effect_PurificationNova_pt", raw_cmd_pt, 2346),
Function.raw_ability(324, "Effect_Repair_autocast", raw_autocast, 3685),
Function.raw_ability(108, "Effect_Repair_pt", raw_cmd_pt, 3685),
Function.raw_ability(109, "Effect_Repair_unit", raw_cmd_unit, 3685),
Function.raw_ability(326, "Effect_Repair_Mule_autocast", raw_autocast, 78, 3685),
Function.raw_ability(325, "Effect_Repair_Mule_unit", raw_cmd_unit, 78, 3685),
Function.raw_ability(328, "Effect_Repair_RepairDrone_autocast", raw_autocast, 3751, 3685),
Function.raw_ability(327, "Effect_Repair_RepairDrone_unit", raw_cmd_unit, 3751, 3685),
Function.raw_ability(330, "Effect_Repair_SCV_autocast", raw_autocast, 316, 3685),
Function.raw_ability(329, "Effect_Repair_SCV_unit", raw_cmd_unit, 316, 3685),
Function.raw_ability(331, "Effect_Restore_autocast", raw_autocast, 3765),
Function.raw_ability(161, "Effect_Restore_unit", raw_cmd_unit, 3765),
Function.raw_ability(332, "Effect_Salvage_quick", raw_cmd, 32),
Function.raw_ability(333, "Effect_Scan_pt", raw_cmd_pt, 399),
Function.raw_ability(113, "Effect_ShadowStride_pt", raw_cmd_pt, 2700, 3687),
Function.raw_ability(334, "Effect_SpawnChangeling_quick", raw_cmd, 181),
Function.raw_ability(335, "Effect_SpawnLocusts_pt", raw_cmd_pt, 2704),
Function.raw_ability(336, "Effect_SpawnLocusts_unit", raw_cmd_unit, 2704),
Function.raw_ability(337, "Effect_Spray_pt", raw_cmd_pt, 3684),
Function.raw_ability(338, "Effect_Spray_Protoss_pt", raw_cmd_pt, 30, 3684),
Function.raw_ability(339, "Effect_Spray_Terran_pt", raw_cmd_pt, 26, 3684),
Function.raw_ability(340, "Effect_Spray_Zerg_pt", raw_cmd_pt, 28, 3684),
Function.raw_ability(341, "Effect_Stim_quick", raw_cmd, 3675),
Function.raw_ability(342, "Effect_Stim_Marauder_quick", raw_cmd, 253, 3675),
Function.raw_ability(343, "Effect_Stim_Marauder_Redirect_quick", raw_cmd, 1684, 3675),
Function.raw_ability(344, "Effect_Stim_Marine_quick", raw_cmd, 380, 3675),
Function.raw_ability(345, "Effect_Stim_Marine_Redirect_quick", raw_cmd, 1683, 3675),
Function.raw_ability(346, "Effect_SupplyDrop_unit", raw_cmd_unit, 255),
Function.raw_ability(347, "Effect_TacticalJump_pt", raw_cmd_pt, 2358),
Function.raw_ability(348, "Effect_TimeWarp_pt", raw_cmd_pt, 2244),
Function.raw_ability(349, "Effect_Transfusion_unit", raw_cmd_unit, 1664),
Function.raw_ability(350, "Effect_ViperConsume_unit", raw_cmd_unit, 2073),
Function.raw_ability(94, "Effect_VoidRayPrismaticAlignment_quick", raw_cmd, 2393),
Function.raw_ability(353, "Effect_WidowMineAttack_autocast", raw_autocast, 2099),
Function.raw_ability(351, "Effect_WidowMineAttack_pt", raw_cmd_pt, 2099),
Function.raw_ability(352, "Effect_WidowMineAttack_unit", raw_cmd_unit, 2099),
Function.raw_ability(537, "Effect_YamatoGun_unit", raw_cmd_unit, 401),
Function.raw_ability(93, "Hallucination_Adept_quick", raw_cmd, 2391),
Function.raw_ability(22, "Hallucination_Archon_quick", raw_cmd, 146),
Function.raw_ability(23, "Hallucination_Colossus_quick", raw_cmd, 148),
Function.raw_ability(92, "Hallucination_Disruptor_quick", raw_cmd, 2389),
Function.raw_ability(24, "Hallucination_HighTemplar_quick", raw_cmd, 150),
Function.raw_ability(25, "Hallucination_Immortal_quick", raw_cmd, 152),
Function.raw_ability(89, "Hallucination_Oracle_quick", raw_cmd, 2114),
Function.raw_ability(26, "Hallucination_Phoenix_quick", raw_cmd, 154),
Function.raw_ability(27, "Hallucination_Probe_quick", raw_cmd, 156),
Function.raw_ability(28, "Hallucination_Stalker_quick", raw_cmd, 158),
Function.raw_ability(29, "Hallucination_VoidRay_quick", raw_cmd, 160),
Function.raw_ability(30, "Hallucination_WarpPrism_quick", raw_cmd, 162),
Function.raw_ability(31, "Hallucination_Zealot_quick", raw_cmd, 164),
Function.raw_ability(354, "Halt_Building_quick", raw_cmd, 315, 3660),
Function.raw_ability(99, "Halt_quick", raw_cmd, 3660),
Function.raw_ability(355, "Halt_TerranBuild_quick", raw_cmd, 348, 3660),
Function.raw_ability(102, "Harvest_Gather_unit", raw_cmd_unit, 3666),
Function.raw_ability(356, "Harvest_Gather_Drone_unit", raw_cmd_unit, 1183, 3666),
Function.raw_ability(357, "Harvest_Gather_Mule_unit", raw_cmd_unit, 166, 3666),
Function.raw_ability(358, "Harvest_Gather_Probe_unit", raw_cmd_unit, 298, 3666),
Function.raw_ability(359, "Harvest_Gather_SCV_unit", raw_cmd_unit, 295, 3666),
Function.raw_ability(103, "Harvest_Return_quick", raw_cmd, 3667),
Function.raw_ability(360, "Harvest_Return_Drone_quick", raw_cmd, 1184, 3667),
Function.raw_ability(361, "Harvest_Return_Mule_quick", raw_cmd, 167, 3667),
Function.raw_ability(154, "Harvest_Return_Probe_quick", raw_cmd, 299, 3667),
Function.raw_ability(362, "Harvest_Return_SCV_quick", raw_cmd, 296, 3667),
Function.raw_ability(17, "HoldPosition_quick", raw_cmd, 3793),
Function.raw_ability(542, "HoldPosition_Battlecruiser_quick", raw_cmd, 3778, 3793),
Function.raw_ability(543, "HoldPosition_Hold_quick", raw_cmd, 18, 3793),
Function.raw_ability(364, "Land_Barracks_pt", raw_cmd_pt, 554, 3678),
Function.raw_ability(365, "Land_CommandCenter_pt", raw_cmd_pt, 419, 3678),
Function.raw_ability(366, "Land_Factory_pt", raw_cmd_pt, 520, 3678),
Function.raw_ability(367, "Land_OrbitalCommand_pt", raw_cmd_pt, 1524, 3678),
Function.raw_ability(363, "Land_pt", raw_cmd_pt, 3678),
Function.raw_ability(368, "Land_Starport_pt", raw_cmd_pt, 522, 3678),
Function.raw_ability(370, "Lift_Barracks_quick", raw_cmd, 452, 3679),
Function.raw_ability(371, "Lift_CommandCenter_quick", raw_cmd, 417, 3679),
Function.raw_ability(372, "Lift_Factory_quick", raw_cmd, 485, 3679),
Function.raw_ability(373, "Lift_OrbitalCommand_quick", raw_cmd, 1522, 3679),
Function.raw_ability(369, "Lift_quick", raw_cmd, 3679),
Function.raw_ability(374, "Lift_Starport_quick", raw_cmd, 518, 3679),
Function.raw_ability(376, "LoadAll_CommandCenter_quick", raw_cmd, 416, 3663),
Function.raw_ability(375, "LoadAll_quick", raw_cmd, 3663),
Function.raw_ability(377, "Load_Bunker_unit", raw_cmd_unit, 407, 3668),
Function.raw_ability(378, "Load_Medivac_unit", raw_cmd_unit, 394, 3668),
Function.raw_ability(379, "Load_NydusNetwork_unit", raw_cmd_unit, 1437, 3668),
Function.raw_ability(380, "Load_NydusWorm_unit", raw_cmd_unit, 2370, 3668),
Function.raw_ability(381, "Load_Overlord_unit", raw_cmd_unit, 1406, 3668),
Function.raw_ability(104, "Load_unit", raw_cmd_unit, 3668),
Function.raw_ability(382, "Load_WarpPrism_unit", raw_cmd_unit, 911, 3668),
Function.raw_ability(86, "Morph_Archon_quick", raw_cmd, 1766),
Function.raw_ability(383, "Morph_BroodLord_quick", raw_cmd, 1372),
Function.raw_ability(78, "Morph_Gateway_quick", raw_cmd, 1520),
Function.raw_ability(384, "Morph_GreaterSpire_quick", raw_cmd, 1220),
Function.raw_ability(385, "Morph_Hellbat_quick", raw_cmd, 1998),
Function.raw_ability(386, "Morph_Hellion_quick", raw_cmd, 1978),
Function.raw_ability(387, "Morph_Hive_quick", raw_cmd, 1218),
Function.raw_ability(388, "Morph_Lair_quick", raw_cmd, 1216),
Function.raw_ability(389, "Morph_LiberatorAAMode_quick", raw_cmd, 2560),
Function.raw_ability(390, "Morph_LiberatorAGMode_pt", raw_cmd_pt, 2558),
Function.raw_ability(392, "Morph_LurkerDen_quick", raw_cmd, 2112),
Function.raw_ability(391, "Morph_Lurker_quick", raw_cmd, 2332),
Function.raw_ability(393, "Morph_Mothership_quick", raw_cmd, 1847),
Function.raw_ability(121, "Morph_ObserverMode_quick", raw_cmd, 3739),
Function.raw_ability(394, "Morph_OrbitalCommand_quick", raw_cmd, 1516),
Function.raw_ability(395, "Morph_OverlordTransport_quick", raw_cmd, 2708),
Function.raw_ability(397, "Morph_OverseerMode_quick", raw_cmd, 3745),
Function.raw_ability(396, "Morph_Overseer_quick", raw_cmd, 1448),
Function.raw_ability(398, "Morph_OversightMode_quick", raw_cmd, 3743),
Function.raw_ability(399, "Morph_PlanetaryFortress_quick", raw_cmd, 1450),
Function.raw_ability(400, "Morph_Ravager_quick", raw_cmd, 2330),
Function.raw_ability(401, "Morph_Root_pt", raw_cmd_pt, 3680),
Function.raw_ability(402, "Morph_SiegeMode_quick", raw_cmd, 388),
Function.raw_ability(403, "Morph_SpineCrawlerRoot_pt", raw_cmd_pt, 1729, 3680),
Function.raw_ability(404, "Morph_SpineCrawlerUproot_quick", raw_cmd, 1725, 3681),
Function.raw_ability(405, "Morph_SporeCrawlerRoot_pt", raw_cmd_pt, 1731, 3680),
Function.raw_ability(406, "Morph_SporeCrawlerUproot_quick", raw_cmd, 1727, 3681),
Function.raw_ability(407, "Morph_SupplyDepot_Lower_quick", raw_cmd, 556),
Function.raw_ability(408, "Morph_SupplyDepot_Raise_quick", raw_cmd, 558),
Function.raw_ability(160, "Morph_SurveillanceMode_quick", raw_cmd, 3741),
Function.raw_ability(409, "Morph_ThorExplosiveMode_quick", raw_cmd, 2364),
Function.raw_ability(410, "Morph_ThorHighImpactMode_quick", raw_cmd, 2362),
Function.raw_ability(411, "Morph_Unsiege_quick", raw_cmd, 390),
Function.raw_ability(412, "Morph_Uproot_quick", raw_cmd, 3681),
Function.raw_ability(413, "Morph_VikingAssaultMode_quick", raw_cmd, 403),
Function.raw_ability(414, "Morph_VikingFighterMode_quick", raw_cmd, 405),
Function.raw_ability(77, "Morph_WarpGate_quick", raw_cmd, 1518),
Function.raw_ability(544, "Morph_WarpGate_autocast", raw_autocast, 1518),
Function.raw_ability(80, "Morph_WarpPrismPhasingMode_quick", raw_cmd, 1528),
Function.raw_ability(81, "Morph_WarpPrismTransportMode_quick", raw_cmd, 1530),
Function.raw_ability(13, "Move_pt", raw_cmd_pt, 3794),
Function.raw_ability(14, "Move_unit", raw_cmd_unit, 3794),
Function.raw_ability(545, "Move_Battlecruiser_pt", raw_cmd_pt, 3776, 3794),
Function.raw_ability(546, "Move_Battlecruiser_unit", raw_cmd_unit, 3776, 3794),
Function.raw_ability(547, "Move_Move_pt", raw_cmd_pt, 16, 3794),
Function.raw_ability(548, "Move_Move_unit", raw_cmd_unit, 16, 3794),
Function.raw_ability(15, "Patrol_pt", raw_cmd_pt, 3795),
Function.raw_ability(16, "Patrol_unit", raw_cmd_unit, 3795),
Function.raw_ability(549, "Patrol_Battlecruiser_pt", raw_cmd_pt, 3777, 3795),
Function.raw_ability(550, "Patrol_Battlecruiser_unit", raw_cmd_unit, 3777, 3795),
Function.raw_ability(551, "Patrol_Patrol_pt", raw_cmd_pt, 17, 3795),
Function.raw_ability(552, "Patrol_Patrol_unit", raw_cmd_unit, 17, 3795),
Function.raw_ability(415, "Rally_Building_pt", raw_cmd_pt, 195, 3673),
Function.raw_ability(416, "Rally_Building_unit", raw_cmd_unit, 195, 3673),
Function.raw_ability(417, "Rally_CommandCenter_pt", raw_cmd_pt, 203, 3690),
Function.raw_ability(418, "Rally_CommandCenter_unit", raw_cmd_unit, 203, 3690),
Function.raw_ability(419, "Rally_Hatchery_Units_pt", raw_cmd_pt, 211, 3673),
Function.raw_ability(420, "Rally_Hatchery_Units_unit", raw_cmd_unit, 211, 3673),
Function.raw_ability(421, "Rally_Hatchery_Workers_pt", raw_cmd_pt, 212, 3690),
Function.raw_ability(422, "Rally_Hatchery_Workers_unit", raw_cmd_unit, 212, 3690),
Function.raw_ability(423, "Rally_Morphing_Unit_pt", raw_cmd_pt, 199, 3673),
Function.raw_ability(424, "Rally_Morphing_Unit_unit", raw_cmd_unit, 199, 3673),
Function.raw_ability(138, "Rally_Nexus_pt", raw_cmd_pt, 207, 3690),
Function.raw_ability(165, "Rally_Nexus_unit", raw_cmd_unit, 207, 3690),
Function.raw_ability(106, "Rally_Units_pt", raw_cmd_pt, 3673),
Function.raw_ability(107, "Rally_Units_unit", raw_cmd_unit, 3673),
Function.raw_ability(114, "Rally_Workers_pt", raw_cmd_pt, 3690),
Function.raw_ability(115, "Rally_Workers_unit", raw_cmd_unit, 3690),
Function.raw_ability(425, "Research_AdaptiveTalons_quick", raw_cmd, 3709),
Function.raw_ability(85, "Research_AdeptResonatingGlaives_quick", raw_cmd, 1594),
Function.raw_ability(426, "Research_AdvancedBallistics_quick", raw_cmd, 805),
Function.raw_ability(553, "Research_AnabolicSynthesis_quick", raw_cmd, 263),
Function.raw_ability(427, "Research_BansheeCloakingField_quick", raw_cmd, 790),
Function.raw_ability(428, "Research_BansheeHyperflightRotors_quick", raw_cmd, 799),
Function.raw_ability(429, "Research_BattlecruiserWeaponRefit_quick", raw_cmd, 1532),
Function.raw_ability(84, "Research_Blink_quick", raw_cmd, 1593),
Function.raw_ability(430, "Research_Burrow_quick", raw_cmd, 1225),
Function.raw_ability(431, "Research_CentrifugalHooks_quick", raw_cmd, 1482),
Function.raw_ability(83, "Research_Charge_quick", raw_cmd, 1592),
Function.raw_ability(432, "Research_ChitinousPlating_quick", raw_cmd, 265),
Function.raw_ability(433, "Research_CombatShield_quick", raw_cmd, 731),
Function.raw_ability(434, "Research_ConcussiveShells_quick", raw_cmd, 732),
Function.raw_ability(554, "Research_CycloneLockOnDamage_quick", raw_cmd, 769),
Function.raw_ability(435, "Research_CycloneRapidFireLaunchers_quick", raw_cmd, 768),
Function.raw_ability(436, "Research_DrillingClaws_quick", raw_cmd, 764),
Function.raw_ability(563, "Research_EnhancedShockwaves_quick", raw_cmd, 822),
Function.raw_ability(69, "Research_ExtendedThermalLance_quick", raw_cmd, 1097),
Function.raw_ability(437, "Research_GlialRegeneration_quick", raw_cmd, 216),
Function.raw_ability(67, "Research_GraviticBooster_quick", raw_cmd, 1093),
Function.raw_ability(68, "Research_GraviticDrive_quick", raw_cmd, 1094),
Function.raw_ability(438, "Research_GroovedSpines_quick", raw_cmd, 1282),
Function.raw_ability(440, "Research_HighCapacityFuelTanks_quick", raw_cmd, 804),
Function.raw_ability(439, "Research_HiSecAutoTracking_quick", raw_cmd, 650),
Function.raw_ability(441, "Research_InfernalPreigniter_quick", raw_cmd, 761),
Function.raw_ability(18, "Research_InterceptorGravitonCatapult_quick", raw_cmd, 44),
Function.raw_ability(442, "Research_MuscularAugments_quick", raw_cmd, 1283),
Function.raw_ability(443, "Research_NeosteelFrame_quick", raw_cmd, 655),
Function.raw_ability(444, "Research_NeuralParasite_quick", raw_cmd, 1455),
Function.raw_ability(445, "Research_PathogenGlands_quick", raw_cmd, 1454),
Function.raw_ability(446, "Research_PersonalCloaking_quick", raw_cmd, 820),
Function.raw_ability(19, "Research_PhoenixAnionPulseCrystals_quick", raw_cmd, 46),
Function.raw_ability(447, "Research_PneumatizedCarapace_quick", raw_cmd, 1223),
Function.raw_ability(139, "Research_ProtossAirArmorLevel1_quick", raw_cmd, 1565, 3692),
Function.raw_ability(140, "Research_ProtossAirArmorLevel2_quick", raw_cmd, 1566, 3692),
Function.raw_ability(141, "Research_ProtossAirArmorLevel3_quick", raw_cmd, 1567, 3692),
Function.raw_ability(116, "Research_ProtossAirArmor_quick", raw_cmd, 3692),
Function.raw_ability(142, "Research_ProtossAirWeaponsLevel1_quick", raw_cmd, 1562, 3693),
Function.raw_ability(143, "Research_ProtossAirWeaponsLevel2_quick", raw_cmd, 1563, 3693),
Function.raw_ability(144, "Research_ProtossAirWeaponsLevel3_quick", raw_cmd, 1564, 3693),
Function.raw_ability(117, "Research_ProtossAirWeapons_quick", raw_cmd, 3693),
Function.raw_ability(145, "Research_ProtossGroundArmorLevel1_quick", raw_cmd, 1065, 3694),
Function.raw_ability(146, "Research_ProtossGroundArmorLevel2_quick", raw_cmd, 1066, 3694),
Function.raw_ability(147, "Research_ProtossGroundArmorLevel3_quick", raw_cmd, 1067, 3694),
Function.raw_ability(118, "Research_ProtossGroundArmor_quick", raw_cmd, 3694),
Function.raw_ability(148, "Research_ProtossGroundWeaponsLevel1_quick", raw_cmd, 1062, 3695),
Function.raw_ability(149, "Research_ProtossGroundWeaponsLevel2_quick", raw_cmd, 1063, 3695),
Function.raw_ability(150, "Research_ProtossGroundWeaponsLevel3_quick", raw_cmd, 1064, 3695),
Function.raw_ability(119, "Research_ProtossGroundWeapons_quick", raw_cmd, 3695),
Function.raw_ability(151, "Research_ProtossShieldsLevel1_quick", raw_cmd, 1068, 3696),
Function.raw_ability(152, "Research_ProtossShieldsLevel2_quick", raw_cmd, 1069, 3696),
Function.raw_ability(153, "Research_ProtossShieldsLevel3_quick", raw_cmd, 1070, 3696),
Function.raw_ability(120, "Research_ProtossShields_quick", raw_cmd, 3696),
Function.raw_ability(70, "Research_PsiStorm_quick", raw_cmd, 1126),
Function.raw_ability(448, "Research_RavenCorvidReactor_quick", raw_cmd, 793),
Function.raw_ability(449, "Research_RavenRecalibratedExplosives_quick", raw_cmd, 803),
Function.raw_ability(97, "Research_ShadowStrike_quick", raw_cmd, 2720),
Function.raw_ability(450, "Research_SmartServos_quick", raw_cmd, 766),
Function.raw_ability(451, "Research_Stimpack_quick", raw_cmd, 730),
Function.raw_ability(453, "Research_TerranInfantryArmorLevel1_quick", raw_cmd, 656, 3697),
Function.raw_ability(454, "Research_TerranInfantryArmorLevel2_quick", raw_cmd, 657, 3697),
Function.raw_ability(455, "Research_TerranInfantryArmorLevel3_quick", raw_cmd, 658, 3697),
Function.raw_ability(452, "Research_TerranInfantryArmor_quick", raw_cmd, 3697),
Function.raw_ability(457, "Research_TerranInfantryWeaponsLevel1_quick", raw_cmd, 652, 3698),
Function.raw_ability(458, "Research_TerranInfantryWeaponsLevel2_quick", raw_cmd, 653, 3698),
Function.raw_ability(459, "Research_TerranInfantryWeaponsLevel3_quick", raw_cmd, 654, 3698),
Function.raw_ability(456, "Research_TerranInfantryWeapons_quick", raw_cmd, 3698),
Function.raw_ability(461, "Research_TerranShipWeaponsLevel1_quick", raw_cmd, 861, 3699),
Function.raw_ability(462, "Research_TerranShipWeaponsLevel2_quick", raw_cmd, 862, 3699),
Function.raw_ability(463, "Research_TerranShipWeaponsLevel3_quick", raw_cmd, 863, 3699),
Function.raw_ability(460, "Research_TerranShipWeapons_quick", raw_cmd, 3699),
Function.raw_ability(464, "Research_TerranStructureArmorUpgrade_quick", raw_cmd, 651),
Function.raw_ability(466, "Research_TerranVehicleAndShipPlatingLevel1_quick", raw_cmd, 864, 3700),
Function.raw_ability(467, "Research_TerranVehicleAndShipPlatingLevel2_quick", raw_cmd, 865, 3700),
Function.raw_ability(468, "Research_TerranVehicleAndShipPlatingLevel3_quick", raw_cmd, 866, 3700),
Function.raw_ability(465, "Research_TerranVehicleAndShipPlating_quick", raw_cmd, 3700),
Function.raw_ability(470, "Research_TerranVehicleWeaponsLevel1_quick", raw_cmd, 855, 3701),
Function.raw_ability(471, "Research_TerranVehicleWeaponsLevel2_quick", raw_cmd, 856, 3701),
Function.raw_ability(472, "Research_TerranVehicleWeaponsLevel3_quick", raw_cmd, 857, 3701),
Function.raw_ability(469, "Research_TerranVehicleWeapons_quick", raw_cmd, 3701),
Function.raw_ability(473, "Research_TunnelingClaws_quick", raw_cmd, 217),
Function.raw_ability(82, "Research_WarpGate_quick", raw_cmd, 1568),
Function.raw_ability(475, "Research_ZergFlyerArmorLevel1_quick", raw_cmd, 1315, 3702),
Function.raw_ability(476, "Research_ZergFlyerArmorLevel2_quick", raw_cmd, 1316, 3702),
Function.raw_ability(477, "Research_ZergFlyerArmorLevel3_quick", raw_cmd, 1317, 3702),
Function.raw_ability(474, "Research_ZergFlyerArmor_quick", raw_cmd, 3702),
Function.raw_ability(479, "Research_ZergFlyerAttackLevel1_quick", raw_cmd, 1312, 3703),
Function.raw_ability(480, "Research_ZergFlyerAttackLevel2_quick", raw_cmd, 1313, 3703),
Function.raw_ability(481, "Research_ZergFlyerAttackLevel3_quick", raw_cmd, 1314, 3703),
Function.raw_ability(478, "Research_ZergFlyerAttack_quick", raw_cmd, 3703),
Function.raw_ability(483, "Research_ZergGroundArmorLevel1_quick", raw_cmd, 1189, 3704),
Function.raw_ability(484, "Research_ZergGroundArmorLevel2_quick", raw_cmd, 1190, 3704),
Function.raw_ability(485, "Research_ZergGroundArmorLevel3_quick", raw_cmd, 1191, 3704),
Function.raw_ability(482, "Research_ZergGroundArmor_quick", raw_cmd, 3704),
Function.raw_ability(494, "Research_ZerglingAdrenalGlands_quick", raw_cmd, 1252),
Function.raw_ability(495, "Research_ZerglingMetabolicBoost_quick", raw_cmd, 1253),
Function.raw_ability(487, "Research_ZergMeleeWeaponsLevel1_quick", raw_cmd, 1186, 3705),
Function.raw_ability(488, "Research_ZergMeleeWeaponsLevel2_quick", raw_cmd, 1187, 3705),
Function.raw_ability(489, "Research_ZergMeleeWeaponsLevel3_quick", raw_cmd, 1188, 3705),
Function.raw_ability(486, "Research_ZergMeleeWeapons_quick", raw_cmd, 3705),
Function.raw_ability(491, "Research_ZergMissileWeaponsLevel1_quick", raw_cmd, 1192, 3706),
Function.raw_ability(492, "Research_ZergMissileWeaponsLevel2_quick", raw_cmd, 1193, 3706),
Function.raw_ability(493, "Research_ZergMissileWeaponsLevel3_quick", raw_cmd, 1194, 3706),
Function.raw_ability(490, "Research_ZergMissileWeapons_quick", raw_cmd, 3706),
Function.raw_ability(10, "Scan_Move_pt", raw_cmd_pt, 19, 3674),
Function.raw_ability(11, "Scan_Move_unit", raw_cmd_unit, 19, 3674),
Function.raw_ability(1, "Smart_pt", raw_cmd_pt, 1),
Function.raw_ability(12, "Smart_unit", raw_cmd_unit, 1),
Function.raw_ability(101, "Stop_quick", raw_cmd, 3665),
Function.raw_ability(555, "Stop_Battlecruiser_quick", raw_cmd, 3783, 3665),
Function.raw_ability(496, "Stop_Building_quick", raw_cmd, 2057, 3665),
Function.raw_ability(497, "Stop_Redirect_quick", raw_cmd, 1691, 3665),
Function.raw_ability(155, "Stop_Stop_quick", raw_cmd, 4, 3665),
Function.raw_ability(54, "Train_Adept_quick", raw_cmd, 922),
Function.raw_ability(498, "Train_Baneling_quick", raw_cmd, 80),
Function.raw_ability(499, "Train_Banshee_quick", raw_cmd, 621),
Function.raw_ability(500, "Train_Battlecruiser_quick", raw_cmd, 623),
Function.raw_ability(56, "Train_Carrier_quick", raw_cmd, 948),
Function.raw_ability(62, "Train_Colossus_quick", raw_cmd, 978),
Function.raw_ability(501, "Train_Corruptor_quick", raw_cmd, 1353),
Function.raw_ability(502, "Train_Cyclone_quick", raw_cmd, 597),
Function.raw_ability(52, "Train_DarkTemplar_quick", raw_cmd, 920),
Function.raw_ability(166, "Train_Disruptor_quick", raw_cmd, 994),
Function.raw_ability(503, "Train_Drone_quick", raw_cmd, 1342),
Function.raw_ability(504, "Train_Ghost_quick", raw_cmd, 562),
Function.raw_ability(505, "Train_Hellbat_quick", raw_cmd, 596),
Function.raw_ability(506, "Train_Hellion_quick", raw_cmd, 595),
Function.raw_ability(51, "Train_HighTemplar_quick", raw_cmd, 919),
Function.raw_ability(507, "Train_Hydralisk_quick", raw_cmd, 1345),
Function.raw_ability(63, "Train_Immortal_quick", raw_cmd, 979),
Function.raw_ability(508, "Train_Infestor_quick", raw_cmd, 1352),
Function.raw_ability(509, "Train_Liberator_quick", raw_cmd, 626),
Function.raw_ability(510, "Train_Marauder_quick", raw_cmd, 563),
Function.raw_ability(511, "Train_Marine_quick", raw_cmd, 560),
Function.raw_ability(512, "Train_Medivac_quick", raw_cmd, 620),
Function.raw_ability(513, "Train_MothershipCore_quick", raw_cmd, 1853),
Function.raw_ability(21, "Train_Mothership_quick", raw_cmd, 110),
Function.raw_ability(514, "Train_Mutalisk_quick", raw_cmd, 1346),
Function.raw_ability(61, "Train_Observer_quick", raw_cmd, 977),
Function.raw_ability(58, "Train_Oracle_quick", raw_cmd, 954),
Function.raw_ability(515, "Train_Overlord_quick", raw_cmd, 1344),
Function.raw_ability(55, "Train_Phoenix_quick", raw_cmd, 946),
Function.raw_ability(64, "Train_Probe_quick", raw_cmd, 1006),
Function.raw_ability(516, "Train_Queen_quick", raw_cmd, 1632),
Function.raw_ability(517, "Train_Raven_quick", raw_cmd, 622),
Function.raw_ability(518, "Train_Reaper_quick", raw_cmd, 561),
Function.raw_ability(519, "Train_Roach_quick", raw_cmd, 1351),
Function.raw_ability(520, "Train_SCV_quick", raw_cmd, 524),
Function.raw_ability(53, "Train_Sentry_quick", raw_cmd, 921),
Function.raw_ability(521, "Train_SiegeTank_quick", raw_cmd, 591),
Function.raw_ability(50, "Train_Stalker_quick", raw_cmd, 917),
Function.raw_ability(522, "Train_SwarmHost_quick", raw_cmd, 1356),
Function.raw_ability(59, "Train_Tempest_quick", raw_cmd, 955),
Function.raw_ability(523, "Train_Thor_quick", raw_cmd, 594),
Function.raw_ability(524, "Train_Ultralisk_quick", raw_cmd, 1348),
Function.raw_ability(525, "Train_VikingFighter_quick", raw_cmd, 624),
Function.raw_ability(526, "Train_Viper_quick", raw_cmd, 1354),
Function.raw_ability(57, "Train_VoidRay_quick", raw_cmd, 950),
Function.raw_ability(76, "TrainWarp_Adept_pt", raw_cmd_pt, 1419),
Function.raw_ability(74, "TrainWarp_DarkTemplar_pt", raw_cmd_pt, 1417),
Function.raw_ability(73, "TrainWarp_HighTemplar_pt", raw_cmd_pt, 1416),
Function.raw_ability(60, "Train_WarpPrism_quick", raw_cmd, 976),
Function.raw_ability(75, "TrainWarp_Sentry_pt", raw_cmd_pt, 1418),
Function.raw_ability(72, "TrainWarp_Stalker_pt", raw_cmd_pt, 1414),
Function.raw_ability(71, "TrainWarp_Zealot_pt", raw_cmd_pt, 1413),
Function.raw_ability(527, "Train_WidowMine_quick", raw_cmd, 614),
Function.raw_ability(49, "Train_Zealot_quick", raw_cmd, 916),
Function.raw_ability(528, "Train_Zergling_quick", raw_cmd, 1343),
Function.raw_ability(529, "UnloadAllAt_Medivac_pt", raw_cmd_pt, 396, 3669),
Function.raw_ability(530, "UnloadAllAt_Medivac_unit", raw_cmd_unit, 396, 3669),
Function.raw_ability(531, "UnloadAllAt_Overlord_pt", raw_cmd_pt, 1408, 3669),
Function.raw_ability(532, "UnloadAllAt_Overlord_unit", raw_cmd_unit, 1408, 3669),
Function.raw_ability(105, "UnloadAllAt_pt", raw_cmd_pt, 3669),
Function.raw_ability(164, "UnloadAllAt_unit", raw_cmd_unit, 3669),
Function.raw_ability(156, "UnloadAllAt_WarpPrism_pt", raw_cmd_pt, 913, 3669),
Function.raw_ability(163, "UnloadAllAt_WarpPrism_unit", raw_cmd_unit, 913, 3669),
Function.raw_ability(533, "UnloadAll_Bunker_quick", raw_cmd, 408, 3664),
Function.raw_ability(534, "UnloadAll_CommandCenter_quick", raw_cmd, 413, 3664),
Function.raw_ability(535, "UnloadAll_NydusNetwork_quick", raw_cmd, 1438, 3664),
Function.raw_ability(536, "UnloadAll_NydusWorm_quick", raw_cmd, 2371, 3664),
Function.raw_ability(100, "UnloadAll_quick", raw_cmd, 3664),
Function.raw_ability(556, "UnloadUnit_quick", raw_cmd, 3796),
Function.raw_ability(557, "UnloadUnit_Bunker_quick", raw_cmd, 410, 3796),
Function.raw_ability(558, "UnloadUnit_CommandCenter_quick", raw_cmd, 415, 3796),
Function.raw_ability(559, "UnloadUnit_Medivac_quick", raw_cmd, 397, 3796),
Function.raw_ability(560, "UnloadUnit_NydusNetwork_quick", raw_cmd, 1440, 3796),
Function.raw_ability(561, "UnloadUnit_Overlord_quick", raw_cmd, 1409, 3796),
Function.raw_ability(562, "UnloadUnit_WarpPrism_quick", raw_cmd, 914, 3796),
]
# pylint: enable=line-too-long
# Create an IntEnum of the function names/ids so that printing the id will
# show something useful.
_Raw_Functions = enum.IntEnum( # pylint: disable=invalid-name
"_Raw_Functions", {f.name: f.id for f in _RAW_FUNCTIONS})
_RAW_FUNCTIONS = [f._replace(id=_Raw_Functions(f.id)) for f in _RAW_FUNCTIONS]
RAW_FUNCTIONS = Functions(_RAW_FUNCTIONS)
# Some indexes to support features.py and action conversion.
RAW_ABILITY_IDS = collections.defaultdict(set) # {ability_id: {funcs}}
for _func in RAW_FUNCTIONS:
if _func.ability_id >= 0:
RAW_ABILITY_IDS[_func.ability_id].add(_func)
RAW_ABILITY_IDS = {k: frozenset(v) for k, v in six.iteritems(RAW_ABILITY_IDS)}
RAW_FUNCTIONS_AVAILABLE = {f.id: f for f in RAW_FUNCTIONS if f.avail_fn}
RAW_ABILITY_ID_TO_FUNC_ID = {k: min(f.id for f in v) # pylint: disable=g-complex-comprehension
for k, v in six.iteritems(RAW_ABILITY_IDS)}
class FunctionCall(collections.namedtuple(
"FunctionCall", ["function", "arguments"])):
"""Represents a function call action.
Attributes:
function: Store the function id, eg 2 for select_point.
arguments: The list of arguments for that function, each being a list of
ints. For select_point this could be: [[0], [23, 38]].
"""
__slots__ = ()
@classmethod
def init_with_validation(cls, function, arguments, raw=False):
"""Return a `FunctionCall` given some validation for the function and args.
Args:
function: A function name or id, to be converted into a function id enum.
arguments: An iterable of function arguments. Arguments that are enum
types can be passed by name. Arguments that only take one value (ie
not a point) don't need to be wrapped in a list.
raw: Whether this is a raw function call.
Returns:
A new `FunctionCall` instance.
Raises:
KeyError: if the enum name doesn't exist.
ValueError: if the enum id doesn't exist.
"""
func = RAW_FUNCTIONS[function] if raw else FUNCTIONS[function]
args = []
for arg, arg_type in zip(arguments, func.args):
arg = numpy_to_python(arg)
if arg_type.values: # Allow enum values by name or int.
if isinstance(arg, six.string_types):
try:
args.append([arg_type.values[arg]])
except KeyError:
raise KeyError("Unknown argument value: %s, valid values: %s" % (
arg, [v.name for v in arg_type.values]))
else:
if isinstance(arg, list):
arg = arg[0]
try:
args.append([arg_type.values(arg)])
except ValueError:
raise ValueError("Unknown argument value: %s, valid values: %s" % (
arg, list(arg_type.values)))
elif isinstance(arg, int): # Allow bare ints.
args.append([arg])
elif isinstance(arg, list):
args.append(arg)
else:
raise ValueError(
"Unknown argument value type: %s, expected int or list of ints, or "
"their numpy equivalents. Value: %s" % (type(arg), arg))
return cls(func.id, args)
@classmethod
def all_arguments(cls, function, arguments, raw=False):
"""Helper function for creating `FunctionCall`s with `Arguments`.
Args:
function: The value to store for the action function.
arguments: The values to store for the arguments of the action. Can either
be an `Arguments` object, a `dict`, or an iterable. If a `dict` or an
iterable is provided, the values will be unpacked into an `Arguments`
object.
raw: Whether this is a raw function call.
Returns:
A new `FunctionCall` instance.
"""
args_type = RawArguments if raw else Arguments
if isinstance(arguments, dict):
arguments = args_type(**arguments)
elif not isinstance(arguments, args_type):
arguments = args_type(*arguments)
return cls(function, arguments)
def __reduce__(self):
return self.__class__, tuple(self)
class ValidActions(collections.namedtuple(
"ValidActions", ["types", "functions"])):
"""The set of types and functions that are valid for an agent to use.
Attributes:
types: A namedtuple of the types that the functions require. Unlike TYPES
above, this includes the sizes for screen and minimap.
functions: A namedtuple of all the functions.
"""
__slots__ = ()
def __reduce__(self):
return self.__class__, tuple(self)
| [
"[email protected]"
]
| |
faf352b930625907a784008bebc86e45147b6b82 | 0ca21d1d60bb9dbe70fb55b7ebace0510695d489 | /examples/youtube_banner.py | 5c280f0137305a832cf9912b4b0e9c0d10e8f3f5 | [
"Apache-2.0"
]
| permissive | colinmford/coldtype | fa5cc65ac318ee22138857ea60d964ca4ecb8267 | 8462dbd5f65f3ef8f3cbc8662a866b7e20ec5985 | refs/heads/main | 2023-07-02T12:34:18.700566 | 2021-08-06T03:40:21 | 2021-08-06T03:40:21 | 393,237,997 | 0 | 0 | Apache-2.0 | 2021-08-06T03:35:41 | 2021-08-06T03:35:40 | null | UTF-8 | Python | false | false | 534 | py | from coldtype import *
from coldtype.fx.skia import phototype
obv = Font.Cacheable("assets/ColdtypeObviously-VF.ttf")
logos = raw_ufo("assets/logos.ufo")
@renderable((2048, 1152))
def banner(r):
return (DATPens([
DATPen().rect(r).f(hsl(0.65)),
(StyledString("COLDTYPE",
Style(obv, 300, wdth=1, tu=-90, r=1, rotate=-10))
.pens()
.f(1)
.understroke(sw=35)
.align(r)
.translate(0, 5)
.ch(phototype(r, blur=5, cut=200, cutw=10)))])) | [
"[email protected]"
]
| |
b0b33db89eb9adc6024895b5acb3afee09f7ccec | 3bbdcdfa6ee6631bea52dd651914cb898062b870 | /base_standard_profiler/cprofile_basemark4.py | d2538ef458d9e697088f2c64b1f273964a85926a | []
| no_license | xiaoyeren/python_high_performance | 55ea5ee9f628e1c1155a6946274c862bda57ae2c | 496a5e55e7f40033c80e9ee3b9190c184d4701d9 | refs/heads/master | 2020-05-24T15:20:00.576786 | 2019-05-13T06:01:35 | 2019-05-13T06:01:35 | 187,329,222 | 1 | 0 | null | 2019-05-18T07:43:11 | 2019-05-18T07:43:11 | null | UTF-8 | Python | false | false | 1,653 | py | # -*- coding: utf-8 -*-
'''
Created on 2019年4月8日 下午9:21:00
Zhukun Luo
Jiangxi University of Finance and Economics
'''
#memory profiler
from app import ParticleSimulator,particle
from random import uniform
from memory_profiler import profile
import sys
def test_evolve():
particles=[particle(0.3,0.5,1),particle(0.0,-0.5,-1),particle(-0.1,-0.4,3)]
simulator=ParticleSimulator(particles)
simulator.evolve(0.1)
p0,p1,p2=particles
def fequal(a,b,eps=1e-5):
return abs(a-b)<eps
assert fequal(p0.x, 0.210269,eps=1e-5)
assert fequal(p0.y,0.543863,eps=1e-5)
assert fequal(p1.x, -0.099334)
assert fequal(p1.y,-0.490034)
assert fequal(p2.x, 0.191358)
assert fequal(p2.y, -0.365227)
@profile
def benchmark():
particles=[particle(uniform(-1.0,1.0),uniform(-1.0,1.0),uniform(-1.0,1.0)) for i in range(1000)]#生成1000个随机测试用例
simulator=ParticleSimulator(particles)
simulator.evolve(0.1)
if __name__ == "__main__":
# test_evolve()
benchmark()
'''
Filename: /home/agnostic/git/python_high_performance/base_standard_profiler/cprofile_basemark4.py
Line # Mem usage Increment Line Contents
================================================
26 70.3 MiB 70.3 MiB @profile
27 def benchmark():
28 70.4 MiB 0.2 MiB particles=[particle(uniform(-1.0,1.0),uniform(-1.0,1.0),uniform(-1.0,1.0)) for i in range(1000)]#生成1000个随机测试用例
29 70.4 MiB 0.0 MiB simulator=ParticleSimulator(particles)
30 70.4 MiB 0.0 MiB simulator.evolve(0.1)
'''
| [
"[email protected]"
]
| |
afb1396453b05ec538e23fc9b5de341ed7ce174a | 6bd4eff3c0ca5b2dd575dbee2b0a02a898f642d6 | /爬虫代码/selenium_study/5.py | c2a473f4c6da7b44b74892a34249d1757934f0aa | []
| no_license | marvinlizhaorui/youshu | 620a9820c6bb4b4729b9a1cbccf4d426afde110e | bf62387ffe564668681b8a514b98d539b7290b4c | refs/heads/master | 2020-04-09T07:39:27.525808 | 2018-09-27T13:05:40 | 2018-09-27T13:05:40 | 160,164,943 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,717 | py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Created on 2018/7/6 17:32
# Project:
# @Author: ZQJ
# @Email : [email protected]
#延时等待
#在selenium中,get()方法会在网页框架加载结束后结束执行,此时如果获取page-source,可能并不是浏览器完全加载完成的页面
#如果某些页面有额外的Ajax请求,我们在网页源代码中也不一定能获取的到,所以这里需要延时等待一段时间,确保节点已经加载出来了
from selenium import webdriver
#隐式等待
#如果selenium没有在DOM中找到节点,将继续等待,等一会再找,超过设定时间后,则抛出找不到节点的异常,默认时间是0
browser = webdriver.Chrome()
browser.implicitly_wait(10)#隐式等待10秒
browser.get('https://www.zhihu.com/explore')
inputs = browser.find_element_by_class_name('zu-top-add-question')
print(inputs)
browser.close()
#显式等待
#指定要查找的节点,然后指定一个最长的等待时间,如果在规定时间内加载出了这个节点,就返回查找的节点,没有就异常
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
browser = webdriver.Chrome()
browser.get('https://www.taobao.com/')
wait = WebDriverWait(browser,10)
inputs = wait.until(EC.presence_of_all_elements_located((By.ID,'q')))
button = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'.btn-search')))
print(inputs,button)
#关于等待条件,还有很多,比如判断标题内容,判断某个节点是否出现了某文字等。p259表格 | [
"[email protected]"
]
| |
2404ebd5a62590faa092657e82cf1301d404f999 | 8db1b9528ace3ce142ea52da1017eb6359f46967 | /py1811/company/employees.py | 558c8b144ea76cb40a9f65e4fb51a1eb1e7a5345 | []
| no_license | ul8ksgdmy/myPythonlearning | 01fbd49d227e2b3095250e7ee40768fa3179f26e | 2ad0d3525cd505edba3fd37e21f601a32872259b | refs/heads/master | 2020-03-31T14:33:13.448891 | 2019-01-09T18:13:26 | 2019-01-09T18:13:26 | 152,299,859 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,594 | py | class Staff:
def __init__(self, empid, name, deptname, gender, tech, age):
self.__empid = empid
self.__name = name
self.__deptname = deptname
self.__gender = gender
self.__tech = tech
self.__age = age
@property
def empid(self):
return self.__empid
@empid.setter
def empid(self, value):
self.__empid = value
@property
def name(self):
return self.__name
@name.setter
def name(self, value):
self.__name = value
@property
def deptname(self):
return self.__deptname
@deptname.setter
def deptname(self, value):
self.__deptname = value
@property
def gender(self):
return self.__gender
@gender.setter
def gender(self, value):
self.__gender = value
@property
def tech(self):
return self.__tech
@tech.setter
def tech(self, value):
self.__tech = value
@property
def age(self):
return self.__age
@age.setter
def age(self, value):
self.__age = value
def __str__(self):
msg = '%s %s %s %s %s %s' % (self.__empid, self.__name, self.__deptname, self.__gender, self.__tech, self.__age)
def printbio(self):
if self.__gender == 'M':
print('%s 직원은 나이가 %s이고, 성별은 남자입니다' % (self.__name, self.age))
else:
print('%s 직원은 나이가 %s이고, 성별은 여자입니다' % (self.__name, self.age))
e = Staff('3', 'Ernie', 'Sales', 'M', 'UNIX, Perl', '23')
e.printbio()
| [
"[email protected]"
]
| |
330fb2705418d5d76c2cb489ed4a712959581740 | c2ce7155a393e1056b5fdc4d3f9b9a89046e9285 | /examples/plugins/fbnet/fbnet_plugin.py | 647616419ce7ed2476b8225eb2999e0bbd972265 | [
"MIT"
]
| permissive | blyucs/aw_nas | 9c068dab1bd84a35e58a4c426f7c852a67b93882 | 8a32196ce342b8ad9e3885895735d1286e25beba | refs/heads/master | 2023-08-19T11:00:00.526229 | 2021-08-21T05:16:13 | 2021-08-21T05:16:13 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,531 | py | import os
import math
import torch
import torch.nn as nn
import torch.optim.lr_scheduler
from torch.optim.lr_scheduler import _LRScheduler
from aw_nas import AwnasPlugin
from aw_nas.objective import BaseObjective
from aw_nas.weights_manager.diff_super_net import DiffSuperNet
from aw_nas.utils.torch_utils import accuracy
from aw_nas.ops import register_primitive
def weights_init(m, deepth=0, max_depth=2):
if deepth > max_depth:
return
if isinstance(m, torch.nn.Conv2d):
torch.nn.init.kaiming_uniform_(m.weight.data)
if m.bias is not None:
torch.nn.init.constant_(m.bias.data, 0)
elif isinstance(m, torch.nn.Linear):
m.weight.data.normal_(0, 0.01)
if m.bias is not None:
m.bias.data.zero_()
elif isinstance(m, torch.nn.BatchNorm2d):
return
elif isinstance(m, torch.nn.ReLU):
return
elif isinstance(m, torch.nn.Module):
deepth += 1
for m_ in m.modules():
weights_init(m_, deepth)
else:
raise ValueError("%s is unk" % m.__class__.__name__)
class WeightInitDiffSuperNet(DiffSuperNet):
NAME = "fb_diff_supernet"
def __init__(self, *args, **kwargs):
super(WeightInitDiffSuperNet, self).__init__(*args, **kwargs)
self.apply(weights_init)
class FBNetBlock(nn.Module):
def __init__(self, C_in, C_out, kernel_size, stride, expansion, bn=True):
super(FBNetBlock, self).__init__()
# assert not bn, "not support bn for now"
bias_flag = not bn
if kernel_size == 1:
padding = 0
elif kernel_size == 3:
padding = 1
elif kernel_size == 5:
padding = 2
elif kernel_size == 7:
padding = 3
else:
raise ValueError("Not supported kernel_size %d" % kernel_size)
inner_dim = int(C_in * expansion)
self.opa = nn.Sequential(
nn.Conv2d(C_in, inner_dim, 1, stride=1, padding=0, bias=bias_flag),
nn.BatchNorm2d(inner_dim),
nn.ReLU(inplace=False),
nn.Conv2d(inner_dim, inner_dim, kernel_size, stride=stride,
padding=padding, bias=bias_flag),
nn.BatchNorm2d(inner_dim),
nn.ReLU(inplace=False),
nn.Conv2d(inner_dim, C_out, 1, stride=1, padding=0, bias=bias_flag),
nn.BatchNorm2d(C_out),
)
self.opb = nn.Sequential(
nn.Conv2d(C_in, C_in, kernel_size, stride=stride, padding=padding, bias=bias_flag),
nn.BatchNorm2d(C_in),
nn.ReLU(inplace=False),
nn.Conv2d(C_in, C_out, 1, stride=1, padding=0, bias=bias_flag),
nn.BatchNorm2d(C_out),
)
self.relus = nn.ReLU(inplace=False)
def forward(self, x):
a = self.opa(x)
b = self.opb(x)
return self.relus(a + b)
def block_0(C_in, C_out, stride, affine):
return FBNetBlock(C_in, C_out, 3, stride, 1)
def block_1(C_in, C_out, stride, affine):
return FBNetBlock(C_in, C_out, 5, stride, 1)
def block_2(C_in, C_out, stride, affine):
return FBNetBlock(C_in, C_out, 7, stride, 1)
def block_3(C_in, C_out, stride, affine):
return FBNetBlock(C_in, C_out, 3, stride, 1./2)
def block_4(C_in, C_out, stride, affine):
return FBNetBlock(C_in, C_out, 5, stride, 1./2)
def block_5(C_in, C_out, stride, affine):
return FBNetBlock(C_in, C_out, 7, stride, 1./2)
def block_6(C_in, C_out, stride, affine):
return FBNetBlock(C_in, C_out, 3, stride, 1./4)
def block_7(C_in, C_out, stride, affine):
return FBNetBlock(C_in, C_out, 5, stride, 1./4)
def block_8(C_in, C_out, stride, affine):
return FBNetBlock(C_in, C_out, 7, stride, 1./4)
register_primitive("block_0", block_0)
register_primitive("block_1", block_1)
register_primitive("block_2", block_2)
register_primitive("block_3", block_3)
register_primitive("block_4", block_4)
register_primitive("block_5", block_5)
register_primitive("block_6", block_6)
register_primitive("block_7", block_7)
register_primitive("block_8", block_8)
class CosineDecayLR(_LRScheduler):
def __init__(self, optimizer, T_max, alpha=1e-4,
t_mul=2, lr_mul=0.9,
last_epoch=-1,
warmup_step=300,
logger=None):
self.T_max = T_max
self.alpha = alpha
self.t_mul = t_mul
self.lr_mul = lr_mul
self.warmup_step = warmup_step
self.logger = logger
self.last_restart_step = 0
self.flag = True
super(CosineDecayLR, self).__init__(optimizer, last_epoch)
self.min_lrs = [b_lr * alpha for b_lr in self.base_lrs]
self.rise_lrs = [1.0 * (b - m) / self.warmup_step
for (b, m) in zip(self.base_lrs, self.min_lrs)]
def get_lr(self):
T_cur = self.last_epoch - self.last_restart_step
assert T_cur >= 0
if T_cur <= self.warmup_step and (not self.flag):
base_lrs = [min_lr + rise_lr * T_cur
for (base_lr, min_lr, rise_lr) in
zip(self.base_lrs, self.min_lrs, self.rise_lrs)]
if T_cur == self.warmup_step:
self.last_restart_step = self.last_epoch
self.flag = True
else:
base_lrs = [self.alpha + (base_lr - self.alpha) *
(1 + math.cos(math.pi * self.last_epoch / self.T_max)) / 2
for base_lr in self.base_lrs]
if T_cur == self.T_max:
self.last_restart_step = self.last_epoch
self.min_lrs = [b_lr * self.alpha for b_lr in self.base_lrs]
self.base_lrs = [b_lr * self.lr_mul for b_lr in self.base_lrs]
self.rise_lrs = [1.0 * (b - m) / self.warmup_step
for (b, m) in zip(self.base_lrs, self.min_lrs)]
self.T_max = int(self.T_max * self.t_mul)
self.flag = False
return base_lrs
torch.optim.lr_scheduler.CosineDecayLR = CosineDecayLR
class LatencyObjective(BaseObjective):
NAME = "latency"
def __init__(self, search_space, alpha=0.2, beta=0.6, lamb=None, latency_file="speed.txt"):
super(LatencyObjective, self).__init__(search_space)
assert os.path.exists(latency_file)
self.alpha = alpha
self.beta = beta
self.lamb = lamb # TODO: find this coeff when using discrete rollout
with open(latency_file, "r") as f:
lat_lines = f.readlines()
self.latency_lut = []
for lat_line in lat_lines:
lat_line = lat_line.rstrip()
self.latency_lut.append([float(x) for x in lat_line.split()])
self._min_lat = sum([min(lat) for lat in self.latency_lut])
self._max_lat = sum([max(lat) for lat in self.latency_lut])
self.logger.info("Min possible latency: %.3f; Max possible latency: %.3f",
self._min_lat, self._max_lat)
@classmethod
def supported_data_types(cls):
return ["image"]
def perf_names(self):
return ["acc", "mean_latency"]
def get_perfs(self, inputs, outputs, targets, cand_net):
acc = float(accuracy(outputs, targets)[0]) / 100
total_latency = 0.
ss = self.search_space
if cand_net.super_net.rollout_type == "discrete":
for i_layer, geno in enumerate(cand_net.genotypes):
prim = geno[0][0]
prims = ss.cell_shared_primitives[ss.cell_layout[i_layer]]
total_latency += float(self.latency_lut[i_layer][prims.index(prim)])
else:
for i_layer, arch in enumerate(cand_net.arch):
latency = (arch[0] * \
torch.Tensor(self.latency_lut[i_layer]).to(arch.device)).sum().item()
if arch[0].ndimension() == 2:
latency /= arch[0].shape[0]
total_latency += latency
return [acc, total_latency]
def get_reward(self, inputs, outputs, targets, cand_net):
acc = float(accuracy(outputs, targets)[0]) / 100
if self.lamb is not None:
latency_penalty = 0.
ss = self.search_space
for i_layer, geno in enumerate(cand_net.genotypes):
prim = geno[0][0]
prims = ss.cell_shared_primitives[ss.cell_layout[i_layer]]
latency_penalty += float(self.latency_lut[i_layer][prims.index(prim)])
# return acc + float(self.lamb) / (latency_penalty - self._min_lat + 1.)
return acc + float(self.lamb) * (1. / latency_penalty - 1. / self._max_lat)
return acc
def get_loss(self, inputs, outputs, targets, cand_net,
add_controller_regularization=True, add_evaluator_regularization=True):
loss = nn.CrossEntropyLoss()(outputs, targets)
if add_controller_regularization:
# differentiable rollout
latency_loss = 0.
for i_layer, arch in enumerate(cand_net.arch):
latency = (arch[0] * \
torch.Tensor(self.latency_lut[i_layer]).to(arch.device)).sum()
if arch[0].ndimension() == 2:
latency = latency / arch[0].shape[0]
latency_loss += latency
loss = loss + self.alpha * (latency_loss).pow(self.beta)
return loss
class FBNetPlugin(AwnasPlugin):
NAME = "fbnet"
objective_list = [LatencyObjective]
weights_manager_list = [WeightInitDiffSuperNet]
| [
"[email protected]"
]
| |
3d390f31a696978f223cf0bb5967e4e08dd69d61 | a2d36e471988e0fae32e9a9d559204ebb065ab7f | /huaweicloud-sdk-functiongraph/huaweicloudsdkfunctiongraph/v2/model/update_dependency_response.py | bc7533af9937123df6012f0286b2109f90fb346b | [
"Apache-2.0"
]
| permissive | zhouxy666/huaweicloud-sdk-python-v3 | 4d878a90b8e003875fc803a61414788e5e4c2c34 | cc6f10a53205be4cb111d3ecfef8135ea804fa15 | refs/heads/master | 2023-09-02T07:41:12.605394 | 2021-11-12T03:20:11 | 2021-11-12T03:20:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,485 | py | # coding: utf-8
import re
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class UpdateDependencyResponse(SdkResponse):
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'id': 'str',
'owner': 'str',
'link': 'str',
'runtime': 'str',
'etag': 'str',
'size': 'int',
'name': 'str',
'description': 'str',
'file_name': 'str'
}
attribute_map = {
'id': 'id',
'owner': 'owner',
'link': 'link',
'runtime': 'runtime',
'etag': 'etag',
'size': 'size',
'name': 'name',
'description': 'description',
'file_name': 'file_name'
}
def __init__(self, id=None, owner=None, link=None, runtime=None, etag=None, size=None, name=None, description=None, file_name=None):
"""UpdateDependencyResponse - a model defined in huaweicloud sdk"""
super(UpdateDependencyResponse, self).__init__()
self._id = None
self._owner = None
self._link = None
self._runtime = None
self._etag = None
self._size = None
self._name = None
self._description = None
self._file_name = None
self.discriminator = None
if id is not None:
self.id = id
if owner is not None:
self.owner = owner
if link is not None:
self.link = link
if runtime is not None:
self.runtime = runtime
if etag is not None:
self.etag = etag
if size is not None:
self.size = size
if name is not None:
self.name = name
if description is not None:
self.description = description
if file_name is not None:
self.file_name = file_name
@property
def id(self):
"""Gets the id of this UpdateDependencyResponse.
依赖包ID。
:return: The id of this UpdateDependencyResponse.
:rtype: str
"""
return self._id
@id.setter
def id(self, id):
"""Sets the id of this UpdateDependencyResponse.
依赖包ID。
:param id: The id of this UpdateDependencyResponse.
:type: str
"""
self._id = id
@property
def owner(self):
"""Gets the owner of this UpdateDependencyResponse.
依赖包拥有者。
:return: The owner of this UpdateDependencyResponse.
:rtype: str
"""
return self._owner
@owner.setter
def owner(self, owner):
"""Sets the owner of this UpdateDependencyResponse.
依赖包拥有者。
:param owner: The owner of this UpdateDependencyResponse.
:type: str
"""
self._owner = owner
@property
def link(self):
"""Gets the link of this UpdateDependencyResponse.
依赖包在obs的存储地址。
:return: The link of this UpdateDependencyResponse.
:rtype: str
"""
return self._link
@link.setter
def link(self, link):
"""Sets the link of this UpdateDependencyResponse.
依赖包在obs的存储地址。
:param link: The link of this UpdateDependencyResponse.
:type: str
"""
self._link = link
@property
def runtime(self):
"""Gets the runtime of this UpdateDependencyResponse.
运行时语言。
:return: The runtime of this UpdateDependencyResponse.
:rtype: str
"""
return self._runtime
@runtime.setter
def runtime(self, runtime):
"""Sets the runtime of this UpdateDependencyResponse.
运行时语言。
:param runtime: The runtime of this UpdateDependencyResponse.
:type: str
"""
self._runtime = runtime
@property
def etag(self):
"""Gets the etag of this UpdateDependencyResponse.
依赖包唯一标志。
:return: The etag of this UpdateDependencyResponse.
:rtype: str
"""
return self._etag
@etag.setter
def etag(self, etag):
"""Sets the etag of this UpdateDependencyResponse.
依赖包唯一标志。
:param etag: The etag of this UpdateDependencyResponse.
:type: str
"""
self._etag = etag
@property
def size(self):
"""Gets the size of this UpdateDependencyResponse.
依赖包大小。
:return: The size of this UpdateDependencyResponse.
:rtype: int
"""
return self._size
@size.setter
def size(self, size):
"""Sets the size of this UpdateDependencyResponse.
依赖包大小。
:param size: The size of this UpdateDependencyResponse.
:type: int
"""
self._size = size
@property
def name(self):
"""Gets the name of this UpdateDependencyResponse.
依赖包名。
:return: The name of this UpdateDependencyResponse.
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""Sets the name of this UpdateDependencyResponse.
依赖包名。
:param name: The name of this UpdateDependencyResponse.
:type: str
"""
self._name = name
@property
def description(self):
"""Gets the description of this UpdateDependencyResponse.
依赖包描述。
:return: The description of this UpdateDependencyResponse.
:rtype: str
"""
return self._description
@description.setter
def description(self, description):
"""Sets the description of this UpdateDependencyResponse.
依赖包描述。
:param description: The description of this UpdateDependencyResponse.
:type: str
"""
self._description = description
@property
def file_name(self):
"""Gets the file_name of this UpdateDependencyResponse.
依赖包文件名。
:return: The file_name of this UpdateDependencyResponse.
:rtype: str
"""
return self._file_name
@file_name.setter
def file_name(self, file_name):
"""Sets the file_name of this UpdateDependencyResponse.
依赖包文件名。
:param file_name: The file_name of this UpdateDependencyResponse.
:type: str
"""
self._file_name = file_name
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
import simplejson as json
if six.PY2:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)
def __repr__(self):
"""For `print`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, UpdateDependencyResponse):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| [
"[email protected]"
]
| |
86350ee5f669f0bc854e56590f671130bd8f3596 | 2c926b4847a44c7f831d47ed0160751d3248e8f4 | /venv/lib/python3.8/site-packages/hubspot/crm/schemas/models/association_definition_egg.py | d1b6615a1cdd93b960bb747090fd47cf71d0bb08 | []
| no_license | Women-in-Tech-Society/WITS_Site | c42cd2c9abe1b5515b80be82dc876a6c3842e42a | 5dbf22f5ee5a36358f6f279af4c13d86d31653c5 | refs/heads/main | 2023-05-11T02:34:05.531902 | 2021-06-01T01:05:12 | 2021-06-01T01:05:12 | 278,658,100 | 0 | 5 | null | 2022-11-22T18:41:35 | 2020-07-10T14:43:28 | Python | UTF-8 | Python | false | false | 9,296 | py | # coding: utf-8
"""
Schemas
The CRM uses schemas to define how custom objects should store and represent information in the HubSpot CRM. Schemas define details about an object's type, properties, and associations. The schema can be uniquely identified by its **object type ID**. # noqa: E501
The version of the OpenAPI document: v3
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from hubspot.crm.schemas.configuration import Configuration
class AssociationDefinitionEgg(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
"from_object_type_id": "str",
"to_object_type_id": "str",
"name": "str",
"cardinality": "str",
"inverse_cardinality": "str",
}
attribute_map = {
"from_object_type_id": "fromObjectTypeId",
"to_object_type_id": "toObjectTypeId",
"name": "name",
"cardinality": "cardinality",
"inverse_cardinality": "inverseCardinality",
}
def __init__(
self,
from_object_type_id=None,
to_object_type_id=None,
name=None,
cardinality=None,
inverse_cardinality=None,
local_vars_configuration=None,
): # noqa: E501
"""AssociationDefinitionEgg - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._from_object_type_id = None
self._to_object_type_id = None
self._name = None
self._cardinality = None
self._inverse_cardinality = None
self.discriminator = None
self.from_object_type_id = from_object_type_id
self.to_object_type_id = to_object_type_id
if name is not None:
self.name = name
self.cardinality = cardinality
self.inverse_cardinality = inverse_cardinality
@property
def from_object_type_id(self):
"""Gets the from_object_type_id of this AssociationDefinitionEgg. # noqa: E501
ID of the primary object type to link from. # noqa: E501
:return: The from_object_type_id of this AssociationDefinitionEgg. # noqa: E501
:rtype: str
"""
return self._from_object_type_id
@from_object_type_id.setter
def from_object_type_id(self, from_object_type_id):
"""Sets the from_object_type_id of this AssociationDefinitionEgg.
ID of the primary object type to link from. # noqa: E501
:param from_object_type_id: The from_object_type_id of this AssociationDefinitionEgg. # noqa: E501
:type: str
"""
if (
self.local_vars_configuration.client_side_validation
and from_object_type_id is None
): # noqa: E501
raise ValueError(
"Invalid value for `from_object_type_id`, must not be `None`"
) # noqa: E501
self._from_object_type_id = from_object_type_id
@property
def to_object_type_id(self):
"""Gets the to_object_type_id of this AssociationDefinitionEgg. # noqa: E501
ID of the target object type ID to link to. # noqa: E501
:return: The to_object_type_id of this AssociationDefinitionEgg. # noqa: E501
:rtype: str
"""
return self._to_object_type_id
@to_object_type_id.setter
def to_object_type_id(self, to_object_type_id):
"""Sets the to_object_type_id of this AssociationDefinitionEgg.
ID of the target object type ID to link to. # noqa: E501
:param to_object_type_id: The to_object_type_id of this AssociationDefinitionEgg. # noqa: E501
:type: str
"""
if (
self.local_vars_configuration.client_side_validation
and to_object_type_id is None
): # noqa: E501
raise ValueError(
"Invalid value for `to_object_type_id`, must not be `None`"
) # noqa: E501
self._to_object_type_id = to_object_type_id
@property
def name(self):
"""Gets the name of this AssociationDefinitionEgg. # noqa: E501
A unique name for this association. # noqa: E501
:return: The name of this AssociationDefinitionEgg. # noqa: E501
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""Sets the name of this AssociationDefinitionEgg.
A unique name for this association. # noqa: E501
:param name: The name of this AssociationDefinitionEgg. # noqa: E501
:type: str
"""
self._name = name
@property
def cardinality(self):
"""Gets the cardinality of this AssociationDefinitionEgg. # noqa: E501
:return: The cardinality of this AssociationDefinitionEgg. # noqa: E501
:rtype: str
"""
return self._cardinality
@cardinality.setter
def cardinality(self, cardinality):
"""Sets the cardinality of this AssociationDefinitionEgg.
:param cardinality: The cardinality of this AssociationDefinitionEgg. # noqa: E501
:type: str
"""
if (
self.local_vars_configuration.client_side_validation and cardinality is None
): # noqa: E501
raise ValueError(
"Invalid value for `cardinality`, must not be `None`"
) # noqa: E501
allowed_values = ["ONE_TO_ONE", "ONE_TO_MANY"] # noqa: E501
if (
self.local_vars_configuration.client_side_validation
and cardinality not in allowed_values
): # noqa: E501
raise ValueError(
"Invalid value for `cardinality` ({0}), must be one of {1}".format( # noqa: E501
cardinality, allowed_values
)
)
self._cardinality = cardinality
@property
def inverse_cardinality(self):
"""Gets the inverse_cardinality of this AssociationDefinitionEgg. # noqa: E501
:return: The inverse_cardinality of this AssociationDefinitionEgg. # noqa: E501
:rtype: str
"""
return self._inverse_cardinality
@inverse_cardinality.setter
def inverse_cardinality(self, inverse_cardinality):
"""Sets the inverse_cardinality of this AssociationDefinitionEgg.
:param inverse_cardinality: The inverse_cardinality of this AssociationDefinitionEgg. # noqa: E501
:type: str
"""
if (
self.local_vars_configuration.client_side_validation
and inverse_cardinality is None
): # noqa: E501
raise ValueError(
"Invalid value for `inverse_cardinality`, must not be `None`"
) # noqa: E501
allowed_values = ["ONE_TO_ONE", "ONE_TO_MANY"] # noqa: E501
if (
self.local_vars_configuration.client_side_validation
and inverse_cardinality not in allowed_values
): # noqa: E501
raise ValueError(
"Invalid value for `inverse_cardinality` ({0}), must be one of {1}".format( # noqa: E501
inverse_cardinality, allowed_values
)
)
self._inverse_cardinality = inverse_cardinality
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(
map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value)
)
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(
map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict")
else item,
value.items(),
)
)
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, AssociationDefinitionEgg):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, AssociationDefinitionEgg):
return True
return self.to_dict() != other.to_dict()
| [
"[email protected]"
]
| |
5f87cfb899ff291aebe0d379f83c4d9e40794c82 | 1483486fae7cc9adf9493dadb1e60c087e2d6af9 | /env/bin/rst2latex.py | f0c782f9868a98bfbd1a61ad368700144ccde6d4 | []
| no_license | e-TPO/server | a8cf711ddef443ccb1008fe2fbcc6ac45369f189 | bf735321a4d3e52ea0b65cee8a9533a8250e5985 | refs/heads/master | 2022-12-14T22:49:30.776005 | 2018-01-27T21:33:53 | 2018-01-27T21:33:53 | 119,088,886 | 1 | 1 | null | 2022-12-08T00:36:21 | 2018-01-26T18:37:09 | CSS | UTF-8 | Python | false | false | 831 | py | #!/home/kuldeep/Projects/etpo/e-tpo-server/env/bin/python3
# $Id: rst2latex.py 5905 2009-04-16 12:04:49Z milde $
# Author: David Goodger <[email protected]>
# Copyright: This module has been placed in the public domain.
"""
A minimal front end to the Docutils Publisher, producing LaTeX.
"""
try:
import locale
locale.setlocale(locale.LC_ALL, '')
except:
pass
from docutils.core import publish_cmdline
description = ('Generates LaTeX documents from standalone reStructuredText '
'sources. '
'Reads from <source> (default is stdin) and writes to '
'<destination> (default is stdout). See '
'<http://docutils.sourceforge.net/docs/user/latex.html> for '
'the full reference.')
publish_cmdline(writer_name='latex', description=description)
| [
"[email protected]"
]
| |
27952a77379562f88c4995946dc5c424979e9996 | 90419da201cd4948a27d3612f0b482c68026c96f | /sdk/python/pulumi_azure_nextgen/customerinsights/v20170101/hub.py | e8e2e5c389f8388281f251dbf8d15ef4de29ea61 | [
"BSD-3-Clause",
"Apache-2.0"
]
| permissive | test-wiz-sec/pulumi-azure-nextgen | cd4bee5d70cb0d332c04f16bb54e17d016d2adaf | 20a695af0d020b34b0f1c336e1b69702755174cc | refs/heads/master | 2023-06-08T02:35:52.639773 | 2020-11-06T22:39:06 | 2020-11-06T22:39:06 | 312,993,761 | 0 | 0 | Apache-2.0 | 2023-06-02T06:47:28 | 2020-11-15T09:04:00 | null | UTF-8 | Python | false | false | 6,944 | py | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outputs
from ._inputs import *
__all__ = ['Hub']
class Hub(pulumi.CustomResource):
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
hub_billing_info: Optional[pulumi.Input[pulumi.InputType['HubBillingInfoFormatArgs']]] = None,
hub_name: Optional[pulumi.Input[str]] = None,
location: Optional[pulumi.Input[str]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
tenant_features: Optional[pulumi.Input[int]] = None,
__props__=None,
__name__=None,
__opts__=None):
"""
Hub resource.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[pulumi.InputType['HubBillingInfoFormatArgs']] hub_billing_info: Billing settings of the hub.
:param pulumi.Input[str] hub_name: The name of the Hub.
:param pulumi.Input[str] location: Resource location.
:param pulumi.Input[str] resource_group_name: The name of the resource group.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Resource tags.
:param pulumi.Input[int] tenant_features: The bit flags for enabled hub features. Bit 0 is set to 1 indicates graph is enabled, or disabled if set to 0. Bit 1 is set to 1 indicates the hub is disabled, or enabled if set to 0.
"""
if __name__ is not None:
warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning)
resource_name = __name__
if __opts__ is not None:
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = dict()
__props__['hub_billing_info'] = hub_billing_info
if hub_name is None:
raise TypeError("Missing required property 'hub_name'")
__props__['hub_name'] = hub_name
__props__['location'] = location
if resource_group_name is None:
raise TypeError("Missing required property 'resource_group_name'")
__props__['resource_group_name'] = resource_group_name
__props__['tags'] = tags
__props__['tenant_features'] = tenant_features
__props__['api_endpoint'] = None
__props__['name'] = None
__props__['provisioning_state'] = None
__props__['type'] = None
__props__['web_endpoint'] = None
alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:customerinsights/latest:Hub"), pulumi.Alias(type_="azure-nextgen:customerinsights/v20170426:Hub")])
opts = pulumi.ResourceOptions.merge(opts, alias_opts)
super(Hub, __self__).__init__(
'azure-nextgen:customerinsights/v20170101:Hub',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'Hub':
"""
Get an existing Hub resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = dict()
return Hub(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter(name="apiEndpoint")
def api_endpoint(self) -> pulumi.Output[str]:
"""
API endpoint URL of the hub.
"""
return pulumi.get(self, "api_endpoint")
@property
@pulumi.getter(name="hubBillingInfo")
def hub_billing_info(self) -> pulumi.Output[Optional['outputs.HubBillingInfoFormatResponse']]:
"""
Billing settings of the hub.
"""
return pulumi.get(self, "hub_billing_info")
@property
@pulumi.getter
def location(self) -> pulumi.Output[Optional[str]]:
"""
Resource location.
"""
return pulumi.get(self, "location")
@property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
"""
Resource name.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="provisioningState")
def provisioning_state(self) -> pulumi.Output[str]:
"""
Provisioning state of the hub.
"""
return pulumi.get(self, "provisioning_state")
@property
@pulumi.getter
def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]:
"""
Resource tags.
"""
return pulumi.get(self, "tags")
@property
@pulumi.getter(name="tenantFeatures")
def tenant_features(self) -> pulumi.Output[Optional[int]]:
"""
The bit flags for enabled hub features. Bit 0 is set to 1 indicates graph is enabled, or disabled if set to 0. Bit 1 is set to 1 indicates the hub is disabled, or enabled if set to 0.
"""
return pulumi.get(self, "tenant_features")
@property
@pulumi.getter
def type(self) -> pulumi.Output[str]:
"""
Resource type.
"""
return pulumi.get(self, "type")
@property
@pulumi.getter(name="webEndpoint")
def web_endpoint(self) -> pulumi.Output[str]:
"""
Web endpoint URL of the hub.
"""
return pulumi.get(self, "web_endpoint")
def translate_output_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
def translate_input_property(self, prop):
return _tables.SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
| [
"[email protected]"
]
| |
3b67bff3e9866cdc68fd19f374d328849aa0c7eb | accb0a012d257731a98376cbc5a10a279c91cfbd | /euler/solutions/euler43.py | 998756e0b04353988b0b697948538ef291856916 | []
| no_license | Danang691/Euler.Py | d52ac436d399a46553be0d9bd24736477a3d2cb0 | f8a198f5b06fd55388e8833108fbeed11e9b8d8b | refs/heads/master | 2022-01-08T00:32:06.724008 | 2019-01-27T22:33:40 | 2019-01-27T22:33:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,096 | py | # -*- coding: utf-8 -*-
from euler.baseeuler import BaseEuler
from itertools import permutations as perms
"""
1. there are only 3,628,800 (10!) 0 to 9 pandigital numbers, so there's no need
to examine all 10 billion 10-digit numbers.
2. consider only numbers whose last 3 digits divide by 17
3. now only check the permutations of the 7 remaining digits
4. this can be reduced further by considering the division by 13 and so on
"""
class Euler(BaseEuler):
def __init__(self):
self._F1 = lambda s: int(s[1:4]) % 2 == 0
self._F2 = lambda s: int(s[2:5]) % 3 == 0
self._F3 = lambda s: int(s[3:6]) % 5 == 0
self._F4 = lambda s: int(s[4:7]) % 7 == 0
self._F5 = lambda s: int(s[5:8]) % 11 == 0
self._F6 = lambda s: int(s[6:9]) % 13 == 0
self._F7 = lambda s: int(s[7:]) % 17 == 0
def solve(self):
t = list(perms('0123456789', 10))
p = [''.join(s) for s in t]
l = [i for i in p if self._F7(i)]
l = [i for i in l if self._F6(i)]
l = [i for i in l if self._F5(i)]
l = [i for i in l if self._F4(i)]
l = [i for i in l if self._F3(i)]
l = [i for i in l if self._F2(i)]
l = [i for i in l if self._F1(i)]
return sum([int(i) for i in l])
@property
def answer(self):
return ('The sum of all 0 to 9 pandigital numbers with this ' +
'property is %d.' % self.solve())
@property
def problem(self):
return '''
Project Euler Problem 43
The number, 1406357289, is a 0 to 9 pandigital number because it is made up of
each of the digits 0 to 9 in some order, but it also has a rather interesting
sub-string divisibility property.
Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note
the following:
- d2d3d4=406 is divisible by 2
- d3d4d5=063 is divisible by 3
- d4d5d6=635 is divisible by 5
- d5d6d7=357 is divisible by 7
- d6d7d8=572 is divisible by 11
- d7d8d9=728 is divisible by 13
- d8d9d10=289 is divisible by 17
Find the sum of all 0 to 9 pandigital numbers with this property.
'''
| [
"[email protected]"
]
| |
a88d08e13d37cfdd2c1dc346f7a68574139545b7 | 9e988c0dfbea15cd23a3de860cb0c88c3dcdbd97 | /sdBs/AllRun/sdssj_202550.42+133040.7/sdB_SDSSJ_202550.42+133040.7_lc.py | 3380ae095c4ebc5b68cf82334e179ac3fe41df68 | []
| no_license | tboudreaux/SummerSTScICode | 73b2e5839b10c0bf733808f4316d34be91c5a3bd | 4dd1ffbb09e0a599257d21872f9d62b5420028b0 | refs/heads/master | 2021-01-20T18:07:44.723496 | 2016-08-08T16:49:53 | 2016-08-08T16:49:53 | 65,221,159 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 372 | py | from gPhoton.gAperture import gAperture
def main():
gAperture(band="NUV", skypos=[306.460083,13.511306], stepsz=30., csvfile="/data2/fleming/GPHOTON_OUTPU/LIGHTCURVES/sdBs/sdB_SDSSJ_202550.42+133040.7 /sdB_SDSSJ_202550.42+133040.7_lc.csv", maxgap=1000., overwrite=True, radius=0.00555556, annulus=[0.005972227,0.0103888972], verbose=3)
if __name__ == "__main__":
main()
| [
"[email protected]"
]
| |
2b6d28c56de1c130b329b37f364f6eea788b0a12 | c1f09426670b5efe35956acd19c67a2de72af284 | /python/8.web/2.Django/mysql_demo/mysql_demo/settings.py | 2d96898508b90792184d03bf68d39719647d02c2 | [
"Apache-2.0"
]
| permissive | keasyops/BaseCode | 388218d89d60b958c1fcc50eb15f29eafabaea1f | 0255f498e1fe67ed2b3f66c84c96e44ef1f7d320 | refs/heads/master | 2023-05-08T05:08:39.754170 | 2021-05-26T10:48:01 | 2021-05-26T10:48:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,191 | py | """
Django settings for mysql_demo project.
Generated by 'django-admin startproject' using Django 2.2.
For more information on this file, see
https://docs.djangoproject.com/zh-hans/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/zh-hans/2.2/ref/settings
"""
import os
# Base_dir:当前项目的绝对路径
# 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/zh-hans/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'o96t+^%_!-@qlgo*0qqr%)2gca9s(l-!ihz_k252hol-ct_r#+'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
"userapp",
]
# 中间件:https://docs.djangoproject.com/zh-hans/2.2/topics/http/middleware/
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 = 'mysql_demo.urls'
# https://docs.djangoproject.com/zh-hans/2.2/ref/settings/#templates
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')], # 模版文件的绝对路径
'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 = 'mysql_demo.wsgi.application'
# Database
# https://docs.djangoproject.com/zh-hans/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'django', # 使用哪个数据库
'USER': 'root', # mysql的用户名
'PASSWORD': 'dntdnt', # 用户名对应的密码
'HOST': '127.0.0.1', # 数据库服务的ip地址
'PORT': 3306, # 对应的端口
# https://docs.djangoproject.com/en/2.2/ref/settings/#std:setting-OPTIONS
'OPTIONS': {
# https://docs.djangoproject.com/en/2.2/ref/settings/#autocommit
# 'AUTOCOMMIT': False,
# https://docs.djangoproject.com/zh-hans/2.2/ref/databases/#setting-sql-mode
# SQLMode可以看我之前写的文章:https://www.cnblogs.com/dotnetcrazy/p/10374091.html
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", # 设置SQL_Model
},
}
}
# Password validation
# https://docs.djangoproject.com/zh-hans/2.2/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/zh-hans/2.2/topics/i18n/
# 使用中文(zh-hans可以这么记==>zh-汉'字')
LANGUAGE_CODE = 'zh-hans'
# 设置中国时间
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/zh-hans/2.2/howto/static-files/
STATIC_URL = '/static/'
| [
"[email protected]"
]
| |
b709475e307f2177d6f520ec264c19b993c3e74b | e3365bc8fa7da2753c248c2b8a5c5e16aef84d9f | /indices/understand.py | b059fd10e57c8b7a29812c4f3990d42419e72bd7 | []
| no_license | psdh/WhatsintheVector | e8aabacc054a88b4cb25303548980af9a10c12a8 | a24168d068d9c69dc7a0fd13f606c080ae82e2a6 | refs/heads/master | 2021-01-25T10:34:22.651619 | 2015-09-23T11:54:06 | 2015-09-23T11:54:06 | 42,749,205 | 2 | 3 | null | 2015-09-23T11:54:07 | 2015-09-18T22:06:38 | Python | UTF-8 | Python | false | false | 2,852 | py | ii = [('BentJDO2.py', 14), ('EmerRN.py', 16), ('CookGHP3.py', 11), ('LyelCPG2.py', 3), ('MarrFDI.py', 4), ('RogePAV2.py', 8), ('CoolWHM2.py', 13), ('KembFFF.py', 7), ('GodwWSL2.py', 60), ('ChanWS.py', 11), ('RogePAV.py', 7), ('SadlMLP.py', 9), ('FerrSDO3.py', 20), ('WilbRLW.py', 15), ('WilbRLW4.py', 18), ('RennJIT.py', 6), ('ProuWCM.py', 28), ('AubePRP2.py', 14), ('CookGHP.py', 14), ('MartHSI2.py', 9), ('LeakWTI2.py', 8), ('UnitAI.py', 3), ('KembFJ1.py', 8), ('WilkJMC3.py', 6), ('WilbRLW5.py', 17), ('LeakWTI3.py', 3), ('PettTHE.py', 5), ('MarrFDI3.py', 8), ('TennAP.py', 1), ('PeckJNG.py', 4), ('KnowJMM.py', 2), ('BailJD2.py', 20), ('AubePRP.py', 26), ('ChalTPW2.py', 27), ('GellWPT.py', 1), ('AdamWEP.py', 6), ('FitzRNS3.py', 14), ('WilbRLW2.py', 28), ('ClarGE2.py', 23), ('GellWPT2.py', 3), ('WilkJMC2.py', 5), ('CarlTFR.py', 31), ('SeniNSP.py', 6), ('LyttELD.py', 6), ('CoopJBT2.py', 36), ('TalfTAC.py', 1), ('GrimSLE.py', 9), ('RoscTTI3.py', 5), ('AinsWRR3.py', 11), ('CookGHP2.py', 12), ('KiddJAE.py', 4), ('AdamHMM.py', 1), ('BailJD1.py', 14), ('RoscTTI2.py', 6), ('CoolWHM.py', 19), ('MarrFDI2.py', 7), ('CrokTPS.py', 20), ('ClarGE.py', 33), ('LandWPA.py', 9), ('BuckWGM.py', 10), ('IrviWVD.py', 5), ('LyelCPG.py', 4), ('GilmCRS.py', 9), ('DaltJMA.py', 9), ('WestJIT2.py', 3), ('DibdTRL2.py', 19), ('AinsWRR.py', 5), ('CrocDNL.py', 8), ('MedwTAI.py', 3), ('LandWPA2.py', 8), ('WadeJEB.py', 23), ('FerrSDO2.py', 22), ('TalfTIT.py', 1), ('NewmJLP.py', 33), ('GodwWLN.py', 21), ('CoopJBT.py', 14), ('KirbWPW2.py', 4), ('SoutRD2.py', 17), ('BackGNE.py', 4), ('LeakWTI4.py', 4), ('LeakWTI.py', 4), ('MedwTAI2.py', 8), ('BachARE.py', 29), ('SoutRD.py', 35), ('DickCSG.py', 4), ('WheeJPT.py', 13), ('MereHHB3.py', 16), ('HowiWRL2.py', 5), ('BailJD3.py', 18), ('MereHHB.py', 3), ('WilkJMC.py', 3), ('HogaGMM.py', 37), ('MartHRW.py', 26), ('MackCNH.py', 8), ('BabbCEM.py', 3), ('FitzRNS4.py', 38), ('CoolWHM3.py', 7), ('DequTKM.py', 7), ('FitzRNS.py', 15), ('BentJRP.py', 14), ('EdgeMHT.py', 23), ('BowrJMM.py', 9), ('LyttELD3.py', 2), ('FerrSDO.py', 7), ('RoscTTI.py', 3), ('ThomGLG.py', 10), ('StorJCC.py', 14), ('KembFJ2.py', 8), ('LewiMJW.py', 16), ('BabbCRD.py', 9), ('MackCNH2.py', 3), ('BellCHM.py', 10), ('SomeMMH.py', 1), ('HaliTBC.py', 21), ('WilbRLW3.py', 27), ('AinsWRR2.py', 5), ('MereHHB2.py', 15), ('BrewDTO.py', 10), ('JacoWHI.py', 1), ('ClarGE3.py', 61), ('MartHRW2.py', 27), ('DibdTRL.py', 29), ('FitzRNS2.py', 27), ('HogaGMM2.py', 7), ('MartHSI.py', 18), ('EvarJSP.py', 28), ('DwigTHH.py', 39), ('NortSTC.py', 5), ('SadlMLP2.py', 18), ('BowrJMM2.py', 7), ('LyelCPG3.py', 10), ('BowrJMM3.py', 5), ('BeckWRE.py', 1), ('TaylIF.py', 17), ('WordWYR.py', 2), ('DibdTBR.py', 5), ('ChalTPW.py', 14), ('ThomWEC.py', 5), ('KeigTSS.py', 3), ('KirbWPW.py', 13), ('WaylFEP.py', 14), ('BentJDO.py', 24), ('ClarGE4.py', 31), ('HowiWRL.py', 1)] | [
"[email protected]"
]
| |
a1f62bcfd6d251a8de4cba3fe7fae4c1151067fd | 09e5cfe06e437989a2ccf2aeecb9c73eb998a36c | /base/lib/python2.7/site-packages/mrcfile/gzipmrcfile.py | 8fd97b41138e1bcef75c9b61cb7c4068055225b7 | [
"LicenseRef-scancode-python-cwi",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-free-unknown",
"Python-2.0",
"BSD-3-Clause"
]
| permissive | jorgediazjr/dials-dev20191018 | b81b19653624cee39207b7cefb8dfcb2e99b79eb | 77d66c719b5746f37af51ad593e2941ed6fbba17 | refs/heads/master | 2020-08-21T02:48:54.719532 | 2020-01-25T01:41:37 | 2020-01-25T01:41:37 | 216,089,955 | 0 | 1 | BSD-3-Clause | 2020-01-25T01:41:39 | 2019-10-18T19:03:17 | Python | UTF-8 | Python | false | false | 2,723 | py | # Copyright (c) 2016, Science and Technology Facilities Council
# This software is distributed under a BSD licence. See LICENSE.txt.
"""
gzipmrcfile
-----------
Module which exports the :class:`GzipMrcFile` class.
Classes:
:class:`GzipMrcFile`: An object which represents a gzipped MRC file.
"""
# Import Python 3 features for future-proofing
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import gzip
from .mrcfile import MrcFile
class GzipMrcFile(MrcFile):
""":class:`~mrcfile.mrcfile.MrcFile` subclass for handling gzipped files.
Usage is the same as for :class:`~mrcfile.mrcfile.MrcFile`.
"""
def __repr__(self):
return "GzipMrcFile('{0}', mode='{1}')".format(self._fileobj.name,
self._mode)
def _open_file(self, name):
"""Override _open_file() to open both normal and gzip files."""
self._fileobj = open(name, self._mode + 'b')
self._iostream = gzip.GzipFile(fileobj=self._fileobj, mode='rb')
def _close_file(self):
"""Override _close_file() to close both normal and gzip files."""
self._iostream.close()
self._fileobj.close()
def _read(self, header_only=False):
"""Override _read() to ensure gzip file is in read mode."""
self._ensure_readable_gzip_stream()
super(GzipMrcFile, self)._read(header_only)
def _ensure_readable_gzip_stream(self):
"""Make sure _iostream is a gzip stream that can be read."""
if self._iostream.mode != gzip.READ:
self._iostream.close()
self._fileobj.seek(0)
self._iostream = gzip.GzipFile(fileobj=self._fileobj, mode='rb')
def _get_file_size(self):
"""Override _get_file_size() to avoid seeking from end."""
self._ensure_readable_gzip_stream()
pos = self._iostream.tell()
extra = len(self._iostream.read())
return pos + extra
def flush(self):
"""Override :meth:`~mrcfile.mrcinterpreter.MrcInterpreter.flush` since
GzipFile objects need special handling.
"""
if not self._read_only:
self._iostream.close()
self._fileobj.seek(0)
self._iostream = gzip.GzipFile(fileobj=self._fileobj, mode='wb')
# Arrays converted to bytes so gzip can calculate sizes correctly
self._iostream.write(self.header.tobytes())
self._iostream.write(self.extended_header.tobytes())
self._iostream.write(self.data.tobytes())
self._iostream.flush()
self._fileobj.truncate()
| [
"[email protected]"
]
| |
8b96e0486d3ae2eff2814c19873fad1b007d1395 | 487ce91881032c1de16e35ed8bc187d6034205f7 | /codes/CodeJamCrawler/16_1_2/sproctor/rank_and_file.py | b7de93089153574c7d0d13e2b4e4ebb4fcfe08eb | []
| no_license | DaHuO/Supergraph | 9cd26d8c5a081803015d93cf5f2674009e92ef7e | c88059dc66297af577ad2b8afa4e0ac0ad622915 | refs/heads/master | 2021-06-14T16:07:52.405091 | 2016-08-21T13:39:13 | 2016-08-21T13:39:13 | 49,829,508 | 2 | 0 | null | 2021-03-19T21:55:46 | 2016-01-17T18:23:00 | Python | UTF-8 | Python | false | false | 863 | py | #!/usr/bin/python
import sys
maxHeight = 2500
def solve(heights):
missingList = []
for i in range(maxHeight + 1):
if heights[i] % 2 == 1:
missingList.append(str(i))
return missingList
def main():
filename = sys.argv[1]
filehandle = open(filename, 'r')
lines = filehandle.readlines()
numberOfTests = int(lines.pop(0))
for i in range(numberOfTests):
n = int(lines.pop(0))
heights = dict([(x, 0) for x in range(maxHeight + 1)])
for j in range(n * 2 - 1):
line = lines.pop(0)
heightStrings = line.split(' ')
heightList = []
for k in range(n):
heights[int(heightStrings[k])] += 1
missingList = solve(heights)
print "Case #" + str(i + 1) + ": " + " ".join(missingList)
if __name__ == "__main__":
main()
| [
"[[email protected]]"
]
| |
14bf94956faba485bce2be72addcd37cd6573471 | 739e41d4f24f79c772d266cded0de9b759c6e953 | /venv/lib/python3.6/site-packages/nlp/datasets/docred/24f714c390b57d5e0642c513b1e98b62e281a8f9d2f875ac1d3e103b07de3cee/docred.py | 3fbcbd2045e9177caa4d92aed978cc11bf9ed9ae | [
"MIT"
]
| permissive | MachineLearningBCAM/Minimax-risk-classifiers-NeurIPS-2020 | 24b7bbdecf459292f8b58be286feab3b9aa341ba | 82586c632268c103de269bcbffa5f7849b174a29 | refs/heads/main | 2023-05-18T15:41:13.495286 | 2021-06-11T18:21:35 | 2021-06-11T18:21:35 | 304,268,819 | 3 | 2 | null | null | null | null | UTF-8 | Python | false | false | 5,257 | py | """DocRED: A Large-Scale Document-Level Relation Extraction Dataset"""
from __future__ import absolute_import, division, print_function
import json
import os
import nlp
_CITATION = """\
@inproceedings{yao2019DocRED,
title={{DocRED}: A Large-Scale Document-Level Relation Extraction Dataset},
author={Yao, Yuan and Ye, Deming and Li, Peng and Han, Xu and Lin, Yankai and Liu, Zhenghao and Liu, \
Zhiyuan and Huang, Lixin and Zhou, Jie and Sun, Maosong},
booktitle={Proceedings of ACL 2019},
year={2019}
}
"""
_DESCRIPTION = """\
Multiple entities in a document generally exhibit complex inter-sentence relations, and cannot be well handled by \
existing relation extraction (RE) methods that typically focus on extracting intra-sentence relations for single \
entity pairs. In order to accelerate the research on document-level RE, we introduce DocRED, a new dataset constructed \
from Wikipedia and Wikidata with three features:
- DocRED annotates both named entities and relations, and is the largest human-annotated dataset for document-level RE from plain text.
- DocRED requires reading multiple sentences in a document to extract entities and infer their relations by synthesizing all information of the document.
- Along with the human-annotated data, we also offer large-scale distantly supervised data, which enables DocRED to be adopted for both supervised and weakly supervised scenarios.
"""
_URLS = {
"dev": "https://drive.google.com/uc?export=download&id=1fDmfUUo5G7gfaoqWWvK81u08m71TK2g7",
"train_distant": "https://drive.google.com/uc?export=download&id=1fDmfUUo5G7gfaoqWWvK81u08m71TK2g7",
"train_annotated": "https://drive.google.com/uc?export=download&id=1NN33RzyETbanw4Dg2sRrhckhWpzuBQS9",
"test": "https://drive.google.com/uc?export=download&id=1lAVDcD94Sigx7gR3jTfStI66o86cflum",
"rel_info": "https://drive.google.com/uc?id=1y9A0zKrvETc1ddUFuFhBg3Xfr7FEL4dW&export=download",
}
class DocRed(nlp.GeneratorBasedBuilder):
"""DocRED: A Large-Scale Document-Level Relation Extraction Dataset"""
def _info(self):
return nlp.DatasetInfo(
description=_DESCRIPTION,
features=nlp.Features(
{
"title": nlp.Value("string"),
"sents": nlp.features.Sequence(nlp.features.Sequence(nlp.Value("string"))),
"vertexSet": nlp.features.Sequence(nlp.features.Sequence({
"name": nlp.Value("string"),
"sent_id": nlp.Value("int32"),
"pos": nlp.features.Sequence(nlp.Value("int32")),
"type": nlp.Value("string"),
})),
"labels": nlp.features.Sequence(
{
"head": nlp.Value("int32"),
"tail": nlp.Value("int32"),
"relation_id": nlp.Value("string"),
"relation_text": nlp.Value("string"),
"evidence": nlp.features.Sequence(nlp.Value("int32")),
}
),
}
),
supervised_keys=None,
homepage="https://github.com/thunlp/DocRED",
citation=_CITATION,
)
def _split_generators(self, dl_manager):
downloads = {}
for key in _URLS.keys():
downloads[key] = dl_manager.download_and_extract(_URLS[key])
# Fix for dummy data
if os.path.isdir(downloads[key]):
downloads[key] = os.path.join(downloads[key], key + ".json")
return [
nlp.SplitGenerator(
name=nlp.Split.VALIDATION, gen_kwargs={"filepath": downloads["dev"], "rel_info": downloads["rel_info"]}
),
nlp.SplitGenerator(
name=nlp.Split.TEST, gen_kwargs={"filepath": downloads["test"], "rel_info": downloads["rel_info"]}
),
nlp.SplitGenerator(
name="train_annotated",
gen_kwargs={"filepath": downloads["train_annotated"], "rel_info": downloads["rel_info"]},
),
nlp.SplitGenerator(
name="train_distant",
gen_kwargs={"filepath": downloads["train_distant"], "rel_info": downloads["rel_info"]},
),
]
def _generate_examples(self, filepath, rel_info):
"""Generate DocRED examples."""
relation_name_map = json.load(open(rel_info))
data = json.load(open(filepath))
for idx, example in enumerate(data):
# Test set has no labels - Results need to be uploaded to Codalab
if "labels" not in example.keys():
example["labels"] = []
for label in example["labels"]:
# Rename and include full relation names
label["relation_text"] = relation_name_map[label["r"]]
label["relation_id"] = label["r"]
label["head"] = label["h"]
label["tail"] = label["t"]
del label["r"]
del label["h"]
del label["t"]
raise ValueError(example)
yield idx, example
| [
"[email protected]"
]
| |
10805b6505117c9dbc083c4c4ea2311f0f7b4543 | 5235a27898cdaeab012c447c50076e7e4641dbf7 | /code/diagnosis/grtest.py | 5b0fabaa9066f506ce45528174962a0401846b6a | [
"MIT"
]
| permissive | mjvakili/gambly | 0a9ab638a5be987efb683acdc8282a8c09880532 | 611765bc42d8c42d76558b486c4025532155036a | refs/heads/master | 2020-04-10T05:32:55.171621 | 2020-03-22T18:51:10 | 2020-03-22T18:51:10 | 50,690,345 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,006 | py | '''
implementation of Gelman-Rubin convergence test
'''
import numpy as np
def single_parameter_gr_test(chains):
"""
inputs:
chains : MCMC samples for one parameter.
shape = (nwalkers , niters)
returns:
potential scale reduction factor
and the variance of the distribution
"""
nwalkers = chains.shape[0]
niters = chains.shape[1]
#Discarding the first half of draws:
chains = chains[: , niters/2:]
nwalkers , niters = chains.shape[0] , chains.shape[1]
#Calculating the within-chain variance:
W = np.mean(np.var(chains, axis=1))
#Calculating the between-chain variance:
chains_means = np.mean(chains, axis=1)
mean_of_chains_means = np.mean(chains_means)
B = (niters/(nwalkers-1.0)) * np.sum((chains_means - mean_of_chains_means)**2.)
# Estimating the variance of distribution:
V = (1. - 1./niters) * W + (1./niters) * B
# Calculating the potential scale reduction factor:
R = np.sqrt(V/W)
return R , V
def gr_test(sample , nwalkers , nburnins , npars):
"""
inputs:
sample = an emcee sample
nwalkers = number of walkers
returns:
Rs = npar-dimensional vector of the
potential scale reduction factors
Vs = npar-dimensional vector of the
variances
"""
#npar = len(sample[0])
niters = len(sample)
chain_ensemble = sample.reshape(niters , nwalkers , npars)
chain_ensemble = chain_ensemble[nburnins: , :]
Rs = np.zeros((npars))
Vs = np.zeros((npars))
for i in range(npars):
chains = chain_ensemble[ : , : , i].T
Rs[i] = single_parameter_gr_test(chains)[0]
Vs[i] = single_parameter_gr_test(chains)[1]
return Rs , Vs
if __name__ == "__main__":
###########NOTE: This part is provided by the user#########
import h5py
sample = h5py.File("emcee2.hdf5")["k"]
nwalkers = 6
nburnins = 1700
npars = 3
print gr_test(sample , nwalkers , nburnins , npars)
| [
"[email protected]"
]
| |
1a35b54134a858ba2ad3e718170f76012f9d65b9 | 0958db6bf636722685f33501408b3e28a45b2b14 | /basic/key_event/key_event2.py | 39ce162819423ee6e70a5b0378eace2fcacbefd3 | [
"MIT"
]
| permissive | KeitaIto123/pygame | eee68fe59f7bf3eb408ff98737150a7d5fe258fc | cf5ba2331dc6b4a930f9c3dacbaa7954f51498db | refs/heads/master | 2020-03-26T10:57:52.613169 | 2017-03-12T14:06:35 | 2017-03-12T14:06:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,056 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pygame
from pygame.locals import *
import sys
SCREEN_SIZE = (640, 480)
pygame.init()
screen = pygame.display.set_mode(SCREEN_SIZE)
pygame.display.set_caption(u"キーイベント2")
img = pygame.image.load("python.png").convert_alpha()
img_rect = img.get_rect()
img_rect.center = (320, 240)
vx = vy = 10 # キーを押したときの移動距離
while True:
# 押されているキーをチェック
pressed_keys = pygame.key.get_pressed()
# 押されているキーに応じて画像を移動
if pressed_keys[K_LEFT]:
img_rect.move_ip(-vx, 0)
if pressed_keys[K_RIGHT]:
img_rect.move_ip(vx, 0)
if pressed_keys[K_UP]:
img_rect.move_ip(0, -vy)
if pressed_keys[K_DOWN]:
img_rect.move_ip(0, vy)
screen.fill((0,0,255))
screen.blit(img, img_rect)
pygame.display.update()
for event in pygame.event.get():
if event.type == QUIT: sys.exit()
if event.type == KEYDOWN and event.key == K_ESCAPE: sys.exit()
| [
"[email protected]"
]
| |
1fbe9ed32949b7b2644e5a348f35cba67707f693 | cd40fd66338bab16c3cac360ec68d0410daf85dc | /asyncio_study/factorial.py | 1646369d3db811c34c538e76b12a6d84dc7cc229 | []
| no_license | suhjohn/Asyncio-Study | c74a95c37d6ce1d0983b5626a4f68d2b80d7ec79 | d9c5a092924a32f18849787fd30cb322a0ff8b15 | refs/heads/master | 2021-05-12T12:28:15.749447 | 2018-01-14T17:25:22 | 2018-01-14T17:25:22 | 117,414,697 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 665 | py | import asyncio
async def factorial(number):
result = 1
for i in range(2, number+1):
print(f"Task for {number}: Compute factorial: {i}")
await asyncio.sleep(1)
result *= i
print(f'Task for {number} finished. Factorial({number}) = {result}')
loop = asyncio.get_event_loop()
'''
Method using async.gather in https://docs.python.org/3/library/asyncio-task.html#future
loop.run_until_complete(asyncio.gather(
factorial(2),
factorial(3),
factorial(4),
))
loop.close()
'''
tasks = [loop.create_task(factorial(i)) for i in range(2, 5)]
wait_tasks = asyncio.wait(tasks)
loop.run_until_complete(wait_tasks)
loop.close()
| [
"[email protected]"
]
| |
be668b7d094dabdba76537bfc6f3d63deed2fd52 | 6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4 | /YGhrwfg6k6zHnmeDh_6.py | 325649a3d1cc40c3f3f3aee4f24b5ae109e7c2e6 | []
| no_license | daniel-reich/ubiquitous-fiesta | 26e80f0082f8589e51d359ce7953117a3da7d38c | 9af2700dbe59284f5697e612491499841a6c126f | refs/heads/master | 2023-04-05T06:40:37.328213 | 2021-04-06T20:17:44 | 2021-04-06T20:17:44 | 355,318,759 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 160 | py |
def get_discounts(nums, d):
discount = int(d.strip("%")) / 100
new_price = []
for x in nums:
new_price.append(x * discount)
return new_price
| [
"[email protected]"
]
| |
916f0b24c134a8b15a9019a7392d2f69d9481bed | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p00005/s108100200.py | 51c7c84132f7cb691304ec7ee31bbe534e088dfc | []
| no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 253 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
def gcd( a, b ):
while b > 0:
a, b = b, a%b
return a
def lcm( a, b ):
return a*b/gcd( a, b )
for s in sys.stdin:
d = map(int, s.split())
a,b = d[0],d[1]
print gcd(a,b),lcm(a,b) | [
"[email protected]"
]
| |
f626a5fe63505768adc81155c86801ddb59cb619 | 2b8fe23680fb8c6596c8b4fd53a2547e32e84617 | /8-DS-Design/EventCounter.py | e1d0c32e969f979b8ced3409173abec7d7174853 | []
| no_license | jigarshah2811/Python-Programming | b441c4815f80bef4d17611cdea851254c59739a9 | a60a11ad29e9dde9e9960006f887d9b66d29e427 | refs/heads/master | 2022-11-20T18:09:11.955564 | 2022-11-04T05:58:19 | 2022-11-04T05:58:19 | 67,324,037 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,007 | py | N = 3
import collections
class Solution(object):
def __init__(self):
self.q = collections.deque()
# Queue((Second, Frequency), )
def eventOccured():
timeMS = getEpochInMill()
second = qtimeMS // 1000
(s, c) = q[-1]
if s == second:
q[-1][1] += 1 # HERE we can save MAX
# if max(q[-1][1], maxval)
else:
q.append((second, 1))
# Purge old records
while len(e) > N:
q.popleft()
def getNumEvents():
res = 0
# Purge old records
while len(self.q) > N:
q.popleft()
for ele in self.q:
res += ele[1]
return res
s = Solution()
assert (s.getNumEvents() == 0)
for i in range(5):
s.eventOccured()
time.sleep(1000) # Adding 5 events in 5 seconds
assert (s.getNumEvents() == 5)
for i in range(5):
s.eventOccured()
time.sleep(10) # Adding 5 events in 6th second
assert (s.getNumEvents == 7)
| [
"[email protected]"
]
| |
b49d40170a4c2d9ecd8aa6b7b668cfdd08d2c580 | ee8c4c954b7c1711899b6d2527bdb12b5c79c9be | /assessment2/amazon/run/core/controllers/spoon.py | e4d6d5e20ebc0f06012645de11ba00ebf94a7cac | []
| no_license | sqlconsult/byte | 02ac9899aebea4475614969b594bfe2992ffe29a | 548f6cb5038e927b54adca29caf02c981fdcecfc | refs/heads/master | 2021-01-25T14:45:42.120220 | 2018-08-11T23:45:31 | 2018-08-11T23:45:31 | 117,135,069 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 364 | py | #!/usr/bin/env python3
from flask import Blueprint, Flask, render_template, request, url_for
controller = Blueprint('spoon', __name__, url_prefix='/spoon')
# @controller.route('/<string:title>', methods=['GET'])
# def lookup(title):
# if title == 'Republic': # TODO 2
# return render_template('republic.html') # TODO 2
# else:
# pass
| [
"[email protected]"
]
| |
cee71c5efb06a3baf0f28594bbcb11c9bdac0c86 | 79c6594e76cbbb5de8fe9dc73a23946c90fac2b1 | /torchbiggraph/util.py | c5954e623f8d6dc9b7058a967b9ea2cfd10fa7c5 | [
"BSD-3-Clause"
]
| permissive | middle-plat-ai/PyTorch-BigGraph | e47e03104b6d640b47ac103170b09e411f0c8391 | 701ec1736ef17280981311f7214f35c96c190434 | refs/heads/master | 2021-11-03T19:47:13.676050 | 2019-04-26T16:49:13 | 2019-04-26T16:52:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,232 | py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import os
import os.path
from collections import defaultdict
from datetime import datetime
from typing import Any, Dict, Iterable, Optional, Set, Tuple
import torch
import torch.multiprocessing as mp
from torch.optim import Optimizer
from .config import ConfigSchema
from .types import Side, EntityName, FloatTensorType
def log(msg: str) -> None:
"""Log msg to stdout with a timestamp. Flush stdout.
"""
print("%s %s" % (datetime.now().strftime("%Y-%m-%d %H:%M:%S"), msg), flush=True)
_verbosity_level = 0
def vlog(msg: str, level: int = 1) -> None:
if _verbosity_level >= level:
log(msg)
def split_almost_equally(size: int, *, num_parts: int) -> Iterable[slice]:
"""Split an interval of the given size into the given number of subintervals
The sizes of the subintervals will be between the floor and the ceil of the
"exact" fractional size, with larger intervals preceding smaller ones.
"""
size_per_part = size // num_parts
num_larger_parts = size % num_parts
prev = 0
for i in range(num_parts):
next_ = prev + size_per_part + (1 if i < num_larger_parts else 0)
yield slice(prev, next_)
prev = next_
def round_up_to_nearest_multiple(value: int, factor: int) -> int:
return ((value - 1) // factor + 1) * factor
def fast_approx_rand(numel: int) -> FloatTensorType:
if numel < 1_000_003:
tensor = torch.randn(numel)
# share_memory_ does return the tensor but its type annotation says it
# doesn't, thus we do this in two separate steps.
tensor.share_memory_()
return tensor
# construct the tensor storage in shared mem so we don't have to copy it
storage = torch.FloatStorage._new_shared(numel)
tensor = torch.FloatTensor(storage)
rand = torch.randn(1_000_003)
excess = numel % 1_000_003
# Using just `-excess` would give bad results when excess == 0.
tensor[:numel - excess].view(-1, 1_000_003)[...] = rand
tensor[numel - excess:] = rand[:excess]
return tensor
class DummyOptimizer(Optimizer):
def __init__(self) -> None:
# This weird dance makes Optimizer accept an empty parameter list.
super().__init__([{'params': []}], {})
def step(self, closure: None = None) -> None:
pass
def state_dict(self) -> Dict[str, Any]:
return {}
def load_state_dict(self, state_dict: Dict[str, Any]) -> None:
pass
def share_memory(self) -> None:
pass
# HOGWILD
def _pool_init():
torch.set_num_threads(1)
torch.manual_seed(os.getpid())
def create_pool(num_workers: int) -> mp.Pool:
# PyTorch relies on OpenMP, which by default parallelizes operations by
# implicitly spawning as many threads as there are cores, and synchronizing
# them with each other. This interacts poorly with Hogwild!-style subprocess
# pools as if each child process spawns its own OpenMP threads there can
# easily be thousands of threads that mostly wait in barriers. Calling
# set_num_threads(1) in both the parent and children prevents this.
# OpenMP can also lead to deadlocks if it gets initialized in the parent
# process before the fork (this bit us in unit tests, due to the generation
# of the test input data). Using the "spawn" context (i.e., fork + exec)
# solved the issue in most cases but still left some deadlocks. See
# https://github.com/pytorch/pytorch/issues/17199 for some more information
# and discussion.
torch.set_num_threads(1)
return mp.Pool(num_workers, initializer=_pool_init)
# config routines
def get_partitioned_types(
config: ConfigSchema,
side: Side,
) -> Tuple[int, Set[EntityName]]:
"""Return the number of partitions on a given side and the partitioned entity types
Each of the entity types that appear on the given side (LHS or RHS) of a relation
type is split into some number of partitions. The ones that are split into one
partition are called "unpartitioned" and behave as if all of their entities
belonged to all buckets. The other ones are the "properly" partitioned ones.
Currently, they must all be partitioned into the same number of partitions. This
function returns that number and the names of the properly partitioned entity
types.
"""
entity_names_by_num_parts: Dict[int, Set[EntityName]] = defaultdict(set)
for relation_config in config.relations:
entity_name = side.pick(relation_config.lhs, relation_config.rhs)
entity_config = config.entities[entity_name]
entity_names_by_num_parts[entity_config.num_partitions].add(entity_name)
if 1 in entity_names_by_num_parts:
del entity_names_by_num_parts[1]
if len(entity_names_by_num_parts) == 0:
return 1, set()
if len(entity_names_by_num_parts) > 1:
raise RuntimeError("Currently num_partitions must be a single "
"value across all partitioned entities.")
(num_partitions, partitioned_entity_names), = entity_names_by_num_parts.items()
return num_partitions, partitioned_entity_names
# compute a randomized AUC using a fixed number of sample points
# NOTE: AUC is the probability that a randomly chosen positive example
# has a higher score than a randomly chosen negative example
def compute_randomized_auc(
pos_: FloatTensorType,
neg_: FloatTensorType,
num_samples: int,
) -> float:
pos_, neg_ = pos_.view(-1), neg_.view(-1)
diff = (pos_[torch.randint(len(pos_), (num_samples,))]
> neg_[torch.randint(len(neg_), (num_samples,))])
return float(diff.float().mean())
def get_num_workers(override: Optional[int]) -> int:
if override is not None:
return override
cpu_count = os.cpu_count()
if cpu_count is not None:
return cpu_count
result = 40
print("WARNING: number of workers unspecified and couldn't autodetect "
"CPU count; defaulting to %d workers." % result)
return result
| [
"[email protected]"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.