blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 616 | content_id stringlengths 40 40 | detected_licenses listlengths 0 69 | license_type stringclasses 2
values | repo_name stringlengths 5 118 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 63 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 2.91k 686M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 220
values | src_encoding stringclasses 30
values | language stringclasses 1
value | is_vendor bool 2
classes | is_generated bool 2
classes | length_bytes int64 2 10.3M | extension stringclasses 257
values | content stringlengths 2 10.3M | authors listlengths 1 1 | author_id stringlengths 0 212 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ff962c602c1f68d63c7883569742a8670659f422 | e6b45b6cc01a921c3cc510f1a5fff3074dd6b2dd | /example_update1/PoissonFEMWithRobinBC_example.py | 3ff8c61a39419d78d70757f91ba1ecd69df871af | [] | no_license | yoczhang/FEALPyExamples | 3bd339bd5f4576630f767a758da9590a1c068410 | 44d9acbecb528374bc67bba50c62711384228d39 | refs/heads/master | 2023-07-24T21:35:50.633572 | 2023-07-05T02:28:13 | 2023-07-05T02:28:13 | 208,667,003 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,646 | py | #!/usr/bin/env python3
#
import sys
import numpy as np
from scipy.sparse.linalg import spsolve
import matplotlib.pyplot as plt
import pyamg
from fealpy.functionspace import LagrangeFiniteElementSpace
from fealpy.boundarycondition import RobinBC
from fealpy.tools.show import showmultirate
p = int(sys.argv[1])
n = int(sys.argv[2])
maxit = int(sys.argv[3])
d = int(sys.argv[4])
if d == 2:
from fealpy.pde.poisson_2d import CosCosData as PDE
elif d == 3:
from fealpy.pde.poisson_3d import CosCosCosData as PDE
pde = PDE()
mesh = pde.init_mesh(n=n)
errorType = ['$|| u - u_h||_{\Omega,0}$',
'$||\\nabla u - \\nabla u_h||_{\Omega, 0}$'
]
errorMatrix = np.zeros((2, maxit), dtype=np.float)
NDof = np.zeros(maxit, dtype=np.float)
for i in range(maxit):
space = LagrangeFiniteElementSpace(mesh, p=p)
NDof[i] = space.number_of_global_dofs()
uh = space.function()
A = space.stiff_matrix()
F = space.source_vector(pde.source)
bc = RobinBC(space, pde.robin)
A, F = bc.apply(A, F)
#uh[:] = spsolve(A, F).reshape(-1)
ml = pyamg.ruge_stuben_solver(A)
uh[:] = ml.solve(F, tol=1e-12, accel='cg').reshape(-1)
errorMatrix[0, i] = space.integralalg.error(pde.solution, uh.value)
errorMatrix[1, i] = space.integralalg.error(pde.gradient, uh.grad_value)
if i < maxit-1:
mesh.uniform_refine()
if d == 2:
fig = plt.figure()
axes = fig.gca(projection='3d')
uh.add_plot(axes, cmap='rainbow')
elif d == 3:
print('The 3d function plot is not been implemented!')
showmultirate(plt, 0, NDof, errorMatrix, errorType, propsize=20)
plt.show()
| [
"yoczhang@126.com"
] | yoczhang@126.com |
76378a3d40f88ad91d83893523dd4b496f47a514 | fda7cc48da6936f77f6dd5eb409c65c39177722f | /staff.py | 909cc801cc6152fa2a27cc424db5d109e0c7b51e | [] | no_license | NgangaMaryanne/Amity-maryanne | 648e29070c9e3f76fcf33d837703517dd5742da2 | 22a2d81532aab5152f1fd3744590717dd3796a9a | refs/heads/master | 2021-01-21T06:18:25.163039 | 2017-03-06T18:26:40 | 2017-03-06T18:26:40 | 83,205,492 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 83 | py | from person import Person
class Staff(Person):
def __init__(self):
pass | [
"maryanne.nganga@andela.com"
] | maryanne.nganga@andela.com |
839806df105cb20e454ffd2a3bbd502d4028218b | 2e47e81ea0aace25a4d54e7bc562a318462440a3 | /structure.py | 0d3716d685a8fd9bce459a40331d1a24efa04542 | [] | no_license | crsrikanth84/test14 | 147eb1af2b664f95b6a9af5d8821fd7879399e1d | d1dee7169790ff4ec94bcbbc921a3cb8b9ee9ccb | refs/heads/master | 2020-07-26T20:59:47.733993 | 2015-04-19T11:16:50 | 2015-04-19T11:16:50 | 34,194,947 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 140 | py | from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
app = QApplication(sys.argv)
dialog = QDialog()
dialog.show()
app.exec_()
| [
"crsrikanth84@gmail.com"
] | crsrikanth84@gmail.com |
8172278c4a1ec0de1e8f95574258c3946848b2b9 | 91d8ed451d1ff0480eb57fdac2ae7a46c2b69eda | /tigerpup/tigerpup/urls.py | 0a3d4cb54d0fdd6bc54a350770552fa43af1576e | [] | no_license | divye1995/tigerpup | 37270d91cb337883b6a70ffd874064b8f50eca7b | 2bfd8e2c3d93ede5885d79fd5c621d2e9c2bad36 | refs/heads/master | 2021-01-13T02:51:58.432119 | 2016-12-22T08:37:56 | 2016-12-22T08:37:56 | 77,127,446 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 277 | py | from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'tigerpup.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
| [
"divyesm@gmail.com"
] | divyesm@gmail.com |
d8850a88780af1666c0bdb0a0538e9bec404bb7b | 670f2530725669a55990c6bd102ff227cfce61db | /SS06/calculator.py | 50aeba73af329c3632ffb4ec15f60767ac8abd79 | [] | no_license | taanh99ams/taanh-fundamental-c4e15 | d9690181fbbfe3a08a54b410972ba5784e063b39 | d86f38b2e1f576484762024b97d8dca8b060c628 | refs/heads/master | 2021-05-12T10:20:00.012271 | 2018-02-09T03:59:50 | 2018-02-09T03:59:50 | 117,336,513 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 762 | py | x = int(input("Enter x "))
op = input("Operation (+, -, *, /) ")
y = int(input("Enter y "))
op_list = ["+", "-", "*", "/"]
#
# print("*" * 20)
# if operation == "+":
# print("{0} + {1} = {2}".format(x, y, x + y))
# elif operation == "-":
# print("{0} - {1} = {2}".format(x, y, x - y))
# elif operation == "*":
# print("{0} * {1} = {2}".format(x, y, x * y))
# elif operation == "/":
# print("{0} / {1} = {2}".formay(x, y, x / y))
# else:
# print("Wrong operation")
#
# print("*" * 20)
# Better way
result = 0
if op == "+":
result = x + y
elif op == "-":
result = x - y
elif op == "*":
result = x * y
elif op == "/":
result = x / y
else:
print("Unsupported operation")
print("{0} {1} {2} = {3}".format(x, op, y, result))
| [
"taanh1999gha@gmail.com"
] | taanh1999gha@gmail.com |
cea744c519951b1d792842fa074670506fc24208 | 760e1c14d056dd75958d367242c2a50e829ac4f0 | /bit/338_counting_bits.py | 81ff431da8a2934e28c5d1339ee654906a25b2a5 | [] | no_license | lawtech0902/py_imooc_algorithm | 8e85265b716f376ff1c53d0afd550470679224fb | 74550d68cd3fd2cfcc92e1bf6579ac3b8f31aa75 | refs/heads/master | 2021-04-26T22:54:42.176596 | 2018-09-23T15:45:22 | 2018-09-23T15:45:22 | 123,894,744 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,266 | py | # _*_ coding: utf-8 _*_
"""
__author__ = 'lawtech'
__date__ = '2018/9/3 下午4:25'
给定一个非负整数 num。对于 0 ≤ i ≤ num 范围中的每个数字 i ,计算其二进制数中的 1 的数目并将它们作为数组返回。
示例 1:
输入: 2
输出: [0,1,1]
示例 2:
输入: 5
输出: [0,1,1,2,1,2]
进阶:
给出时间复杂度为O(n*sizeof(integer))的解答非常容易。但你可以在线性时间O(n)内用一趟扫描做到吗?
要求算法的空间复杂度为O(n)。
你能进一步完善解法吗?要求在C++或任何其他语言中不使用任何内置函数(如 C++ 中的 __builtin_popcount)来执行此操作。
考虑二进制数的规律。[000,001,010,011,100,101,110,111],分别对应[0,1,2,3,4,5,6,7]。
从上述二进制数可以看出来,4-7的二进制数既是对0-3的二进制数的最高位从0变成1,也就是说后面的二进制数都是在之前所有二进制的最高位加一位1。
"""
class Solution:
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
res = [0]
for i in range(1, num + 1):
res.append(res[i & (i - 1)] + 1)
return res
if __name__ == '__main__':
print(Solution().countBits(5))
| [
"584563542@qq.com"
] | 584563542@qq.com |
f7b9ecb10dce9558e1675d321f7394ed645f50be | d635031bd451142be52edc39d44e266dd698d91f | /StockDataAnalysis/data/invalid_stock_check.py | f7f31353d3b984d55d8811f14f3be23f054f7cf6 | [] | no_license | niting1201/Stock_Data_Analysis | 936291f13fd42db00b43cd110c3ed02793170e19 | 5a0a715631e4febeff5c599f1281c92c0f9296de | refs/heads/master | 2021-10-08T09:02:24.238846 | 2018-12-10T06:49:09 | 2018-12-10T06:49:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 579 | py | import re
import pymysql
import tushare as ts
nonedata = 0
emptystable = 0
with open('stocklist.txt', 'r', encoding='utf-8') as f:
for i in f:
tem = [t for t in re.split("\,|\\n", i) if t]
data = ts.get_hist_data(tem[-1], start='2018-01-01', end='2018-12-31')
try:
if len(data.index)==0:
emptystable += 1
print(tem[-1],'is an empty table')
except Exception as e:
nonedata += 1
print(tem[-1],'is none')
print("total nonedata", nonedata)
print("total emptystable", emptystable)
print("total invalid", nonedata + emptystable) | [
"873729746@qq.com"
] | 873729746@qq.com |
ca5a58c7fb44b6dc9dfd58b6bfbda78e814270e3 | 3e238b3549163f1a352bb0802794dd3f1965c61f | /src/SkypeRobot/msg/_Move.py | d0af8282fa5c1305971910f7db61e241409659c2 | [] | no_license | czw90130/SkypeRobot | 2771839c0b304a49a89419908fbebd994a71cef9 | a9a252097318388b376f49bb2dafbb536e2bc990 | refs/heads/master | 2021-01-01T17:28:33.328579 | 2013-10-06T20:00:06 | 2013-10-06T20:00:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,532 | py | """autogenerated by genpy from SkypeRobot/Move.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class Move(genpy.Message):
_md5sum = "6915f32f700bc1942ecaa4b776cd432c"
_type = "SkypeRobot/Move"
_has_header = False #flag to mark the presence of a Header object
_full_text = """int16 LeftWhell
int16 RightWhell
uint16 MoveState
uint16 ArmState
"""
__slots__ = ['LeftWhell','RightWhell','MoveState','ArmState']
_slot_types = ['int16','int16','uint16','uint16']
def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
LeftWhell,RightWhell,MoveState,ArmState
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(Move, self).__init__(*args, **kwds)
#message fields cannot be None, assign default values for those that are
if self.LeftWhell is None:
self.LeftWhell = 0
if self.RightWhell is None:
self.RightWhell = 0
if self.MoveState is None:
self.MoveState = 0
if self.ArmState is None:
self.ArmState = 0
else:
self.LeftWhell = 0
self.RightWhell = 0
self.MoveState = 0
self.ArmState = 0
def _get_types(self):
"""
internal API method
"""
return self._slot_types
def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
_x = self
buff.write(_struct_2h2H.pack(_x.LeftWhell, _x.RightWhell, _x.MoveState, _x.ArmState))
except struct.error as se: self._check_types(se)
except TypeError as te: self._check_types(te)
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
try:
end = 0
_x = self
start = end
end += 8
(_x.LeftWhell, _x.RightWhell, _x.MoveState, _x.ArmState,) = _struct_2h2H.unpack(str[start:end])
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
_x = self
buff.write(_struct_2h2H.pack(_x.LeftWhell, _x.RightWhell, _x.MoveState, _x.ArmState))
except struct.error as se: self._check_types(se)
except TypeError as te: self._check_types(te)
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
try:
end = 0
_x = self
start = end
end += 8
(_x.LeftWhell, _x.RightWhell, _x.MoveState, _x.ArmState,) = _struct_2h2H.unpack(str[start:end])
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
_struct_I = genpy.struct_I
_struct_2h2H = struct.Struct("<2h2H")
| [
"czw90130@gmail.com"
] | czw90130@gmail.com |
e6565e710f30887e40469c723dab3c5d85fdbd45 | c7f1472e37e2f0b9fde1bc02d11f9443e9cd4f89 | /forms.py | 6cc437122818dfd73f4e89849f0ce62d73efd61e | [] | no_license | nathan3000/lesson_aims | e0733cc59f466a68c99b9b1d25fa22ebaf86ff2e | f3526d52ea69de627881fb37409c8fcf6ec534ca | refs/heads/master | 2021-06-20T04:18:08.539694 | 2017-01-07T11:31:09 | 2017-01-07T11:31:09 | 34,262,372 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,576 | py | from flask.ext.wtf import Form
from wtforms import SelectField, TextAreaField, TextField, validators
class RequiredIf(object):
# a validator which makes a field required if
# another field is set and has a truthy value
def __init__(self, other_field_name, values, message=None):
self.other_field_name = other_field_name
self.values = values
if not message:
message = u'This field is required.'
self.message = message
def __call__(self, form, field):
other_field = form._fields.get(self.other_field_name)
if other_field is None:
raise Exception('no field named "%s" in form' % self.other_field_name)
for value in self.values:
if (other_field.data == value) and (not field.data):
raise validators.ValidationError(self.message)
class AimsForm(Form):
groupName = SelectField('Group Name', [validators.NumberRange(0, message="Please select a group.")], coerce=int)
seriesName = SelectField('Series Name', [validators.NumberRange(0, message="Please select a series.")], coerce=int, )
biblePassage = TextField('Bible Passage', [validators.Required()])
whatTheyLearnt = TextAreaField('Today your child learnt that..', [validators.Required()])
lessonAim = TextAreaField('Lesson Aim', [RequiredIf('groupName', [2,3])])
tip1 = TextAreaField('Tip #1', [validators.Required()])
tip2 = TextAreaField('Tip #2')
memoryVerse = TextField('Memory Verse', [RequiredIf('groupName', [2,3])])
newSeriesName = TextField('New Series Name', [RequiredIf('seriesName', [0])]) | [
"nooglefish@gmail.com"
] | nooglefish@gmail.com |
b8cc8b86fe4f78e1448c6d2c8f29e104cee505ca | c8370776bbba96cd396c3e775760cffc55375110 | /app.py | 9d4ed696707371eec65d23f26bd0ea9dc39647db | [] | no_license | lohiadivyansh96/sl9 | e88a278220845b11444fa73c1b4c9308263d8173 | ac3ff8f356c77a79e51be83c5321dd14e16acc2a | refs/heads/master | 2021-08-22T16:56:26.357301 | 2017-11-30T17:58:33 | 2017-11-30T17:58:33 | 112,642,498 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,076 | py | from flask import Flask, redirect, render_template, request, url_for
import time #time and date related functions
#import re #regular expressions
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def prg9serverFunction():
if request.method == "GET":
return render_template("index.html")
if request.method == "POST":
#Check if date entered in dd/mm/yyyy format and is not an invalid date
# Eg. 31/11/2016 - November has 30 days only, not 31
# Eg. 30/02/1998 - February will never have 30 days
# Client Side Java Script did not validate this
# Using Python's 'time' package and 'strptime' function to do these validations
#Use strptime() function which raises an exception if date is invalid
try:
time.strptime(request.form["dob"],"%d/%m/%Y")
except ValueError:
msg = "You entered an invalid date! This is validated by the server-side Python Program"
return render_template("Prg9.html", msg=msg)
#If form fields are valid return success HTML page
return render_template("success.html")
if __name__ == '__main__':
app.run()
| [
"lohiadivyansh12@gmail.com"
] | lohiadivyansh12@gmail.com |
3e4c7c0a206a8f84ceeee5a002e7c2433b47715e | 4c76da4802fd60643bf86a46c795fe4e895bd137 | /Test3.py | c359df0d6a806b0527dfb233d2a79b32ceaa5fbc | [] | no_license | Keonhong/IT_Education_Center | 16bb2329124013dd2f0bc79e97ea40efcf1f3b0d | b58150dfe837ec9b26b4f0b29c42348659965db0 | refs/heads/master | 2021-05-14T18:57:34.019971 | 2018-02-06T08:16:34 | 2018-02-06T08:16:34 | 116,095,585 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 12,767 | py | import urllib.request
import time
import json
import datetime
import os
g_Radiator = False
g_Gas_Valve = False
g_Balcony_Windows = False
g_Door = False
g_AI_Mode = False
g_humidifier = False
g_dehumidifier = False
access_key = "zKXKKnSlFbzQlSo3VGM7RSWUTndjwM0szSJhbK%2F85hKnvtPxU6zBzaudnzPFNNHf5j1azPl%2B7p4IfYMW8%2Bi4lg%3D%3D"
def get_request_url(url):
req = urllib.request.Request(url)
try:
response = urllib.request.urlopen(req)
if response.getcode() == 200:
print("[%s] URL request Success" %datetime.datetime.now())
return response.read().decode('UTF-8')
except Exception as e:
print(e)
print("[%s] Error for URL:%s"%(datetime.datetime.now(),url))
return None
def getForecastTimeDataResponse(base_date,base_time,nx,ny):
end_point = "http://newsky2.kma.go.kr/service/SecndSrtpdFrcstInfoService2/ForecastTimeData"
parameters = "?base_date=" + base_date
parameters += "&base_time=" + base_time
parameters += "&nx=" + nx
parameters += "&ny=" + ny
parameters += "&_type=json&serviceKey=" + access_key
url = end_point+parameters
retData = get_request_url(url)
if(retData == None):
return None
else:
return json.loads(retData)
def main():
jsonResult = []
base_date = time.strftime("%Y%m%d", time.localtime(time.time()))
base_time = time.strftime("%H%M", time.localtime(time.time()))
nx = "89"
ny = "91"
jsonData = getForecastTimeDataResponse(base_date,base_time,nx,ny)
# HK Comment] JSON 데이터 분석하는 코드를 작성할 것
print("%s_%s_Weather.json" %(base_date,base_time))
with open("%s_%s_Weather.json" %(base_date,base_time),'w',encoding='utf8')as outfile:
retJson = json.dumps(jsonResult, indent=4, sort_keys=True,ensure_ascii=False)
outfile.write(retJson)
def print_main_menu():
print("\n1. 장비상태 확인")
print("2. 장비제어")
print("3. 스마트모드")
print("4. 시뮬레이션 모드")
print("5. 프로그램 종료")
def print_device_status(device_name,devcie_status):
print("%s 상태: "% device_name, end="")
if devcie_status == True: print("작동")
else: print("정지")
def print_device_status1(device_name,devcie_status1):
print("%s 상태: "% device_name, end="")
if devcie_status1 == True: print("열림") # 장비에 맞는 상태 메세지를 출력할 것
else: print("닫힘") # 힌트] 메세지와 관련된 파라메터 추가
def check_device_status():
print_device_status('\n난방기', g_Radiator)
print_device_status('가스밸브', g_Gas_Valve)
print_device_status1('발코니(베란다) 창문', g_Balcony_Windows)
print_device_status1('출입문', g_Door)
print_device_status('가습기', g_humidifier)
print_device_status('제습기', g_dehumidifier)
def print_device_menu():
print("\n상태 변경할 기기를 선택하세요.")
print("1. 난방기")
print("2. 가스밸브")
print("3. 발코니(베란다)창")
print("4. 출입문")
print("5. 가습기")
print("6. 제습기")
def control_device():
global g_Radiator, g_Gas_Valve, g_Balcony_Windows, g_Door, g_humidifier, g_dehumidifier
check_device_status()
print_device_menu()
menu_num = int(input("번호를 입력하세요: "))
if menu_num == 1: g_Radiator = not g_Radiator
if menu_num == 2: g_Gas_Valve = not g_Gas_Valve
if menu_num == 3: g_Balcony_Windows = not g_Balcony_Windows
if menu_num == 4: g_Door = not g_Door
if menu_num == 5: g_humidifier = not g_humidifier
if menu_num == 6: g_dehumidifier = not g_dehumidifier
check_device_status()
def smart_mode():
global g_AI_Mode
print("1. 인공지능 모드 조회")
print("2. 인공지능 모드 상태 변경")
print("3. 실시간 기상정보 Update 신청하기")
print("4. 실시간 기상정보 Update 불러오기")
menu_num = int(input("메뉴를 선택하세요: "))
if menu_num == 1:
print("현재 인공지능 모드: ", end='')
if g_AI_Mode == True: print("작동")
else: print("정지")
elif menu_num == 2:
g_AI_Mode = not g_AI_Mode
print("현재 인공지능 모드: ", end='')
if g_AI_Mode == True: print("작동")
else: print("정지")
elif menu_num == 3:
print("실시간 기상정보 Update 신청하기")
get_realtime_weather_info()
else:
print("\n실시간 기상정보 Update 불러오기")
print("=" *50)
get_weather_info()
def get_realtime_weather_info():
if __name__ == '__main__':
main()
def get_weather_info():
base_date = time.strftime("%Y%m%d", time.localtime(time.time()))
base_time = time.strftime("%H%M", time.localtime(time.time()))
with open("%s_%s_Weather.json" %(base_date,base_time), encoding='UTF8') as json_file:
json_object = json.load(json_file)
json_string = json.dumps(json_object)
retJson = json.loads(json_string)
for retJson in retJson:
print("['baseDate'] = " + str(retJson['baseDate']))
print("['category'] = " + str(retJson['category']))
print("['fcstDate'] = " + str(retJson['fcstDate']))
print("['fcstTime'] = " + str(retJson['fcstTime']))
print("['fcstValue'] = " + str(retJson['fcstValue']))
print("['nx'] = " + str(retJson['nx']))
print("['ny'] = " + str(retJson['ny']))
print("=" *50)
def simulation_mode():
print("\n1. Rain Day Simulation (발코니창 제어)")
print("2. Damp Day Simulation (제습기 제어)")
print("3. Dry Day Simulation (가습기 제어)")
print("4. Sunny Day Simulation (제습기/가습기 제어)")
menu_num = int(input("메뉴를 선택하세요: "))
if menu_num == 1:
precipitation_forecast_simulation()
elif menu_num == 2:
Damp_forecast_simulation()
elif menu_num == 3:
Dry_forecast_simulation()
elif menu_num == 4:
Sunny_Day_simulation()
def precipitation_forecast_simulation():
global g_Balcony_Windows
base_date = time.strftime("%Y%m%d", time.localtime(time.time()))
base_time = time.strftime("%H%M", time.localtime(time.time()))
retJson = []
jsonResult ={
"baseDate": base_date,
"baseTime": base_time,
"category": "RN1",
"fcstDate": base_date,
"fcstTime": base_time,
"fcstValue": 10,
"nx": 89,
"ny": 91
}
retJson.append(jsonResult)
if not os.path.isfile('Rain_simulator.json'):
with open('Rain_simulator.json','w',encoding='UTF8') as outfile:
readable_result = json.dumps(retJson,indent=4, sort_keys=True, ensure_ascii=False)
outfile.write(readable_result)
print('Rain_simulator.json SAVED')
if(retJson[0]['category']) == 'RN1':
print("RN1//fcstValue = " + str(retJson[0]['fcstValue']))
if retJson[0]['fcstValue'] > 0:
if g_Balcony_Windows == True:
print("\n***비가 올 예정이오니 열려 있는 창문을 닫습니다.***")
g_Balcony_Windows = not g_Balcony_Windows
check_device_status()
else:
print("***비가 올 예정이오니 창문 개방은 삼가하시기 바랍니다.***")
def Damp_forecast_simulation():
global g_Balcony_Windows , g_dehumidifier
base_date = time.strftime("%Y%m%d", time.localtime(time.time()))
base_time = time.strftime("%H%M", time.localtime(time.time()))
retJson = []
jsonResult ={
"baseDate": base_date,
"baseTime": base_time,
"category": "REH",
"fcstDate": base_date,
"fcstTime": base_time,
"fcstValue": 90,
"nx": 89,
"ny": 91
}
retJson.append(jsonResult)
if not os.path.isfile('Rain_simulator.json'):
with open('Damp_simulator.json','w',encoding='UTF8') as outfile:
readable_result = json.dumps(retJson,indent=4, sort_keys=True, ensure_ascii=False)
outfile.write(readable_result)
print('Damp_simulator.json SAVED')
if(retJson[0]['category']) == 'REH':
print("REH//fcstValue = " + str(retJson[0]['fcstValue']))
if retJson[0]['fcstValue'] > 80:
if g_Balcony_Windows == True:
print("\n***습도가 높으므로 열려 있는 창문을 닫고, 제습기를 가동하겠습니다.***")
g_Balcony_Windows = not g_Balcony_Windows
g_dehumidifier = not g_dehumidifier
check_device_status()
else:
print("***습도가 높으므로 제습기를 가동하겠습니다.***")
g_dehumidifier = not g_dehumidifier
check_device_status()
def Dry_forecast_simulation():
global g_Balcony_Windows, g_humidifier
base_date = time.strftime("%Y%m%d", time.localtime(time.time()))
base_time = time.strftime("%H%M", time.localtime(time.time()))
retJson = []
jsonResult ={
"baseDate": base_date,
"baseTime": base_time,
"category": "REH",
"fcstDate": base_date,
"fcstTime": base_time,
"fcstValue": 30,
"nx": 89,
"ny": 91
}
retJson.append(jsonResult)
if not os.path.isfile('Rain_simulator.json'):
with open('Dry_simulator.json','w',encoding='UTF8') as outfile:
readable_result = json.dumps(retJson,indent=4, sort_keys=True, ensure_ascii=False)
outfile.write(readable_result)
print('Dry_simulator.json SAVED')
if(retJson[0]['category']) == 'REH1':
print("REH//fcstValue = " + str(retJson[0]['fcstValue']))
if retJson[0]['fcstValue'] < 40:
if g_Balcony_Windows == True:
print("\n***습도가 낮으므로 열려 있는 창문을 닫고, 가습기를 가동하겠습니다.***")
g_Balcony_Windows = not g_Balcony_Windows
g_humidifier = not g_humidifier
check_device_status()
else:
print("***습도가 낮으므로 가습기를 가동하겠습니다.***")
g_humidifier = not g_humidifier
check_device_status()
def Sunny_Day_simulation():
global g_Balcony_Windows, g_humidifier, g_dehumidifier
base_date = time.strftime("%Y%m%d", time.localtime(time.time()))
base_time = time.strftime("%H%M", time.localtime(time.time()))
retJson = []
jsonResult ={
"baseDate": base_date,
"baseTime": base_time,
"category": "SKY",
"fcstDate": base_date,
"fcstTime": base_time,
"fcstValue": 1,
"nx": 89,
"ny": 91
}
retJson.append(jsonResult)
if not os.path.isfile('Rain_simulator.json'):
with open('Sunny_Day_simulator.json','w',encoding='UTF8') as outfile:
readable_result = json.dumps(retJson,indent=4, sort_keys=True, ensure_ascii=False)
outfile.write(readable_result)
print('Sunny_Day_simulator.json SAVED')
if(retJson[0]['category']) == 'SKY':
print("SKY//fcstValue = " + str(retJson[0]['fcstValue']))
if retJson[0]['fcstValue'] <= 2:
if g_Balcony_Windows == False:
print("\n***화창한 날씨입니다^^ 닫힌 창문을 열고,제습기와 가습기 작동을 정지합니다.***")
g_Balcony_Windows = not g_Balcony_Windows
g_dehumidifier = not g_dehumidifier
g_humidifier = not g_humidifier
check_device_status()
else:
print("\n***화창한 날씨입니다^^ 제습기와 가습기 작동을 정지합니다.***")
g_Balcony_Windows = not g_Balcony_Windows
g_dehumidifier = not g_dehumidifier
g_humidifier = not g_humidifier
check_device_status()
while True:
print_main_menu()
menu_num = int(input("메뉴를 선택하세요: "))
if menu_num == 1: # check_device_status() HK Comment] 장비 상태 출력하는 함수를 작성할 것
check_device_status()
elif menu_num == 2:
control_device()
elif menu_num == 3:
smart_mode()
elif menu_num == 4:
simulation_mode()
else: break | [
"noreply@github.com"
] | Keonhong.noreply@github.com |
76be0f2511f3d9277a903af119ad4439369adab6 | 38bffb2258b5373b45d85321edb6012c32b7acc4 | /Practice/Problem Solving/MigratoryBirds.py | 7d5094fac99c8b8be193c4345f986fda2253ae05 | [
"MIT"
] | permissive | aviral36/HackerRank-Solutions | c1b66a417634b6567fd13539109d72998b34eb5d | 699451518dfd9e41e222f8b5ca25d4c34f611168 | refs/heads/master | 2021-07-26T13:36:47.151443 | 2021-06-17T14:45:55 | 2021-06-17T14:45:55 | 139,997,738 | 1 | 2 | MIT | 2020-10-01T04:59:16 | 2018-07-06T14:54:13 | Python | UTF-8 | Python | false | false | 565 | py | #!/bin/python
import sys
def migratoryBirds(n, ar):
s=list(set(ar))
coulis=[]
for i in s:
coulis.append(ar.count(i))
maxima=max(coulis)
l=list()
count1=coulis.count(max(coulis))
if count1==1:
ind=coulis.index(maxima)
return s[ind]
else:
while count1!=0:
ind=coulis.index(maxima)
l.append(s[ind])
l.sort()
return l[0]
n = int(raw_input().strip())
ar = map(int, raw_input().strip().split(' '))
result = migratoryBirds(n, ar)
print(result)
| [
"noreply@github.com"
] | aviral36.noreply@github.com |
7312db3ca01af1b1dc7bd31689cf25dba3a9f00f | 3f0d36f172cfee0f69db74931de82187e29a9ef3 | /scripts/create_production_html.py | 0de6e3d395d1458319912b0767a8393e76552d5f | [
"MIT"
] | permissive | adm78/visualchemeng-js | 76c9d8405af0fe66afc26267e37d5e1cc6267a89 | df8d2b92a17b0550bd2254e54fb532fb8b570c73 | refs/heads/master | 2022-08-29T13:36:09.800578 | 2022-07-24T14:17:56 | 2022-07-24T14:17:56 | 102,987,910 | 8 | 2 | null | null | null | null | UTF-8 | Python | false | false | 4,299 | py | # VCE Project - create_production_html.py
#
# This script can be used to create an app production html from a test html
#
# Andrew D. McGuire 2020
# amcguire227@gmail.com
#
# TODO: default production file should be ../production/test_filename (relative to test file), if not provided
# ----------------------------------------------------------
import argparse
import os.path
import git
from bs4 import BeautifulSoup
parser = argparse.ArgumentParser(description=('Create a production ready application html (i.e. one that uses only remote sources) ' +
'from a test hmtl application (i.e. one that uses a mixture of local and remote sources).'),
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-f', dest='test_html_path', type=str, help='path to the test .html file to be processed')
parser.add_argument('-c', dest='commit_hash', type=str, help='the commit hash to be used for remote vce repository files (last local commit if not provided)',
default=None)
parser.add_argument('-o', dest='production_html_path', type=str, help='the path of the production .html file to be created')
parser.add_argument('-g', dest='vce_repo_path', required=False,
help='the path to the vce git repository that the test html lives in (auto-find is attempted if not provided)')
parser.add_argument('--cdn', dest='cdn_path_root', default="https://rawcdn.githack.com/adm78/visualchemeng_js", required=False,
help='the cdn path root to use for remote files')
args = parser.parse_args()
if args.commit_hash is None:
args.commit_hash = git.Repo(search_parent_directories=True).head.object.hexsha
if args.vce_repo_path is None:
args.vce_repo_path = git.Repo(search_parent_directories=True).working_tree_dir
class ProductionHTMLGenerator(object):
def __init__(self, test_html_path: str, commit_hash: str, production_html_path: str, vce_repo_path: str, cdn_path_root: str):
super(ProductionHTMLGenerator, self).__init__()
self._test_html_path = os.path.abspath(test_html_path)
self._production_html_path = os.path.abspath(production_html_path)
self._vce_repo_path = os.path.abspath(vce_repo_path)
self._cdn_path_root = cdn_path_root
self._commit_hash = commit_hash
def generate(self):
with open(self._test_html_path, "r") as f:
contents = f.read()
soup = BeautifulSoup(contents, 'lxml')
links = soup.find_all('link')
for link in links:
src = link['href']
if self._is_vce_path(src):
link['href'] = self._get_remote_path(src)
images = soup.find_all('img')
for image in images:
src = image['src']
if self._is_vce_path(src):
image['src'] = self._get_remote_path(src)
scripts = soup.find_all('script')
for script in scripts:
src = script['src']
if self._is_vce_path(src):
script['src'] = self._get_remote_path(src)
with open(self._production_html_path, "w") as f:
f.write(soup.prettify())
print("Production html output to {}".format(self._production_html_path))
def _is_vce_path(self, src: str) -> bool:
return not (src.startswith('https://') or src.startswith('http://'))
def _get_remote_path(self, src: str) -> str:
abs_src_path = os.path.normpath(os.path.join(self._test_html_path, '..', src))
path_rel_to_repo_root = abs_src_path.replace(self._vce_repo_path, '', 1).replace('\\', '/')
if path_rel_to_repo_root.startswith('/'):
path_rel_to_repo_root = path_rel_to_repo_root.replace('/', '', 1)
remote_path = "{}/{}/{}".format(self._cdn_path_root, self._commit_hash, path_rel_to_repo_root)
return remote_path
if __name__ == '__main__':
generator = ProductionHTMLGenerator(test_html_path=args.test_html_path, commit_hash=args.commit_hash, production_html_path=args.production_html_path,
vce_repo_path=args.vce_repo_path, cdn_path_root=args.cdn_path_root)
generator.generate()
| [
"andrew.mcguire@spirocontrol.com"
] | andrew.mcguire@spirocontrol.com |
8b13f453089664e22c9cd377339d493878b30f89 | 43e5441f74359d620be6f7f80c99622769ea9774 | /venv/Lib/site-packages/cma/fitness_functions2.py | b05afae699ea080bbdbf824990670620695da9b6 | [
"BSD-3-Clause"
] | permissive | 33Da/deeplearn_eassy | 96f1bd09fe3df907c650378215eb686e4ab2801e | 82d60c5ec3aec60822d68d13f11ef1320d0bba2e | refs/heads/master | 2023-02-07T15:02:00.202693 | 2021-01-05T05:03:22 | 2021-01-05T05:03:22 | 326,892,905 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 16,742 | py | # -*- coding: utf-8 -*-
"""versatile container for test objective functions.
For the time being this is probably best used like::
from cma.fitness_functions2 import ff
Tested with::
import cma, cma.fitness_functions2
cma.ff2 = cma.fitness_functions2
cma.ff2.__dict__
dff, dff2 = dir(cma.ff), dir(cma.ff2)
for f in dff2:
if f in dff and f not in ('BBOB', 'epslow',
'fun_as_arg') and not f.startswith('_'):
try:
getattr(cma.ff, f)(aa([1.,2,3])) == getattr(cma.ff2, f)(aa([1.,2,3]))
except:
try:
assert getattr(cma.ff, f)(aa([1.,2,3]), cma.ff.sphere)\
== getattr(cma.ff2, f)(aa([1.,2,3]), cma.ff2.sphere)
except:
assert all(getattr(cma.ff, f)(aa([1.,2,3]), cma.ff.sphere)
== getattr(cma.ff2, f)(aa([1.,2,3]), cma.ff2.sphere))
"""
from __future__ import (absolute_import, division, print_function,
) # unicode_literals, with_statement)
# from __future__ import collections.MutableMapping
# does not exist in future, otherwise Python 2.5 would work, since 0.91.01
__author__ = "Nikolaus Hansen"
from .utilities.python3for2 import *
del absolute_import, division, print_function
import numpy as np
# arange, cos, size, eye, inf, dot, floor, outer, zeros, linalg.eigh,
# sort, argsort, random, ones,...
from numpy import array, dot, isscalar, sum # sum is not needed
# from numpy import inf, exp, log, isfinite
# to access the built-in sum fct: ``__builtins__.sum`` or ``del sum``
# removes the imported sum and recovers the shadowed build-in
try: np.median([1,2,3,2]) # fails currently in pypy, also sigma_vec.scaling
except AttributeError:
def _median(x):
x = sorted(x)
if len(x) % 2:
return x[len(x) // 2]
return (x[len(x) // 2 - 1] + x[len(x) // 2]) / 2
np.median = _median
from .utilities.utils import rglen as _rglen
# $Source$ # according to PEP 8 style guides, but what is it good for?
# $Id: fitness_functions.py 4150 2015-03-20 13:53:36Z hansen $
# bash $: svn propset svn:keywords 'Date Revision Id' fitness_functions.py
from . import bbobbenchmarks as BBOB
from .fitness_transformations import rotate #, ComposedFunction, Function
def _iqr(x):
x = sorted(x)
i1 = int(len(x) / 4)
i3 = int(3*len(x) / 4)
return x[i3] - x[i1]
def somenan(x, fun, p=0.1):
"""returns sometimes np.NaN, otherwise fun(x)"""
if np.random.rand(1) < p:
return np.NaN
else:
return fun(x)
def epslow(fun, eps=1e-7, Neff=lambda x: int(len(x)**0.5)):
return lambda x: fun(x[:Neff(x)]) + eps * np.mean(x**2)
def rand(x):
"""Random test objective function"""
return np.random.random(1)[0]
def linear(x):
return -x[0]
def lineard(x):
if 1 < 3 and any(array(x) < 0):
return np.nan
if 1 < 3 and sum([(10 + i) * x[i] for i in _rglen(x)]) > 50e3:
return np.nan
return -sum(x)
def sphere(x):
"""Sphere (squared norm) test objective function"""
# return np.random.rand(1)[0]**0 * sum(x**2) + 1 * np.random.rand(1)[0]
return sum((x + 0)**2)
def subspace_sphere(x, visible_ratio=1/2):
"""
"""
# here we could use an init function, that is this would
# preferably be a class
m = int(visible_ratio * len(x) + 1)
x = np.asarray(x)[np.random.permutation(len(x))[:m]]
return sum(x**2)
def pnorm(x, p=0.5):
return sum(np.abs(x)**p)**(1./p)
def grad_sphere(x, *args):
return 2*array(x, copy=False)
def grad_to_one(x, *args):
return array(x, copy=False) - 1
def sphere_pos(x):
"""Sphere (squared norm) test objective function"""
# return np.random.rand(1)[0]**0 * sum(x**2) + 1 * np.random.rand(1)[0]
c = 0.0
if x[0] < c:
return np.nan
return -c**2 + sum((x + 0)**2)
def spherewithoneconstraint(x):
return sum((x + 0)**2) if x[0] > 1 else np.nan
def elliwithoneconstraint(x, idx=[-1]):
return ellirot(x) if all(array(x)[idx] > 1) else np.nan
def spherewithnconstraints(x):
return sum((x + 0)**2) if all(array(x) > 1) else np.nan
# zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
def noisysphere(x, noise=2.10e-9, cond=1.0, noise_offset=0.10):
"""noise=10 does not work with default popsize, ``cma.NoiseHandler(dimension, 1e7)`` helps"""
return elli(x, cond=cond) * np.exp(0 + noise * np.random.randn() / len(x)) + noise_offset * np.random.rand()
def spherew(x):
"""Sphere (squared norm) with sum x_i = 1 test objective function"""
# return np.random.rand(1)[0]**0 * sum(x**2) + 1 * np.random.rand(1)[0]
# s = sum(abs(x))
# return sum((x/s+0)**2) - 1/len(x)
# return sum((x/s)**2) - 1/len(x)
return -0.01 * x[0] + abs(x[0])**-2 * sum(x[1:]**2)
def epslowsphere(x, eps=1e-7, Neff=lambda x: int(len(x)**0.5)):
"""TODO: define as wrapper"""
return np.mean(x[:Neff(x)]**2) + eps * np.mean(x**2)
def partsphere(x):
"""Sphere (squared norm) test objective function"""
partsphere.evaluations += 1
# return np.random.rand(1)[0]**0 * sum(x**2) + 1 * np.random.rand(1)[0]
dim = len(x)
x = array([x[i % dim] for i in range(2 * dim)])
N = 8
i = partsphere.evaluations % dim
# f = sum(x[i:i + N]**2)
f = sum(x[np.random.randint(dim, size=N)]**2)
return f
partsphere.evaluations = 0
def sectorsphere(x):
"""asymmetric Sphere (squared norm) test objective function"""
return sum(x**2) + (1e6 - 1) * sum(x[x < 0]**2)
def cornersphere(x):
"""Sphere (squared norm) test objective function constraint to the corner"""
nconstr = len(x) - 0
if any(x[:nconstr] < 1):
return np.NaN
return sum(x**2) - nconstr
def cornerelli(x):
""" """
if any(x < 1):
return np.NaN
return elli(x) - elli(np.ones(len(x)))
def cornerellirot(x):
""" """
if any(x < 1):
return np.NaN
return ellirot(x)
def normalSkew(f):
N = np.random.randn(1)[0]**2
if N < 1:
N = f * N # diminish blow up lower part
return N
def noiseC(x, func=sphere, fac=10, expon=0.8):
f = func(x)
N = np.random.randn(1)[0] / np.random.randn(1)[0]
return max(1e-19, f + (float(fac) / len(x)) * f**expon * N)
def noise(x, func=sphere, fac=10, expon=1):
f = func(x)
# R = np.random.randn(1)[0]
R = np.log10(f) + expon * abs(10 - np.log10(f)) * np.random.rand(1)[0]
# sig = float(fac)/float(len(x))
# R = log(f) + 0.5*log(f) * random.randn(1)[0]
# return max(1e-19, f + sig * (f**np.log10(f)) * np.exp(R))
# return max(1e-19, f * np.exp(sig * N / f**expon))
# return max(1e-19, f * normalSkew(f**expon)**sig)
return f + 10**R # == f + f**(1+0.5*RN)
def cigar(x, rot=0, cond=1e6, noise=0):
"""Cigar test objective function"""
if rot:
x = rotate(x)
x = [x] if isscalar(x[0]) else x # scalar into list
f = [(x[0]**2 + cond * sum(x[1:]**2)) * np.exp(noise * np.random.randn(1)[0] / len(x)) for x in x]
return f if len(f) > 1 else f[0] # 1-element-list into scalar
def grad_cigar(x, *args):
grad = 2 * 1e6 * np.array(x)
grad[0] /= 1e6
return grad
def diagonal_cigar(x, cond=1e6):
axis = np.ones(len(x)) / len(x)**0.5
proj = dot(axis, x) * axis
s = sum(proj**2)
s += cond * sum((x - proj)**2)
return s
def tablet(x, cond=1e6, rot=0):
"""Tablet test objective function"""
x = np.asarray(x)
if rot and rot is not tablet:
x = rotate(x)
x = [x] if isscalar(x[0]) else x # scalar into list
f = [cond * x[0]**2 + sum(x[1:]**2) for x in x]
return f if len(f) > 1 else f[0] # 1-element-list into scalar
def grad_tablet(x, *args):
grad = 2 * np.array(x)
grad[0] *= 1e6
return grad
def cigtab(y):
"""Cigtab test objective function"""
X = [y] if isscalar(y[0]) else y
f = [1e-4 * x[0]**2 + 1e4 * x[1]**2 + sum(x[2:]**2) for x in X]
return f if len(f) > 1 else f[0]
def cigtab2(x, condition=1e8, n_axes=None, n_short_axes=None):
"""cigtab with 5% long and short axes.
`n_axes: int`, if not `None`, sets the number of long axes to
`n_axes` and also the number of short axes if `n_short_axes` is
`None`.
"""
m = n_axes
if m is None:
m = max((1, int(0.05 * (len(x) + 1./2))))
ms = n_short_axes
if ms is None:
ms = m
x = np.asarray(x)
f = sum(x[m:-ms]**2)
f += condition**-0.5 * sum(x[:m]**2)
f += condition**0.5 * sum(x[-ms:]**2)
return f
def twoaxes(y):
"""Cigtab test objective function"""
X = [y] if isscalar(y[0]) else y
N2 = len(X[0]) // 2
f = [1e6 * sum(x[0:N2]**2) + sum(x[N2:]**2) for x in X]
return f if len(f) > 1 else f[0]
def ellirot(x):
return elli(array(x), 1)
def hyperelli(x):
N = len(x)
return sum((np.arange(1, N + 1) * x)**2)
def halfelli(x):
l = len(x) // 2
felli = elli(x[:l])
return felli + 1e-8 * sum(x[l:]**2)
def elli(x, rot=0, xoffset=0, cond=1e6, actuator_noise=0.0, both=False):
"""Ellipsoid test objective function"""
x = np.asarray(x)
if not isscalar(x[0]): # parallel evaluation
return [elli(xi, rot) for xi in x] # could save 20% overall
if rot:
x = rotate(x)
N = len(x)
if actuator_noise:
x = x + actuator_noise * np.random.randn(N)
ftrue = sum(cond**(np.arange(N) / (N - 1.)) * (x + xoffset)**2) \
if N > 1 else (x + xoffset)**2
alpha = 0.49 + 1. / N
beta = 1
felli = np.random.rand(1)[0]**beta * ftrue * \
max(1, (10.**9 / (ftrue + 1e-99))**(alpha * np.random.rand(1)[0]))
# felli = ftrue + 1*np.random.randn(1)[0] / (1e-30 +
# np.abs(np.random.randn(1)[0]))**0
if both:
return (felli, ftrue)
else:
# return felli # possibly noisy value
return ftrue # + np.random.randn()
def grad_elli(x, *args):
cond = 1e6
N = len(x)
return 2 * cond**(np.arange(N) / (N - 1.)) * array(x, copy=False)
def fun_as_arg(x, *args):
"""``fun_as_arg(x, fun, *more_args)`` calls ``fun(x, *more_args)``.
Use case::
fmin(cma.fun_as_arg, args=(fun,), gradf=grad_numerical)
calls fun_as_args(x, args) and grad_numerical(x, fun, args=args)
"""
fun = args[0]
more_args = args[1:] if len(args) > 1 else ()
return fun(x, *more_args)
def grad_numerical(x, func, epsilon=None):
"""symmetric gradient"""
eps = 1e-8 * (1 + abs(x)) if epsilon is None else epsilon
grad = np.zeros(len(x))
ei = np.zeros(len(x)) # float is 1.6 times faster than int
for i in _rglen(x):
ei[i] = eps[i]
grad[i] = (func(x + ei) - func(x - ei)) / (2*eps[i])
ei[i] = 0
return grad
def elliconstraint(x, cfac=1e8, tough=True, cond=1e6):
"""ellipsoid test objective function with "constraints" """
N = len(x)
f = sum(cond**(np.arange(N)[-1::-1] / (N - 1)) * x**2)
cvals = (x[0] + 1,
x[0] + 1 + 100 * x[1],
x[0] + 1 - 100 * x[1])
if tough:
f += cfac * sum(max(0, c) for c in cvals)
else:
f += cfac * sum(max(0, c + 1e-3)**2 for c in cvals)
return f
def rosen(x, alpha=1e2):
"""Rosenbrock test objective function"""
x = [x] if isscalar(x[0]) else x # scalar into list
x = np.asarray(x)
f = [sum(alpha * (x[:-1]**2 - x[1:])**2 + (1. - x[:-1])**2) for x in x]
return f if len(f) > 1 else f[0] # 1-element-list into scalar
def grad_rosen(x, *args):
N = len(x)
grad = np.zeros(N)
grad[0] = 2 * (x[0] - 1) + 200 * (x[1] - x[0]**2) * -2 * x[0]
i = np.arange(1, N - 1)
grad[i] = 2 * (x[i] - 1) - 400 * (x[i+1] - x[i]**2) * x[i] + 200 * (x[i] - x[i-1]**2)
grad[N-1] = 200 * (x[N-1] - x[N-2]**2)
return grad
def rosen_chained(x, alpha=1e2):
x = [x] if isscalar(x[0]) else x # scalar into list
f = [(1. - x[0])**2 + sum(alpha * (x[:-1]**2 - x[1:])**2) for x in x]
return f if len(f) > 1 else f[0] # 1-element-list into scalar
def diffpow(x, rot=0):
"""Diffpow test objective function"""
N = len(x)
if rot:
x = rotate(x)
return sum(np.abs(x)**(2. + 4.*np.arange(N) / (N - 1.)))**0.5
def rosenelli(x):
N = len(x)
Nhalf = int((N + 1) / 2)
return rosen(x[:Nhalf]) + elli(x[Nhalf:], cond=1)
def ridge(x, expo=2):
x = [x] if isscalar(x[0]) else x # scalar into list
f = [x[0] + 100 * np.sum(x[1:]**2)**(expo / 2.) for x in x]
return f if len(f) > 1 else f[0] # 1-element-list into scalar
def ridgecircle(x, expo=0.5):
"""happy cat by HG Beyer"""
a = len(x)
s = sum(x**2)
return ((s - a)**2)**(expo / 2) + s / a + sum(x) / a
def happycat(x, alpha=1. / 8):
s = sum(x**2)
return ((s - len(x))**2)**alpha + (s / 2 + sum(x)) / len(x) + 0.5
def flat(x):
return 1
return 1 if np.random.rand(1) < 0.9 else 1.1
return np.random.randint(1, 30)
def ackley(x):
"""default domain is ``[-32.768, 32.768]^n``"""
x = np.asarray(x)
a, b = 20, 0.2
s = np.exp(-b * np.sqrt(np.mean(x**2)))
scos = np.exp(np.mean(np.cos(2 * np.pi * x)))
return a * (1 - s) + (np.exp(1) - scos)
def branin(x):
# in [0,15]**2
y = x[1]
x = x[0] + 5
return (y - 5.1 * x**2 / 4 / np.pi**2 + 5 * x / np.pi - 6)**2 + 10 * (1 - 1 / 8 / np.pi) * np.cos(x) + 10 - 0.397887357729738160000
def goldsteinprice(x):
x1 = x[0]
x2 = x[1]
return (1 + (x1 + x2 + 1)**2 * (19 - 14 * x1 + 3 * x1**2 - 14 * x2 + 6 * x1 * x2 + 3 * x2**2)) * (
30 + (2 * x1 - 3 * x2)**2 * (18 - 32 * x1 + 12 * x1**2 + 48 * x2 - 36 * x1 * x2 + 27 * x2**2)) - 3
def griewank(x):
# was in [-600 600]
x = (600. / 5) * x
return 1 - np.prod(np.cos(x / np.sqrt(1. + np.arange(len(x))))) + sum(x**2) / 4e3
def rastrigin(x):
"""Rastrigin test objective function"""
if not isscalar(x[0]):
N = len(x[0])
return [10 * N + sum(xi**2 - 10 * np.cos(2 * np.pi * xi)) for xi in x]
# return 10*N + sum(x**2 - 10*np.cos(2*np.pi*x), axis=1)
N = len(x)
return 10 * N + sum(x**2 - 10 * np.cos(2 * np.pi * x))
def schaffer(x):
""" Schaffer function x0 in [-100..100]"""
N = len(x)
s = x[0:N - 1]**2 + x[1:N]**2
return sum(s**0.25 * (np.sin(50 * s**0.1)**2 + 1))
def schwefelelli(x):
s = 0
f = 0
for i in _rglen(x):
s += x[i]
f += s**2
return f
def schwefelmult(x, pen_fac=1e4):
"""multimodal Schwefel function with domain -500..500"""
y = [x] if isscalar(x[0]) else x
N = len(y[0])
f = array([418.9829 * N - 1.27275661e-5 * N - sum(x * np.sin(np.abs(x)**0.5))
+ pen_fac * sum((abs(x) > 500) * (abs(x) - 500)**2) for x in y])
return f if len(f) > 1 else f[0]
def schwefel2_22(x):
"""Schwefel 2.22 function"""
return sum(np.abs(x)) + np.prod(np.abs(x))
def optprob(x):
n = np.arange(len(x)) + 1
f = n * x * (1 - x)**(n - 1)
return sum(1 - f)
def lincon(x, theta=0.01):
"""ridge like linear function with one linear constraint"""
if x[0] < 0:
return np.NaN
return theta * x[1] + x[0]
def rosen_nesterov(x, rho=100):
"""needs exponential number of steps in a non-increasing
f-sequence.
x_0 = (-1,1,...,1)
See Jarre (2011) "On Nesterov's Smooth Chebyshev-Rosenbrock
Function"
"""
f = 0.25 * (x[0] - 1)**2
f += rho * sum((x[1:] - 2 * x[:-1]**2 + 1)**2)
return f
def powel_singular(x):
# ((8 * np.sin(7 * (x[i] - 0.9)**2)**2 ) + (6 * np.sin()))
res = np.sum((x[i - 1] + 10 * x[i])**2 + 5 * (x[i + 1] - x[i + 2])**2 +
(x[i] - 2 * x[i + 1])**4 + 10 * (x[i - 1] - x[i + 2])**4
for i in range(1, len(x) - 2))
return 1 + res
def styblinski_tang(x):
"""in [-5, 5]
found also in Lazar and Jarre 2016, optimum in f(-2.903534...)=0
"""
# x_opt = N * [-2.90353402], seems to have essentially
# (only) 2**N local optima
return (39.1661657037714171054273576010019 * len(x))**1 + \
sum(x**4 - 16 * x**2 + 5 * x) / 2
def trid(x):
return sum((x-1)**2) - sum(x[:-1] * x[1:])
def bukin(x):
"""Bukin function from Wikipedia, generalized simplistically from 2-D.
http://en.wikipedia.org/wiki/Test_functions_for_optimization"""
s = 0
for k in range((1+len(x)) // 2):
z = x[2 * k]
y = x[min((2*k + 1, len(x)-1))]
s += 100 * np.abs(y - 0.01 * z**2)**0.5 + 0.01 * np.abs(z + 10)
return s
def zerosum(x):
"""abs(sum xi) has an n-1 dimensionsal solution space.
http://infinity77.net/global_optimization/test_functions_nd_Z.html#go_benchmark.ZeroSum
https://github.com/CMA-ES/c-cmaes/issues/19#issue-323799789
"""
s = np.sum(x)
return 1 + 1e2 * np.abs(s)**0.5 if s else 0.0 | [
"764720843@qq.com"
] | 764720843@qq.com |
1a99d0ed0b4ee08a58a57690a57e1d9ec6635e68 | bbd8085b2e1c8555ac43a584e4987868feebde4e | /LTN.py | 101076dfced44cdc04bc0eaa4055e37615be48e4 | [] | no_license | jimmyyang886/News | 92716f89ec512273f359b8585940f572d52ed493 | 7328539d7b42f5f72b95ef206940a2bed1dfb9d6 | refs/heads/main | 2022-12-22T00:26:20.661593 | 2020-10-02T19:47:45 | 2020-10-02T19:47:45 | 300,720,207 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,975 | py | #!/usr/bin/env python
# coding: utf-8
import datetime
from datetime import date
import os
import random
import time
import requests
from bs4 import BeautifulSoup as bs4
#from pathvalidate import sanitize_filename
from codes import codes
from proxies_cyc import *
import requests.packages.urllib3
requests.packages.urllib3.disable_warnings()
headers = { "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/83.0.4103.97 Safari/537.36"}
domain = "https://news.ltn.com.tw/"
query = "search?keyword={keyword}&conditions={condition}&start_time={ST}&end_time={ET}&page={page}"
class ltn(object):
def __init__(self, query_list, publisher, txtpath):
self.query_list=query_list
self.txtpath=txtpath
self.publisher=publisher
self.LastnID= self.dlcheck()
self.news_id = 9999999
def dlcheck(self):
if len(os.listdir(self.txtpath)) != 0:
nID = []
for _file in os.listdir(self.txtpath):
_nID = _file[:-4]
nID.append(int(_nID))
LastnID = max(set(nID))
else:
LastnID = 888888
return LastnID
def start_query(self):
url = domain + query.format(keyword=self.query_list["keyword"],
condition=self.query_list["condition"],
ST=self.query_list["start_time"],
ET=self.query_list["end_time"],
page=self.query_list["page"])
print(f"URL: {url}\n")
try:
res = proxy_request_cycling(url, publisher, True)
#web_session = requests.session()
#res = web_session.get(url, headers=headers)
soup = bs4(res.text, "html.parser")
self.get_news_list(soup)
except Exception as e:
print("\n------ERROR----->")
print(f"Catch an Exception: {e}\nURL:{url}")
print("<------ERROR-----\n")
pass
def get_news_list(self,soup):
news_class = ['business', 'weeklybiz', 'politics']
news_list = soup.select("ul[class='searchlist boxTitle'] > li")
for news in news_list:
print(self.news_id, self.LastnID)
if int(self.news_id) <= self.LastnID:
break
pub_time = news.select("span")[0].text
article = news.select("a")[0]
print(f"News: {article.text}\n"
f"Link: {article.attrs['href']}\n"
f"Class: {article.attrs['href'].split('/')[-3]}")
if article.attrs['href'].split("/")[-3] in news_class:
self.news_id = article.attrs['href'].split("/")[-1]
if int(self.news_id)<=self.LastnID:
break
if not self.isNewsExists(pub_time):
title = article.text
link = article.attrs['href']
self.get_each_news(pub_time, title, link)
# time.sleep(random.randint(2, 5))
if int(self.news_id)>self.LastnID:
self.next_page_if_exists(soup)
pass
def get_each_news(self, pub_time: str, title: str, link: str):
try:
res= proxy_request_cycling(link, publisher, True)
# web_ss = requests.session()
# res = web_ss.get(link, headers=headers)
soup = bs4(res.text, "html.parser")
self.get_each_news_content(pub_time, title, link, soup)
except Exception as e:
print(f"Catch an Exception: \nID: {self.news_id}\nMSG: {e}\n\n")
pass
def isNewsExists(self, pub_time):
year = pub_time.split("-")[0]
file_path = f"./News/{year}/{self.news_id}.txt"
try:
return os.path.exists(file_path)
except Exception as e:
print(f"Check News is Exists: {e}")
return False
def next_page_if_exists(self, soup):
p_next = soup.select("a[data-desc='下一頁']")
if len(p_next) > 0:
self.query_list["page"] = p_next[0].attrs["href"].split("=")[-1]
self.start_query()
else:
query_list["end_time"] = query_list["start_time"]
query_list["start_time"] = query_list["start_time"] - datetime.timedelta(days=30 * 3)
query_list["page"] = 1
if query_list["start_time"] < datetime.datetime(2016, 1, 1).date():
print(f"Search start time: {query_list['start_time']}")
print(f"\n-----Finished-----\n\n")
return
else:
self.start_query()
def get_each_news_content(self, pub_time: str, title: str, link: str, soup: bs4):
all_content = ''
content_list = soup.findAll("p", attrs={'class': None})
for content in content_list:
# print(f"{content.text}")
if '一手掌握經濟脈動' in content.text:
break
elif '示意圖' in content.text or len(content.text) <= 1:
continue
else:
all_content += content.text
# print(f"{all_content}")
self.write_to_file( pub_time, title, link, all_content)
pass
def write_to_file(self, pub_time: str, title: str, link: str, content: str):
current_year = pub_time.split("-")[0]
try:
os.makedirs(self.txtpath, exist_ok=True)
#file_name = sanitize_filename(file_name)
except IOError as e:
print(f"Write Into File Error:\nTitle: {title}\nMSG: {e}")
finally:
print(f"\nWrite Into: {self.txtpath +'/'+ self.news_id + '.txt'}\n")
#if len(file_name) > 0:
with open(self.txtpath +'/'+ self.news_id + ".txt", "w+", encoding='utf-8') as f:
f.write(f"")
f.write(f"標題: {title}\n")
f.write(f"時間: {pub_time}\n")
# f.write(f"記者: {reporter}\n")
f.write("========\n")
f.write(content)
f.close()
pass
# Last Disconnect2019-09-22 ~ 2019-12-21
# Stop at 2019-03-26 ~ 2019-06-24
# Stop at 2018-03-31 ~ 2018-06-29
# Stop at 2017-01-05 ~ 2017-04-05
#now = datetime.datetime(2017, 4, 5).date()
now = date.today()
start_time = time.time()
for sid, v in codes.items():
if v.type == "股票" and v.market == "上市":
publisher = 'LTN'
txtpath=publisher+'/'+sid+'_'+v.name
if not os.path.exists(txtpath):
os.mkdir(txtpath)
query_list = {"keyword": v.name, "condition": "and", "start_time": now - datetime.timedelta(days=30 * 3),
"end_time": now, "page": 1}
stock=ltn(query_list, publisher, txtpath)
stock.start_query()
| [
"noreply@github.com"
] | jimmyyang886.noreply@github.com |
0e997f99f5ae4ff61403fd37cd1941d7cffea84c | 9a541359b4faf1936028d5be9b0a4022e0182e81 | /insert-csv-into-el.py | 4fa6ffab215ce5c67a8b569cafa3c1ad33da8f90 | [] | no_license | oneum20/dataframe-and-elasticsearch-example | c05f95dfae1045355f14fb52af53e4c256ad3bba | adc5f0856f90cafee199d45225eea7257df73eb4 | refs/heads/main | 2023-06-11T16:03:39.819259 | 2021-06-27T06:33:17 | 2021-06-27T06:33:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 766 | py | import numpy as np
import pandas as pd
from elasticsearch import Elasticsearch
from elasticsearch import helpers
# Set variables
csv_file = input("CSV Path : ")
ip = input("ElasticSearch Server IP : ")
port = input("ElasticSearch Server Port : ")
idx = input("ElasticSearch Index : ")
type = input("ElasticSearch Type : ")
# get csv data
data = pd.read_csv(csv_file).replace(np.NaN, '', regex=True)
# config el info
es = Elasticsearch(host=ip, port=port)
# check index & create index
if not es.indices.exists(index=idx):
print("Not exist index... Create index : ", idx)
es.indices.create(index=idx,body={})
# insert df into el
documents = data.to_dict(orient='records')
helpers.bulk(es, documents, index=idx, doc_type=type, raise_on_error=True)
| [
"noreply@github.com"
] | oneum20.noreply@github.com |
b3f9172581d47d657254fbf2a9833535b3b426ff | 2ec6e84f6418e3bd94c549eea05a2b2c0a05d683 | /header_operations.py | bfcdcce469105a4d4ec8acaa69bd0fed3943fbeb | [] | no_license | GerGotha/adimitools | a901f6a3882f74e3efdf3e7d3242d52c2760f607 | b6beeccfc19fdccf6a2c68077c30b76d273290c7 | refs/heads/master | 2021-07-18T20:32:48.935601 | 2018-10-11T02:44:53 | 2018-10-11T02:44:53 | 152,511,338 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 196,175 | py | ###################################################
# header_operations.py
# This file cfontains opcode declarations
# DO NOT EDIT THIS FILE!
###################################################
# Thanks to Lav and other talented members
# of the modding community for their help
# improving the comments for the module system!
###################################################
#--------------------------------------------------------------------------
# CONTROL OPERATIONS
#--------------------------------------------------------------------------
call_script = 1 # (call_script,<script_id>),
end_try = 3 # deprecated, use try_end instead
try_end = 3 # (try_end),
try_begin = 4 # (try_begin),
else_try_begin = 5 # deprecated, use else_try instead
else_try = 5 # (else_try),
try_for_range = 6 # Works like a for loop from lower-bound up to (upper-bound - 1)
# (try_for_range,<destination>,<lower_bound>,<upper_bound>),
try_for_range_backwards = 7 # Same as above but starts from (upper-bound - 1) down-to lower bound.
# (try_for_range_backwards,<destination>,<lower_bound>,<upper_bound>),
try_for_parties = 11 # (try_for_parties,<destination>),
try_for_agents = 12 # (try_for_agents, <destination>, [<position_no>], [<radius_fixed_point>]), #avoid using pos0
try_for_prop_instances = 16 # (try_for_prop_instances, <destination>, [<scene_prop_id>]), # if scene_prop_id is not given, it loops through all prop instances.
try_for_players = 17 # (try_for_players, <destination>, [skip_server]),
store_script_param_1 = 21 # (store_script_param_1,<destination>), --(Within a script) stores the first script parameter.
store_script_param_2 = 22 # (store_script_param_2,<destination>), --(Within a script) stores the second script parameter.
store_script_param = 23 # (store_script_param,<destination>,<script_param_no>), --(Within a script) stores <script_param_no>th script parameter.
#--------------------------------------------------------------------------
# CONDITION OPERATIONS
#--------------------------------------------------------------------------
ge = 30 # greater than or equal to -- (ge,<value>,<value>),
eq = 31 # equal to -- (eq,<value>,<value>),
gt = 32 # greater than -- (gt,<value>,<value>),
is_between = 33 # (is_between,<value>,<lower_bound>,<upper_bound>), #greater than or equal to lower bound and less than upper bound
entering_town = 36 # (entering_town,<town_id>),
map_free = 37 # (map_free),
encountered_party_is_attacker = 39 # (encountered_party_is_attacker),
# Checks that the party encountered on the world map was following player (i.e. either player was trying to run away or at the very least this is a head-on clash).
conversation_screen_is_active = 42 # (conversation_screen_active), #used in mission template triggers only
# Checks that the player is currently in dialogue with some agent. Can only be used in triggers of module_mission_templates.py file.
in_meta_mission = 44 # deprecated, do not use.
set_player_troop = 47 # (set_player_troop,<troop_id>),
store_repeat_object = 50 # stores the index of a repeated dialog option for repeat_for_factions, etc...
get_operation_set_version = 55 # (get_operation_set_version, <destination>),
set_physics_delta_time = 58 # (set_physics_delta_time, <fixed_value>), #Default is 0.025 (40 fps).
set_result_string = 60 # sets the result string for game scripts that need one (set_result_string, <string_id>),
is_camera_in_first_person = 61 # (is_camera_in_first_person),
set_camera_in_first_person = 62 # (set_camera_in_first_person, <value>), # 1 = first, 0 = third person
game_key_get_mapped_key_name = 65 # (game_key_get_mapped_key_name, <string_register>, <game_key>),
key_is_down = 70 # fails if the key is not currently down (key_is_down, <key_id>),
key_clicked = 71 # fails if the key is not clicked on the specific frame (key_clicked, <key_id>),
game_key_is_down = 72 # fails if the game key is not currently down (key_is_down, <game_key_id>),
game_key_clicked = 73 # fails if the game key is not clicked on the specific frame (game_key_clicked, <game_key_id>),
mouse_get_position = 75 # (mouse_get_position, <position_no>), #x and y values of position are filled
omit_key_once = 77 # game omits any bound action for the key once (omit_key_once, <key_id>),
clear_omitted_keys = 78 # (clear_omitted_keys),
get_global_cloud_amount = 90 # (get_global_cloud_amount, <destination>), #returns a value between 0-100
set_global_cloud_amount = 91 # (set_global_cloud_amount, <value>), #value is clamped to 0-100
get_global_haze_amount = 92 # (get_global_haze_amount, <destination>), #returns a value between 0-100
set_global_haze_amount = 93 # (set_global_haze_amount, <value>), #value is clamped to 0-100
hero_can_join = 101 # (hero_can_join, [party_id]),
hero_can_join_as_prisoner = 102 # (hero_can_join_as_prisoner, [party_id]),
party_can_join = 103 # (party_can_join),
party_can_join_as_prisoner = 104 # (party_can_join_as_prisoner),
troops_can_join = 105 # (troops_can_join,<value>),
troops_can_join_as_prisoner = 106 # (troops_can_join_as_prisoner,<value>),
party_can_join_party = 107 # (party_can_join_party, <joiner_party_id>, <host_party_id>,[flip_prisoners]),
party_end_battle = 108 # (party_end_battle,<party_no>),
main_party_has_troop = 110 # (main_party_has_troop,<troop_id>),
party_is_in_town = 130 # (party_is_in_town,<party_id_1>,<party_id_2>),
party_is_in_any_town = 131 # (party_is_in_any_town,<party_id>),
party_is_active = 132 # (party_is_active,<party_id>),
player_has_item = 150 # (player_has_item,<item_id>),
troop_has_item_equipped = 151 # (troop_has_item_equipped,<troop_id>,<item_id>),
troop_is_mounted = 152 # (troop_is_mounted,<troop_id>),
troop_is_guarantee_ranged = 153 # (troop_is_guarantee_ranged, <troop_id>),
troop_is_guarantee_horse = 154 # (troop_is_guarantee_horse, <troop_id>),
check_quest_active = 200 # (check_quest_active,<quest_id>),
check_quest_finished = 201 # (check_quest_finished,<quest_id>),
check_quest_succeeded = 202 # (check_quest_succeeded,<quest_id>),
check_quest_failed = 203 # (check_quest_failed,<quest_id>),
check_quest_concluded = 204 # (check_quest_concluded,<quest_id>),
is_trial_version = 250 # (is_trial_version),
is_edit_mode_enabled = 255 # (is_edit_mode_enabled),
options_get_damage_to_player = 260 # (options_get_damage_to_player, <destination>), #0 = 1/4, 1 = 1/2, 2 = 1/1
options_set_damage_to_player = 261 # (options_set_damage_to_player, <value>), #0 = 1/4, 1 = 1/2, 2 = 1/1
options_get_damage_to_friends = 262 # (options_get_damage_to_friends, <destination>), #0 = 1/2, 1 = 3/4, 2 = 1/1
options_set_damage_to_friends = 263 # (options_set_damage_to_friends, <value>), #0 = 1/2, 1 = 3/4, 2 = 1/1
options_get_combat_ai = 264 # (options_get_combat_ai, <destination>), #0 = good, 1 = average, 2 = poor
options_set_combat_ai = 265 # (options_set_combat_ai, <value>), #0 = good, 1 = average, 2 = poor
options_get_campaign_ai = 266 # (options_get_campaign_ai, <destination>), #0 = good, 1 = average, 2 = poor
options_set_campaign_ai = 267 # (options_set_campaign_ai, <value>), #0 = good, 1 = average, 2 = poor
options_get_combat_speed = 268 # (options_get_combat_speed, <destination>), #0 = slowest, 1 = slower, 2 = normal, 3 = faster, 4 = fastest
options_set_combat_speed = 269 # (options_set_combat_speed, <value>), #0 = slowest, 1 = slower, 2 = normal, 3 = faster, 4 = fastest
options_get_battle_size = 270 # (options_get_battle_size, <destination>), # returns battle size slider value in 0-1000 range.
options_set_battle_size = 271 # (options_set_battle_size, <value>), # sets battle size slider value in 0-1000 range.
profile_get_banner_id = 350 # (profile_get_banner_id, <destination>),
profile_set_banner_id = 351 # (profile_set_banner_id, <value>),
get_achievement_stat = 370 # (get_achievement_stat, <destination>, <achievement_id>, <stat_index>),
set_achievement_stat = 371 # (set_achievement_stat, <achievement_id>, <stat_index>, <value>),
unlock_achievement = 372 # (unlock_achievement, <achievement_id>),
send_message_to_url = 380 # (send_message_to_url, <string_id>, <encode_url>), #result will be returned to script_game_receive_url_response
# multiplayer
multiplayer_send_message_to_server = 388 # (multiplayer_send_int_to_server, <message_type>),
multiplayer_send_int_to_server = 389 # (multiplayer_send_int_to_server, <message_type>, <value>),
multiplayer_send_2_int_to_server = 390 # (multiplayer_send_2_int_to_server, <message_type>, <value>, <value>),
multiplayer_send_3_int_to_server = 391 # (multiplayer_send_3_int_to_server, <message_type>, <value>, <value>, <value>),
multiplayer_send_4_int_to_server = 392 # (multiplayer_send_4_int_to_server, <message_type>, <value>, <value>, <value>, <value>),
multiplayer_send_string_to_server = 393 # (multiplayer_send_string_to_server, <message_type>, <string_id>),
multiplayer_send_message_to_player = 394 # (multiplayer_send_message_to_player, <player_id>, <message_type>),
multiplayer_send_int_to_player = 395 # (multiplayer_send_int_to_player, <player_id>, <message_type>, <value>),
multiplayer_send_2_int_to_player = 396 # (multiplayer_send_2_int_to_player, <player_id>, <message_type>, <value>, <value>),
multiplayer_send_3_int_to_player = 397 # (multiplayer_send_3_int_to_player, <player_id>, <message_type>, <value>, <value>, <value>),
multiplayer_send_4_int_to_player = 398 # (multiplayer_send_4_int_to_player, <player_id>, <message_type>, <value>, <value>, <value>, <value>),
multiplayer_send_string_to_player = 399 # (multiplayer_send_string_to_player, <player_id>, <message_type>, <string_id>),
get_max_players = 400 # (get_max_players, <destination>),
player_is_active = 401 # (player_is_active, <player_id>),
player_get_team_no = 402 # (player_get_team_no, <destination>, <player_id>),
player_set_team_no = 403 # (player_get_team_no, <destination>, <player_id>),
player_get_troop_id = 404 # (player_get_troop_id, <destination>, <player_id>),
player_set_troop_id = 405 # (player_set_troop_id, <destination>, <player_id>),
player_get_agent_id = 406 # (player_get_agent_id, <destination>, <player_id>),
player_get_gold = 407 # (player_get_gold, <destination>, <player_id>),
player_set_gold = 408 # (player_set_gold, <player_id>, <value>, <max_value>), #set max_value to 0 if no limit is wanted
player_spawn_new_agent = 409 # (player_spawn_new_agent, <player_id>, <entry_point>),
player_add_spawn_item = 410 # (player_add_spawn_item, <player_id>, <item_slot_no>, <item_id>),
multiplayer_get_my_team = 411 # (multiplayer_get_my_team, <destination>),
multiplayer_get_my_troop = 412 # (multiplayer_get_my_troop, <destination>),
multiplayer_set_my_troop = 413 # (multiplayer_get_my_troop, <destination>),
multiplayer_get_my_gold = 414 # (multiplayer_get_my_gold, <destination>),
multiplayer_get_my_player = 415 # (multiplayer_get_my_player, <destination>),
multiplayer_clear_scene = 416 # (multiplayer_clear_scene),
multiplayer_is_server = 417 # (multiplayer_is_server),
multiplayer_is_dedicated_server = 418 # (multiplayer_is_dedicated_server),
game_in_multiplayer_mode = 419 # (game_in_multiplayer_mode),
multiplayer_make_everyone_enemy = 420 # (multiplayer_make_everyone_enemy),
player_control_agent = 421 # (player_control_agent, <player_id>, <agent_id>),
player_get_item_id = 422 # (player_get_item_id, <destination>, <player_id>, <item_slot_no>), #only for server
player_get_banner_id = 423 # (player_get_banner_id, <destination>, <player_id>),
game_get_reduce_campaign_ai = 424 # (game_get_reduce_campaign_ai, <destination>), #depreciated, use options_get_campaign_ai instead
multiplayer_find_spawn_point = 425 # (multiplayer_find_spawn_point, <destination>, <team_no>, <examine_all_spawn_points>, <is_horseman>),
set_spawn_effector_scene_prop_kind = 426 # (set_spawn_effector_scene_prop_kind <team_no> <scene_prop_kind_no>)
set_spawn_effector_scene_prop_id = 427 # (set_spawn_effector_scene_prop_id <scene_prop_id>)
player_set_is_admin = 429 # (player_set_is_admin, <player_id>, <value>), #value is 0 or 1
player_is_admin = 430 # (player_is_admin, <player_id>),
player_get_score = 431 # (player_get_score, <destination>, <player_id>),
player_set_score = 432 # (player_set_score,<player_id>, <value>),
player_get_kill_count = 433 # (player_get_kill_count, <destination>, <player_id>),
player_set_kill_count = 434 # (player_set_kill_count,<player_id>, <value>),
player_get_death_count = 435 # (player_get_death_count, <destination>, <player_id>),
player_set_death_count = 436 # (player_set_death_count, <player_id>, <value>),
player_get_ping = 437 # (player_get_ping, <destination>, <player_id>),
player_is_busy_with_menus = 438 # (player_is_busy_with_menus, <player_id>),
player_get_is_muted = 439 # (player_get_is_muted, <destination>, <player_id>),
player_set_is_muted = 440 # (player_set_is_muted, <player_id>, <value>, [mute_for_everyone]), #mute_for_everyone optional parameter should be set to 1 if player is muted for everyone (this works only on server).
player_get_unique_id = 441 # (player_get_unique_id, <destination>, <player_id>), #can only bew used on server side
player_get_gender = 442 # (player_get_gender, <destination>, <player_id>),
team_get_bot_kill_count = 450 # (team_get_bot_kill_count, <destination>, <team_id>),
team_set_bot_kill_count = 451 # (team_get_bot_kill_count, <destination>, <team_id>),
team_get_bot_death_count = 452 # (team_get_bot_death_count, <destination>, <team_id>),
team_set_bot_death_count = 453 # (team_get_bot_death_count, <destination>, <team_id>),
team_get_kill_count = 454 # (team_get_kill_count, <destination>, <team_id>),
team_get_score = 455 # (team_get_score, <destination>, <team_id>),
team_set_score = 456 # (team_set_score, <team_id>, <value>),
team_set_faction = 457 # (team_set_faction, <team_id>, <faction_id>),
team_get_faction = 458 # (team_get_faction, <destination>, <team_id>),
player_save_picked_up_items_for_next_spawn = 459 # (player_save_picked_up_items_for_next_spawn, <player_id>),
player_get_value_of_original_items = 460 # (player_get_value_of_original_items, <player_id>), #this operation returns values of the items, but default troop items will be counted as zero (except horse)
player_item_slot_is_picked_up = 461 # (player_item_slot_is_picked_up, <player_id>, <item_slot_no>), #item slots are overriden when player picks up an item and stays alive until the next round
kick_player = 465 # (kick_player, <player_id>),
ban_player = 466 # (ban_player, <player_id>, <value>, <player_id>), #set value = 1 for banning temporarily, assign 2nd player id as the administrator player id if banning is permanent
save_ban_info_of_player = 467 # (save_ban_info_of_player, <player_id>),
ban_player_using_saved_ban_info = 468 # (ban_player_using_saved_ban_info),
start_multiplayer_mission = 470 # (start_multiplayer_mission, <mission_template_id>, <scene_id>, <started_manually>),
server_add_message_to_log = 473 # (server_add_message_to_log, <string_id>),
server_get_renaming_server_allowed = 475 # (server_get_renaming_server_allowed, <destination>), #0-1
server_get_changing_game_type_allowed= 476 # (server_get_changing_game_type_allowed, <destination>), #0-1
##477 used for: server_set_anti_cheat = 477 # (server_set_anti_cheat, <value>), #0 = off, 1 = on
server_get_combat_speed = 478 # (server_get_combat_speed, <destination>), #0-2
server_set_combat_speed = 479 # (server_set_combat_speed, <value>), #0-2
server_get_friendly_fire = 480 # (server_get_friendly_fire, <destination>),
server_set_friendly_fire = 481 # (server_set_friendly_fire, <value>), #0 = off, 1 = on
server_get_control_block_dir = 482 # (server_get_control_block_dir, <destination>),
server_set_control_block_dir = 483 # (server_set_control_block_dir, <value>), #0 = automatic, 1 = by mouse movement
server_set_password = 484 # (server_set_password, <string_id>),
server_get_add_to_game_servers_list = 485 # (server_get_add_to_game_servers_list, <destination>),
server_set_add_to_game_servers_list = 486 # (server_set_add_to_game_servers_list, <value>),
server_get_ghost_mode = 487 # (server_get_ghost_mode, <destination>),
server_set_ghost_mode = 488 # (server_set_ghost_mode, <value>),
server_set_name = 489 # (server_set_name, <string_id>),
server_get_max_num_players = 490 # (server_get_max_num_players, <destination>),
server_set_max_num_players = 491 # (server_set_max_num_players, <value>),
server_set_welcome_message = 492 # (server_set_welcome_message, <string_id>),
server_get_melee_friendly_fire = 493 # (server_get_melee_friendly_fire, <destination>),
server_set_melee_friendly_fire = 494 # (server_set_melee_friendly_fire, <value>), #0 = off, 1 = on
server_get_friendly_fire_damage_self_ratio = 495 # (server_get_friendly_fire_damage_self_ratio, <destination>),
server_set_friendly_fire_damage_self_ratio = 496 # (server_set_friendly_fire_damage_self_ratio, <value>), #0-100
server_get_friendly_fire_damage_friend_ratio = 497 # (server_get_friendly_fire_damage_friend_ratio, <destination>),
server_set_friendly_fire_damage_friend_ratio = 498 # (server_set_friendly_fire_damage_friend_ratio, <value>), #0-100
server_get_anti_cheat = 499 # (server_get_anti_cheat, <destination>),
server_set_anti_cheat = 477 # (server_set_anti_cheat, <value>), #0 = off, 1 = on
## Set_slot operations. These assign a value to a slot.
troop_set_slot = 500 # (troop_set_slot,<troop_id>,<slot_no>,<value>),
party_set_slot = 501 # (party_set_slot,<party_id>,<slot_no>,<value>),
faction_set_slot = 502 # (faction_set_slot,<faction_id>,<slot_no>,<value>),
scene_set_slot = 503 # (scene_set_slot,<scene_id>,<slot_no>,<value>),
party_template_set_slot = 504 # (party_template_set_slot,<party_template_id>,<slot_no>,<value>),
agent_set_slot = 505 # (agent_set_slot,<agent_id>,<slot_no>,<value>),
quest_set_slot = 506 # (quest_set_slot,<quest_id>,<slot_no>,<value>),
item_set_slot = 507 # (item_set_slot,<item_id>,<slot_no>,<value>),
player_set_slot = 508 # (player_set_slot,<player_id>,<slot_no>,<value>),
team_set_slot = 509 # (team_set_slot,<team_id>,<slot_no>,<value>),
scene_prop_set_slot = 510 # (scene_prop_set_slot,<scene_prop_instance_id>,<slot_no>,<value>),
## Get_slot operations. These retrieve the value of a slot.
troop_get_slot = 520 # (troop_get_slot,<destination>,<troop_id>,<slot_no>),
party_get_slot = 521 # (party_get_slot,<destination>,<party_id>,<slot_no>),
faction_get_slot = 522 # (faction_get_slot,<destination>,<faction_id>,<slot_no>),
scene_get_slot = 523 # (scene_get_slot,<destination>,<scene_id>,<slot_no>),
party_template_get_slot = 524 # (party_template_get_slot,<destination>,<party_template_id>,<slot_no>),
agent_get_slot = 525 # (agent_get_slot,<destination>,<agent_id>,<slot_no>),
quest_get_slot = 526 # (quest_get_slot,<destination>,<quest_id>,<slot_no>),
item_get_slot = 527 # (item_get_slot,<destination>,<item_id>,<slot_no>),
player_get_slot = 528 # (player_get_slot,<destination>,<player_id>,<slot_no>),
team_get_slot = 529 # (team_get_slot,<destination>,<player_id>,<slot_no>),
scene_prop_get_slot = 530 # (scene_prop_get_slot,<destination>,<scene_prop_instance_id>,<slot_no>),
## slot_eq operations. These check whether the value of a slot is equal to a given value.
troop_slot_eq = 540 # (troop_slot_eq,<troop_id>,<slot_no>,<value>),
party_slot_eq = 541 # (party_slot_eq,<party_id>,<slot_no>,<value>),
faction_slot_eq = 542 # (faction_slot_eq,<faction_id>,<slot_no>,<value>),
scene_slot_eq = 543 # (scene_slot_eq,<scene_id>,<slot_no>,<value>),
party_template_slot_eq = 544 # (party_template_slot_eq,<party_template_id>,<slot_no>,<value>),
agent_slot_eq = 545 # (agent_slot_eq,<agent_id>,<slot_no>,<value>),
quest_slot_eq = 546 # (quest_slot_eq,<quest_id>,<slot_no>,<value>),
item_slot_eq = 547 # (item_slot_eq,<item_id>,<slot_no>,<value>),
player_slot_eq = 548 # (player_slot_eq,<player_id>,<slot_no>,<value>),
team_slot_eq = 549 # (team_slot_eq,<team_id>,<slot_no>,<value>),
scene_prop_slot_eq = 550 # (scene_prop_slot_eq,<scene_prop_instance_id>,<slot_no>,<value>),
## slot_ge operations. These check whether the value of a slot is greater than or equal to a given value.
troop_slot_ge = 560 # (troop_slot_ge,<troop_id>,<slot_no>,<value>),
party_slot_ge = 561 # (party_slot_ge,<party_id>,<slot_no>,<value>),
faction_slot_ge = 562 # (faction_slot_ge,<faction_id>,<slot_no>,<value>),
scene_slot_ge = 563 # (scene_slot_ge,<scene_id>,<slot_no>,<value>),
party_template_slot_ge = 564 # (party_template_slot_ge,<party_template_id>,<slot_no>,<value>),
agent_slot_ge = 565 # (agent_slot_ge,<agent_id>,<slot_no>,<value>),
quest_slot_ge = 566 # (quest_slot_ge,<quest_id>,<slot_no>,<value>),
item_slot_ge = 567 # (item_slot_ge,<item_id>,<slot_no>,<value>),
player_slot_ge = 568 # (player_slot_ge,<player_id>,<slot_no>,<value>),
team_slot_ge = 569 # (team_slot_ge,<team_id>,<slot_no>,<value>),
scene_prop_slot_ge = 570 # (scene_prop_slot_ge,<scene_prop_instance_id>,<slot_no>,<value>),
play_sound_at_position = 599 # (play_sound_at_position, <sound_id>, <position_no>, [options]),
play_sound = 600 # (play_sound,<sound_id>,[options]),
play_track = 601 # (play_track,<track_id>, [options]), # 0 = default, 1 = fade out current track, 2 = stop current track
play_cue_track = 602 # (play_cue_track,<track_id>), #starts immediately
music_set_situation = 603 # (music_set_situation, <situation_type>),
music_set_culture = 604 # (music_set_culture, <culture_type>),
stop_all_sounds = 609 # (stop_all_sounds, [options]), # 0 = stop only looping sounds, 1 = stop all sounds
store_last_sound_channel = 615 # (store_last_sound_channel, <destination>),
stop_sound_channel = 616 # (stop_sound_channel, <sound_channel_no>),
copy_position = 700 # copies position_no_2 to position_no_1
# (copy_position,<position_no_1>,<position_no_2>),
init_position = 701 # (init_position,<position_no>),
get_trigger_object_position = 702 # (get_trigger_object_position,<position_no>),
get_angle_between_positions = 705 # (get_angle_between_positions, <destination_fixed_point>, <position_no_1>, <position_no_2>),
position_has_line_of_sight_to_position = 707 # (position_has_line_of_sight_to_position, <position_no_1>, <position_no_2>),
get_distance_between_positions = 710 # gets distance in centimeters. # (get_distance_between_positions,<destination>,<position_no_1>,<position_no_2>),
get_distance_between_positions_in_meters = 711 # gets distance in meters. # (get_distance_between_positions_in_meters,<destination>,<position_no_1>,<position_no_2>),
get_sq_distance_between_positions = 712 # gets squared distance in centimeters # (get_sq_distance_between_positions,<destination>,<position_no_1>,<position_no_2>),
get_sq_distance_between_positions_in_meters = 713 # gets squared distance in meters # (get_sq_distance_between_positions_in_meters,<destination>,<position_no_1>,<position_no_2>),
position_is_behind_position = 714 # (position_is_behind_position,<position_no_1>,<position_no_2>),
get_sq_distance_between_position_heights = 715 # gets squared distance in centimeters # (get_sq_distance_between_position_heights,<destination>,<position_no_1>,<position_no_2>),
position_transform_position_to_parent = 716 # (position_transform_position_to_parent,<dest_position_no>,<position_no>,<position_no_to_be_transformed>),
position_transform_position_to_local = 717 # (position_transform_position_to_local, <dest_position_no>,<position_no>,<position_no_to_be_transformed>),
position_copy_rotation = 718 # (position_copy_rotation,<position_no_1>,<position_no_2>), copies rotation of position_no_2 to position_no_1
position_copy_origin = 719 # (position_copy_origin,<position_no_1>,<position_no_2>), copies origin of position_no_2 to position_no_1
position_move_x = 720 # movement is in cms, [0 = local; 1=global]
# (position_move_x,<position_no>,<movement>,[value]),
position_move_y = 721 # (position_move_y,<position_no>,<movement>,[value]),
position_move_z = 722 # (position_move_z,<position_no>,<movement>,[value]),
position_rotate_x = 723 # (position_rotate_x,<position_no>,<angle>),
position_rotate_y = 724 # (position_rotate_y,<position_no>,<angle>),
position_rotate_z = 725 # (position_rotate_z,<position_no>,<angle>,[use_global_z_axis]), # set use_global_z_axis as 1 if needed, otherwise you don't have to give that.
position_get_x = 726 # (position_get_x,<destination_fixed_point>,<position_no>), #x position in meters * fixed point multiplier is returned
position_get_y = 727 # (position_get_y,<destination_fixed_point>,<position_no>), #y position in meters * fixed point multiplier is returned
position_get_z = 728 # (position_get_z,<destination_fixed_point>,<position_no>), #z position in meters * fixed point multiplier is returned
position_set_x = 729 # (position_set_x,<position_no>,<value_fixed_point>), #meters / fixed point multiplier is set
position_set_y = 730 # (position_set_y,<position_no>,<value_fixed_point>), #meters / fixed point multiplier is set
position_set_z = 731 # (position_set_z,<position_no>,<value_fixed_point>), #meters / fixed point multiplier is set
position_get_scale_x = 735 # (position_get_scale_x,<destination_fixed_point>,<position_no>), #x scale in meters * fixed point multiplier is returned
position_get_scale_y = 736 # (position_get_scale_y,<destination_fixed_point>,<position_no>), #y scale in meters * fixed point multiplier is returned
position_get_scale_z = 737 # (position_get_scale_z,<destination_fixed_point>,<position_no>), #z scale in meters * fixed point multiplier is returned
position_rotate_x_floating = 738 # (position_rotate_x_floating,<position_no>,<angle>), #angle in degree * fixed point multiplier
position_rotate_y_floating = 739 # (position_rotate_y_floating,<position_no>,<angle>), #angle in degree * fixed point multiplier
position_rotate_z_floating = 734 # (position_rotate_z_floating,<position_no>,<angle>), #angle in degree * fixed point multiplier
position_get_rotation_around_z = 740 # (position_get_rotation_around_z,<destination>,<position_no>), #rotation around z axis is returned as angle
position_normalize_origin = 741 # (position_normalize_origin,<destination_fixed_point>,<position_no>),
# destination = convert_to_fixed_point(length(position.origin))
# position.origin *= 1/length(position.origin) #so it normalizes the origin vector
position_get_rotation_around_x = 742 # (position_get_rotation_around_x, <destination>, <position_no>), #rotation around x axis is returned as angle
position_get_rotation_around_y = 743 # (position_get_rotation_around_y, <destination>, <position_no>), #rotation around y axis is returned as angle
position_set_scale_x = 744 # (position_set_scale_x, <position_no>, <value_fixed_point>), #x scale in meters / fixed point multiplier is set
position_set_scale_y = 745 # (position_set_scale_y, <position_no>, <value_fixed_point>), #y scale in meters / fixed point multiplier is set
position_set_scale_z = 746 # (position_set_scale_z, <position_no>, <value_fixed_point>), #z scale in meters / fixed point multiplier is set
position_get_screen_projection = 750 # (position_get_screen_projection, <position_no_1>, <position_no_2>), returns screen projection of position_no_2 to position_no_1
mouse_get_world_projection = 751 # (mouse_get_world_projection, <position_no_1>, <position_no_2>), returns camera position (position_no_1) and mouse projection to back of world (position_no_2)
position_set_z_to_ground_level = 791 # (position_set_z_to_ground_level, <position_no>), #only works during a mission
position_get_distance_to_terrain= 792 # (position_get_distance_to_terrain, <destination_fixed_point>, <position_no>), #only works during a mission
position_get_distance_to_ground_level = 793 # (position_get_distance_to_ground_level, <destination>, <position_no>), #only works during a mission
start_presentation = 900 # (start_presentation, <presentation_id>),
start_background_presentation = 901 # (start_background_presentation, <presentation_id>), #can only be used in game menus
presentation_set_duration = 902 # (presentation_set_duration, <duration-in-1/100-seconds>), #there must be an active presentation
is_presentation_active = 903 # (is_presentation_active, <presentation_id),
create_text_overlay = 910 # (create_text_overlay, <destination>, <string_id>), #returns overlay id
create_mesh_overlay = 911 # (create_mesh_overlay, <destination>, <mesh_id>), #returns overlay id
create_button_overlay = 912 # (create_button_overlay, <destination>, <string_id>), #returns overlay id
create_image_button_overlay = 913 # (create_image_button_overlay, <destination>, <mesh_id>, <mesh_id>), #returns overlay id. second mesh is the pressed button mesh
create_slider_overlay = 914 # (create_slider_overlay, <destination>, <min_value>, <max_value>), #returns overlay id
create_progress_overlay = 915 # (create_progress_overlay, <destination>, <min_value>, <max_value>), #returns overlay id
create_combo_button_overlay = 916 # (create_combo_button_overlay, <destination>), #returns overlay id
create_text_box_overlay = 917 # (create_text_box_overlay, <destination>), #returns overlay id
create_check_box_overlay = 918 # (create_check_box_overlay, <destination>), #returns overlay id
create_simple_text_box_overlay = 919 # (create_simple_text_box_overlay, <destination>), #returns overlay id
overlay_set_text = 920 # (overlay_set_text, <overlay_id>, <string_id>),
overlay_set_color = 921 # (overlay_set_color, <overlay_id>, <color>), #color in RGB format like 0xRRGGBB (put hexadecimal values for RR GG and BB parts)
overlay_set_alpha = 922 # (overlay_set_alpha, <overlay_id>, <alpha>), #alpha in A format like 0xAA (put hexadecimal values for AA part)
overlay_set_hilight_color = 923 # (overlay_set_hilight_color, <overlay_id>, <color>), #color in RGB format like 0xRRGGBB (put hexadecimal values for RR GG and BB parts)
overlay_set_hilight_alpha = 924 # (overlay_set_hilight_alpha, <overlay_id>, <alpha>), #alpha in A format like 0xAA (put hexadecimal values for AA part)
overlay_set_size = 925 # (overlay_set_size, <overlay_id>, <position_no>), #position's x and y values are used
overlay_set_position = 926 # (overlay_set_position, <overlay_id>, <position_no>), #position's x and y values are used
overlay_set_val = 927 # (overlay_set_val, <overlay_id>, <value>), #can be used for sliders, combo buttons and check boxes
overlay_set_boundaries = 928 # (overlay_set_boundaries, <overlay_id>, <min_value>, <max_value>),
overlay_set_area_size = 929 # (overlay_set_area_size, <overlay_id>, <position_no>), #position's x and y values are used
overlay_set_mesh_rotation = 930 # (overlay_set_mesh_rotation, <overlay_id>, <position_no>), #position's rotation values are used for rotations around x, y and z axis
overlay_add_item = 931 # (overlay_add_item, <overlay_id>, <string_id>), # adds an item to the combo box
overlay_animate_to_color = 932 # (overlay_animate_to_color, <overlay_id>, <duration-in-1/1000-seconds>, <color>), #alpha value will not be used
overlay_animate_to_alpha = 933 # (overlay_animate_to_alpha, <overlay_id>, <duration-in-1/1000-seconds>, <color>), #only alpha value will be used
overlay_animate_to_highlight_color = 934 # (overlay_animate_to_highlight_color, <overlay_id>, <duration-in-1/1000-seconds>, <color>), #alpha value will not be used
overlay_animate_to_highlight_alpha = 935 # (overlay_animate_to_highlight_alpha, <overlay_id>, <duration-in-1/1000-seconds>, <color>), #only alpha value will be used
overlay_animate_to_size = 936 # (overlay_animate_to_size, <overlay_id>, <duration-in-1/1000-seconds>, <position_no>), #position's x and y values are used as
overlay_animate_to_position = 937 # (overlay_animate_to_position, <overlay_id>, <duration-in-1/1000-seconds>, <position_no>), #position's x and y values are used as
create_image_button_overlay_with_tableau_material = 938 # (create_image_button_overlay_with_tableau_material, <destination>, <mesh_id>, <tableau_material_id>, <value>), #returns overlay id. value is passed to tableau_material
# when mesh_id is -1, a default mesh is generated automatically
create_mesh_overlay_with_tableau_material = 939 # (create_mesh_overlay_with_tableau_material, <destination>, <mesh_id>, <tableau_material_id>, <value>), #returns overlay id. value is passed to tableau_material
# when mesh_id is -1, a default mesh is generated automatically
create_game_button_overlay = 940 # (create_game_button_overlay, <destination>, <string_id>), #returns overlay id
create_in_game_button_overlay = 941 # (create_in_game_button_overlay, <destination>, <string_id>), #returns overlay id
create_number_box_overlay = 942 # (create_number_box_overlay, <destination>, <min_value>, <max_value>), #returns overlay id
create_listbox_overlay = 943 # (create_list_box_overlay, <destination>), #returns overlay id
create_mesh_overlay_with_item_id = 944 # (create_mesh_overlay_with_item_id, <destination>, <item_id>), #returns overlay id.
set_container_overlay = 945 # (set_container_overlay, <overlay_id>), #sets the container overlay that new overlays will attach to. give -1 to reset
overlay_get_position = 946 # (overlay_get_position, <destination>, <overlay_id>),
overlay_set_display = 947 # (overlay_set_display, <overlay_id>, <value>), #shows/hides overlay (1 = show, 0 = hide)
create_combo_label_overlay = 948 # (create_combo_label_overlay, <destination>), #returns overlay id
overlay_obtain_focus = 949 # (overlay_obtain_focus, <overlay_id>), #works for textboxes only
overlay_set_tooltip = 950 # (overlay_set_tooltip, <overlay_id>, <string_id>),
overlay_set_container_overlay = 951 # (overlay_set_container_overlay, <overlay_id>, <container_overlay_id>), # -1 to reset
overlay_set_additional_render_height = 952 # (overlay_set_additional_render_height, <overlay_id>, <height_adder>),
overlay_set_material = 956 # (overlay_set_material, <overlay_id>, <string_no>),
show_object_details_overlay = 960 # (show_object_details_overlay, <value>), #0 = hide, 1 = show
show_item_details = 970 # (show_item_details, <item_id>, <position_no>, <price_multiplier>), #price_multiplier is percent, usually returned by script_game_get_item_[buy/sell]_price_factor
close_item_details = 971 # (close_item_details),
show_item_details_with_modifier = 972 # (show_item_details_with_modifier, <item_id>, <item_modifier>, <position_no>, <price_multiplier>), #price_multiplier is percent, usually returned by script_game_get_item_[buy/sell]_price_factor
context_menu_add_item = 980 # (right_mouse_menu_add_item, <string_id>, <value>), #must be called only inside script_game_right_mouse_menu_get_buttons
auto_save = 985 # (auto_save),
allow_ironman = 988 # (allow_ironman, <value>), # 1 = allow, 0 = disallow
get_average_game_difficulty = 990 # (get_average_game_difficulty, <destination>),
get_level_boundary = 991 # (get_level_boundary, <destination>, <level_no>),
#-------------------------
# Mission Condition types
#-------------------------
all_enemies_defeated = 1003 # (all_enemies_defeated),
race_completed_by_player = 1004 # (race_completed_by_player),
num_active_teams_le = 1005 # (num_active_teams_le,<value>),
main_hero_fallen = 1006 # (main_hero_fallen),
#----------------------------
# NEGATIONS
#----------------------------
neg = 0x80000000 # (neg|<operation>),
this_or_next = 0x40000000 # (this_or_next|<operation>),
lt = neg | ge # less than -- (lt,<value>,<value>),
neq = neg | eq # not equal to -- (neq,<value>,<value>),
le = neg | gt # less or equal to -- (le,<value>,<value>),
#-------------------------------------------------------------------------------------------
# CONSEQUENCE OPERATIONS -
#-------------------------------------------------------------------------------------------
finish_party_battle_mode = 1019 # (finish_party_battle_mode),
set_party_battle_mode = 1020 # (set_party_battle_mode),
set_camera_follow_party = 1021 # (set_camera_follow_party,<party_id>), #Works on map only.
start_map_conversation = 1025 # (start_map_conversation,<troop_id>),
rest_for_hours = 1030 # (rest_for_hours,<rest_period>,[time_speed],[remain_attackable]),
rest_for_hours_interactive = 1031 # (rest_for_hours_interactive,<rest_period>,[time_speed],[remain_attackable]),
add_xp_to_troop = 1062 # (add_xp_to_troop,<value>,[troop_id]),
add_gold_as_xp = 1063 # (add_gold_as_xp,<value>,[troop_id]),
add_xp_as_reward = 1064 # (add_xp_as_reward,<value>),
add_gold_to_party = 1070 # party_id should be different from 0
# (add_gold_to_party,<value>,<party_id>),
set_party_creation_random_limits= 1080 # (set_party_creation_random_limits, <min_value>, <max_value>), (values should be between 0, 100)
troop_set_note_available = 1095 # (troop_set_note_available, <troop_id>, <value>), #1 = available, 0 = not available
faction_set_note_available = 1096 # (faction_set_note_available, <faction_id>, <value>), #1 = available, 0 = not available
party_set_note_available = 1097 # (party_set_note_available, <party_id>, <value>), #1 = available, 0 = not available
quest_set_note_available = 1098 # (quest_set_note_available, <quest_id>, <value>), #1 = available, 0 = not available
#1090-1091-1092 is taken, see below (info_page)
spawn_around_party = 1100 # ID of spawned party is put into reg(0)
# (spawn_around_party,<party_id>,<party_template_id>),
set_spawn_radius = 1103 # (set_spawn_radius,<value>),
display_debug_message = 1104 # (display_debug_message,<string_id>,[hex_colour_code]), #displays message only in debug mode, but writes to rgl_log.txt in both release and debug modes when edit mode is enabled
display_log_message = 1105 # (display_log_message,<string_id>,[hex_colour_code]),
display_message = 1106 # (display_message,<string_id>,[hex_colour_code]),
set_show_messages = 1107 # (set_show_messages,<value>), #0 disables window messages 1 re-enables them.
add_troop_note_tableau_mesh = 1108 # (add_troop_note_tableau_mesh,<troop_id>,<tableau_material_id>),
add_faction_note_tableau_mesh = 1109 # (add_faction_note_tableau_mesh,<faction_id>,<tableau_material_id>),
add_party_note_tableau_mesh = 1110 # (add_party_note_tableau_mesh,<party_id>,<tableau_material_id>),
add_quest_note_tableau_mesh = 1111 # (add_quest_note_tableau_mesh,<quest_id>,<tableau_material_id>),
add_info_page_note_tableau_mesh = 1090 # (add_info_page_note_tableau_mesh,<info_page_id>,<tableau_material_id>),
add_troop_note_from_dialog = 1114 # (add_troop_note_from_dialog,<troop_id>,<note_slot_no>, <value>), #There are maximum of 8 slots. value = 1 -> shows when the note is added
add_faction_note_from_dialog = 1115 # (add_faction_note_from_dialog,<faction_id>,<note_slot_no>, <value>), #There are maximum of 8 slots value = 1 -> shows when the note is added
add_party_note_from_dialog = 1116 # (add_party_note_from_dialog,<party_id>,<note_slot_no>, <value>), #There are maximum of 8 slots value = 1 -> shows when the note is added
add_quest_note_from_dialog = 1112 # (add_quest_note_from_dialog,<quest_id>,<note_slot_no>, <value>), #There are maximum of 8 slots value = 1 -> shows when the note is added
add_info_page_note_from_dialog = 1091 # (add_info_page_note_from_dialog,<info_page_id>,<note_slot_no>, <value>), #There are maximum of 8 slots value = 1 -> shows when the note is added
add_troop_note_from_sreg = 1117 # (add_troop_note_from_sreg,<troop_id>,<note_slot_no>,<string_id>, <value>), #There are maximum of 8 slots value = 1 -> shows when the note is added
add_faction_note_from_sreg = 1118 # (add_faction_note_from_sreg,<faction_id>,<note_slot_no>,<string_id>, <value>), #There are maximum of 8 slots value = 1 -> shows when the note is added
add_party_note_from_sreg = 1119 # (add_party_note_from_sreg,<party_id>,<note_slot_no>,<string_id>, <value>), #There are maximum of 8 slots value = 1 -> shows when the note is added
add_quest_note_from_sreg = 1113 # (add_quest_note_from_sreg,<quest_id>,<note_slot_no>,<string_id>, <value>), #There are maximum of 8 slots value = 1 -> shows when the note is added
add_info_page_note_from_sreg = 1092 # (add_info_page_note_from_sreg,<info_page_id>,<note_slot_no>,<string_id>, <value>), #There are maximum of 8 slots value = 1 -> shows when the note is added
tutorial_box = 1120 # (tutorial_box,<string_id>,<string_id>), #deprecated use dialog_box instead.
dialog_box = 1120 # (dialog_box,<text_string_id>,<title_string_id>),
question_box = 1121 # (question_box,<string_id>, [<yes_string_id>], [<no_string_id>]),
tutorial_message = 1122 # (tutorial_message,<string_id>, <color>, <auto_close_time>), #set string_id = -1 for hiding the message
tutorial_message_set_position = 1123 # (tutorial_message_set_position, <position_x>, <position_y>),
tutorial_message_set_size = 1124 # (tutorial_message_set_size, <size_x>, <size_y>),
tutorial_message_set_center_justify = 1125 # (tutorial_message_set_center_justify, <val>), #set not 0 for center justify, 0 for not center justify
tutorial_message_set_background = 1126 # (tutorial_message_set_background, <value>), #1 = on, 0 = off, default is off
set_tooltip_text = 1130 # (set_tooltip_text, <string_id>),
reset_price_rates = 1170 # (reset_price_rates),
set_price_rate_for_item = 1171 # (set_price_rate_for_item,<item_id>,<value_percentage>),
set_price_rate_for_item_type = 1172 # (set_price_rate_for_item_type,<item_type_id>,<value_percentage>),
party_join = 1201 # (party_join),
party_join_as_prisoner = 1202 # (party_join_as_prisoner),
troop_join = 1203 # (troop_join,<troop_id>),
troop_join_as_prisoner = 1204 # (troop_join_as_prisoner,<troop_id>),
remove_member_from_party = 1210 # (remove_member_from_party,<troop_id>,[party_id]),
remove_regular_prisoners = 1211 # (remove_regular_prisoners,<party_id>),
remove_troops_from_companions = 1215 # (remove_troops_from_companions,<troop_id>,<value>),
remove_troops_from_prisoners = 1216 # (remove_troops_from_prisoners,<troop_id>,<value>),
heal_party = 1225 # (heal_party,<party_id>),
disable_party = 1230 # (disable_party,<party_id>),
enable_party = 1231 # (enable_party,<party_id>),
remove_party = 1232 # (remove_party,<party_id>), #remove only active spawned parties or you will corrupt the game! Non-spawned parties may be disabled...
add_companion_party = 1233 # (add_companion_party,<troop_id_hero>),
add_troop_to_site = 1250 # (add_troop_to_site,<troop_id>,<scene_id>,<entry_no>),
remove_troop_from_site = 1251 # (remove_troop_from_site,<troop_id>,<scene_id>),
modify_visitors_at_site = 1261 # (modify_visitors_at_site,<scene_id>),
reset_visitors = 1262 # (reset_visitors),
set_visitor = 1263 # (set_visitor,<entry_no>,<troop_id>,[<dna>]),
set_visitors = 1264 # (set_visitors,<entry_no>,<troop_id>,<number_of_troops>),
add_visitors_to_current_scene = 1265 # (add_visitors_to_current_scene,<entry_no>,<troop_id>,<number_of_troops>, <team_no>, <group_no>), #team no and group no are used in multiplayer mode only. default team in entry is used in single player mode
scene_set_day_time = 1266 # (scene_set_day_time, <value>), #value in hours (0-23), must be called within ti_before_mission_start triggers
set_relation = 1270 # (set_relation,<faction_id>,<faction_id>,<value>),
faction_set_name = 1275 # (faction_set_name, <faction_id>, <string_id>),
faction_set_color = 1276 # (faction_set_color, <faction_id>, <value>),
faction_get_color = 1277 # (faction_get_color, <color>, <faction_id>)
#Quest stuff
start_quest = 1280 # (start_quest,<quest_id>),
complete_quest = 1281 # (complete_quest,<quest_id>),
succeed_quest = 1282 # (succeed_quest,<quest_id>), #also concludes the quest
fail_quest = 1283 # (fail_quest,<quest_id>), #also concludes the quest
cancel_quest = 1284 # (cancel_quest,<quest_id>),
set_quest_progression = 1285 # (set_quest_progression,<quest_id>,<value>),
conclude_quest = 1286 # (conclude_quest,<quest_id>),
setup_quest_text = 1290 # (setup_quest_text,<quest_id>),
setup_quest_giver = 1291 # (setup_quest_giver,<quest_id>, <string_id>),
#encounter outcomes.
start_encounter = 1300 # (start_encounter,<party_id>),
leave_encounter = 1301 # (leave_encounter),
encounter_attack = 1302 # (encounter_attack),
select_enemy = 1303 # (select_enemy,<value>),
set_passage_menu = 1304 # (set_passage_menu,<value>),
auto_set_meta_mission_at_end_commited = 1305 # (auto_set_meta_mission_at_end_commited),
#simulate_battle = 1305 # (simulate_battle,<value>),
end_current_battle = 1307 # (end_current_battle),
set_mercenary_source_party = 1320 # selects party from which to buy mercenaries
# (set_mercenary_source_party,<party_id>),
set_merchandise_modifier_quality = 1490 # Quality rate in percentage (average quality = 100),
# (set_merchandise_modifier_quality,<value>),
set_merchandise_max_value = 1491 # (set_merchandise_max_value,<value>),
reset_item_probabilities = 1492 # (reset_item_probabilities),
set_item_probability_in_merchandise = 1493 # (set_item_probability_in_merchandise,<itm_id>,<value>),
#active Troop
#set_active_troop = 1050
troop_set_name = 1501 # (troop_set_name, <troop_id>, <string_no>),
troop_set_plural_name = 1502 # (troop_set_plural_name, <troop_id>, <string_no>),
troop_set_face_key_from_current_profile= 1503 # (troop_set_face_key_from_current_profile, <troop_id>),
troop_set_type = 1505 # (troop_set_type,<troop_id>,<gender>),
troop_get_type = 1506 # (troop_get_type,<destination>,<troop_id>),
troop_is_hero = 1507 # (troop_is_hero,<troop_id>),
troop_is_wounded = 1508 # (troop_is_wounded,<troop_id>), #only for heroes!
troop_set_auto_equip = 1509 # (troop_set_auto_equip,<troop_id>,<value>),#disables otr enables auto-equipping
troop_ensure_inventory_space = 1510 # (troop_ensure_inventory_space,<troop_id>,<value>),
troop_sort_inventory = 1511 # (troop_sort_inventory,<troop_id>),
troop_add_merchandise = 1512 # (troop_add_merchandise,<troop_id>,<item_type_id>,<value>),
troop_add_merchandise_with_faction = 1513 # (troop_add_merchandise_with_faction,<troop_id>,<faction_id>,<item_type_id>,<value>), #faction_id is given to check if troop is eligible to produce that item
troop_get_xp = 1515 # (troop_get_xp, <destination>, <troop_id>),
troop_get_class = 1516 # (troop_get_class, <destination>, <troop_id>),
troop_set_class = 1517 # (troop_set_class, <troop_id>, <value>),
troop_raise_attribute = 1520 # (troop_raise_attribute,<troop_id>,<attribute_id>,<value>),
troop_raise_skill = 1521 # (troop_raise_skill,<troop_id>,<skill_id>,<value>),
troop_raise_proficiency = 1522 # (troop_raise_proficiency,<troop_id>,<proficiency_no>,<value>),
troop_raise_proficiency_linear = 1523 # raises weapon proficiencies linearly without being limited by weapon master skill
# (troop_raise_proficiency,<troop_id>,<proficiency_no>,<value>),
troop_add_proficiency_points = 1525 # (troop_add_proficiency_points,<troop_id>,<value>),
troop_add_gold = 1528 # (troop_add_gold,<troop_id>,<value>),
troop_remove_gold = 1529 # (troop_remove_gold,<troop_id>,<value>),
troop_add_item = 1530 # (troop_add_item,<troop_id>,<item_id>,[modifier]),
troop_remove_item = 1531 # (troop_remove_item,<troop_id>,<item_id>),
troop_clear_inventory = 1532 # (troop_clear_inventory,<troop_id>),
troop_equip_items = 1533 # (troop_equip_items,<troop_id>), #equips the items in the inventory automatically
troop_inventory_slot_set_item_amount = 1534 # (troop_inventory_slot_set_item_amount,<troop_id>,<inventory_slot_no>,<value>),
troop_inventory_slot_get_item_amount = 1537 # (troop_inventory_slot_get_item_amount,<destination>,<troop_id>,<inventory_slot_no>),
troop_inventory_slot_get_item_max_amount = 1538 # (troop_inventory_slot_get_item_max_amount,<destination>,<troop_id>,<inventory_slot_no>),
troop_add_items = 1535 # (troop_add_items,<troop_id>,<item_id>,<number>),
troop_remove_items = 1536 # puts cost of items to reg0
# (troop_remove_items,<troop_id>,<item_id>,<number>),
troop_loot_troop = 1539 # (troop_loot_troop,<target_troop>,<source_troop_id>,<probability>),
troop_get_inventory_capacity = 1540 # (troop_get_inventory_capacity,<destination>,<troop_id>),
troop_get_inventory_slot = 1541 # (troop_get_inventory_slot,<destination>,<troop_id>,<inventory_slot_no>),
troop_get_inventory_slot_modifier = 1542 # (troop_get_inventory_slot_modifier,<destination>,<troop_id>,<inventory_slot_no>),
troop_set_inventory_slot = 1543 # (troop_set_inventory_slot,<troop_id>,<inventory_slot_no>,<value>),
troop_set_inventory_slot_modifier = 1544 # (troop_set_inventory_slot_modifier,<troop_id>,<inventory_slot_no>,<value>),
troop_set_faction = 1550 # (troop_set_faction,<troop_id>,<faction_id>),
troop_set_age = 1555 # (troop_set_age, <troop_id>, <age_slider_pos>), #Enter a value between 0..100
troop_set_health = 1560 # (troop_set_health,<troop_id>,<relative health (0-100)>),
troop_get_upgrade_troop = 1561 # (troop_get_upgrade_troop,<destination>,<troop_id>,<upgrade_path>), #upgrade_path can be: 0 = get first node, 1 = get second node (returns -1 if not available)
#Items...
item_get_type = 1570 # (item_get_type, <destination>, <item_id>), #returned values are listed at header_items.py (values starting with itp_type_)
#Parties...
party_get_num_companions = 1601 # (party_get_num_companions,<destination>,<party_id>),
party_get_num_prisoners = 1602 # (party_get_num_prisoners,<destination>,<party_id>),
party_set_flags = 1603 # (party_set_flags, <party_id>, <flag>, <clear_or_set>), #sets flags like pf_default_behavior. see header_parties.py for flags.
party_set_marshall = 1604 # (party_set_marshal, <party_id>, <value>)
party_set_extra_text = 1605 # (party_set_extra_text,<party_id>, <string>)
party_set_aggressiveness = 1606 # (party_set_aggressiveness, <party_id>, <number>),
party_set_courage = 1607 # (party_set_courage, <party_id>, <number>),
party_get_current_terrain = 1608 # (party_get_current_terrain,<destination>,<party_id>),
party_get_template_id = 1609 # (party_get_template_id,<destination>,<party_id>),
party_add_members = 1610 # (party_add_members,<party_id>,<troop_id>,<number>), #returns number added in reg0
party_add_prisoners = 1611 # (party_add_prisoners,<party_id>,<troop_id>,<number>),#returns number added in reg0
party_add_leader = 1612 # (party_add_leader,<party_id>,<troop_id>,[<number>]),
party_force_add_members = 1613 # (party_force_add_members,<party_id>,<troop_id>,<number>),
party_force_add_prisoners = 1614 # (party_force_add_prisoners,<party_id>,<troop_id>,<number>),
party_remove_members = 1615 # stores number removed to reg0
# (party_remove_members,<party_id>,<troop_id>,<number>),
party_remove_prisoners = 1616 # stores number removed to reg0
# (party_remove_members,<party_id>,<troop_id>,<number>),
party_clear = 1617 # (party_clear,<party_id>),
party_wound_members = 1618 # (party_wound_members,<party_id>,<troop_id>,<number>),
party_remove_members_wounded_first = 1619 # stores number removed to reg0
# (party_remove_members_wounded_first,<party_id>,<troop_id>,<number>),
party_set_faction = 1620 # (party_set_faction,<party_id>,<faction_id>),
party_relocate_near_party = 1623 # (party_relocate_near_party,<party_id>,<target_party_id>,<value_spawn_radius>),
party_get_position = 1625 # (party_get_position,<position_no>,<party_id>),
party_set_position = 1626 # (party_set_position,<party_id>,<position_no>),
map_get_random_position_around_position= 1627 # (map_get_random_position_around_position,<dest_position_no>,<source_position_no>,<radius>),
map_get_land_position_around_position = 1628 # (map_get_land_position_around_position,<dest_position_no>,<source_position_no>,<radius>),
map_get_water_position_around_position = 1629 # (map_get_water_position_around_position,<dest_position_no>,<source_position_no>,<radius>),
party_count_members_of_type = 1630 # (party_count_members_of_type,<destination>,<party_id>,<troop_id>),
party_count_companions_of_type = 1631 # (party_count_companions_of_type,<destination>,<party_id>,<troop_id>),
party_count_prisoners_of_type = 1632 # (party_count_prisoners_of_type,<destination>,<party_id>,<troop_id>),
party_get_free_companions_capacity = 1633 # (party_get_free_companions_capacity,<destination>,<party_id>),
party_get_free_prisoners_capacity = 1634 # (party_get_free_prisoners_capacity,<destination>,<party_id>),
party_get_ai_initiative = 1638 # (party_get_ai_initiative,<destination>,<party_id>), #result is between 0-100
party_set_ai_initiative = 1639 # (party_set_ai_initiative,<party_id>,<value>), #value is between 0-100
party_set_ai_behavior = 1640 # (party_set_ai_behavior,<party_id>,<ai_bhvr>),
party_set_ai_object = 1641 # (party_set_ai_object,<party_id>,<party_id>),
party_set_ai_target_position = 1642 # (party_set_ai_target_position,<party_id>,<position_no>),
party_set_ai_patrol_radius = 1643 # (party_set_ai_patrol_radius,<party_id>,<radius_in_km>),
party_ignore_player = 1644 # (party_ignore_player, <party_id>,<duration_in_hours>), #don't pursue player party for this duration
party_set_bandit_attraction = 1645 # (party_set_bandit_attraction, <party_id>,<attaraction>), #set how attractive a target the party is for bandits (0..100)
party_get_helpfulness = 1646 # (party_get_helpfulness,<destination>,<party_id>),
party_set_helpfulness = 1647 # (party_set_helpfulness, <party_id>, <number>), #tendency to help friendly parties under attack. (0-10000, 100 default.)
party_set_ignore_with_player_party = 1648 # (party_set_ignore_with_player_party, <party_id>, <value>),
party_get_ignore_with_player_party = 1649 # (party_get_ignore_with_player_party, <party_id>),
party_get_num_companion_stacks = 1650 # (party_get_num_companion_stacks,<destination>,<party_id>),
party_get_num_prisoner_stacks = 1651 # (party_get_num_prisoner_stacks, <destination>,<party_id>),
party_stack_get_troop_id = 1652 # (party_stack_get_troop_id, <destination>,<party_id>,<stack_no>),
party_stack_get_size = 1653 # (party_stack_get_size, <destination>,<party_id>,<stack_no>),
party_stack_get_num_wounded = 1654 # (party_stack_get_num_wounded, <destination>,<party_id>,<stack_no>),
party_stack_get_troop_dna = 1655 # (party_stack_get_troop_dna, <destination>,<party_id>,<stack_no>),
party_prisoner_stack_get_troop_id = 1656 # (party_get_prisoner_stack_troop,<destination>,<party_id>,<stack_no>),
party_prisoner_stack_get_size = 1657 # (party_get_prisoner_stack_size, <destination>,<party_id>,<stack_no>),
party_prisoner_stack_get_troop_dna = 1658 # (party_prisoner_stack_get_troop_dna, <destination>,<party_id>,<stack_no>),
party_attach_to_party = 1660 # (party_attach_to_party, <party_id>, <party_id to attach to>),
party_detach = 1661 # (party_detach, <party_id>),
party_collect_attachments_to_party = 1662 # (party_collect_attachments_to_party, <party_id>, <destination party_id>),
party_quick_attach_to_current_battle = 1663 # (party_quick_attach_to_current_battle, <party_id>, <side (0:players side, 1:enemy side)>),
party_get_cur_town = 1665 # (party_get_cur_town, <destination>, <party_id>),
party_leave_cur_battle = 1666 # (party_leave_cur_battle, <party_id>),
party_set_next_battle_simulation_time = 1667 # (party_set_next_battle_simulation_time,<party_id>,<next_simulation_time_in_hours>),
party_set_name = 1669 # (party_set_name, <party_id>, <string_no>),
party_add_xp_to_stack = 1670 # (party_add_xp_to_stack, <party_id>, <stack_no>, <xp_amount>),
party_get_morale = 1671 # (party_get_morale, <destination>,<party_id>),
party_set_morale = 1672 # (party_set_morale, <party_id>, <value>), #value is clamped to range [0...100].
party_upgrade_with_xp = 1673 # (party_upgrade_with_xp, <party_id>, <xp_amount>, <upgrade_path>), #upgrade_path can be:
#0 = choose random, 1 = choose first, 2 = choose second
party_add_xp = 1674 # (party_add_xp, <party_id>, <xp_amount>),
party_add_template = 1675 # (party_add_template, <party_id>, <party_template_id>, [reverse_prisoner_status]),
party_set_icon = 1676 # (party_set_icon, <party_id>, <map_icon_id>),
party_set_banner_icon = 1677 # (party_set_banner_icon, <party_id>, <map_icon_id>),
party_add_particle_system = 1678 # (party_add_particle_system, <party_id>, <particle_system_id>),
party_clear_particle_systems = 1679 # (party_clear_particle_systems, <party_id>),
party_get_battle_opponent = 1680 # (party_get_battle_opponent, <destination>, <party_id>),
party_get_icon = 1681 # (party_get_icon, <destination>, <party_id>),
party_set_extra_icon = 1682 # (party_set_extra_icon, <party_id>, <map_icon_id>, <up_down_distance_fixed_point>, <up_down_frequency_fixed_point>, <rotate_frequency_fixed_point>, <fade_in_out_frequency_fixed_point>), #frequencies are in number of revolutions per second
party_get_skill_level = 1685 # (party_get_skill_level, <destination>, <party_id>, <skill_no>),
agent_get_speed = 1689 # (agent_get_speed, <position_no>, <agent_id>), #will return speed in x and y
get_battle_advantage = 1690 # (get_battle_advantage, <destination>),
set_battle_advantage = 1691 # (set_battle_advantage, <value>),
agent_refill_wielded_shield_hit_points = 1692 # (agent_refill_wielded_shield_hit_points, <agent_id>),
agent_is_in_special_mode = 1693 # (agent_is_in_special_mode,<agent_id>),
party_get_attached_to = 1694 # (party_get_attached_to, <destination>, <party_id>),
party_get_num_attached_parties = 1695 # (party_get_num_attached_parties, <destination>, <party_id>),
party_get_attached_party_with_rank = 1696 # (party_get_attached_party_with_rank, <destination>, <party_id>, <attached_party_no>),
inflict_casualties_to_party_group = 1697 # (inflict_casualties_to_party, <parent_party_id>, <attack_rounds>, <party_id_to_add_causalties_to>),
distribute_party_among_party_group = 1698 # (distribute_party_among_party_group, <party_to_be_distributed>, <group_root_party>),
agent_is_routed = 1699 # (agent_is_routed,<agent_id>),
#Agents
#store_distance_between_positions,
#position_is_behind_poisiton,
get_player_agent_no = 1700 # (get_player_agent_no,<destination>),
get_player_agent_kill_count = 1701 # (get_player_agent_kill_count,<destination>,[get_wounded]), #Set second value to non-zero to get wounded count. returns lifetime kill counts
agent_is_alive = 1702 # (agent_is_alive,<agent_id>),
agent_is_wounded = 1703 # (agent_is_wounded,<agent_id>),
agent_is_human = 1704 # (agent_is_human,<agent_id>),
get_player_agent_own_troop_kill_count = 1705 # (get_player_agent_own_troop_kill_count,<destination>,[get_wounded]), #Set second value to non-zero to get wounded count
agent_is_ally = 1706 # (agent_is_ally,<agent_id>),
agent_is_non_player = 1707 # (agent_is_non_player, <agent_id>),
agent_is_defender = 1708 # (agent_is_defender,<agent_id>),
agent_is_active = 1712 # (agent_is_active,<agent_id>),
#agent_is_routed = 1699 # (agent_is_routed,<agent_id>),
#agent_is_in_special_mode = 1693 # (agent_is_in_special_mode,<agent_id>),
agent_get_look_position = 1709 # (agent_get_look_position, <position_no>, <agent_id>),
agent_get_position = 1710 # (agent_get_position,<position_no>,<agent_id>),
agent_set_position = 1711 # (agent_set_position,<agent_id>,<position_no>),
#agent_get_speed = 1689 # (agent_get_speed, <position_no>, <agent_id>), #will return speed in x and y
#agent_is_active = 1712 # (agent_is_active,<agent_id>),
agent_set_look_target_agent = 1713 # (agent_set_look_target_agent, <agent_id>, <agent_id>), #second agent_id is the target
agent_get_horse = 1714 # (agent_get_horse,<destination>,<agent_id>),
agent_get_rider = 1715 # (agent_get_rider,<destination>,<agent_id>),
agent_get_party_id = 1716 # (agent_get_party_id,<destination>,<agent_id>),
agent_get_entry_no = 1717 # (agent_get_entry_no,<destination>,<agent_id>),
agent_get_troop_id = 1718 # (agent_get_troop_id,<destination>, <agent_id>),
agent_get_item_id = 1719 # (agent_get_item_id,<destination>, <agent_id>), (works only for horses, returns -1 otherwise)
store_agent_hit_points = 1720 # set absolute to 1 to retrieve actual hps, otherwise will return relative hp in range [0..100]
# (store_agent_hit_points,<destination>,<agent_id>,[absolute]),
agent_set_hit_points = 1721 # set absolute to 1 if value is absolute, otherwise value will be treated as relative number in range [0..100]
# (agent_set_hit_points,<agent_id>,<value>,[absolute]),
agent_deliver_damage_to_agent = 1722 # (agent_deliver_damage_to_agent, <agent_id_deliverer>, <agent_id>, <value>, [item_id]), #if value <= 0, then damage will be calculated using the weapon item. # item_id is the item that the damage is delivered. can be ignored.
agent_get_kill_count = 1723 # (agent_get_kill_count,<destination>,<agent_id>,[get_wounded]), #Set second value to non-zero to get wounded count
agent_get_player_id = 1724 # (agent_get_player_id,<destination>,<agent_id>),
agent_set_invulnerable_shield = 1725 # (agent_set_invulnerable_shield, <agent_id>),
agent_get_wielded_item = 1726 # (agent_get_wielded_item,<destination>,<agent_id>,<hand_no>),
agent_get_ammo = 1727 # (agent_get_ammo,<destination>,<agent_id>, <value>), #value = 1 gets ammo for wielded item, value = 0 gets ammo for all items
#agent_get_ammo_for_slot = 1825 # (agent_get_ammo_for_slot, <destination>, <agent_id>, <slot_no>), #slot no can be between 0-3
agent_refill_ammo = 1728 # (agent_refill_ammo,<agent_id>),
#agent_refill_wielded_shield_hit_points = 1692 # (agent_refill_wielded_shield_hit_points, <agent_id>),
agent_has_item_equipped = 1729 # (agent_has_item_equipped,<agent_id>,<item_id>),
agent_set_scripted_destination = 1730 # (agent_set_scripted_destination,<agent_id>,<position_no>,<auto_set_z_to_ground_level>,<no_rethink>), #auto_set_z_to_ground_level can be 0 (false) or 1 (true), no_rethink = 1 to save resources
agent_get_scripted_destination = 1731 # (agent_get_scripted_destination,<position_no>,<agent_id>),
agent_force_rethink = 1732 # (agent_force_rethink, <agent_id>),
agent_set_no_death_knock_down_only = 1733 # (agent_set_no_death_knock_down_only, <agent_id>, <value>), #0 for disable, 1 for enable
agent_set_horse_speed_factor = 1734 # (agent_set_horse_speed_factor, <agent_id>, <speed_multiplier-in-1/100>),
agent_clear_scripted_mode = 1735 # (agent_clear_scripted_mode,<agent_id>),
agent_set_speed_limit = 1736 # (agent_set_speed_limit,<agent_id>,<speed_limit(kilometers/hour)>), #Affects AI only
agent_ai_set_always_attack_in_melee = 1737 # (agent_ai_set_always_attack_in_melee, <agent_id>,<value>), #to be used in sieges so that agents don't wait on the ladder.
agent_get_simple_behavior = 1738 # (agent_get_simple_behavior, <destination>, <agent_id>), #constants are written in header_mission_templates.py, starting with aisb_
agent_get_combat_state = 1739 # (agent_get_combat_state, <destination>, <agent_id>),
agent_set_animation = 1740 # (agent_set_animation, <agent_id>, <anim_id>, [channel_no]), #channel_no default is 0. Top body only animations should have channel_no value as 1.
agent_set_stand_animation = 1741 # (agent_set_stand_action, <agent_id>, <anim_id>),
agent_set_walk_forward_animation = 1742 # (agent_set_walk_forward_action, <agent_id>, <anim_id>),
agent_set_animation_progress = 1743 # (agent_set_animation_progress, <agent_id>, <value_fixed_point>), #value should be between 0-1 (as fixed point)
agent_set_look_target_position = 1744 # (agent_set_look_target_position, <agent_id>, <position_no>),
agent_set_attack_action = 1745 # (agent_set_attack_action, <agent_id>, <value>, <value>), #value: -2 = clear any attack action, 0 = thrust, 1 = slashright, 2 = slashleft, 3 = overswing - second value 0 = ready and release, 1 = ready and hold
agent_set_defend_action = 1746 # (agent_set_defend_action, <agent_id>, <value>, <duration-in-1/1000-seconds>), #value_1: -2 = clear any defend action, 0 = defend_down, 1 = defend_right, 2 = defend_left, 3 = defend_up
agent_set_wielded_item = 1747 # (agent_set_wielded_item, <agent_id>, <item_id>),
agent_set_scripted_destination_no_attack = 1748 # (agent_set_scripted_destination_no_attack,<agent_id>,<position_no>,<auto_set_z_to_ground_level>), #auto_set_z_to_ground_level can be 0 (false) or 1 (true)
agent_fade_out = 1749 # (agent_fade_out, <agent_id>),
agent_play_sound = 1750 # (agent_play_sound, <agent_id>, <sound_id>),
agent_start_running_away = 1751 # (agent_start_running_away, <agent_id>, [position_no]), # if position no is entered, agent will run away to that location. pos0 is not allowed (will be ignored).
agent_stop_running_away = 1752 # (agent_stop_run_away, <agent_id>),
agent_ai_set_aggressiveness = 1753 # (agent_ai_set_aggressiveness, <agent_id>, <value>), #100 is the default aggressiveness. higher the value, less likely to run back
agent_set_kick_allowed = 1754 # (agent_set_kick_allowed, <agent_id>, <value>), #0 for disable, 1 for allow
remove_agent = 1755 # (remove_agent, <agent_id>),
agent_get_attached_scene_prop = 1756 # (agent_get_attached_scene_prop, <destination>, <agent_id>)
agent_set_attached_scene_prop = 1757 # (agent_set_attached_scene_prop, <agent_id>, <scene_prop_id>)
agent_set_attached_scene_prop_x = 1758 # (agent_set_attached_scene_prop_x, <agent_id>, <value>)
#agent_set_attached_scene_prop_y = 1809 # (agent_set_attached_scene_prop_y, <agent_id>, <value>)
agent_set_attached_scene_prop_z = 1759 # (agent_set_attached_scene_prop_z, <agent_id>, <value>)
agent_get_time_elapsed_since_removed = 1760 # (agent_get_time_elapsed_since_dead, <destination>, <agent_id>),
agent_get_number_of_enemies_following = 1761 # (agent_get_number_of_enemies_following, <destination>, <agent_id>),
agent_set_no_dynamics = 1762 # (agent_set_no_dynamics, <agent_id>, <value>), #0 = turn dynamics off, 1 = turn dynamics on (required for cut-scenes)
agent_get_attack_action = 1763 # (agent_get_attack_action, <destination>, <agent_id>), #returned values: free = 0, readying_attack = 1, releasing_attack = 2, completing_attack_after_hit = 3, attack_parried = 4, reloading = 5, after_release = 6, cancelling_attack = 7
agent_get_defend_action = 1764 # (agent_get_defend_action, <destination>, <agent_id>), #returned values: free = 0, parrying = 1, blocking = 2
agent_get_group = 1765 # (agent_get_group, <destination>, <agent_id>),
agent_set_group = 1766 # (agent_set_group, <agent_id>, <value>),
agent_get_action_dir = 1767 # (agent_get_action_dir, <destination>, <agent_id>), #invalid = -1, down = 0, right = 1, left = 2, up = 3
agent_get_animation = 1768 # (agent_get_animation, <destination>, <agent_id>, <body_part), #0 = lower body part, 1 = upper body part
agent_is_in_parried_animation = 1769 # (agent_is_in_parried_animation, <agent_id>),
agent_get_team = 1770 # (agent_get_team, <destination>, <agent_id>),
agent_set_team = 1771 # (agent_set_team, <agent_id>, <value>),
agent_get_class = 1772 # (agent_get_class ,<destination>, <agent_id>),
agent_get_division = 1773 # (agent_get_division ,<destination>, <agent_id>),
agent_unequip_item = 1774 # (agent_unequip_item, <agent_id>, <item_id>, [weapon_slot_no]), #weapon_slot_no is optional, and can be between 1-4 (used only for weapons, not armor). in either case, item_id has to be set correctly.
class_is_listening_order = 1775 # (class_is_listening_order, <team_no>, <sub_class>),
agent_set_ammo = 1776 # (agent_set_ammo,<agent_id>,<item_id>,<value>), #value = a number between 0 and maximum ammo
agent_add_offer_with_timeout = 1777 # (agent_add_offer_with_timeout, <agent_id>, <agent_id>, <duration-in-1/1000-seconds>), #second agent_id is offerer, 0 value for duration is an infinite offer
agent_check_offer_from_agent = 1778 # (agent_check_offer_from_agent, <agent_id>, <agent_id>), #second agent_id is offerer
agent_equip_item = 1779 # (agent_equip_item, <agent_id>, <item_id>, [weapon_slot_no],[modifier]), #for weapons, agent needs to have an empty weapon slot. weapon_slot_no is optional, and can be between 1-4 (used only for weapons, not armor).
entry_point_get_position = 1780 # (entry_point_get_position, <position_no>, <entry_no>),
entry_point_set_position = 1781 # (entry_point_set_position, <entry_no>, <position_no>),
entry_point_is_auto_generated = 1782 # (entry_point_is_auto_generated, <entry_no>),
agent_set_division = 1783 # (agent_set_division, <agent_id>, <value>),
team_get_hold_fire_order = 1784 # (team_get_hold_fire_order, <destination>, <team_no>, <sub_class>),
team_get_movement_order = 1785 # (team_get_movement_order, <destination>, <team_no>, <sub_class>),
team_get_riding_order = 1786 # (team_get_riding_order, <destination>, <team_no>, <sub_class>),
team_get_weapon_usage_order = 1787 # (team_get_weapon_usage_order, <destination>, <team_no>, <sub_class>),
teams_are_enemies = 1788 # (teams_are_enemies, <team_no>, <team_no_2>),
team_give_order = 1790 # (team_give_order, <team_no>, <sub_class>, <order_id>),
team_set_order_position = 1791 # (team_set_order_position, <team_no>, <sub_class>, <position_no>),
team_get_leader = 1792 # (team_get_leader, <destination>, <team_no>),
team_set_leader = 1793 # (team_set_leader, <team_no>, <new_leader_agent_id>),
team_get_order_position = 1794 # (team_get_order_position, <position_no>, <team_no>, <sub_class>),
team_set_order_listener = 1795 # (team_set_order_listener, <team_no>, <sub_class>, <value>), #merge with old listeners if value is non-zero #clear listeners if sub_class is less than zero
team_set_relation = 1796 # (team_set_relation, <team_no>, <team_no_2>, <value>), # -1 for enemy, 1 for friend, 0 for neutral
close_order_menu = 1789 # (close_order_menu),
set_rain = 1797 # (set_rain,<rain-type>,<strength>), (rain_type: 1= rain, 2=snow ; strength: 0 - 100)
set_fog_distance = 1798 # (set_fog_distance, <distance_in_meters>, [fog_color]),
get_scene_boundaries = 1799 # (get_scene_boundaries, <position_min>, <position_max>),
scene_prop_enable_after_time = 1800 # (scene_prop_enable_after_time, <scene_prop_id>, <value>)
scene_prop_has_agent_on_it = 1801 # (scene_prop_has_agent_on_it, <scene_prop_id>, <agent_id>)
agent_clear_relations_with_agents = 1802 # (agent_clear_relations_with_agents, <agent_id>),
agent_add_relation_with_agent = 1803 # (agent_add_relation_with_agent, <agent_id>, <agent_id>, <value>), #-1 = enemy, 0 = neutral (no friendly fire at all), 1 = ally
agent_get_item_slot = 1804 # (agent_get_item_slot, <destination>, <agent_id>, <value>), value between 0-7, order is weapon1, weapon2, weapon3, weapon4, head_armor, body_armor, leg_armor, hand_armor
ai_mesh_face_group_show_hide = 1805 # (ai_mesh_face_group_show_hide, <group_no>, <value>), # 1 for enable, 0 for disable
agent_is_alarmed = 1806 # (agent_is_alarmed, <agent_id>),
agent_set_is_alarmed = 1807 # (agent_set_is_alarmed, <agent_id>, <value>), # 1 for enable, 0 for disable
agent_stop_sound = 1808 # (agent_stop_sound, <agent_id>),
agent_set_attached_scene_prop_y = 1809 # (agent_set_attached_scene_prop_y, <agent_id>, <value>)
scene_prop_get_num_instances = 1810 # (scene_prop_get_num_instances, <destination>, <scene_prop_id>),
scene_prop_get_instance = 1811 # (scene_prop_get_instance, <destination>, <scene_prop_id>, <instance_no>),
scene_prop_get_visibility = 1812 # (scene_prop_get_visibility, <destination>, <scene_prop_id>),
scene_prop_set_visibility = 1813 # (scene_prop_set_visibility, <scene_prop_id>, <value>),
scene_prop_set_hit_points = 1814 # (scene_prop_set_hit_points, <scene_prop_id>, <value>),
scene_prop_get_hit_points = 1815 # (scene_prop_get_hit_points, <destination>, <scene_prop_id>),
scene_prop_get_max_hit_points = 1816 # (scene_prop_get_max_hit_points, <destination>, <scene_prop_id>),
scene_prop_get_team = 1817 # (scene_prop_get_team, <value>, <scene_prop_id>),
scene_prop_set_team = 1818 # (scene_prop_set_team, <scene_prop_id>, <value>),
scene_prop_set_prune_time = 1819 # (scene_prop_set_prune_time, <scene_prop_id>, <value>), # prune time can only be set to objects that are already on the prune queue. static objects are not affected by this operation.
scene_prop_set_cur_hit_points = 1820 # (scene_prop_set_cur_hit_points, <scene_prop_id>, <value>),
scene_prop_fade_out = 1822 # (scene_prop_fade_out, <scene_prop_id>, <fade_out_time>)
scene_prop_fade_in = 1823 # (scene_prop_fade_in, <scene_prop_id>, <fade_in_time>)
agent_get_ammo_for_slot = 1825 # (agent_get_ammo_for_slot, <destination>, <agent_id>, <slot_no>), #slot no can be between 0-3
agent_is_in_line_of_sight = 1826 # (agent_is_in_line_of_sight, <agent_id>, <position_no>), # rotation of the position register is not used.
agent_deliver_damage_to_agent_advanced = 1827 # (agent_deliver_damage_to_agent_advanced, <destination>, <agent_id_deliverer>, <agent_id>, <value>, [item_id]), #if value <= 0, then damage will be calculated using the weapon item. # item_id is the item that the damage is delivered. can be ignored.
#this advanced mode of agent_deliver_damage_to_agent has 2 differences. 1- the delivered damage is returned. 2- the damage delivery is done after checking the relationship between agents. this might cause no damage, or even damage to the shooter agent because of a friendly fire.
team_get_gap_distance = 1828 # (team_get_gap_distance, <destination>, <team_no>, <sub_class>),
add_missile = 1829 # (add_missile, <agent_id>, <starting_position>, <starting_speed_fixed_point>, <weapon_item_id>, <weapon_item_modifier>, <missile_item_id>, <missile_item_modifier>), # starting position also contains the direction of the arrow
scene_item_get_num_instances = 1830 # (scene_item_get_num_instances, <destination>, <item_id>),
scene_item_get_instance = 1831 # (scene_item_get_instance, <destination>, <item_id>, <instance_no>),
scene_spawned_item_get_num_instances = 1832 # (scene_spawned_item_get_num_instances, <destination>, <item_id>),
scene_spawned_item_get_instance = 1833 # (scene_spawned_item_get_instance, <destination>, <item_id>, <instance_no>),
scene_allows_mounted_units = 1834 # (scene_allows_mounted_units),
class_set_name = 1837 # (class_set_name, <sub_class>, <string_id>),
prop_instance_is_valid = 1838 # (prop_instance_is_valid, <scene_prop_id>),
prop_instance_get_variation_id = 1840 # (prop_instance_get_variation_id, <destination>, <scene_prop_id>),
prop_instance_get_variation_id_2 = 1841 # (prop_instance_get_variation_id_2, <destination>, <scene_prop_id>),
prop_instance_get_position = 1850 # (prop_instance_get_position, <position_no>, <scene_prop_id>),
prop_instance_get_starting_position = 1851 # (prop_instance_get_starting_position, <position_no>, <scene_prop_id>),
prop_instance_get_scale = 1852 # (prop_instance_get_scale, <position_no>, <scene_prop_id>),
prop_instance_get_scene_prop_kind = 1853 # (prop_instance_get_scene_prop_type, <destination>, <scene_prop_id>)
prop_instance_set_scale = 1854 # (prop_instance_set_scale, <scene_prop_id>, <value_x_fixed_point>, <value_y_fixed_point>, <value_z_fixed_point>),
prop_instance_set_position = 1855 # (prop_instance_set_position, <scene_prop_id>, <position_no>, [dont_send_to_clients]),
#dont_send_to_clients default is 0, therefore it is sent to clients. if you are just doing some physics checks with scene props, then don't send them to clients
prop_instance_animate_to_position = 1860 # (prop_instance_animate_to_position, <scene_prop_id>, position, <duration-in-1/100-seconds>),
prop_instance_stop_animating = 1861 # (prop_instance_stop_animating, <scene_prop_id>),
prop_instance_is_animating = 1862 # (prop_instance_is_animating, <destination>, <scene_prop_id>),
prop_instance_get_animation_target_position = 1863 # (prop_instance_get_animation_target_position, <pos>, <scene_prop_id>)
prop_instance_enable_physics = 1864 # (prop_instance_enable_physics, <scene_prop_id>, <value>), #0 for disable, 1 for enable
prop_instance_rotate_to_position = 1865 # (prop_instance_rotate_to_position, <scene_prop_id>, position, <duration-in-1/100-seconds>, <total_rotate_angle>),
prop_instance_initialize_rotation_angles = 1866 # (prop_instance_initialize_rotation_angles, <scene_prop_id>),
prop_instance_refill_hit_points = 1870 # (prop_instance_refill_hit_points, <scene_prop_id>),
prop_instance_dynamics_set_properties = 1871 # (prop_instance_dynamics_set_properties,<scene_prop_id>,mass_friction),
prop_instance_dynamics_set_velocity = 1872 # (prop_instance_dynamics_set_velocity,<scene_prop_id>,linear_velocity),
prop_instance_dynamics_set_omega = 1873 # (prop_instance_dynamics_set_omega,<scene_prop_id>,angular_velocity),
prop_instance_dynamics_apply_impulse = 1874 # (prop_instance_dynamics_apply_impulse,<scene_prop_id>,impulse_force),
prop_instance_receive_damage = 1877 # (prop_instance_receive_damage, <scene_prop_id>, <agent_id>, <damage_value>),
prop_instance_intersects_with_prop_instance = 1880 # (prop_instance_intersects_with_prop_instance, <scene_prop_id>, <scene_prop_id>), #give second scene_prop_id as -1 to check all scene props.
#cannot check polygon-to-polygon physics models, but can check any other combinations between sphere, capsule and polygon physics models.
prop_instance_play_sound = 1881 # (prop_instance_play_sound, <scene_prop_id>, <sound_id>, [flags]), # sound flags can be given
prop_instance_stop_sound = 1882 # (prop_instance_stop_sound, <scene_prop_id>),
prop_instance_clear_attached_missiles = 1885 # (prop_instance_clear_attached_missiles, <scene_prop_id>), # Works only with dynamic scene props (non-retrievable missiles)
prop_instance_add_particle_system = 1886 # (prop_instance_add_particle_system, <scene_prop_id>, <par_sys_id>, <position_no>), # position is local, not global.
prop_instance_stop_all_particle_systems= 1887 # (prop_instance_stop_all_particle_systems, <scene_prop_id>),
replace_prop_instance = 1889 # (replace_prop_instance, <scene_prop_id>, <new_scene_prop_id>),
replace_scene_props = 1890 # (replace_scene_props, <old_scene_prop_id>,<new_scene_prop_id>),
replace_scene_items_with_scene_props = 1891 # (replace_scene_items_with_scene_props, <old_item_id>,<new_scene_prop_id>),
cast_ray = 1900 # (cast_ray, <destination>, <hit_position_register>, <ray_position_register>, [<ray_length_fixed_point>]), #Casts a ray of length [<ray_length_fixed_point>] starting from <ray_position_register> and stores the closest hit position into <hit_position_register> (fails if no hits). If the body hit is a prop instance, its id will be stored into <destination>
#---------------------------
# Mission Consequence types
#---------------------------
set_mission_result = 1906 # (set_mission_result,<value>),
finish_mission = 1907 # (finish_mission, <delay_in_seconds>),
jump_to_scene = 1910 # (jump_to_scene,<scene_id>,<entry_no>),
set_jump_mission = 1911 # (set_jump_mission,<mission_template_id>),
set_jump_entry = 1912 # (set_jump_entry,<entry_no>),
start_mission_conversation = 1920 # (start_mission_conversation,<troop_id>),
add_reinforcements_to_entry = 1930 # (add_reinforcements_to_entry,<mission_template_entry_no>,<value>),
mission_enable_talk = 1935 # (mission_enable_talk), #can talk with troops during battles
mission_disable_talk = 1936 # (mission_disable_talk), #disables talk option for the mission
mission_tpl_entry_set_override_flags = 1940 # (mission_tpl_entry_set_override_flags, <mission_template_id>, <entry_no>, <value>),
mission_tpl_entry_clear_override_items = 1941 # (mission_tpl_entry_clear_override_items, <mission_template_id>, <entry_no>),
mission_tpl_entry_add_override_item = 1942 # (mission_tpl_entry_add_override_item, <mission_template_id>, <entry_no>, <item_kind_id>),
mission_tpl_are_all_agents_spawned = 1943 # (mission_tpl_are_all_agents_spawned), #agents >300 may keep spawning after ti_after_mission_start (still fires .1 second too early)
set_current_color = 1950 # red, green, blue: a value of 255 means 100%
# (set_current_color,<value>,<value>,<value>),
set_position_delta = 1955 # x, y, z
# (set_position_delta,<value>,<value>,<value>),
add_point_light = 1960 # (add_point_light,[flicker_magnitude],[flicker_interval]), #flicker_magnitude between 0 and 100, flicker_interval is in 1/100 seconds
add_point_light_to_entity = 1961 # (add_point_light_to_entity,[flicker_magnitude],[flicker_interval]), #flicker_magnitude between 0 and 100, flicker_interval is in 1/100 seconds
particle_system_add_new = 1965 # (particle_system_add_new,<par_sys_id>,[position_no]),
particle_system_emit = 1968 # (particle_system_emit,<par_sys_id>,<value_num_particles>,<value_period>),
particle_system_burst = 1969 # (particle_system_burst,<par_sys_id>,<position_no>,[percentage_burst_strength]),
set_spawn_position = 1970 # (set_spawn_position, <position_no>),
spawn_item = 1971 # (spawn_item, <item_kind_id>, <item_modifier>, [seconds_before_pruning]), #if seconds_before_pruning = 0 then item never gets pruned
spawn_agent = 1972 # (spawn_agent,<troop_id>), (stores agent_id in reg0)
spawn_horse = 1973 # (spawn_horse,<item_kind_id>, <item_modifier>), (stores agent_id in reg0)
spawn_scene_prop = 1974 # (spawn_scene_prop, <scene_prop_id>), (stores prop_instance_id in reg0) not yet.
particle_system_burst_no_sync = 1975 # (particle_system_burst_without_sync,<par_sys_id>,<position_no>,[percentage_burst_strength]),
spawn_item_without_refill = 1976 # (spawn_item_without_refill, <item_kind_id>, <item_modifier>, [seconds_before_pruning]), #if seconds_before_pruning = 0 then item never gets pruned
agent_get_item_cur_ammo = 1977 # (agent_get_item_cur_ammo, <destination>, <agent_id>, <slot_no>)
cur_item_add_mesh = 1964 # (cur_item_add_mesh, <mesh_name_string_no>, [<lod_begin>], [<lod_end>]), #only call inside ti_on_init_item in module_items # lod values are optional. lod_end is not included.
cur_item_set_material = 1978 # (cur_item_set_material, <string_no>, <sub_mesh_no>, [<lod_begin>], [<lod_end>]), #only call inside ti_on_init_item in module_items # lod values are optional. lod_end is not included.
cur_tableau_add_tableau_mesh = 1980 # (cur_tableau_add_tableau_mesh, <tableau_material_id>, <value>, <position_register_no>), #value is passed to tableau_material
cur_item_set_tableau_material = 1981 # (cur_item_set_tableu_material, <tableau_material_id>, <instance_code>), #only call inside ti_on_init_item in module_items; instance_code is simply passed as a parameter to the tableau
cur_scene_prop_set_tableau_material = 1982 # (cur_scene_prop_set_tableau_material, <tableau_material_id>, <instance_code>), #only call inside ti_on_init_scene_prop in module_scene_props; instance_code is simply passed as a parameter to the tableau
cur_map_icon_set_tableau_material = 1983 # (cur_map_icon_set_tableau_material, <tableau_material_id>, <instance_code>), #only call inside ti_on_init_map_icon in module_scene_props; instance_code is simply passed as a parameter to the tableau
cur_tableau_render_as_alpha_mask = 1984 # (cur_tableau_render_as_alpha_mask)
cur_tableau_set_background_color = 1985 # (cur_tableau_set_background_color, <value>),
cur_agent_set_banner_tableau_material = 1986 # (cur_agent_set_banner_tableau_material, <tableau_material_id>)
cur_tableau_set_ambient_light = 1987 # (cur_tableau_set_ambient_light, <red_fixed_point>, <green_fixed_point>, <blue_fixed_point>),
cur_tableau_set_camera_position = 1988 # (cur_tableau_set_camera_position, <position_no>),
cur_tableau_set_camera_parameters = 1989 # (cur_tableau_set_camera_parameters, <is_perspective>, <camera_width_times_1000>, <camera_height_times_1000>, <camera_near_times_1000>, <camera_far_times_1000>),
cur_tableau_add_point_light = 1990 # (cur_tableau_add_point_light, <map_icon_id>, <position_no>, <red_fixed_point>, <green_fixed_point>, <blue_fixed_point>),
cur_tableau_add_sun_light = 1991 # (cur_tableau_add_sun_light, <map_icon_id>, <position_no>, <red_fixed_point>, <green_fixed_point>, <blue_fixed_point>),
cur_tableau_add_mesh = 1992 # (cur_tableau_add_mesh, <mesh_id>, <position_no>, <value_fixed_point>, <value_fixed_point>),
# first value fixed point is the scale factor, second value fixed point is alpha. use 0 for default values
cur_tableau_add_mesh_with_vertex_color = 1993 # (cur_tableau_add_mesh_with_vertex_color, <mesh_id>, <position_no>, <value_fixed_point>, <value_fixed_point>, <value>),
# first value fixed point is the scale factor, second value fixed point is alpha. value is vertex color. use 0 for default values. vertex_color has no default value.
cur_tableau_add_map_icon = 1994 # (cur_tableau_add_map_icon, <map_icon_id>, <position_no>, <value_fixed_point>),
# value fixed point is the scale factor
cur_tableau_add_troop = 1995 # (cur_tableau_add_troop, <troop_id>, <position_no>, <animation_id>, <instance_no>), #if instance_no value is 0 or less, then the face is not generated randomly (important for heroes)
cur_tableau_add_horse = 1996 # (cur_tableau_add_horse, <item_id>, <position_no>, <animation_id>),
cur_tableau_set_override_flags = 1997 # (cur_tableau_set_override_flags, <value>),
cur_tableau_clear_override_items = 1998 # (cur_tableau_clear_override_items),
cur_tableau_add_override_item = 1999 # (cur_tableau_add_override_item, <item_kind_id>),
cur_tableau_add_mesh_with_scale_and_vertex_color = 2000 # (cur_tableau_add_mesh_with_scale_and_vertex_color, <mesh_id>, <position_no>, <position_no>, <value_fixed_point>, <value>),
# second position_no is x,y,z scale factors (with fixed point values). value fixed point is alpha. value is vertex color. use 0 for default values. scale and vertex_color has no default values.
mission_cam_set_mode = 2001 # (mission_cam_set_mode, <mission_cam_mode>, <duration-in-1/1000-seconds>, <value>), # when leaving manual mode, duration defines the animation time from the initial position to the new position. set as 0 for instant camera position update
# if value = 0, then camera velocity will be linear. else it will be non-linear
mission_get_time_speed = 2002 # (mission_get_time_speed, <destination_fixed_point>),
mission_set_time_speed = 2003 # (mission_set_time_speed, <value_fixed_point>), #this works only when cheat mode is enabled
mission_time_speed_move_to_value = 2004 # (mission_speed_move_to_value, <value_fixed_point>, <duration-in-1/1000-seconds>), #this works only when cheat mode is enabled
mission_set_duel_mode = 2006 # (mission_set_duel_mode, <value>), #value: 0 = off, 1 = on
mission_cam_set_screen_color = 2008 #(mission_cam_set_screen_color, <value>), #value is color together with alpha
mission_cam_animate_to_screen_color = 2009 #(mission_cam_animate_to_screen_color, <value>, <duration-in-1/1000-seconds>), #value is color together with alpha
mission_cam_get_position = 2010 # (mission_cam_get_position, <position_register_no>),
mission_cam_set_position = 2011 # (mission_cam_set_position, <position_register_no>),
mission_cam_animate_to_position = 2012 # (mission_cam_animate_to_position, <position_register_no>, <duration-in-1/1000-seconds>, <value>), # if value = 0, then camera velocity will be linear. else it will be non-linear
mission_cam_get_aperture = 2013 # (mission_cam_get_aperture, <destination>),
mission_cam_set_aperture = 2014 # (mission_cam_set_aperture, <value>),
mission_cam_animate_to_aperture = 2015 # (mission_cam_animate_to_aperture, <value>, <duration-in-1/1000-seconds>, <value>), # if value = 0, then camera velocity will be linear. else it will be non-linear
mission_cam_animate_to_position_and_aperture = 2016 # (mission_cam_animate_to_position_and_aperture, <position_register_no>, <value>, <duration-in-1/1000-seconds>, <value>), # if value = 0, then camera velocity will be linear. else it will be non-linear
mission_cam_set_target_agent = 2017 # (mission_cam_set_target_agent, <agent_id>, <value>), #if value = 0 then do not use agent's rotation, else use agent's rotation
mission_cam_clear_target_agent = 2018 # (mission_cam_clear_target_agent),
mission_cam_set_animation = 2019 # (mission_cam_set_animation, <anim_id>),
talk_info_show = 2020 # (talk_info_show, <hide_or_show>), :0=hide 1=show
talk_info_set_relation_bar = 2021 # (talk_info_set_relation_bar, <value>), :set relation bar to a value between -100 to 100, enter an invalid value to hide the bar.
talk_info_set_line = 2022 # (talk_info_set_line, <line_no>, <string_no>)
#mesh related
set_background_mesh = 2031 # (set_background_mesh, <mesh_id>),
set_game_menu_tableau_mesh = 2032 # (set_game_menu_tableau_mesh, <tableau_material_id>, <value>, <position_register_no>), #value is passed to tableau_material
# position contains the following information: x = x position of the mesh, y = y position of the mesh, z = scale of the mesh
#change_window types.
change_screen_return = 2040 # (change_screen_return),
change_screen_loot = 2041 # (change_screen_loot, <troop_id>),
change_screen_trade = 2042 # (change_screen_trade, <troop_id>),
change_screen_exchange_members = 2043 # (change_screen_exchange_members, [0,1 = exchange_leader], [party_id]), #if party id is not given, current party will be used
change_screen_trade_prisoners = 2044 # (change_screen_trade_prisoners),
change_screen_buy_mercenaries = 2045 # (change_screen_buy_mercenaries),
change_screen_view_character = 2046 # (change_screen_view_character),
change_screen_training = 2047 # (change_screen_training),
change_screen_mission = 2048 # (change_screen_mission),
change_screen_map_conversation = 2049 # (change_screen_map_conversation, <troop_id>),
# Starts the mission, same as (change_screen_mission). However once the mission starts, player will get into dialog with the specified troop, and once the dialog ends, the mission will automatically end.
change_screen_exchange_with_party = 2050 # (change_screen_exchange_with_party, <party_id>),
change_screen_equip_other = 2051 # (change_screen_equip_other, <troop_id>),
change_screen_map = 2052
change_screen_notes = 2053 # (change_screen_notes, <note_type>, <object_id>), #Note type can be 1 = troops, 2 = factions, 3 = parties, 4 = quests, 5 = info_pages
change_screen_quit = 2055 # (change_screen_quit),
change_screen_give_members = 2056 # (change_screen_give_members, [party_id]), #if party id is not given, current party will be used
change_screen_controls = 2057 # (change_screen_controls),
change_screen_options = 2058 # (change_screen_options),
jump_to_menu = 2060 # (jump_to_menu,<menu_id>),
disable_menu_option = 2061 # (disable_menu_option),
agent_get_damage_modifier = 2065 # (agent_get_damage_modifier, <destination>, <agent_id>), # output value is in percentage, 100 is default
agent_get_accuracy_modifier = 2066 # (agent_get_accuracy_modifier, <destination>, <agent_id>), # output value is in percentage, 100 is default, value can be between [0..1000]
agent_get_speed_modifier = 2067 # (agent_get_speed_modifier, <destination>, <agent_id>), # output value is in percentage, 100 is default, value can be between [0..1000]
agent_get_reload_speed_modifier = 2068 # (agent_get_reload_speed_modifier, <destination>, <agent_id>), # output value is in percentage, 100 is default, value can be between [0..1000]
agent_get_use_speed_modifier = 2069 # (agent_get_use_speed_modifier, <destination>, <agent_id>), # output value is in percentage, 100 is default, value can be between [0..1000]
store_trigger_param = 2070 # (store_trigger_param, <destination>, <trigger_param_no>),
store_trigger_param_1 = 2071 # (store_trigger_param_1,<destination>),
store_trigger_param_2 = 2072 # (store_trigger_param_2,<destination>),
store_trigger_param_3 = 2073 # (store_trigger_param_3,<destination>),
set_trigger_result = 2075 # (set_trigger_result, <value>),
agent_get_bone_position = 2076 # (agent_get_bone_position, <position_no>, <agent_no>, <bone_no>, [<local_or_global>]), # returns position of bone. Option 0 for local to agent position, 1 for global
agent_ai_set_interact_with_player = 2077 # (agent_ai_set_interact_with_player, <agent_no>, <value>), # 0 for disable, 1 for enable.
agent_ai_get_look_target = 2080 # (agent_ai_get_look_target, <destination>, <agent_id>),
agent_ai_get_move_target = 2081 # (agent_ai_get_move_target, <destination>, <agent_id>),
agent_ai_get_behavior_target = 2082 # (agent_ai_get_behavior_target, <destination>, <agent_id>),
agent_ai_set_can_crouch = 2083 # (agent_ai_set_can_crouch, <agent_id>, <value>), # 0 for false, 1 for true.
agent_set_max_hit_points = 2090 # set absolute to 1 if value is absolute, otherwise value will be treated as relative number in range [0..100]
# (agent_set_max_hit_points,<agent_id>,<value>,[absolute]),
agent_set_damage_modifier = 2091 # (agent_set_damage_modifier, <agent_id>, <value>), # value is in percentage, 100 is default
agent_set_accuracy_modifier = 2092 # (agent_set_accuracy_modifier, <agent_id>, <value>), # value is in percentage, 100 is default, value can be between [0..1000]
agent_set_speed_modifier = 2093 # (agent_set_speed_modifier, <agent_id>, <value>), # value is in percentage, 100 is default, value can be between [0..1000]
agent_set_reload_speed_modifier = 2094 # (agent_set_reload_speed_modifier, <agent_id>, <value>), # value is in percentage, 100 is default, value can be between [0..1000]
agent_set_use_speed_modifier = 2095 # (agent_set_use_speed_modifier, <agent_id>, <value>), # value is in percentage, 100 is default, value can be between [0..1000]
agent_set_visibility = 2096 # (agent_set_visibility, <agent_id>, <value>), # 0 for invisible, 1 for visible.
agent_get_crouch_mode = 2097 # (agent_get_crouch_mode, <destination>, <agent_id>),
agent_set_crouch_mode = 2098 # (agent_set_crouch_mode, <agent_id>, <value>), # 0-1
agent_set_ranged_damage_modifier = 2099 # (agent_set_ranged_damage_modifier, <agent_id>, <value>), # value is in percentage, 100 is default
val_lshift = 2100 # (val_lshift, <destination>, <value>), # shifts the bits of destination to left by value amount.
val_rshift = 2101 # (val_rshift, <destination>, <value>), # shifts the bits of destination to right by value amount.
val_add = 2105 #dest, operand :: dest = dest + operand
# (val_add,<destination>,<value>),
val_sub = 2106 #dest, operand :: dest = dest + operand
# (val_sub,<destination>,<value>),
val_mul = 2107 #dest, operand :: dest = dest * operand
# (val_mul,<destination>,<value>),
val_div = 2108 #dest, operand :: dest = dest / operand
# (val_div,<destination>,<value>),
val_mod = 2109 #dest, operand :: dest = dest mod operand
# (val_mod,<destination>,<value>),
val_min = 2110 #dest, operand :: dest = min(dest, operand)
# (val_min,<destination>,<value>),
val_max = 2111 #dest, operand :: dest = max(dest, operand)
# (val_max,<destination>,<value>),
val_clamp = 2112 #dest, operand :: dest = max(min(dest,<upper_bound> - 1),<lower_bound>)
# (val_clamp,<destination>,<lower_bound>, <upper_bound>),
val_abs = 2113 #dest :: dest = abs(dest)
# (val_abs,<destination>),
val_or = 2114 #dest, operand :: dest = dest | operand
# (val_or,<destination>,<value>),
val_and = 2115 #dest, operand :: dest = dest & operand
# (val_and,<destination>,<value>),
store_or = 2116 #dest, op1, op2 : dest = op1 | op2
# (store_or,<destination>,<value>,<value>),
store_and = 2117 #dest, op1, op2 : dest = op1 & op2
# (store_and,<destination>,<value>,<value>),
store_mod = 2119 #dest, op1, op2 : dest = op1 % op2
# (store_mod,<destination>,<value>,<value>),
store_add = 2120 #dest, op1, op2 : dest = op1 + op2
# (store_add,<destination>,<value>,<value>),
store_sub = 2121 #dest, op1, op2 : dest = op1 - op2
# (store_sub,<destination>,<value>,<value>),
store_mul = 2122 #dest, op1, op2 : dest = op1 * op2
# (store_mul,<destination>,<value>,<value>),
store_div = 2123 #dest, op1, op2 : dest = op1 / op2
# (store_div,<destination>,<value>,<value>),
set_fixed_point_multiplier = 2124 # (set_fixed_point_multiplier, <value>),
# sets the precision of the values that are named as value_fixed_point or destination_fixed_point.
# Default is 1 (every fixed point value will be regarded as an integer)
store_sqrt = 2125 # (store_sqrt, <destination_fixed_point>, <value_fixed_point>), takes square root of the value
store_pow = 2126 # (store_pow, <destination_fixed_point>, <value_fixed_point>, <value_fixed_point), takes square root of the value
#dest, op1, op2 : dest = op1 ^ op2
store_sin = 2127 # (store_sin, <destination_fixed_point>, <value_fixed_point>), takes sine of the value that is in degrees
store_cos = 2128 # (store_cos, <destination_fixed_point>, <value_fixed_point>), takes cosine of the value that is in degrees
store_tan = 2129 # (store_tan, <destination_fixed_point>, <value_fixed_point>), takes tangent of the value that is in degrees
convert_to_fixed_point = 2130 # (convert_to_fixed_point, <destination_fixed_point>), multiplies the value with the fixed point multiplier
convert_from_fixed_point= 2131 # (convert_from_fixed_point, <destination>), divides the value with the fixed point multiplier
assign = 2133 # had to put this here so that it can be called from conditions.
# (assign,<destination>,<value>),
shuffle_range = 2134 # (shuffle_range,<reg_no>,<reg_no>),
store_random = 2135 # deprecated, use store_random_in_range instead.
store_random_in_range = 2136 # gets random number in range [range_low,range_high] excluding range_high
# (store_random_in_range,<destination>,<range_low>,<range_high>),
store_asin = 2140 # (store_asin, <destination_fixed_point>, <value_fixed_point>),
store_acos = 2141 # (store_acos, <destination_fixed_point>, <value_fixed_point>),
store_atan = 2142 # (store_atan, <destination_fixed_point>, <value_fixed_point>),
store_atan2 = 2143 # (store_atan2, <destination_fixed_point>, <value_fixed_point>, <value_fixed_point>), #first value is y, second is x
store_troop_gold = 2149 # (store_troop_gold,<destination>,<troop_id>),
store_num_free_stacks = 2154 # (store_num_free_stacks,<destination>,<party_id>),
store_num_free_prisoner_stacks = 2155 # (store_num_free_prisoner_stacks,<destination>,<party_id>),
store_party_size = 2156 # (store_party_size,<destination>,[party_id]),
store_party_size_wo_prisoners = 2157 # (store_party_size_wo_prisoners,<destination>,[party_id]),
store_troop_kind_count = 2158 # deprecated, use party_count_members_of_type instead
store_num_regular_prisoners = 2159 # (store_mum_regular_prisoners,<destination>,<party_id>),
store_troop_count_companions = 2160 # (store_troop_count_companions,<destination>,<troop_id>,[party_id]),
store_troop_count_prisoners = 2161 # (store_troop_count_prisoners,<destination>,<troop_id>,[party_id]),
store_item_kind_count = 2165 # (store_item_kind_count,<destination>,<item_id>,[troop_id]),
store_free_inventory_capacity = 2167 # (store_free_inventory_capacity,<destination>,[troop_id]),
store_skill_level = 2170 # (store_skill_level,<destination>,<skill_id>,[troop_id]),
store_character_level = 2171 # (store_character_level,<destination>,[troop_id]),
store_attribute_level = 2172 # (store_attribute_level,<destination>,<troop_id>,<attribute_id>),
store_troop_faction = 2173 # (store_troop_faction,<destination>,<troop_id>),
store_faction_of_troop = 2173 # (store_troop_faction,<destination>,<troop_id>),
store_troop_health = 2175 # (store_troop_health,<destination>,<troop_id>,[absolute]),
# set absolute to 1 to get actual health; otherwise this will return percentage health in range (0-100)
store_proficiency_level = 2176 # (store_proficiency_level,<destination>,<troop_id>,<attribute_id>),
# (store_troop_health,<destination>,<troop_id>,[absolute]),
store_relation = 2190 # (store_relation,<destination>,<faction_id_1>,<faction_id_2>),
set_conversation_speaker_troop = 2197 # (set_conversation_speaker_troop, <troop_id>),
# Allows to dynamically switch speaking troops during the dialog when developer doesn't know in advance who will be doing the speaking. Should be placed in post-talk code section of dialog entry.
set_conversation_speaker_agent = 2198 # (set_conversation_speaker_troop, <agent_id>),
# Allows to dynamically switch speaking agents during the dialog when developer doesn't know in advance who will be doing the speaking. Should be placed in post-talk code section of dialog entry.
store_conversation_agent = 2199 # (store_conversation_agent,<destination>),
# Stores identifier of agent who is currently speaking.
store_conversation_troop = 2200 # (store_conversation_troop,<destination>),
# Stores identifier of troop who is currently speaking.
store_partner_faction = 2201 # (store_partner_faction,<destination>),
store_encountered_party = 2202 # (store_encountered_party,<destination>),
store_encountered_party2 = 2203 # (store_encountered_party2,<destination>),
store_faction_of_party = 2204 # (store_faction_of_party, <destination>, <party_id>),
set_encountered_party = 2205 # (set_encountered_party,<destination>),
#store_current_town = 2210 # deprecated, use store_current_scene instead
#store_current_site = 2211 # deprecated, use store_current_scene instead
store_current_scene = 2211 # (store_current_scene,<destination>),
store_zoom_amount = 2220 # (store_zoom_amount, <destination_fixed_point>),
set_zoom_amount = 2221 # (set_zoom_amount, <value_fixed_point>),
is_zoom_disabled = 2222 # (is_zoom_disabled),
store_item_value = 2230 # (store_item_value,<destination>,<item_id>),
store_troop_value = 2231 # (store_troop_value,<destination>,<troop_id>),
store_partner_quest = 2240 # (store_partner_quest,<destination>),
store_random_quest_in_range = 2250 # (store_random_quest_in_range,<destination>,<lower_bound>,<upper_bound>),
store_random_troop_to_raise = 2251 # (store_random_troop_to_raise,<destination>,<lower_bound>,<upper_bound>),
store_random_troop_to_capture = 2252 # (store_random_troop_to_capture,<destination>,<lower_bound>,<upper_bound>),
store_random_party_in_range = 2254 # (store_random_party_in_range,<destination>,<lower_bound>,<upper_bound>),
store01_random_parties_in_range = 2255 # stores two random, different parties in a range to reg0 and reg1.
# (store01_random_parties_in_range,<lower_bound>,<upper_bound>),
store_random_horse = 2257 # (store_random_horse,<destination>)
store_random_equipment = 2258 # (store_random_equipment,<destination>)
store_random_armor = 2259 # (store_random_armor,<destination>)
store_quest_number = 2261 # (store_quest_number,<destination>,<quest_id>),
store_quest_item = 2262 # (store_quest_item,<destination>,<item_id>),
store_quest_troop = 2263 # (store_quest_troop,<destination>,<troop_id>),
store_current_hours = 2270 # (store_current_hours,<destination>),
store_time_of_day = 2271 # (store_time_of_day,<destination>),
store_current_day = 2272 # (store_current_day,<destination>),
is_currently_night = 2273 # (is_currently_night),
store_distance_to_party_from_party = 2281 # (store_distance_to_party_from_party,<destination>,<party_id>,<party_id>),
get_party_ai_behavior = 2290 # (get_party_ai_behavior,<destination>,<party_id>),
get_party_ai_object = 2291 # (get_party_ai_object,<destination>,<party_id>),
party_get_ai_target_position = 2292 # (party_get_ai_target_position,<position_no>,<party_id>),
get_party_ai_current_behavior = 2293 # (get_party_ai_current_behavior,<destination>,<party_id>),
get_party_ai_current_object = 2294 # (get_party_ai_current_object,<destination>,<party_id>),
store_num_parties_created = 2300 # (store_num_parties_created,<destination>,<party_template_id>),
store_num_parties_destroyed = 2301 # (store_num_parties_destroyed,<destination>,<party_template_id>),
store_num_parties_destroyed_by_player = 2302 # (store_num_parties_destroyed_by_player,<destination>,<party_template_id>),
# Searching operations.
store_num_parties_of_template = 2310 # (store_num_parties_of_template,<destination>,<party_template_id>),
store_random_party_of_template = 2311 # fails if no party exists with tempolate_id (expensive)
# (store_random_party_of_template,<destination>,<party_template_id>),
str_is_empty = 2318 # (str_is_empty, <string_register>),
str_clear = 2319 # (str_clear, <string_register>)
str_store_string = 2320 # (str_store_string,<string_register>,<string_id>),
str_store_string_reg = 2321 # (str_store_string_reg,<string_register>,<string_no>), #copies one string register to another.
str_store_troop_name = 2322 # (str_store_troop_name,<string_register>,<troop_id>),
str_store_troop_name_plural = 2323 # (str_store_troop_name_plural,<string_register>,<troop_id>),
str_store_troop_name_by_count = 2324 # (str_store_troop_name_by_count,<string_register>,<troop_id>,<number>),
str_store_item_name = 2325 # (str_store_item_name,<string_register>,<item_id>),
str_store_item_name_plural = 2326 # (str_store_item_name_plural,<string_register>,<item_id>),
str_store_item_name_by_count = 2327 # (str_store_item_name_by_count,<string_register>,<item_id>),
str_store_party_name = 2330 # (str_store_party_name,<string_register>,<party_id>),
str_store_agent_name = 2332 # (str_store_agent_name,<string_register>,<agent_id>),
str_store_faction_name = 2335 # (str_store_faction_name,<string_register>,<faction_id>),
str_store_quest_name = 2336 # (str_store_quest_name,<string_register>,<quest_id>),
str_store_info_page_name = 2337 # (str_store_info_page_name,<string_register>,<info_page_id>),
str_store_date = 2340 # (str_store_date,<string_register>,<number_of_hours_to_add_to_the_current_date>),
str_store_troop_name_link = 2341 # (str_store_troop_name_link,<string_register>,<troop_id>),
str_store_party_name_link = 2342 # (str_store_party_name_link,<string_register>,<party_id>),
str_store_faction_name_link = 2343 # (str_store_faction_name_link,<string_register>,<faction_id>),
str_store_quest_name_link = 2344 # (str_store_quest_name_link,<string_register>,<quest_id>),
str_store_info_page_name_link = 2345 # (str_store_info_page_name_link,<string_register>,<info_page_id>),
str_store_class_name = 2346 # (str_store_class_name,<stribg_register>,<class_id>)
str_store_player_username = 2350 # (str_store_player_username,<string_register>,<player_id>), #used in multiplayer mode only
str_store_server_password = 2351 # (str_store_server_password, <string_register>),
str_store_server_name = 2352 # (str_store_server_name, <string_register>),
str_store_welcome_message = 2353 # (str_store_welcome_message, <string_register>),
str_encode_url = 2355 # (str_encode_url, <string_register>),
#mission ones:
store_remaining_team_no = 2360 # (store_remaining_team_no,<destination>),
store_mission_timer_a_msec = 2365 # (store_mission_timer_a_msec,<destination>),
store_mission_timer_b_msec = 2366 # (store_mission_timer_b_msec,<destination>),
store_mission_timer_c_msec = 2367 # (store_mission_timer_c_msec,<destination>),
store_mission_timer_a = 2370 # (store_mission_timer_a,<destination>),
store_mission_timer_b = 2371 # (store_mission_timer_b,<destination>),
store_mission_timer_c = 2372 # (store_mission_timer_c,<destination>),
reset_mission_timer_a = 2375 # (reset_mission_timer_a),
reset_mission_timer_b = 2376 # (reset_mission_timer_b),
reset_mission_timer_c = 2377 # (reset_mission_timer_c),
set_cheer_at_no_enemy = 2379 # (set_cheer_at_no_enemy, <value>), # values:0->do not cheer (do as commander says), 1->cheer
store_enemy_count = 2380 # (store_enemy_count,<destination>),
store_friend_count = 2381 # (store_friend_count,<destination>),
store_ally_count = 2382 # (store_ally_count,<destination>),
store_defender_count = 2383 # (store_defender_count,<destination>),
store_attacker_count = 2384 # (store_attacker_count,<destination>),
store_normalized_team_count = 2385 #(store_normalized_team_count,<destination>, <team_no>), #Counts the number of agents belonging to a team
# and normalizes the result regarding battle_size and advantage.
set_postfx = 2386
set_river_shader_to_mud = 2387 #changes river material for muddy env
show_troop_details = 2388 # (show_troop_details, <troop_id>, <position>, <troop_price>)
set_skybox = 2389 # (set_skybox, <non_hdr_skybox_index>, <hdr_skybox_index>) #forces selected skybox for a scene, use -1 to disable
set_startup_sun_light = 2390 # (set_startup_sun_light, <r>, <g>, <b>) #changes the sun light color
set_startup_ambient_light = 2391 # (set_startup_ambient_light, <r>, <g>, <b>) #changes the ambient light color
set_startup_ground_ambient_light = 2392 # (set_startup_ground_ambient_light, <r>, <g>, <b>) #changes the ground ambient light color
rebuild_shadow_map = 2393 # (rebuild_shadow_map),
get_startup_sun_light = 2394 # (get_startup_sun_light, <position_no>),
get_startup_ambient_light = 2395 # (get_startup_ambient_light, <position_no>),
get_startup_ground_ambient_light = 2396 # (get_startup_ground_ambient_light, <position_no>),
set_shader_param_int = 2400 # (set_shader_param_int, <parameter_name>, <value>), #Sets the int shader parameter <parameter_name> to <value>
set_shader_param_float = 2401 # (set_shader_param_float, <parameter_name>, <value>), #Sets the float shader parameter <parameter_name> to <value>
set_shader_param_float4 = 2402 # (set_shader_param_float4, <parameter_name>, <valuex>, <valuey>, <valuez>, <valuew>), #Sets the float4 shader parameter <parameter_name> to <valuex/y/z/w>
set_shader_param_float4x4 = 2403 # (set_shader_param_float4x4, <parameter_name>, [0][0], [0][1], [0][2], [1][0], [1][1], [1][2], [2][0], [2][1], [2][2], [3][0], [3][1], [3][2]), #Sets the float4x4 shader parameter <parameter_name> to the given values .w components are 0001 by default
prop_instance_deform_to_time = 2610 # (prop_instance_deform_to_time, <prop_instance_no>, <value>), # value gives the vertex animation time.
prop_instance_deform_in_range = 2611 # (prop_instance_deform_in_range, <prop_instance_no>, <start_frame>, <end_frame>, <duration-in-1/1000-seconds>), #play animation from start frame to end frame
prop_instance_deform_in_cycle_loop = 2612 # (prop_instance_deform_in_cycle_loop, <prop_instance_no>, <start_frame>, <end_frame>, <duration-in-1/1000-seconds> #cyclical animation within start-end frame
prop_instance_get_current_deform_progress = 2615 # (prop_instance_get_current_deform_progress, <destination>, <prop_instance_no>), #returns a percentage value between 0 and 100 if animation is still in progress. returns 100 otherwise.
prop_instance_get_current_deform_frame = 2616 # (prop_instance_get_current_deform_frame, <destination>, <prop_instance_no>), #returns current frame with round to nearest
prop_instance_set_material = 2617 # (prop_instance_set_material, <prop_instance_no>, <sub_mesh_no>, <string_register>), #give sub mesh as -1 to change all meshes' materials.
agent_ai_get_num_cached_enemies = 2670 # (agent_ai_get_num_cached_enemies, <destination>, <agent_no>), #nearby enemies, nearest to farthest
agent_ai_get_cached_enemy = 2671 # (agent_ai_get_cached_enemy, <destination>, <agent_no>, <cache_index>), #this operation may return -1 if the cached enemy is not active anymore
item_get_weight = 2700 # (item_get_weight, <destination_fixed_point>, <item_kind_no>), #Stores <item_kind_no>'s weight into <destination_fixed_point>
item_get_value = 2701 # (item_get_value, <destination>, <item_kind_no>), #Stores <item_kind_no>'s value into <destination>
item_get_difficulty = 2702 # (item_get_difficulty, <destination>, <item_kind_no>), #Stores <item_kind_no>'s difficulty into <destination>
item_get_head_armor = 2703 # (item_get_head_armor, <destination>, <item_kind_no>), #Stores <item_kind_no>'s head armor into <destination>
item_get_body_armor = 2704 # (item_get_body_armor, <destination>, <item_kind_no>), #Stores <item_kind_no>'s body armor into <destination>
item_get_leg_armor = 2705 # (item_get_leg_armor, <destination>, <item_kind_no>), #Stores <item_kind_no>'s leg armor into <destination>
item_get_hit_points = 2706 # (item_get_hit_points, <destination>, <item_kind_no>), #Stores <item_kind_no>'s hit points into <destination>
item_get_weapon_length = 2707 # (item_get_weapon_length, <destination>, <item_kind_no>), #Stores <item_kind_no>'s weapon length into <destination>
item_get_speed_rating = 2708 # (item_get_speed_rating, <destination>, <item_kind_no>), #Stores <item_kind_no>'s speed rating into <destination>
item_get_missile_speed = 2709 # (item_get_missile_speed, <destination>, <item_kind_no>), #Stores <item_kind_no>'s missile speed into <destination>
item_get_max_ammo = 2710 # (item_get_max_ammo, <destination>, <item_kind_no>), #Stores <item_kind_no>'s max ammo into <destination>
item_get_accuracy = 2711 # (item_get_accuracy, <destination>, <item_kind_no>), #Stores <item_kind_no>'s accuracy into <destination>
item_get_shield_height = 2712 # (item_get_shield_height, <destination_fixed_point>, <item_kind_no>), #Stores <item_kind_no>'s shield height into <destination>
item_get_horse_scale = 2713 # (item_get_horse_scale, <destination_fixed_point>, <item_kind_no>), #Stores <item_kind_no>'s horse scale into <destination>
item_get_horse_speed = 2714 # (item_get_horse_speed, <destination>, <item_kind_no>), #Stores <item_kind_no>'s horse speed into <destination>
item_get_horse_maneuver = 2715 # (item_get_horse_maneuver, <destination>, <item_kind_no>), #Stores <item_kind_no>'s horse maneuver into <destination>
item_get_food_quality = 2716 # (item_get_food_quality, <destination>, <item_kind_no>), #Stores <item_kind_no>'s food quality into <destination>
item_get_abundance = 2717 # (item_get_abundance, <destination>, <item_kind_no>), #Stores <item_kind_no>'s abundance into <destination>
item_get_thrust_damage = 2718 # (item_get_thrust_damage, <destination>, <item_kind_no>), #Stores <item_kind_no>'s thrust damage into <destination>
item_get_thrust_damage_type = 2719 # (item_get_thrust_damage_type, <destination>, <item_kind_no>), #Stores <item_kind_no>'s thrust damage type into <destination>
item_get_swing_damage = 2720 # (item_get_swing_damage, <destination>, <item_kind_no>), #Stores <item_kind_no>'s thrust damage into <destination>
item_get_swing_damage_type = 2721 # (item_get_swing_damage_type, <destination>, <item_kind_no>), #Stores <item_kind_no>'s thrust damage type into <destination>
item_get_horse_charge_damage = 2722 # (item_get_horse_charge_damage, <destination>, <item_kind_no>), #Stores <item_kind_no>'s thrust damage into <destination>
item_has_property = 2723 # (item_has_property, <item_kind_no>, <property>), #Fails if <item_kind_no> doesn't have <property>
item_has_capability = 2724 # (item_has_capability, <item_kind_no>, <capability>), #Fails if <item_kind_no> doesn't have <capability>
item_has_modifier = 2725 # (item_has_modifier, <item_kind_no>, <item_modifier_no>), #Fails if <item_modifier_no> is not a valid modifier for <item_kind_no> # use imod_xxx instead of imodbit_xxx
item_has_faction = 2726 # (item_has_faction, <item_kind_no>, <faction_no>), #Fails if <item_kind_no> doesn't have <faction_no> in its faction list
str_store_player_face_keys = 2747 # (str_store_player_face_keys, <string_no>, <player_id>), #Stores <player_id>'s face key into string.
player_set_face_keys = 2748 # (player_set_face_keys, <player_id>, <string_no>), #Sets <player_id>'s face keys from string.
str_store_troop_face_keys = 2750 # (str_store_troop_face_keys, <string_no>, <troop_no>, [<alt>]), #Stores <troop_no>'s face key into string. if [<alt>] is non-zero the second pair of face keys is stored
troop_set_face_keys = 2751 # (troop_set_face_keys, <troop_no>, <string_no>, [<alt>]), #Sets <troop_no>'s face keys from string. if [<alt>] is non-zero the second pair of face keys is set.
face_keys_get_hair = 2752 # (face_keys_get_hair, <destination>, <string_no>), #Stores face key's hair value into <destination>
face_keys_set_hair = 2753 # (face_keys_set_hair, <string_no>, <value>), #Sets face key's hair value
face_keys_get_beard = 2754 # (face_keys_get_beard, <destination>, <string_no>), #Stores face key's beard value into <destination>
face_keys_set_beard = 2755 # (face_keys_set_beard, <string_no>, <value>), #Sets face key's beard value
face_keys_get_face_texture = 2756 # (face_keys_get_face_texture, <destination>, <string_no>), #Stores face key's face texture value into <destination>
face_keys_set_face_texture = 2757 # (face_keys_set_face_texture, <string_no>, <value>), #Sets face key's face texture value
face_keys_get_hair_texture = 2758 # (face_keys_get_hair_texture, <destination>, <string_no>), #Stores face key's hair texture value into <destination>
face_keys_set_hair_texture = 2759 # (face_keys_set_hair_texture, <string_no>, <value>), #Sets face key's hair texture value
face_keys_get_hair_color = 2760 # (face_keys_get_hair_color, <destination>, <string_no>), #Stores face key's hair color value into <destination>
face_keys_set_hair_color = 2761 # (face_keys_set_hair_color, <string_no>, <value>), #Sets face key's hair color value
face_keys_get_age = 2762 # (face_keys_get_age, <destination>, <string_no>), #Stores face key's age value into <destination>
face_keys_set_age = 2763 # (face_keys_set_age, <string_no>, <value>), #Sets face key's age value
face_keys_get_skin_color = 2764 # (face_keys_get_skin_color, <destination>, <string_no>), #Stores face key's skin color value into <destination>
face_keys_set_skin_color = 2765 # (face_keys_set_skin_color, <string_no>, <value>), #Sets face key's skin color value
face_keys_get_morph_key = 2766 # (face_keys_get_morph_key, <destination>, <string_no>, <key_no>), #Stores face key's morph key value (0-7) into <destination>
face_keys_set_morph_key = 2767 # (face_keys_set_morph_key, <string_no>, <key_no>, <value>), #Sets face key's morph key value (0-7)
#-------------------------------------------
lhs_operations = [try_for_range,
try_for_range_backwards,
try_for_parties,
try_for_agents,
try_for_prop_instances,
try_for_players,
store_script_param_1,
store_script_param_2,
store_script_param,
store_repeat_object,
get_operation_set_version,
get_global_cloud_amount,
get_global_haze_amount,
options_get_damage_to_player,
options_get_damage_to_friends,
options_get_combat_ai,
options_get_campaign_ai,
options_get_combat_speed,
options_get_battle_size,
profile_get_banner_id,
get_achievement_stat,
get_max_players,
player_get_team_no,
player_get_troop_id,
player_get_agent_id,
player_get_gold,
multiplayer_get_my_team,
multiplayer_get_my_troop,
multiplayer_get_my_gold,
multiplayer_get_my_player,
player_get_score,
player_get_kill_count,
player_get_death_count,
player_get_ping,
player_get_is_muted,
player_get_unique_id,
player_get_gender,
player_get_item_id,
player_get_banner_id,
game_get_reduce_campaign_ai,
multiplayer_find_spawn_point,
team_get_bot_kill_count,
team_get_bot_death_count,
team_get_kill_count,
team_get_score,
team_get_faction,
player_get_value_of_original_items,
server_get_renaming_server_allowed,
server_get_changing_game_type_allowed,
server_get_friendly_fire,
server_get_control_block_dir,
server_get_combat_speed,
server_get_add_to_game_servers_list,
server_get_ghost_mode,
server_get_max_num_players,
server_get_melee_friendly_fire,
server_get_friendly_fire_damage_self_ratio,
server_get_friendly_fire_damage_friend_ratio,
server_get_anti_cheat,
troop_get_slot,
party_get_slot,
faction_get_slot,
scene_get_slot,
party_template_get_slot,
agent_get_slot,
quest_get_slot,
item_get_slot,
player_get_slot,
team_get_slot,
scene_prop_get_slot,
store_last_sound_channel,
get_angle_between_positions,
get_distance_between_positions,
get_distance_between_positions_in_meters,
get_sq_distance_between_positions,
get_sq_distance_between_positions_in_meters,
get_sq_distance_between_position_heights,
position_get_x,
position_get_y,
position_get_z,
position_get_scale_x,
position_get_scale_y,
position_get_scale_z,
position_get_rotation_around_z,
position_normalize_origin,
position_get_rotation_around_x,
position_get_rotation_around_y,
position_get_distance_to_terrain,
position_get_distance_to_ground_level,
create_text_overlay,
create_mesh_overlay,
create_button_overlay,
create_image_button_overlay,
create_slider_overlay,
create_progress_overlay,
create_combo_button_overlay,
create_text_box_overlay,
create_check_box_overlay,
create_simple_text_box_overlay,
create_image_button_overlay_with_tableau_material,
create_mesh_overlay_with_tableau_material,
create_game_button_overlay,
create_in_game_button_overlay,
create_number_box_overlay,
create_listbox_overlay,
create_mesh_overlay_with_item_id,
overlay_get_position,
create_combo_label_overlay,
get_average_game_difficulty,
get_level_boundary,
faction_get_color,
troop_get_type,
troop_get_xp,
troop_get_class,
troop_inventory_slot_get_item_amount,
troop_inventory_slot_get_item_max_amount,
troop_get_inventory_capacity,
troop_get_inventory_slot,
troop_get_inventory_slot_modifier,
troop_get_upgrade_troop,
item_get_type,
item_get_missile_speed,
party_get_num_companions,
party_get_num_prisoners,
party_get_current_terrain,
party_get_template_id,
party_count_members_of_type,
party_count_companions_of_type,
party_count_prisoners_of_type,
party_get_free_companions_capacity,
party_get_free_prisoners_capacity,
party_get_helpfulness,
party_get_ignore_with_player_party,
party_get_ai_initiative,
party_get_num_companion_stacks,
party_get_num_prisoner_stacks,
party_stack_get_troop_id,
party_stack_get_size,
party_stack_get_num_wounded,
party_stack_get_troop_dna,
party_prisoner_stack_get_troop_id,
party_prisoner_stack_get_size,
party_prisoner_stack_get_troop_dna,
party_get_cur_town,
party_get_morale,
party_get_battle_opponent,
party_get_icon,
party_get_skill_level,
get_battle_advantage,
party_get_attached_to,
party_get_num_attached_parties,
party_get_attached_party_with_rank,
get_player_agent_no,
get_player_agent_kill_count,
get_player_agent_own_troop_kill_count,
agent_get_horse,
agent_get_rider,
agent_get_party_id,
agent_get_entry_no,
agent_get_troop_id,
agent_get_item_id,
store_agent_hit_points,
agent_get_kill_count,
agent_get_player_id,
agent_get_wielded_item,
agent_get_ammo,
agent_get_simple_behavior,
agent_get_combat_state,
agent_get_attached_scene_prop,
agent_get_time_elapsed_since_removed,
agent_get_number_of_enemies_following,
agent_get_attack_action,
agent_get_defend_action,
agent_get_group,
agent_get_action_dir,
agent_get_animation,
agent_get_team,
agent_get_class,
agent_get_division,
team_get_hold_fire_order,
team_get_movement_order,
team_get_riding_order,
team_get_weapon_usage_order,
team_get_leader,
agent_get_item_slot,
scene_prop_get_num_instances,
scene_prop_get_instance,
scene_prop_get_visibility,
scene_prop_get_hit_points,
scene_prop_get_max_hit_points,
scene_prop_get_team,
agent_get_ammo_for_slot,
agent_deliver_damage_to_agent_advanced,
team_get_gap_distance,
# add_missile, MOTO causes local variable unused warnings?
scene_item_get_num_instances,
scene_item_get_instance,
scene_spawned_item_get_num_instances,
scene_spawned_item_get_instance,
prop_instance_get_variation_id,
prop_instance_get_variation_id_2,
prop_instance_get_position,
prop_instance_get_starting_position,
prop_instance_get_scale,
prop_instance_get_scene_prop_kind,
prop_instance_is_animating,
prop_instance_get_animation_target_position,
cast_ray,
agent_get_item_cur_ammo,
mission_get_time_speed,
mission_cam_get_aperture,
agent_get_damage_modifier,
agent_get_accuracy_modifier,
agent_get_speed_modifier,
agent_get_reload_speed_modifier,
agent_get_use_speed_modifier,
store_trigger_param,
store_trigger_param_1,
store_trigger_param_2,
store_trigger_param_3,
agent_ai_get_look_target,
agent_ai_get_move_target,
agent_ai_get_behavior_target,
agent_get_crouch_mode,
store_or,
store_and,
store_mod,
store_add,
store_sub,
store_mul,
store_div,
store_sqrt,
store_pow,
store_sin,
store_cos,
store_tan,
assign,
store_random,
store_random_in_range,
store_asin,
store_acos,
store_atan,
store_atan2,
store_troop_gold,
store_num_free_stacks,
store_num_free_prisoner_stacks,
store_party_size,
store_party_size_wo_prisoners,
store_troop_kind_count,
store_num_regular_prisoners,
store_troop_count_companions,
store_troop_count_prisoners,
store_item_kind_count,
store_free_inventory_capacity,
store_skill_level,
store_character_level,
store_attribute_level,
store_troop_faction,
store_troop_health,
store_proficiency_level,
store_relation,
store_conversation_agent,
store_conversation_troop,
store_partner_faction,
store_encountered_party,
store_encountered_party2,
store_faction_of_party,
store_current_scene,
store_zoom_amount,
store_item_value,
store_troop_value,
store_partner_quest,
store_random_quest_in_range,
store_random_troop_to_raise,
store_random_troop_to_capture,
store_random_party_in_range,
store_random_horse,
store_random_equipment,
store_random_armor,
store_quest_number,
store_quest_item,
store_quest_troop,
store_current_hours,
store_time_of_day,
store_current_day,
store_distance_to_party_from_party,
get_party_ai_behavior,
get_party_ai_object,
get_party_ai_current_behavior,
get_party_ai_current_object,
store_num_parties_created,
store_num_parties_destroyed,
store_num_parties_destroyed_by_player,
store_num_parties_of_template,
store_random_party_of_template,
store_remaining_team_no,
store_mission_timer_a_msec,
store_mission_timer_b_msec,
store_mission_timer_c_msec,
store_mission_timer_a,
store_mission_timer_b,
store_mission_timer_c,
store_enemy_count,
store_friend_count,
store_ally_count,
store_defender_count,
store_attacker_count,
store_normalized_team_count,
prop_instance_get_current_deform_progress,
prop_instance_get_current_deform_frame,
agent_ai_get_num_cached_enemies,
agent_ai_get_cached_enemy,
item_get_weight,
item_get_value,
item_get_difficulty,
item_get_head_armor,
item_get_body_armor,
item_get_leg_armor,
item_get_hit_points,
item_get_weapon_length,
item_get_speed_rating,
item_get_missile_speed,
item_get_max_ammo,
item_get_accuracy,
item_get_shield_height,
item_get_horse_scale,
item_get_horse_speed,
item_get_horse_maneuver,
item_get_food_quality,
item_get_abundance,
item_get_thrust_damage,
item_get_thrust_damage_type,
item_get_swing_damage,
item_get_swing_damage_type,
item_get_horse_charge_damage,
get_startup_sun_light,
get_startup_ambient_light,
get_startup_ground_ambient_light,
face_keys_get_hair,
face_keys_get_beard,
face_keys_get_face_texture,
face_keys_get_hair_texture,
face_keys_get_hair_color,
face_keys_get_age,
face_keys_get_skin_color,
face_keys_get_morph_key
]
global_lhs_operations = [val_lshift,
val_rshift,
val_add,
val_sub,
val_mul,
val_div,
val_max,
val_min,
val_mod
]
can_fail_operations = [ge,
eq,
gt,
is_between,
entering_town,
map_free,
encountered_party_is_attacker,
conversation_screen_is_active,
in_meta_mission,
troop_is_hero,
troop_is_wounded,
key_is_down,
key_clicked,
game_key_is_down,
game_key_clicked,
hero_can_join,
hero_can_join_as_prisoner,
party_can_join,
party_can_join_as_prisoner,
troops_can_join,
troops_can_join_as_prisoner,
party_can_join_party,
main_party_has_troop,
party_is_in_town,
party_is_in_any_town,
party_is_active,
player_has_item,
troop_has_item_equipped,
troop_is_mounted,
troop_is_guarantee_ranged,
troop_is_guarantee_horse,
player_is_active,
multiplayer_is_server,
multiplayer_is_dedicated_server,
game_in_multiplayer_mode,
player_is_admin,
player_is_busy_with_menus,
player_item_slot_is_picked_up,
check_quest_active,
check_quest_finished,
check_quest_succeeded,
check_quest_failed,
check_quest_concluded,
is_trial_version,
is_edit_mode_enabled,
troop_slot_eq,
party_slot_eq,
faction_slot_eq,
scene_slot_eq,
party_template_slot_eq,
agent_slot_eq,
quest_slot_eq,
item_slot_eq,
player_slot_eq,
team_slot_eq,
scene_prop_slot_eq,
troop_slot_ge,
party_slot_ge,
faction_slot_ge,
scene_slot_ge,
party_template_slot_ge,
agent_slot_ge,
quest_slot_ge,
item_slot_ge,
player_slot_ge,
team_slot_ge,
scene_prop_slot_ge,
position_has_line_of_sight_to_position,
position_is_behind_position,
is_presentation_active,
all_enemies_defeated,
race_completed_by_player,
num_active_teams_le,
main_hero_fallen,
lt,
neq,
le,
teams_are_enemies,
agent_is_alive,
agent_is_wounded,
agent_is_human,
agent_is_ally,
agent_is_non_player,
agent_is_defender,
agent_is_active,
agent_is_routed,
agent_is_in_special_mode,
agent_is_in_parried_animation,
class_is_listening_order,
agent_check_offer_from_agent,
entry_point_is_auto_generated,
scene_prop_has_agent_on_it,
agent_is_alarmed,
agent_is_in_line_of_sight,
scene_prop_get_instance,
scene_item_get_instance,
scene_allows_mounted_units,
prop_instance_is_valid,
cast_ray,
prop_instance_intersects_with_prop_instance,
agent_has_item_equipped,
map_get_land_position_around_position,
map_get_water_position_around_position,
mission_tpl_are_all_agents_spawned,
is_zoom_disabled,
is_currently_night,
store_random_party_of_template,
str_is_empty,
item_has_property,
item_has_capability,
item_has_modifier,
item_has_faction
]
#WSE since the newst adimi tool version... also WSE support
#Add the following definitions to the end (!) of header_operations.py
go_to = 0 #(go_to, <statement_no>), #Jump to <statement_no>
break_loop = 8 #(break_loop), #Break out of a loop, no matter how deeply nested in try_begin blocks
continue_loop = 9 #(continue_loop), #Continue to the next iteration of a loop, no matter how deeply nested in try_begin blocks
try_for_agents = 12 #(try_for_agents, <cur_agent_no>, [<position_no>], [<radius_fixed_point>]), #Loops through agents in the scene. If [<position_no>] and [<radius_fixed_point>] are defined, it will only loop through agents in the chosen area
try_for_dict_keys = 18 #(try_for_dict_keys, <cur_key_string_register>, <dict>), #Loops through keys of <2>
server_set_max_num_players = 491 #(server_set_max_num_players, <max_players>, [<max_private_players>]), #Sets maximum players to <max_players> and maximum private players to [<max_private_players>] (default = same as <max_players>). Both values must be in the range 2-250, [<max_private_players>] can't be lower than <max_players>
position_rotate_x = 723 #(position_rotate_x, <position_register>, <angle>, [<use_global_axis>]), #Rotates <position_register> around the x-axis by <angle> degrees
position_rotate_y = 724 #(position_rotate_y, <position_register>, <angle>, [<use_global_axis>]), #Rotates <position_register> around the y-axis by <angle> degrees
position_rotate_z = 725 #(position_rotate_z, <position_register>, <angle>, [<use_global_axis>]), #Rotates <position_register> around the z-axis by <angle> degrees
position_rotate_z_floating = 734 #(position_rotate_z_floating, <position_register>, <angle_fixed_point>, [<use_global_axis>]), #Rotates <position_register> around the z-axis by <angle_fixed_point> degrees
position_rotate_x_floating = 738 #(position_rotate_x_floating, <position_register>, <angle_fixed_point>, [<use_global_axis>]), #Rotates <position_register> around the x-axis by <angle_fixed_point> degrees
position_rotate_y_floating = 739 #(position_rotate_y_floating, <position_register>, <angle_fixed_point>, [<use_global_axis>]), #Rotates <position_register> around the y-axis by <angle_fixed_point> degrees
is_vanilla_warband = 1004 #(is_vanilla_warband), #Fails only when WSE is running
prop_instance_receive_damage = 1877 #(prop_instance_receive_damage, <prop_instance_no>, <agent_no>, <damage>, [<advanced>]), #<prop_instance_no> received <damage> damage from <agent_no>. If [<advanced>] is non-zero ti_on_scene_prop_hit will be called and the damage dealt will be sent to clients.
store_trigger_param = 2070 #(store_trigger_param, <destination>, [<trigger_param_no>]), #Stores [<trigger_param_no>] into <destination>
val_shr = 2800 #(val_shr, <value>, <shift>), #Performs an arithmetic right bit shift by <shift> on <value>
store_shr = 2801 #(store_shr, <destination>, <value>, <shift>), #Performs an arithmetic right bit shift by <shift> on <value> and stores the result into <destination>
val_lshr = 2802 #(val_lshr, <value>, <shift>), #Performs a logical right bit shift by <shift> on <value>
store_lshr = 2803 #(store_lshr, <destination>, <value>, <shift>), #Performs a logical right bit shift by <shift> on <value> and stores the result into <destination>
val_shl = 2804 #(val_shl, <value>, <shift>), #Performs a left bit shift by <shift> on <value>
store_shl = 2805 #(store_shl, <destination>, <value>, <shift>), #Performs a left bit shift by <shift> on <value> and stores the result into <destination>
val_xor = 2806 #(val_xor, <value1>, <value2>), #Performs a bitwise exclusive or between <value1> and <value2>
store_xor = 2807 #(store_xor, <destination>, <value1>, <value2>), #Performs a bitwise exclusive or between <value1> and <value2> and stores the result into <destination>
val_not = 2808 #(val_not, <value>), #Performs a bitwise complement on <value>
store_not = 2809 #(store_not, <destination>, <value>), #Performs a bitwise complement on <value> and stores the result into <destination>
player_set_banner_id = 2900 #(player_set_banner_id, <player_no>, <banner_no>), #Sets <player_no>'s banner to <banner_no>
player_set_username = 2901 #(player_set_username, <player_no>, <string_no>), #Sets <player_no>'s username to <string_no>
register_get = 3000 #(register_get, <destination>, <index>), #Stores the value of register <index> into <destination>
register_set = 3001 #(register_set, <index>, <value>), #Sets the value of register <index> to <value>
store_wse_version = 3002 #(store_wse_version, <destination>, <component>), #Stores <component> of the WSE version (0: major, 1: minor, 2: build) version into <destination>
item_slot_gt = 3003 #(item_slot_gt, <item_kind_no>, <slot_no>, <value>), #Fails if <item_kind_no>'s <slot_no> is not greater than <value>
party_template_slot_gt = 3004 #(party_template_slot_gt, <party_template_no>, <slot_no>, <value>), #Fails if <party_template_no>'s <slot_no> is not greater than <value>
troop_slot_gt = 3005 #(troop_slot_gt, <troop_no>, <slot_no>, <value>), #Fails if <troop_no>'s <slot_no> is not greater than <value>
faction_slot_gt = 3006 #(faction_slot_gt, <faction_no>, <slot_no>, <value>), #Fails if <faction_no>'s <slot_no> is not greater than <value>
quest_slot_gt = 3007 #(quest_slot_gt, <quest_no>, <slot_no>, <value>), #Fails if <quest_no>'s <slot_no> is not greater than <value>
scene_slot_gt = 3008 #(scene_slot_gt, <site_no>, <slot_no>, <value>), #Fails if <site_no>'s <slot_no> is not greater than <value>
party_slot_gt = 3009 #(party_slot_gt, <party_no>, <slot_no>, <value>), #Fails if <party_no>'s <slot_no> is not greater than <value>
player_slot_gt = 3010 #(player_slot_gt, <player_no>, <slot_no>, <value>), #Fails if <player_no>'s <slot_no> is not greater than <value>
team_slot_gt = 3011 #(team_slot_gt, <team_no>, <slot_no>, <value>), #Fails if <team_no>'s <slot_no> is not greater than <value>
agent_slot_gt = 3012 #(agent_slot_gt, <agent_no>, <slot_no>, <value>), #Fails if <agent_no>'s <slot_no> is not greater than <value>
scene_prop_slot_gt = 3013 #(scene_prop_slot_gt, <prop_instance_no>, <slot_no>, <value>), #Fails if <prop_instance_no>'s <slot_no> is not greater than <value>
store_current_trigger = 3014 #(store_current_trigger, <destination>), #Stores the current trigger into <destination> (0 if not in a trigger)
return_values = 3015 #(return_values, [<value_1>], [<value_2>], [<value_3>], [<value_4>], [<value_5>], [<value_6>], [<value_7>], [<value_8>], [<value_9>], [<value_10>], [<value_11>], [<value_12>], [<value_13>], [<value_14>], [<value_15>], [<value_16>]), #Stores up to 16 return values
store_num_return_values = 3016 #(store_num_return_values, <destination>), #Stores the amount of return values available into <destination>
store_return_value = 3017 #(store_return_value, <destination>, [<value>]), #Stores return value no. [<value>] into <destination>
set_forced_lod = 3018 #(set_forced_lod, <lod_level>), #Forces the current trigger entity's LOD level to <lod_level> (0 = auto)
send_message_to_url_advanced = 3019 #(send_message_to_url_advanced, <url_string>, <user_agent_string>, [<success_callback_script_no>], [<failure_callback_script_no>], [<skip_parsing>], [<timeout>]), #Sends a HTTP request to <url_string> with <user_agent_string>. If the request succeeds, [<success_callback_script_no>] will be called. The script will behave like game_receive_url_response, unless [<skip_parsing>] is non-zero, in which case the script will receive no arguments and s0 will contain the full response. If the request fails, [<failure_callback_script_no>] will be called.
mtsrand = 3020 #(mtsrand, <value>), #Seeds the MT19937 random generator with <value>
mtrand = 3021 #(mtrand, <destination>, <min>, <max>), #Stores a random value between <min> and <max> into <destination> using the MT19937 random generator
get_time = 3022 #(get_time, <destination>, [<local>]), #Stores the current UNIX time into <destination>. If [<local>] is non-zero, it will store local time instead of universal time.
order_flag_is_active = 3023 #(order_flag_is_active), #Fails if the order flag is not being placed
play_bink_file = 3024 #(play_bink_file, <path_from_module_directory>, [<duration_in_ms>]), #Plays a .bik file located at <path_from_module_directory>. If [<duration_in_ms>] is not set the full movie will be played
process_advanced_url_messages = 3025 #(process_advanced_url_messages), #Forces processing of URL messages sent with send_message_to_url_advanced
sleep_ms = 3026 #(sleep_ms, <time>), #Sleeps (blocking the game) for <time> ms
timer_reset = 3027 #(timer_reset, <timer_register_no>, [<use_game_time>]), #Resets <timer_register_no>. If [<use_game_time>] is non-zero the timer will count game time rather than mission time
timer_get_elapsed_time = 3028 #(timer_get_elapsed_time, <destination>, <timer_register_no>), #Stores <timer_register_no>'s elapsed time into <destination>
shell_open_url = 3029 #(shell_open_url, <url>), #Open <url> in default browser. Support only http://, https://, ftp:// and ts3server:// urls.
game_key_get_key = 3100 #(game_key_get_key, <destination>, <game_key_no>), #Stores the key mapped to <game_key_no> into <destination>
key_released = 3101 #(key_released, <key>), #Fails if <key> wasn't released in the current frame
game_key_released = 3102 #(game_key_released, <game_key_no>), #Fails if <game_key_no> wasn't released in the current frame
dict_create = 3200 #(dict_create, <destination>), #Creates an empty dictionary object and stores it into <destination>
dict_free = 3201 #(dict_free, <dict>), #Frees the dictionary object <dict>. A dictionary can't be used after freeing it
dict_load_file = 3202 #(dict_load_file, <dict>, <file>, [<mode>]), #Loads a dictionary file into <dict>. Setting [<mode>] to 0 (default) clears <dict> and then loads the file, setting [<mode>] to 1 doesn't clear <dict> but overrides any key that's already present, [<mode>] to 2 doesn't clear <dict> and doesn't overwrite keys that are already present
dict_load_dict = 3203 #(dict_load_dict, <dict_1>, <dict_2>, [<mode>]), #Loads <dict_2> into <dict_1>. [<mode>]: see above
dict_save = 3204 #(dict_save, <dict>, <file>), #Saves <dict> into a file. For security reasons, <file> is just a name, not a full path, and will be stored into a WSE managed directory
dict_clear = 3205 #(dict_clear, <dict>), #Clears all key-value pairs from <dict>
dict_is_empty = 3206 #(dict_is_empty, <dict>), #Fails if <dict> is not empty
dict_has_key = 3207 #(dict_has_key, <dict>, <key>), #Fails if <key> is not present in <dict>
dict_get_size = 3208 #(dict_get_size, <destination>, <dict>), #Stores the count of key-value pairs in <dict> into <destination>
dict_delete_file = 3209 #(dict_delete_file, <file>), #Deletes dictionary file <file> from disk
dict_get_str = 3210 #(dict_get_str, <string_register>, <dict>, <key>, [<default>]), #Stores the string value paired to <key> into <string_register>. If the key is not found and [<default>] is set, [<default>] will be stored instead. If [<default>] is not set, an empty string will be stored
dict_get_int = 3211 #(dict_get_int, <destination>, <dict>, <key>, [<default>]), #Stores the numeric value paired to <key> into <destination>. If the key is not found and [<default>] is set, [<default>] will be stored instead. If [<default>] is not set, 0 will be stored
dict_set_str = 3212 #(dict_set_str, <dict>, <key>, <string_no>), #Adds (or changes) <string_no> as the string value paired to <key>
dict_set_int = 3213 #(dict_set_int, <dict>, <key>, <value>), #Adds (or changes) <value> as the numeric value paired to <key>
agent_get_item_modifier = 3300 #(agent_get_item_modifier, <destination>, <agent_no>), #Stores <agent_no>'s horse item modifier (-1 if agent is not a horse) into <destination>
agent_get_item_slot_modifier = 3301 #(agent_get_item_slot_modifier, <destination>, <agent_no>, <item_slot_no>), #Stores <agent_no>'s <item_slot_no> modifier into <destination>
agent_get_animation_progress = 3302 #(agent_get_animation_progress, <destination>, <agent_no>, [<channel_no>]), #Stores <agent_no>'s channel [<channel_no>] animation progress (in %%) into <destination>
agent_get_dna = 3303 #(agent_get_dna, <destination>, <agent_no>), #Stores <agent_no>'s dna into <destination>
agent_get_ground_scene_prop = 3304 #(agent_get_ground_scene_prop, <destination>, <agent_no>), #Stores the prop instance on which <agent_no> is standing into <destination>
agent_get_item_slot_ammo = 3305 #(agent_get_item_slot_ammo, <destination>, <agent_no>, <item_slot_no>), #Stores <agent_no>'s <item_slot_no> ammo count into <destination>
agent_set_item_slot_ammo = 3306 #(agent_set_item_slot_ammo, <agent_no>, <item_slot_no>, <value>), #Sets <agent_no>'s <item_slot_no> ammo count to <value>
agent_get_item_slot_hit_points = 3307 #(agent_get_item_slot_hit_points, <destination>, <agent_no>, <item_slot_no>), #Stores <agent_no>'s <item_slot_no> shield hitpoints into <destination>
agent_set_item_slot_hit_points = 3308 #(agent_set_item_slot_hit_points, <agent_no>, <item_slot_no>, <value>), #Sets <agent_no>'s <item_slot_no> shield hitpoints to <value>
agent_get_wielded_item_slot_no = 3309 #(agent_get_wielded_item_slot_no, <destination>, <agent_no>, [<hand_no>]), #Stores <agent_no>'s wielded item slot for [<hand_no>] into <destination>
agent_get_scale = 3310 #(agent_get_scale, <destination_fixed_point>, <agent_no>), #Stores <agent_no>'s scale into <destination_fixed_point>
agent_set_forced_lod = 3311 #(agent_set_forced_lod, <agent_no>, <lod_level>), #Forces <agent_no>'s LOD level to <lod_level> (0 = auto)
agent_get_item_slot_flags = 3312 #(agent_get_item_slot_flags, <destination>, <agent_no>, <item_slot_no>), #Stores <agent_no>'s <item_slot_no> item slot flags into <destination>
agent_ai_get_move_target_position = 3313 #(agent_ai_get_move_target_position, <position_register>, <agent_no>), #Stores <agent_no>'s move target position agent into <position_register>
agent_set_horse = 3314 #(agent_set_horse, <agent_no>, <horse_agent_no>), #Sets <agent_no>'s horse to <horse_agent_no> (-1 for no horse)
agent_ai_set_simple_behavior = 3315 #(agent_ai_set_simple_behavior, <agent_no>, <simple_behavior>, [<guaranteed_time>]), #Sets <agent_no>'s behavior to <simple_behavior> and guarantees it won't be changed for [<guaranteed_time>] seconds. If [<guaranteed_time>] is not specified or <= 0, it won't be changed until agent_force_rethink is called
agent_accelerate = 3316 #(agent_accelerate, <agent_no>, <position_register_no>), #Uses x, y, z components of <position_register_no> to apply acceleration to <agent_no>
agent_set_item_slot_modifier = 3317 #(agent_set_item_slot_modifier, <agent_no>, <item_slot_no>, <item_modifier_no>), #Sets <agent_no>'s <item_slot_no> modifier to <item_modifier_no>
multiplayer_send_chat_message_to_player = 3400 #(multiplayer_send_chat_message_to_player, <player_no>, <sender_player_no>, <text>, [<type>]), #Sends <text> to <player_no> as a (native compatible) chat message by <sender_player_no>. Works only on servers. [<type>]: 0 = chat, 1 = team chat
multiplayer_get_cur_profile = 3401 #(multiplayer_get_cur_profile, <destination>), #Stores the current multiplayer profile into <destination>
multiplayer_get_num_profiles = 3402 #(multiplayer_get_num_profiles, <destination>), #Stores the number of multiplayer profiles into <destination>
server_set_password_admin = 3500 #(server_set_password_admin, <password>), #Sets <password> as server administrator password
server_set_password_private = 3501 #(server_set_password_private, <password>), #Sets <password> as server private player password
server_map_rotation_get_count = 3502 #(server_map_rotation_get_count, <destination>), #Stores the number of maps in rotation into <destination>
server_map_rotation_get_index = 3503 #(server_map_rotation_get_index, <destination>), #Stores the current map rotation index into <destination>
server_map_rotation_set_index = 3504 #(server_map_rotation_set_index, <index>), #Sets the current rotation index to <index>
server_map_rotation_get_map = 3505 #(server_map_rotation_get_map, <destination>, <index>), #Stores the map at <index> into <destination>
server_map_rotation_add_map = 3506 #(server_map_rotation_add_map, <site_no>, [<index>]), #Adds <site_no> to the map rotation at [<index>]
server_map_rotation_remove_map = 3507 #(server_map_rotation_remove_map, [<index>]), #Removes the map at [<index>] from the map rotation (does not work when only one left)
get_server_option_at_connect = 3508 #(get_server_option_at_connect, <destination>, [<index>]), #Stores option [<index>] into <destination>
store_cur_mission_template_no = 3600 #(store_cur_mission_template_no, <destination>), #Stores the current mission template into <destination>
camera_in_first_person = 3601 #(camera_in_first_person), #Fails if the camera is not in first person
set_camera_in_first_person = 3602 #(set_camera_in_first_person, <value>), #Sets the camera to first or third person
set_show_use_tooltip = 3603 #(set_show_use_tooltip, <tooltip_type>, [<value>]), #Enables or disables use tooltips. See header_common_addon.py for possible types
set_ally_collision_threshold = 3604 #(set_ally_collision_threshold, <low_boundary>, <high_boundary>), #Changes the animation progress boundaries (in percents) that determine if attacks on allies will collide (default: 45% <= x <= 60%)
set_prop_collision_threshold = 3605 #(set_prop_collision_threshold, <attack_direction>, <low_boundary>, <high_boundary>), #Changes the animation progress boundaries (in percents) that determine if swing attacks on props will collide (default: 40% <= x <= 80% (75% for overheads))
particle_system_remove = 3606 #(particle_system_remove, [<particle_system_no>]), #Removes [<particle_system_no>] (all particle systems if not set or -1) from the current entity (can be used in several in triggers)
get_camera_position = 3607 #(get_camera_position, <position_register_no>), #Stores camera position and rotation into <position_register_no>
get_spectated_agent_no = 3608 #(get_spectated_agent_no, <destination>), #Stores spectated agent no into <destination>
prop_instance_set_forced_lod = 3609 #(prop_instance_set_forced_lod, <prop_instance_no>, <lod_level>), #Forces <prop_instance_no>'s LOD level to <lod_level> (0 = auto)
prop_instance_set_variation_id = 3610 #(prop_instance_set_variation_id, <prop_instance_no>, <value>), #Sets <prop_instance_no>'s variation id to <value>
prop_instance_set_variation_id_2 = 3611 #(prop_instance_set_variation_id_2, <prop_instance_no>, <value>), #Sets <prop_instance_no>'s variation id 2 to <value>
stop_time = 3612 #(stop_time, <value>), #Stops/resumes the mission. Works only in singleplayer with cheat mode enabled.
cur_missile_get_path_point_position = 3613 #(cur_missile_get_path_point_position, <position_register>, <path_point_no>), #Stores the position of the missile's <path_point_no> (0-499) into <position_register> (can be used in ti_on_init_missile)
get_water_level = 3614 #(get_water_level, <destination_fixed_point>), #Stores the water level into <destination_fixed_point>
missile_remove_on_hit = 3615 #(missile_remove_on_hit), #Causes a missile item not to spawn on hit (can be only used inside ti_on_missile_hit)
troop_get_skill_points = 3700 #(troop_get_skill_points, <destination>, <troop_no>), #Stores <troop_no>'s unused skill points into <destination>
troop_set_skill_points = 3701 #(troop_set_skill_points, <troop_no>, <value>), #Sets <troop_no>'s unused skill points to <value>
troop_get_attribute_points = 3702 #(troop_get_attribute_points, <destination>, <troop_no>), #Stores <troop_no>'s unused attribute points into <destination>
troop_set_attribute_points = 3703 #(troop_set_attribute_points, <troop_no>, <value>), #Sets <troop_no>'s unused attribute points to <value>
troop_get_proficiency_points = 3704 #(troop_get_proficiency_points, <destination>, <troop_no>), #Stores <troop_no>'s unused proficiency points into <destination>
troop_set_proficiency_points = 3705 #(troop_set_proficiency_points, <troop_no>, <value>), #Sets <troop_no>'s unused proficiency points to <value>
troop_has_flag = 3706 #(troop_has_flag, <troop_no>, <flag>), #Fails if <troop_no> doesn't have <flag>
troop_set_skill = 3707 #(troop_set_skill, <troop_no>, <skill_no>, <value>), #Sets <troop_no>'s <skill_no> to <value>
troop_set_attribute = 3708 #(troop_set_attribute, <troop_no>, <attribute>, <value>), #Sets <troop_no>'s <attribute> to <value>
troop_set_proficiency = 3709 #(troop_set_proficiency, <troop_no>, <proficiency>, <value>), #Sets <troop_no>'s <proficiency> to <value>
party_stack_get_experience = 3900 #(party_stack_get_experience, <destination>, <party_no>, <party_stack_no>), #Stores the experience of <party_no>'s <party_stack_no> into <destination>
party_stack_get_num_upgradeable = 3901 #(party_stack_get_num_upgradeable, <destination>, <party_no>, <party_stack_no>), #Stores the amount of upgradeable troops in <party_no>'s <party_stack_no> into <destination>
party_has_flag = 3902 #(party_has_flag, <party_no>, <flag>), #Fails if <party_no> doesn't have <flag>
party_heal_members = 3903 #(party_heal_members, <party_no>, <troop_no>, <number>), #Heals <number> <troop_no> of <party_no>
position_get_vector_to_position = 4100 #(position_get_vector_to_position, <destination_fixed_point>, <dest_position_register>, <position_register_1>, <position_register_2>), #Stores the vector from <position_register_1> to <position_register_2> into <dest_position_register> and its length into <destination_fixed_point>
position_align_to_ground = 4101 #(position_align_to_ground, <position_register>, [<point_up>], [<set_z_to_ground_level>]), #Aligns <position_register> to the ground (or to the ground normal if [<point_up>] is set)
str_equals = 4200 #(str_equals, <string_1>, <string_2>, [<case_insensitive>]), #Fails if <string_1> is not equal to <string_2>
str_contains = 4201 #(str_contains, <string_1>, <string_2>, [<case_insensitive>]), #Fails if <string_1> doesn't contain <string_2>
str_starts_with = 4202 #(str_starts_with, <string_1>, <string_2>, [<case_insensitive>]), #Fails if <string_1> doesn't start with <string_2>
str_ends_with = 4203 #(str_ends_with, <string_1>, <string_2>, [<case_insensitive>]), #Fails if <string_1> doesn't end with <string_2>
str_is_alpha = 4204 #(str_is_alpha, <string_1>, [<index>]), #Fails if character [<index>] of <string_1> isn't alphabetic. If [<index>] is not defined or is -1, the entire string is checked
str_is_digit = 4205 #(str_is_digit, <string_1>, [<index>]), #Fails if character [<index>] of <string_1> isn't a digit. If [<index>] is not defined or is -1, the entire string is checked
str_is_whitespace = 4206 #(str_is_whitespace, <string_1>, [<index>]), #Fails if character [<index>] of <string_1> isn't whitespace. If [<index>] is not defined or is -1, the entire string is checked
str_length = 4207 #(str_length, <destination>, <string_1>), #Stores the length of <string_1> into <destination>
str_index_of = 4208 #(str_index_of, <destination>, <string_1>, <string_2>, [<start>], [<end>]), #Stores the index of the first occurrence of <string_2> in <string_1> into <destination>. Search bounds can be specified with [<start>] and [<end>]
str_last_index_of = 4209 #(str_last_index_of, <destination>, <string_1>, <string_2>, [<start>], [<end>]), #Stores the index of the last occurrence of <string_2> in <string_1> into <destination>. Search bounds can be specified with [<start>] and [<end>]
str_get_char = 4210 #(str_get_char, <destination>, <string_1>, [<index>]), #Stores the numeric value of the [<index>]th character in <string_1> into <destination>
str_to_num = 4211 #(str_to_num, <destination_fixed_point>, <string_1>, [<use_fixed_point_multiplier>]), #Stores the numeric value of <string_1> into <destination_fixed_point>. Decimal values will be rounded to integers, for more precision set [<use_fixed_point_multiplier>] to non-zero
str_compare = 4212 #(str_compare, <destination>, <string_1>, <string_2>, [<case_insensitive>]), #Stores the relationship between <string_1> and <string_2> into <destination> (-1: s1 < s2, 0: s1 = s2, 1: s1 > s2)
str_split = 4213 #(str_split, <destination>, <string_register>, <string_1>, <delimiter>, [<skip_empty>], [<max>]), #Splits <string_1> using <delimiter> into a range of string registers, starting from <string_register>, storing [<max>] substrings at most (default = unlimited), ignoring empty (zero length) substrings if [<skip_empty>] (default = false). Stores the amount of substrings split into <destination>
str_sort = 4214 #(str_sort, <string_register>, [<count>], [<case_insensitive>], [<descending>]), #Sorts a range of [<count>] string registers starting from <string_register>
str_store_lower = 4215 #(str_store_lower, <string_register>, <string_1>), #Stores the lowercase version of <string_1> into <string_register>
str_store_upper = 4216 #(str_store_upper, <string_register>, <string_1>), #Stores the uppercase version of <string_1> into <string_register>
str_store_trim = 4217 #(str_store_trim, <string_register>, <string_1>, [<trim_mode>]), #Stores the whitespace trimmed version of <string_1> into <string_register>. [<trim_mode>]: 0 (default) = trim leading and trailing, 1 = trim leading, 2 = trim trailing
str_store_replace = 4218 #(str_store_replace, <string_register>, <string_1>, <string_2>, <string_3>), #Stores <string_1> into <string_register>, replacing occurrences of <string_2> with <string_3>
str_store_md5 = 4219 #(str_store_md5, <string_register>, <string_1>), #MD5 encrypts <string_1> and stores it into <string_register>
str_store_substring = 4220 #(str_store_substring, <string_register>, <string_1>, [<start>], [<length>]), #Stores a substring of <string_1> into <string_register>, starting from [<start>]. If [<length>] is not specified, everything on the right of <start> will be used
str_store_reverse = 4221 #(str_store_reverse, <string_register>, <string_1>), #Stores the reverse of <string_register> into <string_1>
str_store_join = 4222 #(str_store_join, <string_register>, <start_string_register>, <count>, [<delimiter>]), #Joins <count> string registers starting from string register <start_string_register>, using [<delimiter>] (default = empty string) and stores them into <string_register>
str_store_replace_spaces_with_underscores = 4223 #(str_store_replace_spaces_with_underscores, <string_register>, <string_1>), #Stores <string_1> into <string_register>, replacing all spaces with underscores
str_store_replace_underscores_with_spaces = 4224 #(str_store_replace_underscores_with_spaces, <string_register>, <string_1>), #Stores <string_1> into <string_register>, replacing all underscores with spaces
str_store_multiplayer_profile_name = 4225 #(str_store_multiplayer_profile_name, <string_register>, <profile_no>), #Stores <profile_no>'s name into <string_register>
str_store_module_setting = 4226 #(str_store_module_setting, <string_register>, <setting>), #Stores the string value (empty if not found) of <setting> in module.ini into <string_register>
str_store_server_password_admin = 4227 #(str_store_server_password_admin, <string_register>), #Stores the server administrator password into <string_register>
str_store_server_password_private = 4228 #(str_store_server_password_private, <string_register>), #Stores the server private player password into <string_register>
str_store_overlay_text = 4229 #(str_store_overlay_text, <string_register>, <overlay_no>), #Stores <overlay_no>'s text into <string_register>
str_store_player_ip = 4230 #(str_store_player_ip, <string_register>, <player_no>), #Stores <player_no>'s IP address into <string_register> (works only on servers)
str_store_game_variable = 4231 #(str_store_game_variable, <string_register>, <variable>), #Stores the string value (empty if not found) of <variable> in game_variables.txt into <string_register>
str_store_skill_name = 4232 #(str_store_skill_name, <string_register>, <skill_no>), #Stores the name of <skill_no> into <string_register>
str_store_float = 4233 #(str_store_float, <string_register>, <fp_register>, [<precision>]), #Stores the string representation of <fp_register> into <string_register> showing [<precision>] decimal digits at most
str_sanitize = 4234 #(str_sanitize, <string_register>), #Removes invalid characters from <string_register>
str_store_item_id = 4235 #(str_store_item_id, <string_register>, <item_no>), #Stores the id of <item_no> into <string_register>
str_is_integer = 4236 #(str_is_integer, <string_1>), #Fails if <string_1> isn't a valid integer
options_get_verbose_casualties = 4300 #(options_get_verbose_casualties, <destination>), #Stores verbose casualties enabled/disabled into <destination>
options_set_verbose_casualties = 4301 #(options_set_verbose_casualties, <value>), #Enables or disables verbose casualties
options_get_cheat_mode = 4302 #(options_get_cheat_mode, <destination>), #Stores cheat mode enabled/disabled into <destination>
options_set_cheat_mode = 4303 #(options_set_cheat_mode, <value>), #Enables or disables cheat mode
options_get_realistic_headshots = 4304 #(options_get_realistic_headshots, <destination>), #Stores "realistic" headshots enabled/disabled into <destination>
options_set_realistic_headshots = 4305 #(options_set_realistic_headshots, <value>), #Enables or disables "realistic" headshots
fld = 4400 #(fld, <fp_register>, <value_fixed_point>), #Loads <value_fixed_point> into <fp_register>
fld_str = 4401 #(fld_str, <fp_register>, <string>), #Parses <string> and loads it into <fp_register>
fld_pos_x = 4402 #(fld_pos_x, <fp_register>, <position_register_no>), #Loads the x component of <position_register_no> into <fp_register>
fld_pos_y = 4403 #(fld_pos_y, <fp_register>, <position_register_no>), #Loads the y component of <position_register_no> into <fp_register>
fld_pos_z = 4404 #(fld_pos_z, <fp_register>, <position_register_no>), #Loads the z component of <position_register_no> into <fp_register>
fst = 4405 #(fst, <destination_fixed_point>, <fp_register>), #Stores <fp_register> into <destination_fixed_point>
fcpy = 4406 #(fcpy, <fp_register_1>, <fp_register_2>), #Copies <fp_register_2> into <fp_register_1>
feq = 4407 #(feq, <destination_fp_register>, <fp_register_1>, <fp_register_2>), #Fails if <fp_register_1> isn't approximately equal to <fp_register_2>
fgt = 4408 #(fgt, <destination_fp_register>, <fp_register_1>, <fp_register_2>), #Fails if <fp_register_1> isn't greater than <fp_register_2>
flt = 4409 #(flt, <destination_fp_register>, <fp_register_1>, <fp_register_2>), #Fails if <fp_register_1> isn't less than <fp_register_2>
fge = 4410 #(fge, <destination_fp_register>, <fp_register_1>, <fp_register_2>), #Fails if <fp_register_1> isn't greater or approximately equal to <fp_register_2>
fle = 4411 #(fle, <destination_fp_register>, <fp_register_1>, <fp_register_2>), #Fails if <fp_register_1> isn't less or approximately equal to <fp_register_2>
fsub = 4412 #(fsub, <destination_fp_register>, <fp_register_1>, <fp_register_2>), #Subtracts <fp_register_2> from <fp_register_1> and stores the result into <destination_fp_register>
fmul = 4413 #(fmul, <destination_fp_register>, <fp_register_1>, <fp_register_2>), #Multiplies <fp_register_1> by <fp_register_2> and stores the result into <destination_fp_register>
fdiv = 4414 #(fdiv, <destination_fp_register>, <fp_register_1>, <fp_register_2>), #Divides <fp_register_1> by <fp_register_2> and stores the result into <destination_fp_register>
fmin = 4415 #(fmin, <destination_fp_register>, <fp_register_1>, <fp_register_2>), #Stores the smaller value between <fp_register_1> and <fp_register_2> into <destination_fp_register>
fmax = 4416 #(fmax, <destination_fp_register>, <fp_register_1>, <fp_register_2>), #Stores the larger value between <fp_register_1> and <fp_register_2> into <destination_fp_register>
fclamp = 4417 #(fclamp, <destination_fp_register>, <fp_register_1>, <fp_register_2>, <fp_register_3>), #Clamps <fp_register_1> between <fp_register_2> and <fp_register_3> and stores the result into <destination_fp_register>
fsqrt = 4418 #(fsqrt, <destination_fp_register>, <fp_register>), #Stores the square root of <fp_register> into <destination_fp_register>
fabs = 4419 #(fabs, <destination_fp_register>, <fp_register>), #Stores the absolute value of <fp_register> into <destination_fp_register>
fceil = 4420 #(fceil, <destination_fp_register>, <fp_register>), #Stores the ceiling of <fp_register> into <destination_fp_register>
ffloor = 4421 #(ffloor, <destination_fp_register>, <fp_register>), #Stores the floor of <fp_register> into <destination_fp_register>
fexp = 4422 #(fexp, <destination_fp_register>, <fp_register>), #Stores e raised to the power of <fp_register> into <destination_fp_register>
fpow = 4423 #(fpow, <destination_fp_register>, <fp_register_1>, <fp_register_2>), #Stores <fp_register_1> raised to the power of <fp_register_2> into <destination_fp_register>
fln = 4424 #(fln, <destination_fp_register>, <fp_register>), #Stores the natural logarithm of <fp_register> into <destination_fp_register>
flog = 4425 #(flog, <destination_fp_register>, <fp_register>, [<base>]), #Stores the base-[<base>] (default: base-10) logarithm of <fp_register> into <destination_fp_register>
fmod = 4426 #(fmod, <destination_fp_register>, <fp_register_1>, <fp_register_2>), #Stores the remainder of <fp_register_1>/<fp_register_2> into <destination_fp_register>
fsin = 4427 #(fsin, <destination_fp_register>, <fp_register>), #Stores the sine of <fp_register> into <destination_fp_register>
fcos = 4428 #(fcos, <destination_fp_register>, <fp_register>), #Stores the cosine of <fp_register> into <destination_fp_register>
ftan = 4429 #(ftan, <destination_fp_register>, <fp_register>), #Stores the tangent of <fp_register> into <destination_fp_register>
fsinh = 4430 #(fsinh, <destination_fp_register>, <fp_register>), #Stores the hyperbolic sine of <fp_register> into <destination_fp_register>
fcosh = 4431 #(fcosh, <destination_fp_register>, <fp_register>), #Stores the hyperbolic cosine of <fp_register> into <destination_fp_register>
ftanh = 4432 #(ftanh, <destination_fp_register>, <fp_register>), #Stores the hyperbolic tangent of <fp_register> into <destination_fp_register>
fasin = 4433 #(fasin, <destination_fp_register>, <fp_register>), #Stores the arc sine of <fp_register> into <destination_fp_register>
facos = 4434 #(facos, <destination_fp_register>, <fp_register>), #Stores the arc cosine of <fp_register> into <destination_fp_register>
fatan = 4435 #(fatan, <destination_fp_register>, <fp_register>), #Stores the arc tangent of <fp_register> into <destination_fp_register>
fatan2 = 4436 #(fatan2, <destination_fp_register>, <fp_register_1>, <fp_register_2>), #Stores the arc cosine of <fp_register_1>/<fp_register_2> into <destination_fp_register>
feval = 4437 #(feval, <expression_string>), #Evaluates <expression_string>. See EVAL_README.txt in WSESDK for more information
scene_set_flags = 4500 #(scene_set_flags, <scene_no>, <flags>), #Sets <scene_no>'s flags to <flags>
scene_set_water_level = 4501 #(scene_set_water_level, <scene_no>, <water_level_fixed_point>), #Sets <scene_no>'s water level to <water_level_fixed_point>
scene_set_bounds = 4502 #(scene_set_bounds, <scene_no>, <min_x_fixed_point>, <min_y_fixed_point>, <max_x_fixed_point>, <max_y_fixed_point>), #Sets <scene_no>'s bounds to (<min_x_fixed_point>, <min_y_fixed_point>) and (<max_x_fixed_point>, <max_y_fixed_point>)
scene_set_outer_terrain = 4503 #(scene_set_outer_terrain, <scene_no>, <outer_terrain_mesh_name>), #Sets <scene_no>'s outer terrain to <outer_terrain_mesh_name>
scene_set_terrain_seed = 4504 #(scene_set_terrain_seed, <scene_no>, <value>), #Sets <scene_no>'s terrain generator terrain seed to <value>
scene_set_river_seed = 4505 #(scene_set_river_seed, <scene_no>, <value>), #Sets <scene_no>'s terrain generator river seed to <value>
scene_set_flora_seed = 4506 #(scene_set_flora_seed, <scene_no>, <value>), #Sets <scene_no>'s terrain generator flora seed to <value>
scene_set_deep_water = 4507 #(scene_set_deep_water, <scene_no>, <value>), #Enables or disables terrain generator deep water for <scene_no>
scene_set_place_river = 4508 #(scene_set_place_river, <scene_no>, <value>), #Enables or disables terrain generator river placement for <scene_no>
scene_set_disable_grass = 4509 #(scene_set_disable_grass, <scene_no>, <value>), #Enables or disables terrain generator grass placement for <scene_no>
scene_set_valley_size = 4510 #(scene_set_valley_size, <scene_no>, <value>), #Sets <scene_no>'s terrain generator valley size to <value> (0-127)
scene_set_hill_height = 4511 #(scene_set_hill_height, <scene_no>, <value>), #Sets <scene_no>'s terrain generator hill height to <value> (0-127)
scene_set_ruggedness = 4512 #(scene_set_ruggedness, <scene_no>, <value>), #Sets <scene_no>'s terrain generator ruggedness to <value> (0-127)
scene_set_vegetation = 4513 #(scene_set_vegetation, <scene_no>, <value>), #Sets <scene_no>'s terrain generator vegetation to <value> (0-127)
scene_set_size = 4514 #(scene_set_size, <scene_no>, <x>, <y>), #Sets <scene_no>'s terrain generator map size to (<x>, <y>) (0-1023)
scene_set_region_type = 4515 #(scene_set_region_type, <scene_no>, <value>), #Sets <scene_no>'s terrain generator region type to <value> (0-15)
scene_set_region_detail = 4516 #(scene_set_region_detail, <scene_no>, <value>), #Sets <scene_no>'s terrain generator region detail to <value> (0-3)
edit_mode_get_num_selected_prop_instances = 4600 #(edit_mode_get_num_selected_prop_instances, <destination>), #Stores the number of selected prop instances into <destination>
edit_mode_get_selected_prop_instance = 4601 #(edit_mode_get_selected_prop_instance, <destination>, <index>), #Stores the <index>th selected prop instance into instance no into <destination>
edit_mode_select_prop_instance = 4602 #(edit_mode_select_prop_instance, <prop_instance_no>), #Stores the <1>th selected prop instance into instance no into <prop_instance_no>
edit_mode_deselect_prop_instance = 4603 #(edit_mode_deselect_prop_instance, <prop_instance_no>), #Stores the <1>th selected prop instance into instance no into <prop_instance_no>
edit_mode_get_highlighted_prop_instance = 4604 #(edit_mode_get_highlighted_prop_instance, <destination>), #Stores the highlighted prop instance into <destination>
edit_mode_set_highlighted_prop_instance = 4605 #(edit_mode_set_highlighted_prop_instance, [<prop_instance_no>]), #Stores the <1>th selected prop instance into instance no into [<prop_instance_no>]
edit_mode_set_enabled = 4606 #(edit_mode_set_enabled, <value>), #Enables or disables edit mode
menu_create_new = 4800 #(menu_create_new, <destination>, <text>, [<mesh_name>], [<flags>], [<script_no>], [<script_param>]), #Creates a dynamic menu and stores its id into <destination>. [<script_no>] (-1 for no script) will be called with params 1 = menu_no, 2 = [<script_param>] when the operations block is executed
menu_add_item = 4801 #(menu_add_item, <menu_no>, <text>, [<conditions_script_no>], [<consequences_script_no>], [<script_param>]), #Adds a new menu item to <menu_no>. [<conditions_script_no>] and [<consequences_script_no>] (-1 for no script) will be called with params 1 = <menu_no>, 2 = [<script_param>] when the conditions/consequences blocks are executed
menu_clear_items = 4802 #(menu_clear_items, <menu_no>), #Removes all menu items from <menu_no>
menu_clear_generated = 4803 #(menu_clear_generated), #Removes all dynamic menus
overlay_get_val = 4900 #(overlay_get_val, <destination>, <overlay_no>), #Stores <overlay_no>'s value into <destination>
presentation_activate = 4901 #(presentation_activate, <presentation_no>), #Activates <presentation_no>. Fails if <presentation_no> is not running
lhs_operations += [
try_for_agents,
store_trigger_param,
val_shr,
store_shr,
val_lshr,
store_lshr,
val_shl,
store_shl,
val_xor,
store_xor,
val_not,
store_not,
register_get,
store_wse_version,
store_current_trigger,
store_num_return_values,
store_return_value,
mtrand,
get_time,
timer_get_elapsed_time,
game_key_get_key,
dict_create,
dict_get_size,
dict_get_int,
agent_get_item_modifier,
agent_get_item_slot_modifier,
agent_get_animation_progress,
agent_get_dna,
agent_get_ground_scene_prop,
agent_get_item_slot_ammo,
agent_get_item_slot_hit_points,
agent_get_wielded_item_slot_no,
agent_get_scale,
agent_get_item_slot_flags,
multiplayer_get_cur_profile,
multiplayer_get_num_profiles,
server_map_rotation_get_count,
server_map_rotation_get_index,
server_map_rotation_get_map,
get_server_option_at_connect,
store_cur_mission_template_no,
get_spectated_agent_no,
get_water_level,
troop_get_skill_points,
troop_get_attribute_points,
troop_get_proficiency_points,
party_stack_get_experience,
party_stack_get_num_upgradeable,
position_get_vector_to_position,
str_length,
str_index_of,
str_last_index_of,
str_get_char,
str_to_num,
str_compare,
str_split,
options_get_verbose_casualties,
options_get_cheat_mode,
options_get_realistic_headshots,
fst,
edit_mode_get_num_selected_prop_instances,
edit_mode_get_selected_prop_instance,
edit_mode_get_highlighted_prop_instance,
menu_create_new,
overlay_get_val,
]
can_fail_operations += [
is_vanilla_warband,
item_slot_gt,
party_template_slot_gt,
troop_slot_gt,
faction_slot_gt,
quest_slot_gt,
scene_slot_gt,
party_slot_gt,
player_slot_gt,
team_slot_gt,
agent_slot_gt,
scene_prop_slot_gt,
order_flag_is_active,
key_released,
game_key_released,
dict_is_empty,
dict_has_key,
camera_in_first_person,
troop_has_flag,
party_has_flag,
str_equals,
str_contains,
str_starts_with,
str_ends_with,
str_is_alpha,
str_is_digit,
str_is_whitespace,
str_is_integer,
feq,
fgt,
flt,
fge,
fle,
presentation_activate,
]
#for mb_warband_module_system_1165_lav
depth_operations = [
try_for_dict_keys,
]
| [
"Milan.Doepper@gmail.com"
] | Milan.Doepper@gmail.com |
833453f218df3ece4c9f8f4c2dcce151ac21b206 | 5b026039603f95525dbca7ed5ab144f2de7c3379 | /templates/runpy/train.py | 2fab9e7131585e0f7edb920779f436de384958e7 | [] | no_license | nayo79/flask_base | 3b7c75a41323e61860cbecf652e0b76684ce42e9 | 41a98c8b21c5ac4af57c83516ae022c59c92d2c3 | refs/heads/master | 2022-04-24T23:54:04.010197 | 2020-04-27T04:53:36 | 2020-04-27T04:53:36 | 259,206,275 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 68 | py | def train():
print("test train module run !!! ")
return | [
"nayo79@naver.com"
] | nayo79@naver.com |
dc12825f1785f0eceb733db879c05efe907c1ac8 | e912af291e1457c61606642f1c7700e678c77a27 | /python/532_k-diff_pairs_in_an_array.py | b3078a0372260afbe3f7744d4defba6a128add92 | [] | no_license | MakrisHuang/LeetCode | 325be680f8f67b0f34527914c6bd0a5a9e62e9c9 | 7609fbd164e3dbedc11308fdc24b57b5097ade81 | refs/heads/master | 2022-08-13T12:13:35.003830 | 2022-07-31T23:03:03 | 2022-07-31T23:03:03 | 128,767,837 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 282 | py | class Solution:
def findPairs(self, nums: List[int], k: int) -> int:
if k > 0:
return len(set(nums) & set(n + k for n in nums))
elif k == 0:
return sum(v > 1 for v in collections.Counter(nums).values())
else:
return 0
| [
"vallwesture@gmail.com"
] | vallwesture@gmail.com |
8f09330c321fc94615ad841d33c7d91785f818a1 | 5a25f24819501e697549078cc5eec18904c1a5e4 | /gestnet.py | eab7265e86e55347d942fb62397c6f6b8c88b42d | [] | no_license | caitlinsmith14/gestnet | d225ec9428f2ce3d4387d59184100b07422f2731 | d14b55c6a475b45a4fbb7ccb45bea8f29fc60a0b | refs/heads/master | 2023-02-25T22:23:42.424648 | 2021-01-27T16:13:47 | 2021-01-27T16:13:47 | 329,521,265 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 16,314 | py | import glob
import matplotlib.pyplot as plt
import os
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchtext.data import BucketIterator, Field, TabularDataset
from tqdm import tqdm
import warnings
###########
# DATASET #
###########
class Dataset: # Dataset object class utilizing Torchtext
def __init__(self, path, batch_size=1):
self.batch_size = batch_size
self.input_field, self.output_field, self.data, self.data_iter = self.process_data(path)
self.word2trialnum = self.make_trial_lookup(path)
self.seg2ind = self.input_field.vocab.stoi # from segment to torchtext vocab index
def process_data(self, path): # create Dataset object from tab-delimited text file
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
make_list = lambda b: [item for item in b.split(',')]
make_float_list = lambda b: [float(item) for item in b.split(',')]
input_field = Field(sequential=True, use_vocab=True, tokenize=make_list) # morpheme segment format
output_field = Field(sequential=True, use_vocab=False, tokenize=make_float_list) # lip trajectory outputs
datafields = [('underlying', None), ('surface', None), ('root_indices', None), ('suffix_indices', None),
('word_indices', input_field), ('lip_output', output_field), ('tb_output', output_field)]
data = TabularDataset(path=path, format='tsv', skip_header=True, fields=datafields)
input_field.build_vocab(data, min_freq=1)
data_iter = BucketIterator(data,
batch_size=self.batch_size,
sort_within_batch=False,
repeat=False,
device=device)
return input_field, output_field, data, data_iter
def make_trial_lookup(self, path): # create lookup dictionary for use by make_trial method
with open(path, 'r') as file:
word2trialnum = {}
for x, line in enumerate(file, start=-1):
word2trialnum[line.split()[0]] = x
return word2trialnum
def make_trial(self, word): # get target outputs for individual word for use by Seq2Seq's evaluate_word method
trialnum = self.word2trialnum[word]
source = self.data.examples[trialnum].word_indices
lip_target = self.data.examples[trialnum].lip_output
tb_target = self.data.examples[trialnum].tb_output
source_list = []
for seg in source:
source_list.append(self.seg2ind[seg])
source_tensor = torch.tensor(source_list, dtype=torch.long).view(-1, 1)
lip_target_tensor = torch.tensor(lip_target, dtype=torch.double).view(-1, 1)
tb_target_tensor = torch.tensor(tb_target, dtype=torch.double).view(-1, 1)
return source_tensor, lip_target_tensor, tb_target_tensor
###########
# ENCODER #
###########
class Encoder(nn.Module):
def __init__(self,
vocab_size, # size of vector representing each segment in vocabulary (created by Dataset)
seg_embed_size, # size of segment embedding
hidden_size): # size of encoder hidden layer
super(Encoder, self).__init__()
self.params = (vocab_size, seg_embed_size, hidden_size)
self.embedding = nn.Embedding(vocab_size, seg_embed_size) # embedding dictionary for each segment
self.rnn = nn.RNN(seg_embed_size, hidden_size) # RNN hidden layer
def forward(self, input_seq):
embedded_seq = self.embedding(input_seq)
output_seq, last_hidden = self.rnn(embedded_seq)
return output_seq, last_hidden, embedded_seq
#############################
# ENCODER-DECODER ATTENTION #
#############################
class EncoderDecoderAttn(nn.Module): # attention mechanism between encoder and decoder hidden states
def __init__(self,
encoder_size, # size of encoder hidden layer
decoder_size, # size of decoder hidden layer
attn_size): # size of attention vector
super(EncoderDecoderAttn, self).__init__() # always call this
self.params = (encoder_size, decoder_size, attn_size)
self.linear = nn.Linear(encoder_size+decoder_size, attn_size) # linear layer
def forward(self, decoder_hidden, encoder_outputs):
decoder_hidden = decoder_hidden.squeeze(0)
input_seq_length = encoder_outputs.shape[0]
repeated_decoder_hidden = decoder_hidden.unsqueeze(1).repeat(1, input_seq_length, 1)
encoder_outputs = encoder_outputs.permute(1, 0, 2)
attn = torch.tanh(self.linear(torch.cat((repeated_decoder_hidden, encoder_outputs), dim=2)))
attn_sum = torch.sum(attn, dim=2)
attn_softmax = F.softmax(attn_sum, dim=1).unsqueeze(1)
attended_encoder_outputs = torch.bmm(attn_softmax, encoder_outputs).squeeze(1)
encoder_norms = encoder_outputs.norm(dim=2)
attn_map = attn_softmax.squeeze(1) * encoder_norms
return attended_encoder_outputs, attn_map
###########
# DECODER #
###########
class Decoder(nn.Module):
def __init__(self,
hidden_size, # size of hidden layer for both encoder and decoder
attn): # encoder-decoder attention mechanism
super(Decoder, self).__init__()
self.params = hidden_size
self.output_size = 2 # number of articulators (lip and tongue body)
self.attn = attn # encoder-decoder attention mechamism
self.rnn = nn.RNN(self.output_size+self.attn.params[0], hidden_size) # RNN hidden layer
self.linear = nn.Linear(hidden_size, self.output_size) # linear layer
def forward(self, input_tok, hidden, encoder_outputs):
input_tok = input_tok.float()
attended, attn_map = self.attn(hidden, encoder_outputs)
rnn_input = torch.cat((input_tok, attended), dim=1).unsqueeze(0)
output, hidden = self.rnn(rnn_input, hidden)
output = self.linear(output.squeeze(0))
return output, hidden, attn_map
##############################
# SEQUENCE TO SEQUENCE MODEL #
##############################
class Seq2Seq(nn.Module): # Combine encoder and decoder into sequence-to-sequence model
def __init__(self,
training_data=None, # training data (Dataset class object)
load='', # path to file for loading previously trained model
seg_embed_size=32, # size of segment embedding
hidden_size=32, # size of hidden layer
attn_size=32, # size of encoder-decoder attention vector
optimizer='adam', # what type of optimizer (Adam or SGD)
learning_rate=.001): # learning rate of the model
super(Seq2Seq, self).__init__()
# Seq2Seq Parameters
self.init_input_tok = nn.Parameter(torch.rand(1, 2)) # initialize first decoder input (learnable)
# Hyperparameters / Device Settings
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
self.loss_function = nn.MSELoss(reduction='sum')
# Load a trained model and its subcomponents
if load:
self.path = re.sub('_[0-9]+.pt', '_', load)
checkpoint = torch.load(load)
self.encoder = Encoder(vocab_size=checkpoint['encoder_params'][0],
seg_embed_size=checkpoint['encoder_params'][1],
hidden_size=checkpoint['encoder_params'][2])
attn = EncoderDecoderAttn(encoder_size=checkpoint['attn_params'][0],
decoder_size=checkpoint['attn_params'][1],
attn_size=checkpoint['attn_params'][2])
self.decoder = Decoder(hidden_size=checkpoint['decoder_params'],
attn=attn)
self.loss_list = checkpoint['loss_list']
self.load_state_dict(checkpoint['seq2seq_state_dict'])
if checkpoint['optimizer_type'] == 'SGD':
self.optimizer = optim.SGD(self.parameters(), lr=learning_rate)
elif checkpoint['optimizer_type'] == 'Adam':
self.optimizer = optim.Adam(self.parameters())
else:
print('Optimizer not loaded! Try again.')
return
self.optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
else: # Initialize a new model and its subcomponents
if not training_data:
print('Required input: training_data (Dataset class object). Try again!')
return
self.path = None
self.encoder = Encoder(vocab_size=len(training_data.input_field.vocab),
seg_embed_size=seg_embed_size,
hidden_size=hidden_size)
attn = EncoderDecoderAttn(encoder_size=hidden_size,
decoder_size=hidden_size,
attn_size=attn_size)
self.decoder = Decoder(hidden_size=hidden_size,
attn=attn)
self.loss_list = []
for name, param in self.named_parameters():
nn.init.uniform_(param.data, -0.08, 0.08)
if optimizer == 'adam':
self.optimizer = optim.Adam(self.parameters(), lr=learning_rate)
elif optimizer == 'sgd':
self.optimizer = optim.SGD(self.parameters(), lr=learning_rate)
else:
'No such optimizer! Try again.'
return
def forward(self, input_seq, target_seq):
input_length = input_seq.shape[0]
target_length = target_seq.shape[0]
target_output_size = self.decoder.output_size
output_seq = torch.zeros(target_length, target_output_size).to(self.device)
attn_map_seq = torch.zeros(target_length, input_length).to(self.device)
encoder_outputs, hidden, embeddings = self.encoder(input_seq)
input_tok = self.init_input_tok
for t in range(target_length):
output_tok, hidden, attn_map = self.decoder(input_tok,
hidden,
encoder_outputs)
output_seq[t] = output_tok
attn_map_seq[t] = attn_map
input_tok = output_tok
return output_seq, attn_map_seq
def train_model(self, training_data, n_epochs=1): # Train the model on the provided dataset
self.train()
with warnings.catch_warnings():
warnings.simplefilter('ignore')
for _ in tqdm(range(n_epochs)):
for i, batch in enumerate(training_data.data_iter):
self.zero_grad()
source = batch.word_indices
target_la = batch.lip_output
target_tb = batch.tb_output
target = torch.cat((target_la, target_tb), 1)
predicted, enc_dec_attn_seq = self(source, target)
loss = self.loss_function(predicted.float(), target.float())
loss.backward()
self.optimizer.step()
self.loss_list.append(self.evaluate_model(training_data, verbose=False))
def evaluate_model(self, training_data, verbose=True): # Evaluate the model's performance on the dataset
self.eval()
epoch_loss = 0
with warnings.catch_warnings():
warnings.simplefilter('ignore')
with torch.no_grad():
for i, batch in enumerate(training_data.data_iter):
source = batch.word_indices
target_la = batch.lip_output
target_tb = batch.tb_output
target = torch.cat((target_la, target_tb), 1)
predicted, _ = self(source, target)
loss = self.loss_function(predicted.float(), target.float())
epoch_loss += loss.item()
average_loss = epoch_loss / len(training_data.data_iter)
if verbose:
print(f'Average loss per word this epoch:')
return average_loss
def plot_loss(self): # Plot the model's average trial loss per epoch
plt.plot(self.loss_list, '-')
plt.title('Average Trial Loss Per Epoch')
plt.ylabel('Sum of Squared Error')
plt.xlabel('Epoch')
def evaluate_word(self, training_data, word, show_target=True): # Evaluate the model's performance on a single word
self.eval()
trial = training_data.make_trial(word)
with torch.no_grad():
source = trial[0]
target_la = trial[1]
target_tb = trial[2]
target = torch.cat((target_la, target_tb), 1)
predicted, enc_dec_attn_seq = self(source, target)
print(f'Target output:\n{target}')
print(f'Predicted output:\n{predicted}')
print(f'Encoder Decoder Attention:\n{enc_dec_attn_seq}')
predicted_la = predicted[:, 0]
predicted_tb = predicted[:, 1]
figure_outputs, (lip_plot, tb_plot) = plt.subplots(2)
figure_outputs.suptitle('Predicted Tract Variable Trajectories')
# Lip Aperture Trajectory Subplot
lip_plot.plot(predicted_la, label='Predicted')
if show_target:
lip_plot.plot(target_la, label='Target')
lip_plot.set_title('Lip Tract Variable')
lip_plot.set_ylabel('Constriction Degree (Lip Aperture)')
lip_plot.set_ylim(10, -5)
lip_plot.legend()
# Tongue Body (Height) Trajectory Subplot
tb_plot.plot(predicted_tb)
if show_target:
tb_plot.plot(target_tb)
tb_plot.set_title('Tongue Body Height Tract Variable')
tb_plot.set_xlabel('Time')
tb_plot.set_ylabel('Constriction Degree (Height)')
tb_plot.set_ylim(20, -5)
# Plot Encoder-Decoder Attention
heatmap_attn, ax = plt.subplots()
heatmap_attn.suptitle('Encoder-Decoder Attention')
im = ax.imshow(enc_dec_attn_seq.permute(1, 0), cmap='gray')
ax.set_xticks([x for x in range(enc_dec_attn_seq.shape[0])])
ax.set_xticklabels([x+1 for x in range(enc_dec_attn_seq.shape[0])])
ax.set_xlabel('Decoder Time Point')
ax.set_yticks([x for x in range(len(re.sub('-', '', word)))])
ax.set_yticklabels(list(re.sub('-', '', word)))
ax.set_ylabel('Input')
plt.show()
def save(self): # Save model to 'saved_models'
save_dict = {'encoder_params': self.encoder.params,
'attn_params': self.decoder.attn.params,
'decoder_params': self.decoder.params,
'seq2seq_state_dict': self.state_dict(),
'optimizer_type': str(self.optimizer)[0:4].strip(),
'optimizer_state_dict': self.optimizer.state_dict(),
'loss_list': self.loss_list}
if not os.path.isdir('saved_models'):
os.mkdir('saved_models')
if self.path is None:
model_num = 1
while glob.glob(os.path.join('saved_models', f'gestnet_{model_num}_*.pt')):
model_num += 1
self.path = os.path.join('saved_models', f'gestnet_{model_num}_')
else:
model_num = self.path.split('_')[-2]
saveas = f'{self.path}{str(len(self.loss_list))}.pt'
torch.save(save_dict, saveas)
print(f'Model saved as gestnet_{model_num}_{str(len(self.loss_list))} in directory saved_models.')
def count_params(self): # Count trainable model parameters
params = sum(p.numel() for p in self.parameters() if p.requires_grad)
print('The model has ' + str(params) + ' trainable parameters.')
# Load a premade Dataset object for stepwise height harmony
with warnings.catch_warnings():
warnings.simplefilter('ignore')
data_stepwise = Dataset('trainingdata_stepwise.txt')
| [
"caitlin.smith14@gmail.com"
] | caitlin.smith14@gmail.com |
2aa7bde3a911350d0e47468c52ea4230a5205852 | 17a71cbb5d1b74fcda2c81406fed268d1afdfce6 | /ariac_behaviors/ariac_flexbe_states/src/ariac_flexbe_states/detect_part_camera_ariac_state.py | deb6877ecaa1701f690f74af8025127a3f398979 | [] | no_license | noahsmit/rosphase3 | 18a4f5a2b876d80d7fc83ec8aa06bd2dcd261213 | 6280a3d6fd0f2467793448b5cdf8bd734ae68755 | refs/heads/master | 2023-06-08T20:17:19.768913 | 2021-06-28T21:32:06 | 2021-06-28T21:32:06 | 375,636,982 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,960 | py | #!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2018, Delft University of Technology
# 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 Delft University of Technology 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.
#
# Authors: the HRWROS mooc instructors
# Modified for using Ariac: Gerard Harkema
import rospy
import rostopic
import inspect
import tf2_ros
import tf2_geometry_msgs
import geometry_msgs.msg
from flexbe_core import EventState, Logger
from geometry_msgs.msg import Pose, PoseStamped
from nist_gear.msg import LogicalCameraImage, Model
from flexbe_core.proxy import ProxySubscriberCached
'''
Created on Sep 5 2018
@author: HRWROS mooc instructors
'''
class DetectPartCameraAriacState(EventState):
'''
State to detect the pose of the part with any of the cameras in the factory simulation of the Ariac
-- time_out float Time in withs the camera to have detected the part
># ref_frame string reference frame for the part pose output key
># camera_topic string the topic name for the camera to detect the part
># camera_frame string frame of the camera
># part string Part to detect
#> pose PoseStamped Pose of the detected part
<= continue if the pose of the part has been succesfully obtained
<= failed otherwise
'''
def __init__(self, time_out = 0.5):
# Declare outcomes, input_keys, and output_keys by calling the super constructor with the corresponding arguments.
super(DetectPartCameraAriacState, self).__init__(outcomes = ['continue', 'failed', 'not_found'], input_keys = ['ref_frame', 'camera_topic', 'camera_frame', 'part'], output_keys = ['pose'])
# Store state parameter for later use.
self._wait = time_out
# tf to transfor the object pose
self._tf_buffer = tf2_ros.Buffer(rospy.Duration(10.0)) #tf buffer length
self._tf_listener = tf2_ros.TransformListener(self._tf_buffer)
def execute(self, userdata):
# This method is called periodically while the state is active.
# Main purpose is to check state conditions and trigger a corresponding outcome.
# If no outcome is returned, the state will stay active.
#rospy.logwarn(userdata.ref_frame)
#rospy.logwarn(userdata.camera_topic)
#rospy.logwarn(userdata.camera_frame)
#rospy.logwarn(userdata.part)
if not self._connected:
userdata.pose = None
return 'failed'
if self._failed:
userdata.pose = None
return 'failed'
elapsed = rospy.get_rostime() - self._start_time;
if (elapsed.to_sec() > self._wait):
return 'time_out'
if self._sub.has_msg(self._topic):
message = self._sub.get_last_msg(self._topic)
#rospy.logwarn(message)
for model in message.models:
if model.type == userdata.part:
part_pose = PoseStamped()
#rospy.logwarn("model.pose")
#rospy.logwarn(model.pose)
part_pose.pose = model.pose
part_pose.header.frame_id = self._camera_frame
part_pose.header.stamp = rospy.Time.now()
# Transform the pose to desired output frame
part_pose = tf2_geometry_msgs.do_transform_pose(part_pose, self._transform)
broadcaster = tf2_ros.StaticTransformBroadcaster()
#rospy.logwarn("pose")
#rospy.logwarn(part_pose)
userdata.pose = part_pose
return 'continue'
userdata.pose = None
return 'not_found'
def on_enter(self, userdata):
# This method is called when the state becomes active, i.e. a transition from another state to this one is taken.
# It is primarily used to start actions which are associated with this state.
self.ref_frame = userdata.ref_frame
self._topic = userdata.camera_topic
self._camera_frame = userdata.camera_frame
self._connected = False
self._failed = False
self._start_time = rospy.get_rostime()
# Subscribe to the topic for the logical camera
(msg_path, msg_topic, fn) = rostopic.get_topic_type(self._topic)
if msg_topic == self._topic:
msg_type = self._get_msg_from_path(msg_path)
self._sub = ProxySubscriberCached({self._topic: msg_type})
self._connected = True
else:
Logger.logwarn('Topic %s for state %s not yet available.\nFound: %s\nWill try again when entering the state...' % (self._topic, self.name, str(msg_topic)))
# Get transform between camera and robot_base
try:
self._transform = self._tf_buffer.lookup_transform(self.ref_frame, self._camera_frame, rospy.Time(0), rospy.Duration(1.0))
except Exception as e:
Logger.logwarn('Could not transform pose: ' + str(e))
self._failed = True
def on_exit(self, userdata):
# This method is called when an outcome is returned and another state gets active.
# It can be used to stop possibly running processes started by on_enter.
pass # Nothing to do
def on_start(self):
# This method is called when the behavior is started.
# If possible, it is generally better to initialize used resources in the constructor
# because if anything failed, the behavior would not even be started.
self._start_time = rospy.Time.now()
def on_stop(self):
# This method is called whenever the behavior stops execution, also if it is cancelled.
# Use this event to clean up things like claimed resources.
pass # Nothing to do
def _get_msg_from_path(self, msg_path):
'''
Created on 11.06.2013
@author: Philipp Schillinger
'''
msg_import = msg_path.split('/')
msg_module = '%s.msg' % (msg_import[0])
package = __import__(msg_module, fromlist=[msg_module])
clsmembers = inspect.getmembers(package, lambda member: inspect.isclass(member) and member.__module__.endswith(msg_import[1]))
return clsmembers[0][1]
| [
"noahsmit1707@gmail.com"
] | noahsmit1707@gmail.com |
3b7afc565fc2ff0482cafb249736d156f6f05efc | 59166105545cdd87626d15bf42e60a9ee1ef2413 | /test/test_ice_hockey_league.py | c6490a78cce2303eb5bfa685c644b362d39686a4 | [] | no_license | mosoriob/dbpedia_api_client | 8c594fc115ce75235315e890d55fbf6bd555fa85 | 8d6f0d04a3a30a82ce0e9277e4c9ce00ecd0c0cc | refs/heads/master | 2022-11-20T01:42:33.481024 | 2020-05-12T23:22:54 | 2020-05-12T23:22:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,309 | py | # coding: utf-8
"""
DBpedia
This is the API of the DBpedia Ontology # noqa: E501
The version of the OpenAPI document: v0.0.1
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import datetime
import dbpedia
from dbpedia.models.ice_hockey_league import IceHockeyLeague # noqa: E501
from dbpedia.rest import ApiException
class TestIceHockeyLeague(unittest.TestCase):
"""IceHockeyLeague unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional):
"""Test IceHockeyLeague
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included """
# model = dbpedia.models.ice_hockey_league.IceHockeyLeague() # noqa: E501
if include_optional :
return IceHockeyLeague(
viaf_id = [
'0'
],
leader_function = [
None
],
art_patron = [
None
],
manager_season = [
None
],
secretary_general = [
None
],
number_of_locations = [
56
],
discipline = [
None
],
type = [
'0'
],
revenue = [
1.337
],
affiliation = [
None
],
season = [
None
],
id = '0',
nla_id = [
'0'
],
chairperson = [
None
],
region_served = [
None
],
superintendent = [
None
],
formation_date = [
'0'
],
number_of_employees = [
56
],
extinction_date = [
'0'
],
player_season = [
None
],
endowment = [
1.337
],
number_of_teams = [
56
],
slogan = [
'0'
],
regional_council = [
None
],
location_city = [
None
],
number_of_volunteers = [
56
],
ideology = [
None
],
description = [
'0'
],
membership = [
'0'
],
ceo = [
None
],
formation_year = [
'0'
],
junior_season = [
None
],
headquarter = [
None
],
extinction_year = [
'0'
],
child_organisation = [
None
],
honours = [
None
],
parent_organisation = [
None
],
organisation_member = [
None
],
number_of_staff = [
56
],
product = [
None
],
hometown = [
None
],
foundation_place = [
None
],
national_selection = [
None
],
current_season = [
'0'
],
label = [
'0'
],
legal_form = [
None
],
general_council = [
None
],
trustee = [
None
],
age = [
56
],
main_organ = [
None
]
)
else :
return IceHockeyLeague(
)
def testIceHockeyLeague(self):
"""Test IceHockeyLeague"""
inst_req_only = self.make_instance(include_optional=False)
inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()
| [
"maxiosorio@gmail.com"
] | maxiosorio@gmail.com |
a310c88b7fc76fe3caaeee1c7776e3216aa9eeec | b6bc6e355e6a36a689385aae1ceae7e0aacf50bd | /lotto/lottoNum.py | 003ab59d2f532211444b93dab70a59dac00bf899 | [] | no_license | water-lilies/Python_basics | e68723ba3503847110db9252bf5b565fef7650ed | 009d0e98e5df710a3937f52088fa9bf97bce5311 | refs/heads/master | 2020-12-12T19:03:29.036315 | 2020-01-16T02:08:22 | 2020-01-16T02:08:22 | 234,207,188 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 464 | py | def lottoNum():
lottoNum = []
while True:
# 탈출조건 : 번호 6개인지 확인
if len(lottoNum) >= 6:
break
else:
# 로또번호 생성
data = random.randint(1, 46)
# 로또번호가 리스트에 있는지 없는지 확인
if data not in lottoNum:
lottoNum.append(data)
return lottoNum
if __name__ == "__main__":
print('main으로 실행') | [
"minji9684@gmail.com"
] | minji9684@gmail.com |
2869e79b808909f85d9ef01837852f9933c99b76 | 5b35521ed6e32cbafb54e88f117784d05f65107a | /blockchain/abi.py | a428e50f9ea876f7991f9349affe871fa9ace2eb | [] | no_license | prashantsengar/TakeMeTo | 79a5a557becb64a5385b7a268751f8ff9d9f666c | 476eb4c3aeac4d0a45f5cff6d23e6d9ec0bced16 | refs/heads/master | 2022-11-18T07:24:51.473735 | 2020-07-17T14:42:26 | 2020-07-17T14:42:26 | 273,710,160 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,813 | py | abi = """[
{
"constant": true,
"inputs": [],
"name": "name",
"outputs": [
{
"name": "",
"type": "string"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "spender",
"type": "address"
},
{
"name": "tokens",
"type": "uint256"
}
],
"name": "approve",
"outputs": [
{
"name": "success",
"type": "bool"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "URLid",
"type": "uint256"
}
],
"name": "isUnderStaking",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "person",
"type": "address"
},
{
"name": "URLid",
"type": "uint256"
}
],
"name": "claimReward",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "totalSupply",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "from",
"type": "address"
},
{
"name": "to",
"type": "address"
},
{
"name": "tokens",
"type": "uint256"
}
],
"name": "transferFrom",
"outputs": [
{
"name": "success",
"type": "bool"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "decimals",
"outputs": [
{
"name": "",
"type": "uint8"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "_totalSupply",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "URLid",
"type": "uint256"
}
],
"name": "ifrewardCalculated",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "tokenOwner",
"type": "address"
}
],
"name": "balanceOf",
"outputs": [
{
"name": "balance",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": false,
"inputs": [],
"name": "acceptOwnership",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "urlID",
"type": "uint256"
},
{
"name": "validator",
"type": "address"
},
{
"name": "up",
"type": "bool"
},
{
"name": "tokens",
"type": "uint128"
}
],
"name": "Vote",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "category",
"type": "uint256"
}
],
"name": "gettotal",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "owner",
"outputs": [
{
"name": "",
"type": "address"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "symbol",
"outputs": [
{
"name": "",
"type": "string"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "a",
"type": "uint256"
},
{
"name": "b",
"type": "uint256"
}
],
"name": "safeSub",
"outputs": [
{
"name": "c",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "pure",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "to",
"type": "address"
},
{
"name": "tokens",
"type": "uint256"
}
],
"name": "transfer",
"outputs": [
{
"name": "success",
"type": "bool"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "category",
"type": "uint256"
},
{
"name": "url",
"type": "string"
},
{
"name": "title",
"type": "string"
},
{
"name": "submitter",
"type": "address"
}
],
"name": "submitUrl",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "a",
"type": "uint256"
},
{
"name": "b",
"type": "uint256"
}
],
"name": "safeDiv",
"outputs": [
{
"name": "c",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "pure",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "spender",
"type": "address"
},
{
"name": "tokens",
"type": "uint256"
},
{
"name": "data",
"type": "bytes"
}
],
"name": "approveAndCall",
"outputs": [
{
"name": "success",
"type": "bool"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "get_contract_address",
"outputs": [
{
"name": "",
"type": "address"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "a",
"type": "uint256"
},
{
"name": "b",
"type": "uint256"
}
],
"name": "safeMul",
"outputs": [
{
"name": "c",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "pure",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "URLid",
"type": "uint256"
}
],
"name": "calculateReward",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "newOwner",
"outputs": [
{
"name": "",
"type": "address"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "tokenAddress",
"type": "address"
},
{
"name": "tokens",
"type": "uint256"
}
],
"name": "transferAnyERC20Token",
"outputs": [
{
"name": "success",
"type": "bool"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "tokenOwner",
"type": "address"
},
{
"name": "spender",
"type": "address"
}
],
"name": "allowance",
"outputs": [
{
"name": "remaining",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "a",
"type": "uint256"
},
{
"name": "b",
"type": "uint256"
}
],
"name": "safeAdd",
"outputs": [
{
"name": "c",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "pure",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "ID",
"type": "uint256"
},
{
"name": "category",
"type": "uint256"
}
],
"name": "getURL",
"outputs": [
{
"name": "",
"type": "string"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_newOwner",
"type": "address"
}
],
"name": "transferOwnership",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"payable": true,
"stateMutability": "payable",
"type": "fallback"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "_from",
"type": "address"
},
{
"indexed": true,
"name": "_to",
"type": "address"
}
],
"name": "OwnershipTransferred",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "from",
"type": "address"
},
{
"indexed": true,
"name": "to",
"type": "address"
},
{
"indexed": false,
"name": "tokens",
"type": "uint256"
}
],
"name": "Transfer",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "tokenOwner",
"type": "address"
},
{
"indexed": true,
"name": "spender",
"type": "address"
},
{
"indexed": false,
"name": "tokens",
"type": "uint256"
}
],
"name": "Approval",
"type": "event"
}
]"""
| [
"noreply@github.com"
] | prashantsengar.noreply@github.com |
f5cb9a7e88cf9f501cc9ffa72882275e918cc0b5 | 3e177bdd3dbd0f6e591494ead92149d1a85e0d99 | /cosine_similarity.py | 32b6f79e3c3fda7a42aa645e0ccbfadf73e36cd0 | [] | no_license | rishiraj7102/Movie-Recommendation-Model | bbb44fa63beb06b433f3ec9bc532bcd249720f77 | 63ecb00a6629b1f2f210ce0b545fbbdea3f4501f | refs/heads/main | 2023-03-05T08:04:10.902064 | 2021-02-17T16:56:58 | 2021-02-17T16:56:58 | 339,792,635 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 335 | py | from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
text=['London Paris London','Paris London Paris']
cv=CountVectorizer()
count_matrix=cv.fit_transform(text)
#print( count_matrix.toarray())
similarity_scores=cosine_similarity(count_matrix)
print(similarity_scores) | [
"noreply@github.com"
] | rishiraj7102.noreply@github.com |
05a598c8074c393627405ac70511151275d19b39 | 2c0f0d4c96467a9c16813b9795d7398561a4c0ae | /src/djangoproject/blog/urls.py | 35e4bae5c22ff15c1457d40025d7942336ec0ed6 | [] | no_license | saniyaagrawal/Blog | 7a72602983de0746c96bbd1c95a6c06bd2dad32f | 9a0333930d9ed290dd9088a1f8c24d2daea69f03 | refs/heads/master | 2022-06-21T07:42:40.441894 | 2020-05-15T05:34:27 | 2020-05-15T05:34:27 | 263,582,667 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 576 | py | from django.urls import path
from .views import PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView
from . import views
urlpatterns = [
path('', PostListView.as_view(), name='blog-home'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'),
path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
path('post/new/', PostCreateView.as_view(), name='post-create'),
path('about/', views.about, name='blog-about'),
] | [
"saniya.agrawal30@gmail.com"
] | saniya.agrawal30@gmail.com |
f9975385c29060a7d3ba91169d285114e2082935 | 712fa46c78f0b4fe29d241c1f4f16068ceea96bb | /mechgame.py | 628c4d54c435d16a9aeb07684399bc1475f68fc3 | [] | no_license | lamburger3/Simple_Mech_Game | e2f53ce7e0dfab45df22e85fc3902bb0de5bf9ec | 60c43c6ab50db6f2f3505b76bc97a28ed6c8c053 | refs/heads/master | 2021-08-24T03:03:57.006079 | 2017-12-07T19:44:16 | 2017-12-07T19:44:16 | 113,491,321 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,750 | py | from random import randint
'''
Create a battle system based on d20s, with each fighter containing AC, and health, like in DND.
1.
There should be 3 presets for the user to choose, "Heavy Mech," "Light Mech," and "Medium Mech,"
all who contain unique stats, light having less AC and health than medium, and medium having less than heavy,
AC and health increasing by increments of twenty each preset, light starting at 30 HP and AC
2.
I should be able to choose my mech preset and have a message print to me telling me what i've chosen.
3.
I should then be given a "Light machinegun" if i've chosen light, an "Assaultcannon" if i've chosen medium,
and a "Heavy Blastcannon" if i've chosen heavy.
Light machinegun does 1d8 damage per hit, Assaultcannon does 1d12, and Heavy Blastcannon does a 1d20
4.
There should be an enemy generated the same way, but preset determined randomly between the 3
5.
I should be prompted to engage the enemy, while being told what i am seeing in-game
6.
If i choose to engage the enemy, combat ensues in turn order where the user starts first, and attack rate is based on a d20 roll that must pass enemy AC, describe every attack as it happens.
7.
Enemy must automatically attack after user has
8.
When a fighter looses, print the name of the winner of the battle.
'''
light_mech_weapon_name = "Light Machine Gun"
light_mech_weapon_die_size = 8
medium_mech_weapon_name = "Assault Cannon"
medium_mech_weapon_die_size = 12
heavy_mech_weapon_name = "Heavy Blast Cannon"
heavy_mech_weapon_die_size = 20
class Weapon():
name = ""
weapon_die_count = 1
weapon_die_size = 6
weapon_modifier = 0
def __init__(self, name, size):
self.name = name
self.weapon_die_size = size
def print_weapon_stats(self):
print("This mech's weapon is called %s. It has the following attack roll:" % self.name)
print("%dd%d + %d" % (self.weapon_die_count, self.weapon_die_size, self.weapon_modifier))
def roll_attack_roll(self):
return randint(1,20)
def roll_damage_roll(self):
sum_of_rolls = 0
for x in range(0, self.weapon_die_count):
sum_of_rolls += randint(1, self.weapon_die_size)
return sum_of_rolls + self.weapon_modifier
light_mech_armor = 10
light_mech_health = 30
medium_mech_armor = 15
medium_mech_health = 50
heavy_mech_armor = 17
heavy_mech_health = 70
class Mech():
#TODO: Add weapon
armor = 0
health = 0
weapon = None
def print_mech_stats(self):
print("This mech has %d armor and %d health" % (self.armor, self.health))
self.weapon.print_weapon_stats()
def __init__(self, armor, health, weapon):
self.armor = armor
self.health = health
#TODO: Verify that this is actually an instance of the Weapon class
self.weapon = weapon
def attack(self):
print("The mech shoots its gun! It rolls a %d" % self.weapon.roll_attack_roll())
print("If this hit, it hit for %d damage" % self.weapon.roll_damage_roll())
def get_random_mech():
return get_mech_of_type(randint(1, 3))
def get_mech_of_type(mech_choice_number):
if (int(mech_choice_number) == 1):
weapon = Weapon(light_mech_weapon_name, light_mech_weapon_die_size)
mech = Mech(light_mech_armor, light_mech_health, weapon)
elif (int(mech_choice_number) == 2):
weapon = Weapon(medium_mech_weapon_name, medium_mech_weapon_die_size)
mech = Mech(medium_mech_armor, medium_mech_health, weapon)
elif (int(mech_choice_number) == 3):
weapon = Weapon(heavy_mech_weapon_name, heavy_mech_weapon_die_size)
mech = Mech(heavy_mech_armor, heavy_mech_health, weapon)
else:
weapon = Weapon(light_mech_weapon_name, light_mech_weapon_die_size)
mech = Mech(light_mech_armor, light_mech_health, weapon)
return mech
'''
Ask the player to choose a type of mech.
'''
def let_player_choose_mech():
#Show options
print("Please choose a mech:")
print("1. Light Mech")
print("2. Medium Mech")
print("3. Heavy Mech")
#Get player input
mech_choice_number = input("")
player_mech = get_mech_of_type(mech_choice_number)
return player_mech
'''
Main function.
Call everything else needed here.
'''
def main():
print("Welcome to Jordan's MechBattler v 1.0!")
player_mech = let_player_choose_mech()
print("You got your mech! Here are its stats:")
player_mech.print_mech_stats()
print("You are going to fight the following mechs!")
for x in range(20):
mech = get_random_mech()
mech.print_mech_stats()
#TODO: Attack a specific target, and see it's armor value
mech.attack()
#Start the program here
main()
| [
"noreply@github.com"
] | lamburger3.noreply@github.com |
ccd797d9bd113bf5dbade1cb215f77a6a5b3b320 | 9d40c348e256bd74455521a7a11d8a4ab5d0d9f0 | /setup.py | b88fc0a1a902044454101d52320b623ab903dd99 | [] | no_license | tianon/etest | acf5bd2f06cf9a5024353cfc8128c3e968b889c2 | 01f24e46caaa3c75c48c43e59a8c03da81e06e3b | refs/heads/master | 2021-01-17T20:11:43.244552 | 2015-05-03T15:10:06 | 2015-05-03T15:10:33 | 36,564,139 | 0 | 0 | null | 2015-05-30T15:38:31 | 2015-05-30T15:38:31 | null | UTF-8 | Python | false | false | 2,447 | py | # Copyright (C) 2014 by Alex Brandt <alunduil@alunduil.com>
#
# etest is freely distributable under the terms of an MIT-style license.
# See COPYING or http://www.opensource.org/licenses/mit-license.php.
import os
from setuptools import setup, find_packages
from codecs import open
with open(os.path.join('etest', 'information.py'), 'r', encoding = 'utf-8') as fh:
exec(fh.read(), globals(), locals())
PARAMS = {}
PARAMS['name'] = NAME # flake8: noqa — provided by exec
PARAMS['version'] = VERSION # flake8: noqa — provided by exec
PARAMS['description'] = DESCRIPTION # flake8: noqa — provided by exec
with open('README.rst', 'r', encoding = 'utf-8') as fh:
PARAMS['long_description'] = fh.read()
PARAMS['url'] = URL # flake8: noqa — provided by exec
PARAMS['author'] = AUTHOR # flake8: noqa — provided by exec
PARAMS['author_email'] = AUTHOR_EMAIL # flake8: noqa — provided by exec
PARAMS['license'] = LICENSE # flake8: noqa — provided by exec
PARAMS['classifiers'] = [
'Development Status :: 3 - Alpha',
# 'Development Status :: 4 - Beta',
# 'Development Status :: 5 - Production/Stable',
# 'Development Status :: 6 - Mature',
# 'Development Status :: 7 - Inactive',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Software Development :: Quality Assurance',
'Topic :: Software Development :: Testing',
'Topic :: Utilities',
]
PARAMS['keywords'] = [
'ebuild',
'test',
'gentoo',
'portage',
'emerge',
]
PARAMS['packages'] = find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"])
PARAMS['package_data'] = {
'etest.parsers': [ 'bash.p' ],
}
PARAMS['install_requires'] = [
'click',
'docker-py',
'ply',
]
PARAMS['test_suite'] = 'nose.collector'
PARAMS['tests_require'] = [
'coverage'
'nose',
]
PARAMS['entry_points'] = {
'console_scripts': [
'etest = etest:etest',
],
}
PARAMS['data_files'] = [
('share/doc/{P[name]}-{P[version]}'.format(P = PARAMS), [
'README.rst',
]),
]
setup(**PARAMS)
| [
"alunduil@alunduil.com"
] | alunduil@alunduil.com |
99912037e790d4ea54aa44f4bede351f712fa169 | d77010e793beb5c1c94c3054a31778d681cc0b37 | /Chap02/conditionals.py | ceabdeb923d10ea936d249dd42c06660d8932058 | [] | no_license | bking2415/python_essentials | 43c3b72f43e6a936c65625c4f35ca32b6446f20a | be34cdba08d6e8dbaf40b1352cef2fc2d109d7b1 | refs/heads/master | 2023-08-26T03:40:35.001337 | 2021-11-10T20:41:06 | 2021-11-10T20:41:06 | 426,770,155 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 312 | py | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
x = 42
y = 42
if x < y:
print('x < y: x is {} and y is {}'.format(x, y))
elif x > y:
print('x > y: x is {} and y is {}'.format(x, y))
elif x == y:
print('x = y: x is {} and y is {}'.format(x, y))
else:
print('do something else')
| [
"55815159+bking2415@users.noreply.github.com"
] | 55815159+bking2415@users.noreply.github.com |
9cfb14731bafed959b3adcbc779a95132884c385 | a1dd6f2e13506b54120532c2ed093dc270eff4ac | /GridServices/TransactiveControl/TNT_Version1/TNSAgent/tns/weather_data/convert.py | 6087a831458ccf32451239b590b0e4c1c0b9be4b | [
"BSD-3-Clause"
] | permissive | shwethanidd/volttron-pnnl-applications-2 | ec8cc01c1ffeff884c091617892fea6e84a3e46e | 24d50729aef8d91036cc13b0f5c03be76f3237ed | refs/heads/main | 2023-06-18T12:13:13.607951 | 2021-06-30T23:00:01 | 2021-06-30T23:00:01 | 359,586,385 | 0 | 0 | BSD-3-Clause | 2021-04-19T20:15:45 | 2021-04-19T20:15:45 | null | UTF-8 | Python | false | false | 3,079 | py | """
Copyright (c) 2020, Battelle Memorial Institute
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. 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.
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.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
This material was prepared as an account of work sponsored by an agency of the
United States Government. Neither the United States Government nor the United
States Department of Energy, nor Battelle, nor any of their employees, nor any
jurisdiction or organization that has cooperated in th.e development of these
materials, makes any warranty, express or implied, or assumes any legal
liability or responsibility for the accuracy, completeness, or usefulness or
any information, apparatus, product, software, or process disclosed, or
represents that its use would not infringe privately owned rights.
Reference herein to any specific commercial product, process, or service by
trade name, trademark, manufacturer, or otherwise does not necessarily
constitute or imply its endorsement, recommendation, or favoring by the
United States Government or any agency thereof, or Battelle Memorial Institute.
The views and opinions of authors expressed herein do not necessarily state or
reflect those of the United States Government or any agency thereof.
PACIFIC NORTHWEST NATIONAL LABORATORY
operated by BATTELLE for the UNITED STATES DEPARTMENT OF ENERGY
under Contract DE-AC05-76RL01830
"""
import pandas as pd
import time
import datetime
tab=pd.read_csv('energyplus.csv')
for i in range(len(tab)):
s=time.mktime(datetime.datetime.strptime(tab['Timestamp'].iloc[i], "%m/%d/%Y %H:%M").timetuple())
tab['Timestamp'].iloc[i]=datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S')
tab.to_csv('prediction_from_simulation.csv',index=False) | [
"shwetha.niddodi@pnnl.gov"
] | shwetha.niddodi@pnnl.gov |
34bc72de52b4e7784e26508dc3fffd91fd652274 | 17d1c1b6807bcc54d05f8dc6ce41fa1bec259093 | /sample/c++/nbody+sph/scripts/visualize.py | 86d53111d6a0a8d6c5c88fe6e637f13a84a6f699 | [
"MIT"
] | permissive | wenyan4work/FDPS | 0334e67330c248aad8757192d0ce2e9a11d30b12 | 2ab4f26e188b2c21b84353c187bf5b39758ebf1a | refs/heads/master | 2021-04-15T16:42:21.741985 | 2021-03-19T14:32:06 | 2021-03-19T14:32:06 | 95,709,114 | 0 | 0 | MIT | 2021-03-19T14:32:20 | 2017-06-28T20:31:31 | C++ | UTF-8 | Python | false | false | 4,520 | py | #!/usr/bin/env /opt/local/bin/python3.6
# -*- coding: utf-8 -*-
#=================================
# Module import
#=================================
try:
import os
import sys
import glob
import struct
import math
import re
import subprocess
except ImportError:
print("Module os,sys,glob,struct,math,re,subprocess are not found.")
quit()
try:
import matplotlib.pyplot as plt
import matplotlib.cm as cm
except ImportError:
print("Module matplotlib.pyplot,cm are not found.")
quit()
try:
import numpy as np
except ImportError:
print("Module numpy is not found.")
quit()
#================================
# Class definition
#================================
class Plotter:
def __init__(self,xmin,xmax,ymin,ymax):
self.xmin = xmin
self.xmax = xmax
self.ymin = ymin
self.ymax = ymax
self.x = []
self.y = []
self.z = []
def read_file(self,filename,skip_freq):
# Read a file
print("reading {0} (skip_freq = {1})".format(filename,skip_freq))
fp = open(filename,"r")
data_num = 0
for line in fp:
items = line.split()
try:
x = float(items[0])
y = float(items[1])
z = float(items[2])
if skip_freq == 0:
self.x.append(x)
self.y.append(y)
self.z.append(z)
else:
data_num += 1
if (data_num == skip_freq):
self.x.append(x)
self.y.append(y)
self.z.append(z)
data_num = 0
except:
print("cannot convert to FP values!")
sys.exit()
fp.close()
print("{} doubles are read.".format(len(self.x)+len(self.y)+len(self.z)))
# Convert to numpy-format
self.x = np.array(self.x)
self.y = np.array(self.y)
self.z = np.array(self.z)
print("converted to numpy-format.")
def make_fig(self,basename,dpi,save_fmt='ps',make_xbb='no'):
# Set file names
ps_file = basename + '.ps'
eps_file = basename + '.eps'
pdf_file = basename + '.pdf'
png_file = basename + '.png'
# Make a figure
font = {'family' : 'Verdana',
'weight' : 'normal',
'size' : '14'}
plt.rc('font',**font)
plt.rc('text',usetex=True)
#fig = plt.figure(1,figsize=(10,10))
#ax = fig.add_subplot(111)
#ax.set_aspect('equal')
fig, ax = plt.subplots()
ax.set_aspect('equal')
# Plot column density of the reference models
ax.set_xlabel(r'$x$',fontsize=20)
ax.set_ylabel(r'$y$',fontsize=20)
ax.tick_params(axis='x',labelsize=24)
ax.tick_params(axis='y',labelsize=24)
ax.set_xlim(self.xmin,self.xmax)
ax.set_ylim(self.ymin,self.ymax)
x_vals = np.resize(self.x,(np.size(self.x),1))
y_vals = np.resize(self.y,(np.size(self.y),1))
ax.scatter(x_vals, y_vals, s=0.16, c='k',edgecolors='none')
# Display figure
fig.tight_layout()
# Save figure
if (save_fmt == 'ps'):
fig.savefig(ps_file)
# Make eps,pdf,bb files
cmd = 'ps2eps -B -l -g -a -f ' + ps_file
subprocess.call(cmd,shell=True)
cmd = 'eps2pdf -B -H -f ' + eps_file
subprocess.call(cmd,shell=True)
if (make_xbb == 'yes'):
cmd = 'extractbb ' + pdf_file
subprocess.call(cmd,shell=True)
elif save_fmt == 'png':
fig.savefig(png_file,dpi=dpi)
if (make_xbb == 'yes'):
cmd = 'extractbb ' + png_file
subprocess.call(cmd,shell=True)
# Close figure
plt.close()
#================================
# Main function
#================================
# Parameter settings
skip_freq = 0
dpi = 800
# Make figures of stellar distributions
#files = glob.glob("pos_star*txt")
files = glob.glob("pos_sph*txt")
for f in files:
basename = os.path.splitext(os.path.basename(f))[0]
xmin = - 0.1
xmax = 0.1
ymin = - 0.1
ymax = 0.1
P = Plotter(xmin,xmax,ymin,ymax)
P.read_file(f,skip_freq)
P.make_fig(basename, dpi, save_fmt='png')
| [
"fdps_official@mail.jmlab.jp"
] | fdps_official@mail.jmlab.jp |
c2ad3692cab8bf34b0d47a5719a9ca1466a2743a | e4907ad49d2ff235b95e54dec152bf4c5441c96a | /generate_data.py | 372b343e67de6584c4e7fc869caa1e007a19a4dd | [] | no_license | asolergayoso/gradfinal | bcc7bfabfb2d1304b6c3ace30b92b07109494f06 | 7389e69a5fe3c9a852d6ed570b58e780883741fe | refs/heads/master | 2020-05-01T20:02:57.428309 | 2019-04-30T17:31:36 | 2019-04-30T17:31:36 | 177,663,300 | 0 | 0 | null | 2019-03-25T20:58:15 | 2019-03-25T20:58:15 | null | UTF-8 | Python | false | false | 1,648 | py | import json
import random
# generates a csv file of num many ip addresses
def generate_ips(number, links):
data = {}
ip_prefix = '172.52.56.'
# dictionary where key is id and val is ip address and val is list of neighbour ip_addresses
ip_dict = {}
# dictionary where key is source id and val is target id
link_list = []
reverse_link_list = []
# Generate Nodes
for num in range(number):
ip_postfix = str(random.randint(0, 255))
# make sure not generate the same ip address more than once
while ip_prefix + ip_postfix in ip_dict:
ip_postfix = str(random.randint(0, 255))
ip_address = ip_prefix + ip_postfix
ip_dict[num] = ip_address
# Generate links
keys = list(ip_dict.keys())
for num in range(links):
source = keys[random.randint(0, len(keys) - 1)]
target = keys[random.randint(0, len(keys) - 1)]
while (source, target) in link_list or (target, source) in reverse_link_list or source == target:
source = keys[random.randint(0, len(keys) - 1)]
target = keys[random.randint(0, len(keys) - 1)]
link_list.append((source, target))
reverse_link_list.append((target, source))
data['links'] = []
data['nodes'] = []
for node in ip_dict:
data['nodes'].append({
'id': node,
'name': ip_dict[node]
})
for tup in link_list:
data['links'].append({
'source': tup[0],
'target': tup[1]
})
with open('ips.json', 'w') as outfile:
json.dump(data, outfile)
generate_ips(50, 200)
| [
"abualhaija.rushdi@gmail.com"
] | abualhaija.rushdi@gmail.com |
b89d0550b5a4cfea40057d068d0aa6e49db7ce87 | 60082162890dd566189117d088df9fa78b1e9a57 | /obj_ser.py | c494a2022b8513bb68a7591170da1800d81b2e82 | [] | no_license | vinita04/cloud_staas | d5e6bae501f3e558c4a93b74e4d0497d4f0554b5 | d9f73afcb52bb2b57624bb2aa8b798165456f540 | refs/heads/master | 2021-04-15T08:06:58.151184 | 2017-06-30T19:13:36 | 2017-06-30T19:13:36 | 94,566,789 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,263 | py | #!/usr/bin/python2
import os,commands,socket,time
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind(("",8888))
#data will recv drive name
data=s.recvfrom(20)
d_name=data[0]
#data1 will recv drive size
data1=s.recvfrom(20)
d_size=data1[0]
#cliaddr will store address of client
cliaddr=data[1][0]
print d_size
print d_name
#creating lvm by the name of client drive
os.system('lvcreate -V'+d_size+' --name '+d_name+' --thin hoja/vini')
#now format the file with ext4/xfs
os.system('mkfs.ext4 /dev/hoja/'+d_name)
#now create mounting point
os.system('mkdir /mnt/'+d_name)
# now mounting drive locally
os.system('mount /dev/hoja/'+d_name+' /mnt/'+d_name)
# now time for nfs server configuration
x=os.system('rpm -q nfs-utils')
if x==0:
print "already installed"
else:
os.system('yum install nfs-utils -y')
# making entry in exports file
entry='/mnt/'+d_name+' '+cliaddr+'(rw,no_root_squash)'
#appending this var to exports file
f=open('/etc/exports','a')
f.write(entry)
f.write('\n')
f.close()
# finally starting nfs service and service persistant
#os.system('systemctl restart nfs-server')
#os.system('systemctl enable nfs-server')
check=os.system('exportfs -r')
if check==0 :
s.sendto("done",data1[1])
else :
print "plz check ur code"
| [
"noreply@github.com"
] | vinita04.noreply@github.com |
4ad6108d4c20bb1b3e070224a659014f71a7d17e | ec1bfb05452fe9f97837954a1c80f7a98e50b4ce | /django_project/django_project/settings/production.py | 2b176735b6afc96c6f70ff7603c624f32e0fa1dc | [] | no_license | RJC0514/RecipeHub | e1c905330e9ff6cea2a989507d776f4fbd30244f | 396e3c16b18cd6c01065e9f7212aa3b458cea64e | refs/heads/master | 2023-08-28T02:14:31.876107 | 2021-10-24T10:23:40 | 2021-10-24T10:23:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 945 | py | """
The production settings file is meant to be used in production. Some settings,
like SECRET_KEY and the database password, are not included for security
reasons. To specify them, see local_example.py for instructions.
Checklist: https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
"""
from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['hackgt.rostersniper.com']
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
# Redirect all non-HTTPS requests to HTTPS
SECURE_SSL_REDIRECT = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https')
# Database https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'hackgt',
'USER': 'hackgt',
'PASSWORD': '## this should be overridden in local.py ##',
'HOST': 'localhost',
'PORT': '5432'
}
}
| [
"rjc0514@gmail.com"
] | rjc0514@gmail.com |
bc7683437144cd95677b14cc04c720e44e358938 | 86f2cc22f9c0d975ea5936dabe33e52be41eeedc | /2019 Pipeline - mp/visionprocesses.py | a930295da1a55b483c5e1675848d1d685cfb8f0c | [
"MIT"
] | permissive | uutzinger/BucketVision | b6492e04b45bfc08c24036800b9ff262cfc1e17a | 3f12431173b0ac280e0c39839dce3de401d16e99 | refs/heads/master | 2022-03-31T02:26:17.919537 | 2020-01-23T02:35:40 | 2020-01-23T02:35:40 | 178,728,334 | 1 | 0 | NOASSERTION | 2019-03-31T18:46:36 | 2019-03-31T18:46:35 | null | UTF-8 | Python | false | false | 5,724 | py | ###############################################################################
# Imports
###############################################################################
# Execution
from threading import Thread
import time
import logging
# Vision
import cv2
# FIRST
import networktables
# 4183
from processimage import ProcessImage
from configs import configs
###############################################################################
# Vision Processing
###############################################################################
class VissionProcesses(Thread):
def __init__(self, source=None, network_table=None):
self.logger = logging.getLogger("VisionProcesses")
self.net_table = network_table
self.source = source
self._frame = None
self._new_frame = False
self.new_frame = False
self.last_frame_time = 0.0
if self.net_table is not None: self.net_table.putNumber("LastFrameTime", self.last_frame_time)
self.processor = ProcessImage()
self.results = list()
self.stopped = True
Thread.__init__(self)
###############################################################################
# Setting
# frame
###############################################################################
@property
def frame(self):
self.new_frame = False
return self._frame
@frame.setter
def frame(self, img):
self._frame = img
self._new_frame = True
###############################################################################
# Support
###############################################################################
@staticmethod
def dict_zip(*dicts):
all_keys = {k for d in dicts for k in d.keys()}
return {k: [d[k] for d in dicts if k in d] for k in all_keys}
def update_results(self):
if self.net_table is not None:
self.net_table.putNumber("LastFrameTime", self.last_frame_time)
self.net_table.putNumber("CurrFrameTime", time.time())
result_data = self.dict_zip(*[r.dict() for r in self.results])
self.net_table.putNumber("NumTargets", len(self.results))
for key, value in result_data.items():
# Here we assume that every param is a number of some kind
self.net_table.putNumberArray(key, value)
def draw_trgt(self):
if self.source is None:
return self.processor.drawtargets(self.frame, self.results)
else:
return self.processor.drawtargets(self.source.frame, self.results)
###############################################################################
# Thread Establishing and Running
###############################################################################
def stop(self):
self.stopped = True
def start(self):
self.stopped = False
if self.net_table is not None:
self.net_table.putBoolean('Overlay', False)
Thread.start(self)
def run(self):
targetting_time_hist = list() # time find target consumes
start_time = time.time() #
num_frames = 0
while not self.stopped:
if self.source is not None:
if self.source.new_frame:
self._new_frame = True
if self._new_frame:
if time.time() - start_time >= 5.0:
print("Targets processed:{}/s".format(num_frames/5.0))
num_frames = 0
start_time = time.time()
self.last_frame_time = time.time()
targetting_start_time = time.time()
if self.source is not None:
frame = self.source.frame
else:
frame = self.frame
self.results = self.processor.FindTarget(frame)
targetting_time_hist.append((time.time() - targetting_start_time))
if len(targetting_time_hist) >= 50:
print("Target detected in:{:.3f} ms".format(sum(targetting_time_hist)/50.0))
targetting_time_hist = list()
if self.net_table is not None:
pass
# self.frame = self.draw_trgt()
# if self.net_table.getBoolean('Overlay', False):
# self.frame = self.draw_trgt()
# elif self.source is None:
# pass
# else:
# self.frame = self.source.frame
elif self.source is not None:
self.frame = self.source.frame
else:
self.new_frame = True
self.update_results()
self._new_frame = False
num_frames = num_frames + 1
#print("\nAP: {} done at {}".format(self.debug_label, time.time()))
###############################################################################
# Testing
###############################################################################
if __name__ == '__main__':
from cv2capture import Cv2Capture
from cv2display import Cv2Display
logging.basicConfig(level=logging.DEBUG)
print("Start Cam")
cam = Cv2Capture(camera_num=0, exposure=-2)
cam.start()
print("Start Proc")
proc = VisionProcesses(cam)
proc.start()
print("Start Display")
sink = Cv2Display(source=proc)
sink.start()
print("Started Everything!")
try:
while True:
pass
except KeyboardInterrupt:
sink.stop()
proc.stop()
cam.stop()
| [
"utzinger@email.arizona.edu"
] | utzinger@email.arizona.edu |
01674507fffa16b6688aa4a838c4a947fa59c70f | 48c86fad0c1e5e5a70cbf8b191436be56d9d53a3 | /nlptools/torch.py | 4fb3ad4c180f6611772b1ca1895ed1576571910b | [] | no_license | outenki/nlptools | e754ca57c2d1c7b2bdd4a2359fa83b053da1e550 | 5ea5dcb6f82da400611b209c2bf629ed8daa503d | refs/heads/master | 2021-06-25T20:22:09.297395 | 2021-04-22T07:22:52 | 2021-04-22T07:22:52 | 223,892,727 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,911 | py | import torch
from torch import optim, nn
from torch.utils.data import DataLoader
from . import data as D
import numpy as np
import tqdm
def get_optimizer(net, algorithm, lr=0.001):
if algorithm == 'rmsprop':
optimizer = optim.RMSprop(net.parameters(), lr=lr)
elif algorithm == 'sgd':
optimizer = optim.SGD(net.parameters(), lr=lr)
elif algorithm == 'adagrad':
optimizer = optim.Adagrad(net.parameters(), lr=lr)
elif algorithm == 'adadelta':
optimizer = optim.Adadelta(net.parameters(), lr=lr)
elif algorithm == 'adam':
optimizer = optim.Adam(net.parameters(), lr=lr)
elif algorithm == 'adamax':
optimizer = optim.Adamax(net.parameters())
return optimizer
def run_deprecated(
model: nn.Module,
data: DataLoader,
optimizer: optim.Optimizer,
criterion: nn.Module,
mode: str,
scheduler,
device,
score_range=None
):
if mode == 'train':
model.train()
elif mode == 'eval':
model.eval()
epoch_loss = 0
data_len = 0
preds = list()
targets = list()
feas = list()
for x, mask, y in tqdm.tqdm(data, ncols=100):
data_len += len(x)
x = x.to(device)
mask = mask.to(device)
y = y.to(device)
optimizer.zero_grad()
res = model(x, mask)
pred = res['pred'].view(-1)
fea = res['fea']
preds.append(pred)
feas.append(fea)
targets.append(y)
loss = criterion(pred, y)
epoch_loss += len(x) * loss.item()
if mode == 'train':
loss.backward()
optimizer.step()
if scheduler:
scheduler.step()
# compute loss and qwk
preds = torch.cat(preds).detach().cpu().numpy()
targets = torch.cat(targets).cpu().numpy()
feas = torch.cat(feas).detach().cpu().numpy()
if score_range:
scores = D.recover_scores(preds, score_range)
targets = D.recover_scores(targets, score_range)
qwk = D.qwk(scores, targets)
loss = epoch_loss/data_len
return {
'qwk': qwk, 'loss': loss, 'pred': preds, 'y': targets, 'fea': feas
}
def run(
model: nn.Module,
data: DataLoader,
optimizer: optim.Optimizer,
criterion: nn.Module,
mode: str,
scheduler,
device,
score_range=None,
att_loss=False,
):
'''
Run training/test step for one epoch.
Note: the length of <data> is not fixed.
The last element of <data> will be used as target of prediction,
while the others will be passed to the model as position arguments
'''
if mode == 'train':
model.train()
elif mode == 'eval':
model.eval()
epoch_loss = 0
data_size = 0
preds = list()
# feas = list()
pred_att = list()
normalized_targets = list()
keys_indices = list()
keys_weights = list()
for dt in tqdm.tqdm(data, ncols=100):
batch_size = len(dt[0])
data_size += batch_size
dt = [d.to(device) for d in dt]
in_data = dt[:-1]
y = dt[-1]
optimizer.zero_grad()
res = model(*in_data)
# pred = res['pred'].view(-1)
if 'keys_indices' in res:
keys_indices.append(res['keys_indices'])
keys_weights.append(res['keys_weights'])
if 'pred' in res:
pred = res['pred'].view(-1)
else:
pred = res['output'].view(-1)
preds.append(pred)
# feas.append(res['fea'])
if res['att'] is not None:
if type(res['att']) == np.ndarray:
pred_att += list(res['att'])
else:
pred_att += list(res['att'].detach().cpu().numpy())
normalized_targets.append(y)
loss = criterion(pred, y)
if att_loss:
p_att = res['att']
g_att = dt[-2].narrow(-1, 0, p_att.shape[1])
loss += criterion(p_att, g_att)
epoch_loss += batch_size * loss.item()
if mode == 'train':
loss.backward()
optimizer.step()
if scheduler:
scheduler.step()
# compute loss and qwk
normalized_preds = torch.cat(preds).detach().cpu().numpy()
preds = normalized_preds
normalized_targets = torch.cat(normalized_targets).cpu().numpy()
targets = normalized_targets
if score_range is not None:
preds = D.recover_scores(normalized_preds, score_range)
targets = D.recover_scores(normalized_targets, score_range)
qwk = D.qwk(preds, targets)
else:
qwk = -1
loss = epoch_loss/data_size
if keys_indices:
# keys_indices:
# [[index_sub1_batch1, index_sub2_batch1],
# [index_sub1_batch2, index_sub2_batch2],
# ...,
# [index_sub1_batchn, index_sub2_batchn]]
# index_subi_batchj: sahpe(batch_size, )
# [[index_sub1_batch1, index_sub1_batch2, ...],
# [index_sub2_batch1, index_sub2_batch2, ...]]
keys_indices = zip(*keys_indices)
# [index_sub1, index_sub2, ...]
keys_indices = [
torch.cat(ki).detach().cpu().numpy() for ki in keys_indices
]
# [(ind1_1, ind2_1), (ind1_2, ind2_2), ..., (ind1_n, ind2_n)]
keys_indices = list(zip(*keys_indices))
keys_weights = zip(*keys_weights)
keys_weights = [
torch.cat(kw).detach().cpu().numpy() for kw in keys_weights
]
keys_weights = list(zip(*keys_weights))
return {
'qwk': qwk, 'loss': loss,
'fea': np.zeros([1, 1]),
'att': pred_att,
'pred': preds,
'normalized_pred': normalized_preds,
'target': targets,
'normalized_target': normalized_targets,
'keys_indices': keys_indices,
'keys_weights': keys_weights
}
| [
"outenki@gmail.com"
] | outenki@gmail.com |
eff20c5832be3938b102557621c2215e2c8e4c53 | 95c612f27c9394da14e510ec70161ae4ed7ff700 | /Corner Detection/Corner Detection.py | 65d0fe360e1ccb48a9f7fb5bfe1da1de712ee77b | [] | no_license | deyh2020/OpenCV-Projects | f1098c87a937699d4bf8261fa1ac46fe660d79e8 | 7dffdc93490b603cdea93b5d217ee95d6a2eabf5 | refs/heads/master | 2023-04-30T16:10:35.251259 | 2021-05-21T18:36:03 | 2021-05-21T18:36:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 437 | py | import cv2
import numpy as np
img = cv2.imread(r"C:\Users\Lenovo\Desktop\New folder\python\openCV\Corner Detection\squares.png")
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
corners = cv2.goodFeaturesToTrack(img_gray, 5, 0.8, 50)
corners = np.int0(corners)
for corner in corners:
x,y = corner.ravel()
cv2.circle(img, (x,y), 5, (0, 0, 255), -1)
cv2.imshow("Image",img)
cv2.waitKey(0)
cv2.destroyAllWindows() | [
"noreply@github.com"
] | deyh2020.noreply@github.com |
4343539467e21b89b01f8a777be58229f4a81646 | 42074fe083d65c0647d85018fae581d4445b85a3 | /task1/task1PythonTools/py27_ldaTopicModeling.py | e5072a203beb426fc7ac5b9bdea39409751c7e61 | [] | no_license | jonchang03/cs598-dm-capstone | 16f4a260a3eb2403649e4adb8796c206454b8720 | 0685128a2db85ec72bea26cac0647a3dd6a3e526 | refs/heads/master | 2020-12-14T17:12:02.743410 | 2020-04-14T21:07:34 | 2020-04-14T21:07:34 | 234,819,774 | 4 | 3 | null | null | null | null | UTF-8 | Python | false | false | 3,585 | py | import logging
import glob
import argparse
from gensim import models
from gensim import matutils
from sklearn.feature_extraction.text import TfidfVectorizer
from time import time
from nltk.tokenize import sent_tokenize
def main(K, numfeatures, sample_file, num_display_words, outputfile):
K_clusters = K
vectorizer = TfidfVectorizer(max_df=0.5, max_features=numfeatures,
min_df=2, stop_words='english',
use_idf=True)
text = []
with open (sample_file, 'r') as f:
text = f.readlines()
t0 = time()
print("Extracting features from the training dataset using a sparse vectorizer")
X = vectorizer.fit_transform(text)
print("done in %fs" % (time() - t0))
print("n_samples: %d, n_features: %d" % X.shape)
# mapping from feature id to acutal word
id2words ={}
for i,word in enumerate(vectorizer.get_feature_names()):
id2words[i] = word
t0 = time()
print("Applying topic modeling, using LDA")
print(str(K_clusters) + " topics")
corpus = matutils.Sparse2Corpus(X, documents_columns=False)
lda = models.ldamodel.LdaModel(corpus, num_topics=K_clusters, id2word=id2words)
print("done in %fs" % (time() - t0))
output_text = []
for i, item in enumerate(lda.show_topics(num_topics=K_clusters, num_words=num_display_words, formatted=False)):
output_text.append("Topic: " + str(i))
for weight,term in item:
output_text.append( term + " : " + str(weight) )
print "writing topics to file:", outputfile
with open ( outputfile, 'w' ) as f:
f.write('\n'.join(output_text))
if __name__=="__main__":
parser = argparse.ArgumentParser(description='This program takes in a file and some parameters and generates topic modeling from the file. This program assumes the file is a line corpus, e.g. list or reviews and outputs the topic with words and weights on the console.')
parser.add_argument('-f', dest='path2datafile', default="review_sample_100000.txt",
help='Specifies the file which is used by to extract the topics. The default file is "review_sample_100000.txt"')
parser.add_argument('-o', dest='outputfile', default="sample_topics.txt",
help='Specifies the output file for the topics, The format is as a topic number followed by a list of words with corresdponding weights of the words. The default output file is "sample_topics.txt"')
parser.add_argument('-K', default=100, type=int,
help='K is the number of topics to use when running the LDA algorithm. Default 100.')
parser.add_argument('-featureNum', default=50000, type=int,
help='feature is the number of features to keep when mapping the bag-of-words to tf-idf vectors, (eg. lenght of vectors). Default featureNum=50000')
parser.add_argument('-displayWN', default=15,type=int,
help='This option specifies how many words to display for each topic. Default is 15 words for each topic.')
parser.add_argument('--logging', action='store_true',
help='This option allows for logging of progress.')
args = parser.parse_args()
#print args
if args.logging:
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
print "using input file:", args.path2datafile
main(args.K, args.featureNum, args.path2datafile, args.displayWN, args.outputfile)
| [
"jonchang03@gmail.com"
] | jonchang03@gmail.com |
94aa5774fd44aa26c53b985ec998453dc38c9f4e | 5b714e8ead9c14ce4c64e847df4022e94943412b | /myo_neural_framework.py | 7e138b1eaf856630ed3d20439382addea996e67f | [
"MIT"
] | permissive | JanIIISobieski/myoelectric-control | 69b91fe13376c2a141fd5b79ba2e8bd5f4902916 | 5bec0e39a79d37c7c34633884e13d9072b02d6a9 | refs/heads/master | 2020-05-04T06:53:29.226219 | 2019-04-11T22:09:57 | 2019-04-11T22:09:57 | 179,016,189 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 578 | py | '''
Code to run the Duke eNable myoelectric arm. Bluetooth communication with
the myoband is based on the work by dzhu and Fernando Cosentino.
The main edits were to add the custom predictor for the predictions.
'''
from __future__ import print_function
from myo_raw import MyoRaw
if __name__ == '__main__':
myoband = MyoRaw(None, 25)
myoband.connect()
try:
while True:
myoband.run(1)
except KeyboardInterrupt:
pass
finally:
myoband.arduino.port.close()
myoband.disconnect()
print("Done")
| [
"gjantoniak@gmail.com"
] | gjantoniak@gmail.com |
fa4cebfa7b4bc5cdbdec9681aa4f1c99c70b9465 | ee4985cfa4908e7abcc214dfecb3cdb2ab11ac8c | /py-readability-metrics/setup.py | 5f77c2378bd557cf82def5728de2f09f66808f70 | [
"MIT"
] | permissive | dimi1357/Loora-cond-bot | 7c961ee6baa38f11a30cd13a08f2867244e4d73b | bf2deca681f867f4d789a6670d65cfb4f5986966 | refs/heads/main | 2023-08-16T03:34:10.020586 | 2021-09-25T20:26:32 | 2021-09-25T20:26:32 | 405,074,950 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,071 | py | #!/user/bin/env python
from setuptools import setup, find_packages
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='py-readability-metrics',
version='1.4.4',
author='Carmine DiMAscio',
author_email='cdimascio@gmail.com',
description='Score text "Readability" with popular formulas and metrics including Flesch-Kincaid, Gunning Fog, ARI, Dale Chall, SMOG, Spache and more',
long_description=long_description,
long_description_content_type="text/markdown",
url='https://github.com/cdimascio/py-readability-metrics',
keywords="readability metrics text difficulty grade level",
packages=find_packages(exclude=['tests']),
package_data={'readability': ['data', 'data/dale_chall_porterstem.txt', 'data/spache_easy_porterstem.txt']},
include_package_data=True,
license='MIT',
install_requires=[
'nltk'
],
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
)
| [
"dimi1357@gmail.com"
] | dimi1357@gmail.com |
aabcd6ef80144bb748e6a268e109ce3c01316111 | 7b97c42cde9ca4fd0b6dca817811d91105142859 | /utilities.py | db1c390bfed65a0f9331f164b0a042ba05607eed | [] | no_license | theodortruffer/certt | 9d930759b62adcdb54abb47e4e0999672c20b294 | c548e99c9ecd5ebea61e59f556de9b1c67d9e3fe | refs/heads/master | 2023-08-30T03:42:37.029107 | 2021-10-28T11:37:16 | 2021-10-28T11:37:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,349 | py | import base64
import cose.algorithms
import cryptography.x509 as x509
import json
import jwt
import math
import requests
from bcolors import bcolors
from cose.headers import KID
from cose.keys import cosekey, keyparam, keyops, keytype
from cose.messages.cosemessage import CM
from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15
from cryptography.x509 import Certificate
from cwt.cose_key_interface import COSEKeyInterface
from datetime import datetime, timedelta
from io import TextIOWrapper
from typing import Dict, Union, List
KEY_FILE = "./data/trusted_keys.json"
ROOT_CERT_URL = "https://www.bit.admin.ch/dam/bit/en/dokumente/pki/scanning_center/swiss_governmentrootcaii.crt.download.crt/swiss_governmentrootcaii.crt"
ACTIVE_KEYS_URL = "https://www.cc.bit.admin.ch/trust/v1/keys/list"
KEY_LIST_URL = "https://www.cc.bit.admin.ch/trust/v1/keys/updates?certFormat=ANDROID"
ECDSA_ALGORITHMS = [
cose.algorithms.Es256,
cose.algorithms.Es384,
cose.algorithms.Es512
]
RSASSA_PSS_ALGORITHMS = [
cose.algorithms.Ps256,
cose.algorithms.Ps384,
cose.algorithms.Ps512
]
TEST_RESULT_MAPPING = {
'260415000': f'{bcolors.OKGREEN}Not Detected{bcolors.ENDC}',
'260373001': f'{bcolors.WARNING}Detected{bcolors.ENDC}'
}
headers = {
'Accept': 'application/json+jws',
'Accept-Encoding': 'gzip',
'Authorization': 'Bearer 0795dc8b-d8d0-4313-abf2-510b12d50939',
'User-Agent': 'ch.admin.bag.covidcertificate.wallet;2.1.1;1626211804080;Android;28'
}
def __num2b64(n: int) -> str:
size = math.ceil(math.ceil(math.log(n, 2)) / 8)
return base64.b64encode(n.to_bytes(size, 'big')).decode()
def __verify_jwt(token: str, root_cert: Certificate) -> None:
header = jwt.get_unverified_header(token)
certs = [base64.b64decode(k) for k in header['x5c']]
cert_chain = [x509.load_der_x509_certificate(der) for der in certs]
cert_chain.append(root_cert)
padding = PKCS1v15()
for i in range(len(cert_chain) - 1):
signed, issuer = cert_chain[i:i + 2]
issuer.public_key().verify(signed.signature,
signed.tbs_certificate_bytes,
padding,
signed.signature_hash_algorithm)
def __load_trusted_keys() -> None:
print("downloading trusted keys..")
root_cert = x509.load_pem_x509_certificate(requests.get(ROOT_CERT_URL).text.encode())
# fetch jwts
active_keys_jwt = requests.get(ACTIVE_KEYS_URL, headers=headers).text
key_list_jwt = requests.get(KEY_LIST_URL, headers=headers).text
# verify signatures
__verify_jwt(active_keys_jwt, root_cert)
__verify_jwt(key_list_jwt, root_cert)
# decode
active_keys = jwt.decode(active_keys_jwt, options={"verify_signature": False})['activeKeyIds']
key_list = jwt.decode(key_list_jwt, options={"verify_signature": False})['certs']
keys = {}
for key_data in key_list:
# filter out inactive keys
if key_data['keyId'] in active_keys:
key_id = key_data.pop('keyId')
keys[key_id] = key_data
with open(KEY_FILE, 'w') as key_file:
json.dump(keys, key_file, indent=2)
def get_trusted_keys(skip_download: bool = False) -> Dict[str, dict]:
if not skip_download:
try:
__load_trusted_keys()
except BaseException as e:
print(f"ERROR: trusted keys could not be downloaded: {bcolors.FAIL}{e=} {type(e)=} {bcolors.ENDC}")
use_file = input(f"{bcolors.UNDERLINE}Use trusted keys from local file?{bcolors.ENDC} (y/N)")
if use_file.lower() != 'y':
exit(1)
with open(KEY_FILE, 'r') as key_file:
return json.load(key_file)
def get_kid(cose_msg: CM) -> Union[bytes, None]:
kid = cose_msg.phdr.get(KID)
if not kid:
kid = cose_msg.uhdr.get(KID)
print("kid found in unprotected header")
if not kid:
print("no kid found")
else:
print("kid found in protected header")
return kid
def build_cose_key(algorithm: cose.headers.Algorithm, kid: bytes, data: dict) -> cosekey:
if algorithm in ECDSA_ALGORITHMS:
print("using primary algorithm..")
return cosekey.CoseKey.from_dict({
keyparam.KpKeyOps: [keyops.VerifyOp],
keyparam.KpKty: keytype.KtyEC2,
keyparam.EC2KpCurve: data['crv'],
keyparam.KpAlg: algorithm,
keyparam.EC2KpX: base64.b64decode(data['x']),
keyparam.EC2KpY: base64.b64decode(data['y']),
keyparam.KpKid: kid
})
elif algorithm in RSASSA_PSS_ALGORITHMS:
print("using secondary algorithm..")
return cosekey.CoseKey.from_dict({
keyparam.KpKeyOps: [keyops.VerifyOp],
keyparam.KpKty: keytype.KtyRSA,
keyparam.KpAlg: algorithm,
keyparam.RSAKpN: base64.b64decode(data['n']),
keyparam.RSAKpE: base64.b64decode(data['e']),
keyparam.KpKid: kid
})
else:
print(bcolors.FAIL + "algorithm not supported: {0}".format(data['alg']) + bcolors.ENDC)
exit(1)
def verify_signature(cose_msg: CM):
public_keys = get_trusted_keys()
algorithm = cose_msg.phdr.get(cose.headers.Algorithm)
kid = get_kid(cose_msg)
cose_key = None
for key, data in public_keys.items():
bkey = base64.b64decode(key)
if bkey == kid:
print("kid found in trusted keys")
cose_key = build_cose_key(algorithm, bytes(bkey.hex(), "ASCII"), data)
if cose_key is None:
print(bcolors.FAIL + "key could not be found in trusted keys, cannot verify signature" + bcolors.ENDC)
exit(1)
cose_msg.key = cose_key
if not cose_msg.verify_signature():
print(bcolors.FAIL + "signature could not be verified" + bcolors.ENDC)
exit(1)
def print_certificate(rules: dict, cert_type: str, data: dict) -> None:
print()
if cert_type == 'v':
__print_vaccination(data, rules["v"])
elif cert_type == 'r':
__print_recovered(data)
elif cert_type == 't':
__print_test(data, rules["t"])
else:
print(f'{bcolors.FAIL}Unknown certificate type: {cert_type}')
exit(1)
def __print_vaccination(data: dict, rules: List[Dict]) -> None:
print(f'{bcolors.BOLD}Vaccination{bcolors.ENDC}')
print(f'Medicinal Product: {data["mp"]}')
print(f'Vaccine: {data["vp"]}')
print(f'Dose Number: {data["dn"]}')
print(f'Total Series of Doses: {data["sd"]}')
print(f'Country of Vaccination: {data["co"]}')
print(f'Issuer: {data["is"]}')
print(f'Issued At: {data["dt"]}')
checked_date = datetime.strptime(data["dt"], '%Y-%m-%d')
check_against_rules(checked_date, data, rules)
def __print_recovered(data: dict) -> None:
print(f'{bcolors.BOLD}Recovered{bcolors.ENDC}')
print(f'Country of Test: {data["co"]}')
print(f'Issuer: {data["is"]}')
print(f'First positive Test Result: {data["fr"]}')
print(f'Valid From: {data["df"]}')
print(f'Valid Until: {data["du"]}')
if datetime.strptime(data["du"], '%Y-%m-%d').timestamp() < datetime.now().timestamp():
print(f'{bcolors.FAIL}Certificate invalid{bcolors.ENDC}')
else:
print(f'{bcolors.OKGREEN}Certificate valid{bcolors.ENDC}')
def __print_test(data: dict, rules: List[Dict]) -> None:
print(f'{bcolors.BOLD}Test{bcolors.ENDC}')
print(f'Type of Test: {data["tt"]}')
print(f'Test Result: {TEST_RESULT_MAPPING[data["tr"]]}')
print(f'Sample Collection: {data["sc"]}')
print(f'Testing Center: {data["tc"]}')
print(f'Country of Test: {data["co"]}')
print(f'Issuer: {data["is"]}')
checked_date = datetime.strptime(data["sc"], '%Y-%m-%dT%H:%M:%SZ')
check_against_rules(checked_date, data, rules)
def check_against_rules(checked_date: datetime, data: dict, rules: List[dict]) -> None:
for rule in rules:
delta = timedelta(rule["days"])
check = True
for key, value in rule["if"].items():
if data[key] != value:
check = False
if check and (checked_date + delta).timestamp() < datetime.now().timestamp():
print(f'{bcolors.FAIL}Certificate invalid{bcolors.ENDC}')
elif check:
print(f'{bcolors.OKGREEN}Certificate valid{bcolors.ENDC}')
| [
"theo@fluxlabs.ch"
] | theo@fluxlabs.ch |
449664c6a652f208251835430b04392c9f31857d | 457d07994582657539a52d2fe8b7c24557ecc1fb | /service10/migrations/0003_auto_20190201_0630.py | 0bcec6dd58bbb0c6baf0b78d282f64a82370ca3c | [] | no_license | ohsehwan/django_admin_nanum | 952c91452697f1ee7718449ceceaf4e434c3da27 | 0478389d3a44592fd2ee6f025f2b4a66c1a2176e | refs/heads/master | 2022-12-23T01:18:58.124355 | 2019-06-21T07:42:49 | 2019-06-21T07:42:49 | 168,487,820 | 3 | 1 | null | 2022-12-08T01:02:50 | 2019-01-31T08:11:59 | JavaScript | UTF-8 | Python | false | false | 597 | py | # Generated by Django 2.1.5 on 2019-02-01 06:30
import ckeditor.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('service10', '0002_mentor'),
]
operations = [
migrations.CreateModel(
name='article',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('html', ckeditor.fields.RichTextField()),
],
),
migrations.DeleteModel(
name='mentor',
),
]
| [
"dxman@naver.com"
] | dxman@naver.com |
bd311c9cdc81c1716e326ae30b80694fe4315389 | d5c63b07839daa13f657263fc9ce6195f88384c4 | /build/help.py | 3ff54ec0f90523cbcb9cd7c58b08b9025549520f | [] | no_license | scardali/junos-automation | d359cf74411cfffdf5c67e763c6c42f9582e1753 | 78927cd1a50381f6591a267d3ada35aa0c9dfc3e | refs/heads/master | 2020-03-31T14:07:35.395780 | 2018-09-05T16:59:45 | 2018-09-05T16:59:45 | 152,280,493 | 0 | 0 | null | 2018-10-09T16:00:42 | 2018-10-09T16:00:41 | null | UTF-8 | Python | false | false | 115 | py | #!/usr/bin/env python
import sys
import json
with open(sys.argv[1]) as f:
print json.dumps(json.load(f),indent=2)
| [
"slangley@juniper.net"
] | slangley@juniper.net |
c0cec181028f1ef6b4e89cc56c9abcc25aa60f51 | 5d7f9dcb09a0b76aaddc293ee844d8698295f123 | /Python/Python_2/Django/ninjagold/apps/gold/urls.py | 8f240f5903fb27415516d7078c3a0fa43a0ccbc9 | [] | no_license | JaxWLee/CodingDojoAssignments | 7cb01f7972b87042a443f70c68ed4c94da66f874 | 5f78eb0b330f0862ad1bd1d82e0eca887b0f457d | refs/heads/master | 2020-03-08T21:50:27.609420 | 2018-06-25T16:56:03 | 2018-06-25T16:56:03 | 128,415,818 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 173 | py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$',views.index),
url(r'^process_money/',views.process),
url(r'^clear/',views.clear)
] | [
"jwlee@mix.wvu.edu"
] | jwlee@mix.wvu.edu |
03a611be28fb36f43d0ca4c80370f50307077924 | 6451d6059ab63939bcafb674dfd45af446344a2c | /tests/helpers/cli.py | 0df861416483ca8646799cf4a52734bc17de3f22 | [
"Apache-2.0"
] | permissive | Onager/l2treviewtools | 61e17b96e33c7bb12d96c36fd2ea6fd89a370f82 | 6b6b24655b40928f34ea42e3c907abbc710f945f | refs/heads/master | 2020-12-30T16:14:42.625778 | 2017-08-07T19:26:46 | 2017-08-07T19:26:46 | 89,578,713 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 899 | py | # -*- coding: utf-8 -*-
"""Tests for command line helper."""
import unittest
from l2treviewtools.helpers import cli as cli_helper
class CLIHelperTest(unittest.TestCase):
"""Tests the command line helper"""
def testRunCommand(self):
"""Tests that the helper can be initialized."""
mock_responses = {u'echo hi': [0, b'hi\n', b'']}
test_helper = cli_helper.CLIHelper(mock_responses=mock_responses)
with self.assertRaises(AttributeError):
test_helper.RunCommand(u'echo hello')
exit_code, stdout, stderr = test_helper.RunCommand(u'echo hi')
self.assertEqual(exit_code, 0)
self.assertEqual(stdout, b'hi\n')
self.assertEqual(stderr, b'')
real_helper = cli_helper.CLIHelper()
exit_code, stdout, stderr = real_helper.RunCommand(u'echo hello')
self.assertEqual(exit_code, 0)
self.assertEqual(stdout, b'hello\n')
self.assertEqual(stderr, b'')
| [
"noreply@github.com"
] | Onager.noreply@github.com |
54d99f7d181bb9e7f6e11f06c799f3e7c24ad426 | dda441692e5a3d90cc3ba1ff4077f51c2ba78b60 | /models/generatorBlocks.py | 40f4afb3fb04c1134bcfc59f34eea8b52d7ba35c | [] | no_license | alenmora/styleGAN | ef7aa304e19186a7e15c6fddae8655953e277794 | ef848d729b06d35beb39b11bc90c7ef94fe73158 | refs/heads/master | 2020-12-08T15:12:21.496287 | 2020-02-10T06:32:32 | 2020-02-10T06:32:32 | 233,014,506 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 12,066 | py | import torch
import torch.nn as nn
import numpy as np
from torch.nn import functional as F
from models.commonBlocks import PixelNorm, Linear, Conv2D, ModulatedConv2D, getActivation
class constantInput(nn.Module):
def __init__(self, nCh, resol=4, makeTrainable = True):
super().__init__()
self.cInput = nn.Parameter(torch.randn(1,nCh,4,4)) #Constant random input
self.cInput.requires_grad_(makeTrainable)
def forward(self, input):
batchSize = input.size(0)
return self.cInput.repeat(batchSize, 1, 1, 1)
class Mapping(nn.Module):
"""
StyleGAN2 mapping generator module
"""
def __init__(self, latentSize=256, dLatentSize=256, mappingLayers = 4, neuronsInMappingLayers = 256, lrmul = 0.01,
activation = 'lrelu', scaleWeights = False, normalizeLayers = False, **kwargs):
super().__init__()
self.latentSize = latentSize
self.dLatentSize = dLatentSize
self.mappingLayers = mappingLayers
assert self.mappingLayers > 0, 'Mapping Module ERROR: The number of mapping layers should be a positive integer'
self.scaleWeights = scaleWeights
self.nNeurons = neuronsInMappingLayers
self.activation = getActivation(activation)
self.lrmul = lrmul
mods = []
inCh = self.latentSize
for layerId in range(self.mappingLayers):
outCh = self.nNeurons if layerId != (self.mappingLayers-1) else self.dLatentSize
mods.append(Linear(inCh, outCh, scaleWeights=self.scaleWeights, lrmul=self.lrmul))
mods.append(self.activation)
if normalizeLayers: mods.append(PixelNorm())
inCh = outCh
self.map = nn.Sequential(*mods)
self.name = 'Mapping subnetwork: '+str(self.map)
def forward(self, x):
return self.map(x)
def __repr__(self):
return self.name
class NoiseLayer(nn.Module):
"""
Module that adds the noise to the ModulatedConv2D output
"""
def __init__(self, outCh, resolution, randomizeNoise = False):
super().__init__()
self.noise = torch.randn(1,1,resolution,resolution)
self.register_buffer('cached_noise', self.noise)
self.randomizeNoise = randomizeNoise
self.weights = nn.Parameter(torch.zeros(1,outCh,1,1), requires_grad=True)
self.name = 'Noise layer: '+str(outCh)
def forward(self, x):
noise = torch.randn(1,1,x.size(2),x.size(3), device=x.device) if self.randomizeNoise else self.noise.to(x.device)
return x+self.weights*noise
def __repr__(self):
return self.name
class StyledConv2D(nn.Module):
"""
Module representing the mixing of a modulated 2DConv and noise addition
"""
def __init__(self, styleCh, inCh, outCh, kernelSize, resolution, padding='same', gain=np.sqrt(2), bias=False, lrmul = 1, scaleWeights=True,
demodulate = True, randomizeNoise = False, activation = 'lrelu'):
super().__init__()
self.conv = ModulatedConv2D(styleCh, inCh, outCh, kernelSize, padding=padding, gain=gain, bias=bias, lrmul=lrmul, scaleWeights=scaleWeights, demodulate=demodulate)
self.noise = NoiseLayer(outCh, resolution, randomizeNoise=randomizeNoise)
self.activation = getActivation(activation)
def forward(self, x, y):
out = self.conv(x, y)
out = self.noise(out)
out = self.activation(out)
return out
def __repr__(self):
return 'StyledConv2D based on '+self.conv.__repr__()
class ToRGB(nn.Module):
"""
Module to transform to image space
"""
def __init__(self, styleCh, inCh, outCh):
super().__init__()
self.conv = ModulatedConv2D(styleCh, inCh, outCh, kernelSize = 1, demodulate=False)
self.bias = nn.Parameter(torch.zeros(1, outCh, 1, 1))
def forward(self, x, y):
out = self.conv(x,y)
out = out + self.bias
return out
def __repr__(self):
return f'ToRGB using '+self.conv.__repr__()
class Synthesis(nn.Module):
"""
StyleGAN2 original synthesis network
"""
def __init__(self, dLatentSize = 256, resolution = 64, fmapBase = 2048, fmapDecay = 1, fmapMax = 256, fmapMin = 1,
randomizeNoise = False, activation = 'lrelu', scaleWeights = False, outCh = 3, upsample = 'bilinear', mode = 'skip',
normalizeLayers = False,**kwargs):
super().__init__()
self.dLatentSize = dLatentSize
self.resolution = resolution
self.fmapBase = fmapBase
self.fmapDecay = fmapDecay
self.fmapMax = fmapMax
self.fmapMin = fmapMin
self.activation = activation
self.upsample = upsample
self.mode = mode
self.outCh = outCh
self.normalizeLayers = normalizeLayers
assert self.mode in ['skip','resnet'], f'Generator ERROR: Invalid synthesis network architecture {self.mode}'
rlog2 = int(np.log2(self.resolution))
assert self.resolution == 2**(rlog2) and self.resolution >= 4, f'Synthesis Module ERROR: The resolution should be a power of 2 greater than 4 ({self.resolution})'
def nf(stage): #Get the number of channels per layer
return np.clip(int(self.fmapBase / (2.0 ** (stage * self.fmapDecay))), self.fmapMin, self.fmapMax)
self.nLayers = 2*rlog2-3 #a maximum resolution of 4x4 requires 1 layer, 8x8 requires 3, 16x16 requires 5,...
self.styleConvs = nn.ModuleList() #Keeps the style convolutional modules
self.toRGB = nn.ModuleList() #Keeps the ToRGB modules
self.lp = nn.ModuleList() #Keeps the 2DConv modules for linear projection when performing resnet architecture
if self.normalizeLayers: self.normalizer = PixelNorm() #Pixel normalizer
def layer(kernel, layerId): #Constructor of layers
resol = int(2**((layerId+5)//2)) #Recover the resolution of the current layer from its id (0 --> 4), (1 --> 8), (2 --> 8), (3 --> 16),...
stage = int(np.log2(resol)-2) #Resolution stage: (4x4 --> 0), (8x8 --> 1), (16x16 --> 2) ...
inCh = nf(stage)
outCh = nf(stage) if layerId % 2 else nf(stage+1) #The even layers give the output for the resolution block, so their number of outCh must be the same of the inCh for the next stage
if not layerId % 2: #Even layer
if self.mode == 'skip': #add the ToRGB module for the given resolution
self.toRGB.append(ToRGB(styleCh=self.dLatentSize, inCh=outCh, outCh=self.outCh))
elif self.mode == 'resnet': #Add the convolution modules for properly matching the channels during the residual connection
if layerId < self.nLayers-1: # (the last layer --which is even-- does not require this module)
self.lp.append(Conv2D(inCh=inCh, outCh=outCh, kernelSize=1))
#Add the required modulated convolutional module
self.styleConvs.append(StyledConv2D(styleCh=self.dLatentSize, inCh=inCh, outCh=outCh, kernelSize=kernel, resolution=resol, randomizeNoise=randomizeNoise, activation=activation))
for layerId in range(self.nLayers): #Create the layers from to self.nLayers-1
layer(kernel=3, layerId=layerId)
if self.mode == 'resnet': #Add the only toRGB module in the resnet architecture
self.toRGB.append(Conv2D(inCh=nf((self.nLayers+1)//2),outCh=self.outCh, kernelSize=1, scaleWeights=self.scaleWeights))
def forward(self, x, w):
"""
Forward function.
y (tensor): the disentangled latent vector
x (tentsor): the constant input map
*args, **kwargs: extra arguments for the forward step in the pogressive growing configuration
"""
if self.mode == 'skip':
return self.forwardSkip_(x,w)
elif self.mode == 'resnet':
return self.forwardResnet_(x,w)
def forwardTo(self, x, w, maxLayer):
"""
Forward tensor y up to layer maxLayer
y (tensor): the disentangled latent vector
maxLayer (int): the layer to forward the tensor up to
x (tentsor): the constant input map
"""
assert maxLayer <= self.nLayers, f'Module Synthesis ERROR: The maxLayer {maxLayer} value in the forwardTo function is larger than the number of layers in the network {self.nLayers}'
assert maxLayer >= 0, f'Module Synthesis ERROR: The maxLayer {maxLayer} value in the forwardTo function must be a nonnegative integer'
if self.mode == 'skip':
return self.forwardSkip_(x,w,maxLayer=maxLayer, getExtraOutputs=True)
elif self.mode == 'resnet':
return self.forwardResnet_(x,w,maxLayer=maxLayer, getExtraOutputs=True)
def forwardFrom(self, x, w, extraInput, minLayer):
"""
Forward tensor y up to layer maxLayer
y (tensor): the disentangled latent vector
x (tensor): the constant input map
extraInput (tensor): for the skip and resnet configs, the carryover and output terms from the previous configuration
minLayer(int): the layer from which to start the forwarding
"""
assert minLayer <= self.nLayers, f'Module Synthesis ERROR: The minLayer {minLayer} value in the forwardFrom function is larger than the number of layers in the network {self.nLayers}'
assert minLayer >= 0, f'Module Synthesis ERROR: The minLayer {minLayer} value in the forwardFrom function must be a nonnegative integer'
if self.mode == 'skip':
return self.forwardSkip_(x,w,output=extraInput,minLayer=minLayer)
elif self.mode == 'resnet':
return self.forwardResnet_(x,w,carryover=extraInput,minLayer=minLayer)
def forwardSkip_(self, x, w, minLayer = 0, maxLayer = None, output = 0, getExtraOutputs = False):
"""
Perform a forward pass using
the architecture with skip connections
"""
if maxLayer is None:
maxLayer = self.nLayers
for layer in range(minLayer, maxLayer): #Apply all layers
if layer % 2: #Odd layer, so increase size
x = F.interpolate(x, scale_factor=2, mode=self.upsample, align_corners=False)
output = F.interpolate(output, scale_factor=2, mode=self.upsample, align_corners=False)
x = self.styleConvs[layer](x, w)
if self.normalizeLayers:
x = self.normalizer(x)
if not layer % 2: #Even layer, so get the generated output for the given resolution, resize it, and add it to the final output
output = output + self.toRGB[layer//2](x, w)
if getExtraOutputs:
return x, output
return output
def forwardResnet_(self, x, w, minLayer = 0, maxLayer = None, carryover = None, getExtraOutputs = False):
"""
Perform a forward pass using
the architecture with residual networks
"""
if maxLayer is None:
maxLayer = self.nLayers
for layer in range(minLayer, maxLayer): #Apply all layers
if layer % 2: #Odd layer, so increase size
x = F.interpolate(x, scale_factor=2, mode=self.upsample, align_corners=False)
carryover = self.lp[layer//2](carryover)
carryover = F.interpolate(carryover, scale_factor=2, mode=self.upsample, align_corners=False)
x = self.styleConvs[layer](x, w)
if self.normalizeLayers:
x = self.normalizer(x)
if not layer % 2: #Even layer, so add and actualize carryover value
if carryover is not None: #If there is a carryover, add it to the output
x = (carryover + x)/np.sqrt(2)
carryover = x
x = self.toRGB[0](x, w) #Use the only toRGB for this net
if getExtraOutputs:
return x, carryover
return x | [
"alejandro@hep.phys.s.u-tokyo.ac.jp"
] | alejandro@hep.phys.s.u-tokyo.ac.jp |
1c921cff029674fa5fac874a4f0f61807e3341c3 | dfd468a5ffd001a47240774e8069da9235304d68 | /ice_cream_parlour.py | 2ec4331a5633233df0bcd87d50f034ec748275c7 | [] | no_license | harshita0902/programming-exercises | 806392902e76a19004c046c5d31352f3107d09d0 | 8a88bee21c418e818474585db14e0a1e6ed226b1 | refs/heads/master | 2021-03-19T05:16:51.946386 | 2020-04-21T17:56:20 | 2020-04-21T17:56:20 | 247,135,791 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 437 | py | def whatFlavors(cost, money):
d = {}
for x, y in enumerate(cost):
if y in d:
return (d[y], x + 1)
else:
d[money-y] = x + 1
if __name__ == '__main__':
t = int(input())
for t_itr in range(t):
money = int(input())
n = int(input())
cost = list(map(int, input().rstrip().split()))
r = whatFlavors(cost, money)
print(r[0],r[1])
| [
"hpandey652@gmail.com"
] | hpandey652@gmail.com |
a16a0a5c324fefcbdee0359ade338ba0685d8fd4 | ba378344205ece2900262e2959c8cdf5b18b4849 | /consumer_server.py | 743ca53c41c7d5445ef475410a418a1a430bdd84 | [] | no_license | danimrey/Udacity-Data-Streaming-Spark | ceeb9cb73fedc9be443bcae1cef6639b56771e50 | 1e153f2ef58fb3dc966d7fb281e711e05f4384cb | refs/heads/main | 2023-02-03T21:03:40.500787 | 2020-12-26T19:45:38 | 2020-12-26T19:45:38 | 324,622,268 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 577 | py | import asyncio
from confluent_kafka import Consumer
BROKER_URL = "PLAINTEXT://localhost:9092"
async def consume(topic_name):
consumer = Consumer({
'bootstrap.servers': BROKER_URL,
'group.id': '0',
})
consumer.subscribe([topic_name])
while True:
messages = consumer.consume()
for message in messages:
print(message.value())
await asyncio.sleep(1.0)
def run_consumer():
asyncio.run(consume('police.calls'))
if __name__ == '__main__':
run_consumer() | [
"danimrey@gmail.com"
] | danimrey@gmail.com |
c9f29336d3bfcae202ae927e4d97e9d16bca2772 | 4b84d33c18f7fccb44743bb6a0d6c41949e35687 | /steps.py | 66424a40f5a4d75e1ca80e83880e487cebfc7c51 | [] | no_license | courtneyholcomb/staircase-steps | 079bac04d2f1c560e212df6aa6c13c11daada958 | 22b2563c0632b539d4ae0d7deb50ac7502fba2ad | refs/heads/master | 2020-08-02T01:33:18.845859 | 2019-09-26T23:04:21 | 2019-09-26T23:04:21 | 211,193,671 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,353 | py | """How many different ways can you climb a staircase of `n` steps?
You can climb 1, 2, or 3 steps at a time.
For one step, we could do this one way: 1
>>> steps(1)
1
For two: 11 2
>>> steps(2)
2
For three: 111 12 21 3
>>> steps(3)
4
For four: 1111 121 211 112 22 13 31
>>> steps(4)
7
For five: 11111 2111 1211 1121 1112 122 121 221 113 131 311 23 32
>>> steps(5)
13
For six steps: 111111 21111 12111 11211 11121 11112 2211 2121 2112
1212 1122 1221 3111 1311 1131 1113 321 312 213 231 132 123 222 33
>>> steps(6)
24
"""
def steps(stairs):
"""How many different ways can you climb a staircase of `n` steps?
You can climb 1, 2, or 3 steps at a time.
"""
def get_combos(stairs):
"""Get all combos of strides you could use to climb given stairs."""
combos = set()
for stride in [1, 2, 3]:
if stairs % stride == 0:
combos.add(str(stride) * int(stairs / stride))
if stairs > stride:
combos.update(str(stride) + combo
for combo in get_combos(stairs - stride))
return combos
return len(get_combos(stairs))
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print("\n*** ALL TEST PASSED! YOU'RE A STAIRMASTER!\n")
| [
"courtneyeholcomb@gmail.com"
] | courtneyeholcomb@gmail.com |
55f57819c1d4758954960879bf878e26885de0ae | e992b76761d2cc95e55d8c21f78f9636b0f74aae | /caches/__init__.py | 1611d10b35c4da8ec7150bb0321420534a499a69 | [
"MIT"
] | permissive | Jaymon/caches | 7d61bed61ef8d3dc8a328ee037c14a4fc994e98f | 3e2aa5fcf51e8de80bea46eb117b73fb1f398e53 | refs/heads/master | 2023-07-20T23:13:55.461196 | 2023-07-12T20:33:49 | 2023-07-12T20:33:49 | 12,884,773 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,162 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, division, print_function, absolute_import
import logging
from caches.compat import *
from caches.core import (
Cache,
DictCache,
SetCache,
SortedSetCache,
SentinelCache,
)
from .interface import get_interfaces, get_interface, set_interface
from .dsn import configure, configure_environ
from .decorators import cached
__version__ = '3.0.0'
logger = logging.getLogger(__name__)
def unsafe_clear(pattern):
"""Clear the keys matching pattern
This uses scan to find keys matching pattern (eg, foo*) and delets them one
at a time
https://github.com/redis/redis/issues/2042
https://stackoverflow.com/a/4006575/5006
:param pattern: str, something like foo* or *bar*
:returns: int, how many keys were deleted
"""
count = 0
for connection_name, inter in get_interfaces().items():
# https://redis.io/commands/scan
# https://stackoverflow.com/a/34166690/5006
for key in inter.scan_iter(match=pattern, count=500):
inter.delete(String(key))
count += 1
return count
configure_environ()
| [
"jay@marcyes.com"
] | jay@marcyes.com |
58ae53ebe1caa1fcd1f4226a2269f75f74b4753c | e3d29948eeaba932a31d01af04e6d9bcb882e55b | /configs/pong_no_frameskip_v4/apex_dqn.py | e733213cc99d9d441911f37e586bdf273d7084b7 | [
"MIT"
] | permissive | kevin5k/rl_algorithms | b53dd718ba9845bee28dde723cdf3517cbaf43cf | eb8e607731c8a0e2f0b79d288e89a0f998574e06 | refs/heads/master | 2022-11-16T10:17:36.786934 | 2020-07-14T02:47:37 | 2020-07-14T02:47:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,398 | py | """Config for ApeX-DQN on Pong-No_FrameSkip-v4.
- Author: Chris Yoon
- Contact: chris.yoon@medipixel.io
"""
from rl_algorithms.common.helper_functions import identity
agent = dict(
type="ApeX",
hyper_params=dict(
gamma=0.99,
tau=5e-3,
buffer_size=int(1e5), # openai baselines: int(1e4)
batch_size=512, # openai baselines: 32
update_starts_from=int(3e4), # openai baselines: int(1e4)
multiple_update=1, # multiple learning updates
train_freq=1, # in openai baselines, train_freq = 4
gradient_clip=10.0, # dueling: 10.0
n_step=5,
w_n_step=1.0,
w_q_reg=0.0,
per_alpha=0.6, # openai baselines: 0.6
per_beta=0.4,
per_eps=1e-6,
loss_type=dict(type="DQNLoss"),
# Epsilon Greedy
max_epsilon=1.0,
min_epsilon=0.1, # openai baselines: 0.01
epsilon_decay=5e-7, # openai baselines: 1e-7 / 1e-1
# grad_cam
grad_cam_layer_list=[
"backbone.cnn.cnn_0.cnn",
"backbone.cnn.cnn_1.cnn",
"backbone.cnn.cnn_2.cnn",
],
# ApeX
num_workers=2,
local_buffer_max_size=1000,
worker_update_interval=50,
logger_interval=1000,
),
learner_cfg=dict(
type="DQNLearner",
device="cuda:0",
backbone=dict(
type="CNN",
configs=dict(
input_sizes=[4, 32, 64],
output_sizes=[32, 64, 64],
kernel_sizes=[8, 4, 3],
strides=[4, 2, 1],
paddings=[1, 0, 0],
),
),
head=dict(
type="DuelingMLP",
configs=dict(
use_noisy_net=False, hidden_sizes=[512], output_activation=identity
),
),
optim_cfg=dict(
lr_dqn=0.0003, # dueling: 6.25e-5, openai baselines: 1e-4
weight_decay=0.0, # this makes saturation in cnn weights
adam_eps=1e-8, # rainbow: 1.5e-4, openai baselines: 1e-8
),
),
worker_cfg=dict(type="DQNWorker", device="cpu",),
logger_cfg=dict(type="DQNLogger",),
comm_cfg=dict(
learner_buffer_port=6554,
learner_worker_port=6555,
worker_buffer_port=6556,
learner_logger_port=6557,
send_batch_port=6558,
priorities_port=6559,
),
)
| [
"noreply@github.com"
] | kevin5k.noreply@github.com |
5edeb038cd1f87c8aac071184fd2fef2036abf0b | 781e2692049e87a4256320c76e82a19be257a05d | /all_data/cs61a/untarred backup/122.py | 887a81dc01674a92d8b5e6f55aff075abf43e9b7 | [] | no_license | itsolutionscorp/AutoStyle-Clustering | 54bde86fe6dbad35b568b38cfcb14c5ffaab51b0 | be0e2f635a7558f56c61bc0b36c6146b01d1e6e6 | refs/heads/master | 2020-12-11T07:27:19.291038 | 2016-03-16T03:18:00 | 2016-03-16T03:18:42 | 59,454,921 | 4 | 0 | null | 2016-05-23T05:40:56 | 2016-05-23T05:40:56 | null | UTF-8 | Python | false | false | 1,076 | py | def num_common_letters(goal_word, guess):
"""Returns the number of letters in goal_word that are also in guess.
As per the rules of the game, goal_word cannot have any repeated
letters, but guess is allowed to have repeated letters.
goal_word and guess are assumed to be of the same length.
goal_word and guess are both instances of the word ADT.
>>> mwfs, mwfl = make_word_from_string, make_word_from_list
>>> num_common_letters(mwfs('steal'), mwfs('least'))
5
>>> num_common_letters(mwfs('steal'), mwfl(['s', 't', 'e', 'e', 'l']))
4
>>> num_common_letters(mwfl(['s', 't', 'e', 'a', 'l']), mwfs('thief'))
2
>>> num_common_letters(mwfl(['c', 'a', 'r']), mwfl(['p', 'e', 't']))
0
"""
goal_letters = get_list(goal_word)
guess_letters = get_list(guess)
common = 0
for guess_letter in guess_letters:
if guess_letter in goal_letters:
common += 1
goal_letters = [letter for letter in goal_letters if letter != guess_letter]
return common
| [
"rrc@berkeley.edu"
] | rrc@berkeley.edu |
cea269f71a06be2e88bab6c122be7e5ec8d08c22 | 8a6c1d9ff5f469774ca4651d46f212474b3435bf | /base/base_driver.py | 8d5ef05be8b058f89c05bfb1479b57f4c18c3888 | [] | no_license | yuanyue888666/test_jinkens_001 | 67a68378dc518e3033a4563f0530adeb530a8646 | b553d0348d967cdb6e25c7d1a46746b75f6d9512 | refs/heads/master | 2020-04-27T15:46:15.202764 | 2019-03-08T03:42:47 | 2019-03-08T03:42:47 | 174,459,619 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 657 | py |
from appium import webdriver
def init_driver():
"""
只要调用,就可以打开对应的应用程序
:return:
"""
# server 启动参数
desired_caps = {}
# 设备信息
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '5.1'
desired_caps['deviceName'] = '192.168.56.101:5555'
# app的信息
desired_caps['appPackage'] = 'com.android.contacts'
desired_caps['appActivity'] = '.activities.PeopleActivity'
# 不要重置应用
desired_caps['noReset'] = True
# 声明我们的driver对象
return webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)
| [
"johndoe@example.com"
] | johndoe@example.com |
661c31dbf3b7905eec3f72d6336db70fc44d7ae0 | 74e2f2eeab0197256aa8e5320d2ce013b1be7133 | /systems/maps.py | 1b7b7164cac98f5b415f7eabe71f3feae7b5cd63 | [] | no_license | xelaadryth/larsethia | 3b30181597f4817504bcc39d0f80927252243771 | 1e47aae201b79cd8fc833d2e614c439b26e74e79 | refs/heads/master | 2021-01-23T03:58:53.066270 | 2017-05-02T00:57:27 | 2017-05-02T00:57:27 | 86,138,243 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 220 | py | # TODO: Create a maps system. For instance, "map" brings up a map of your current area if you have one,
# "map world" brings up the overworld map
# "map briskell" brings up the map of Briskell no matter where you are
| [
"xdelaadryth@github.com"
] | xdelaadryth@github.com |
3566bcd48596c99e66b58657195c38253557e43d | c52c28726e72327d4230dc9b541c48647447d107 | /PyBank/test.py | c39af7addbf5aa1c3d725dc34623b59bd9d57847 | [] | no_license | Sephka/python-challenge | 6486a5d0282b3e930cdd325099a3c68f0ec091df | ab9d4bbe78d57172d7c217ecc60159efaa04ee11 | refs/heads/master | 2020-07-22T01:22:37.282710 | 2019-09-11T01:37:03 | 2019-09-11T01:37:03 | 207,028,461 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,467 | py | # Import things and stuff
import os
import csv
# Declaring CSV Columns
date = []
profLoss = []
# Declaring Variables
totalMonths = 0
netTotal = 0
avgChange = 0
greatestIncreaseDate = ''
greatestIncreaseTotal = 0
greatestDecreaseDate = ''
greatestDecreaseTotal = 0
# Path to collect data from the resources folder
bankCsv = os.path.join('Resources','budget_data.csv')
# Read in the CSV file
with open(bankCsv, newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
# print(row['Date'], row['Profit/Losses'])
# Iterate each month
totalMonths = totalMonths + 1
# Add all totals
netTotal = netTotal + int(row['Profit/Losses'])
'''
Old Method
# Read in the CSV file
with open(bankCsv, 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
header = next(csvreader)
print("Financial Analysis")
print("-"*30)
for row in csvreader:
date.append(row[0])
profLoss.append(int(row[1]))
# Greatest Increase conditional
value = int(row[1])
if greatestIncreaseTotal < value:
greatestIncreaseTotal = value
greatestIncreaseDate = row[0]
# Greatest Decrease conditional
if greatestDecreaseTotal > value:
greatestDecreaseTotal = value
greatestDecreaseDate = row[0]
totalMonths = totalMonths + 1
netTotal = netTotal + int(row[1])
'''
print(f"Total months: {totalMonths}")
print(f"Total: {netTotal}")
avgChange = 0
print(f"Average Change: {avgChange}")
print(f"Greatest increase in Profits: {greatestIncreaseDate} {greatestIncreaseTotal}")
print(f"Greatest decrease in Profits: {greatestDecreaseDate} {greatestDecreaseTotal}")
'''
with open(bankCsv, 'r') as csvfile:
a = [{k: str(v) for k, v in row.items()}
for row in csv.DictReader(csvfile, skipinitialspace=True)]
print(a[0].get('Date'))
'''
# csvreader = csv.reader(csvfile, delimiter=',')
# header = next(csvreader)
# print("Financial Analysis")
# print("-"*30)
#
lst = ['a','a','b','b','b','b','c','d','c','z','e','a','f']
occurences_dct = {}
for i in lst:
if i not in occurences_dct:
occurences_dct[i] = 1
else:
occurences_dct[i] += 1
print(occurences_dct)
lst2 = [['z', 9], ['a', 101], ['b', 2]]
lst2.sort(key = lambda x: x[1])
print(sorted(lst2, key = lambda x: x[1]))
print(lst2)
print(max(lst2, key = lambda x: x[1]))
print(max(lst2, key = lambda x: x[1])[0])
highest_votes = max([dct[i] for i in dct], key = lambda x: x[1])[0]
winner = [i for i in dct if dct[i][0] == highest_votes]
print(winner[0])
| [
"32805735+Sephka@users.noreply.github.com"
] | 32805735+Sephka@users.noreply.github.com |
797db0df433e1026567672c18c1bce927555f23b | 04ba44c348779892adbef835c72a979641e319cd | /AbolfazlSeifi_HW2_Maktab50/Abolfazl seifi_HW2_maktab50-2.py | b3656a3c77d06aee63a4fa14444372a37f81c590 | [] | no_license | abolfazlseifi/AbolfazlSeifi_HWs_Maktab50 | d79e4cbd96d9da32ddde5d4a1d09318cc55846fc | 6c87194702b033313940da8537ccb88176714c10 | refs/heads/main | 2023-04-26T23:29:35.622685 | 2021-05-16T12:56:13 | 2021-05-16T12:56:13 | 344,373,506 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 118 | py | x =input("Enter Your Number list: ")
x=x.split()
print("\nYour list is: ",x)
x = tuple(x)
print("\nYour tuple is: ",x) | [
"seifi.eng@gmail.com"
] | seifi.eng@gmail.com |
bb363a4b0a54d81231fd2205c390be28f59d47f5 | 79416a103ae2f5af2bc83935489312c5519774e0 | /rmsd.py | b7e1e8aea580ff65ffb91fea41386de7b0061983 | [] | no_license | MSSevs1313/BioinformaticsHW4 | be2fddd57139cdd85a6ed79414ab810d52bbe39b | 86d1d455f4f0889a800e1bc980450c2c1e29b772 | refs/heads/master | 2016-09-14T00:32:19.535860 | 2016-04-27T00:43:14 | 2016-04-27T00:43:14 | 57,168,478 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,811 | py | import math
def find_rmsd(a, b):
print "The RMSD of set1 and set2 is: %f" % rmsd(a, b)
centroidA = align_to_origin(a, find_centroid(a))
centroidB = align_to_origin(b, find_centroid(b))
print "Both sets are aligned to the origin."
print "Set1's centroid: %s" % round_centroid(centroidA)
print "Set2's centroid: %s" % round_centroid(centroidB)
print "The optimal RMSD of set1 and set2 after translation is: %f" % rmsd(a, b)
# find the distance between two points a and b
def distance(a, b):
total = 0
for ptA, ptB in zip(a, b):
total += (ptA - ptB) ** 2
return total
# find the rmsd between two lists of points using the distance
# between each point
def rmsd(a, b):
total = 0
for (ptA, ptB) in zip(a, b):
total += distance(ptA, ptB)
total /= len(a)
return math.sqrt(total)
# aligns a given list to the origin by subtracting
# the centroid from each point
def align_to_origin(listA, centroid):
# centroid = find_centroid(listA)
for pt in listA:
if not pt == centroid:
pt[6] = float(pt[6]) - float(centroid[6])
pt[7] = float(pt[7]) - float(centroid[7])
pt[8] = float(pt[8]) - float(centroid[8])
centroid[6] = 0.0
centroid[7] = 0.0
centroid[8] = 0.0
# return find_centroid(listA)
# finds the centroid of a list, ie the average of each coordinate
def find_centroid(aList):
xAv, yAv, zAv = (0,)*3
for pt in aList:
xAv += pt[0]
yAv += pt[1]
zAv += pt[2]
xAv /= len(aList)
yAv /= len(aList)
zAv /= len(aList)
return [xAv, yAv, zAv]
# rounds and absolute values the centroid
# otherwise returns just really small numbers (####e^-18, etc.)
def round_centroid(centroid):
return [abs(round(x, 5)) for x in centroid]
| [
"MSSevs1313@gmail.com"
] | MSSevs1313@gmail.com |
9808dd7f6cb3c4f34d801fa34e4fda3e2717b5d7 | a15b050e661c31880acc72465421f3ba4906ef06 | /0x06-python-classes/101-square.py | ffd6008dce8087b7476ce7b4b8aa8ac3e838cdf3 | [] | no_license | zacwoll/holbertonschool-higher_level_programming | 0c483195f50a55fe0bfae5cff03c0c86719d8063 | 9c7dda67dc5681fd96b90d6f05ee9748a37ed8b8 | refs/heads/master | 2022-12-22T04:54:13.815410 | 2020-09-25T16:03:41 | 2020-09-25T16:03:41 | 259,412,215 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,844 | py | #!/usr/bin/python3
"""Represent a Square Object with a __repr__ toString"""
class Square:
"""A Square"""
def __init__(self, size=0, position=(0, 0)):
"""Init"""
self.__size = size
self.__position = position
def __repr__(self):
"""Square toString"""
to_str = ''
if self.__size == 0:
to_str += '\n'
else:
to_str += ('\n' * self.__position[1])
for i in range(self.__size):
to_str += (' ' * self.__position[0])
to_str += ('#' * self.__size + '\n')
return to_str[:-1]
@property
def size(self):
"""gets the value of size"""
return self.__size
@size.setter
def size(self, value):
"""sets the value of size"""
if type(value) != int:
raise TypeError("size must be an integer")
if value < 0:
raise ValueError("size must be >= 0")
self.__size = value
def area(self):
"""Area of Square"""
return self.__size ** 2
@property
def position(self):
"""gets the value of position"""
return self.__position
@position.setter
def position(self, value):
"""Sets the value of position"""
if type(value) != tuple or len(value) != 2 or \
not all(type(x) == int and x >= 0 for x in a):
raise TypeError('position must be a \
tuple of 2 positive integers')
self.__position = value
def my_print(self):
"""Print the square."""
if self.__size == 0:
print()
else:
print('\n' * self.__position[1], end='')
for i in range(self.__size):
print(' ' * self.__position[0], end='')
print('#' * self.__size)
| [
"zacwoll@gmail.com"
] | zacwoll@gmail.com |
bfdcd61276829644d4aa9a0cef2743329b7e5bcf | bc23d8ae929a38e5c4d2ce93f4b7982308f40922 | /test_platform/testTask_app/views.py | 3f26ba6174d17aebb5da650584a4a9b6472ed772 | [] | no_license | anier26/reafact_testplatform | e30d0a0e689411c0b4264f7470c39b5370fd9dfa | 79a5beb8157a27fa12723b95db3317ae66d41862 | refs/heads/master | 2021-07-13T05:47:59.676763 | 2021-04-06T06:32:29 | 2021-04-06T06:32:29 | 241,179,060 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,331 | py | import json
from unittest import TestResult
from testTask_app.extend.task_thread import TaskThread
from django.shortcuts import render
from project_app.models import Project
from model_app.models import Module
from django.http import JsonResponse,HttpResponseRedirect
from testTask_app.models import TestTask, TaskResult
from testcase_app.models import TestCase
def task_manage(request):
tasks_list=TestTask.objects.all()
return render(request,"task_list.html",{"type":"list","tasks":tasks_list})
def task_add(request):
return render(request,"task_add.html",{"type":"add"})
def edit_task(request,tid):
return render(request, "task_edit.html",{"type":"edit"})
def del_task(request,tid):
task=TestTask.objects.get(id=tid)
task.delete()
return HttpResponseRedirect("/testTask/")
def run_task(request):
if request.method == "POST":
tid=request.POST.get("task_id","")
if tid == "":
return JsonResponse({"status":10202,"message": "task id is not null"})
tasks=TestTask.objects.all()
for i in tasks:
if i.status == 1:
return JsonResponse({"status": 10201, "message": "任务执行中请稍等..."})
task = TestTask.objects.get(id=tid)
task.status = 1
task.save()
TaskThread(tid).run()
return JsonResponse({"status": 10200, "message": "开始执行"})
else:
return JsonResponse({"status": 10203, "message": "执行失败"})
# 保存任务: 创建和编辑taskid= 0 创建,id不等于更新
def save_task(request):
if request.method == "POST":
task_id = request.POST.get("task_id","");
name= request.POST.get("name","")
desc =request.POST.get("desc","")
cases=request.POST.get("cases","")
print("name",name,desc)
print("用例",type(cases),cases)
if name == "" or cases =="":
return JsonResponse({"status":10102,"message":"参数不能为空"})
if task_id == "0":
TestTask.objects.create(name=name,describe=desc,cases=cases)
else:
task=TestTask.objects.get(id=task_id)
task.name=name
task.describe=desc
task.cases=cases
task.save()
return JsonResponse({"status":10200,"message":"success"})
else:
return JsonResponse({"status":10101,"message":"请求方法错误"})
def get_cases_tree(request):
if request.method == "GET":
projects = Project.objects.all()
data_list = []
for project in projects:
project_dict = {
"name": project.name,
"isParent": True
}
modules = Module.objects.filter(project_id=project.id)
module_list = []
for module in modules:
module_dict = {
"name": module.name,
"isParent": True
}
cases = TestCase.objects.filter(module_id=module.id)
case_list = []
for case in cases:
case_dict = {
"name": case.name,
"isParent": False,
"id": case.id
}
case_list.append(case_dict)
module_dict["children"] = case_list
module_list.append(module_dict)
project_dict["children"] = module_list
data_list.append(project_dict)
return JsonResponse({"status": 10200, "message": "success", "data": data_list})
if request.method=="POST":
tid=request.POST.get("tid","")
print("tid: " ,tid)
if tid == "":
return JsonResponse({"status": 10101, "message": "error!任务id不能为空"})
task = TestTask.objects.get(id=tid)
caselist=json.loads(task.cases)
task_data = {
"name":task.name,
"desc":task.describe
}
projects = Project.objects.all()
data_list = []
for project in projects:
project_dict = {
"name": project.name,
"isParent": True
}
modules = Module.objects.filter(project_id=project.id)
module_list = []
for module in modules:
module_dict = {
"name": module.name,
"isParent": True
}
cases = TestCase.objects.filter(module_id=module.id)
case_list = []
for case in cases:
if case.id in caselist:
case_dict = {
"name": case.name,
"isParent": False,
"id": case.id,
"checked":True,
}
else:
case_dict = {
"name": case.name,
"isParent": False,
"id": case.id,
"checked": False,
}
case_list.append(case_dict)
module_dict["children"] = case_list
module_list.append(module_dict)
project_dict["children"] = module_list
data_list.append(project_dict)
task_data["cases"] = data_list
return JsonResponse({"status": 10200, "message": "success", "data": task_data})
def result(request,tid):
results = TaskResult.objects.filter(task_id=tid).order_by("-create_time")
return render(request, "task_result.html",{"results": results,"type":"result"})
def see_log(request):
if request.method == "POST":
rid = request.POST.get("result_id", "")
if rid == "":
return JsonResponse({"status": 10105, "message": "任务id不能为空"})
result = TaskResult.objects.get(id = rid)
result.result
return JsonResponse({"status": 10200, "message": "success","data":result.result})
else:
return JsonResponse({"status": 10101, "message": "请求方法错误"}) | [
"498494576@qq.com"
] | 498494576@qq.com |
243f60d7878f2aa451bc474adeb9eabc12b8fe43 | 83587a388def18103578a1a437025194ba37b117 | /SceneMap/Tiles/Water.py | 0925cbc05abe55910a838b27a1fd538dabe00440 | [] | no_license | manoftheponcho/ANuStart | b6cad41fe3d8b5325c7e745ceffd89917c139ccc | 7f8ce370b88179bc24a7b6bcf8d5793a7a9681f9 | refs/heads/master | 2020-12-25T14:38:40.461115 | 2017-01-25T01:53:27 | 2017-01-25T01:53:27 | 66,581,285 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,830 | py | import pyglet
class Water:
# do some string gymnastics to make this readable, remembering pyglet's bottom-to-top ordering
image_string = ''.join(['{0}{0}{0}{1}{1}{0}{0}{0}{0}{1}{0}{0}{0}{0}{0}{1}',
'{0}{0}{1}{1}{0}{0}{0}{0}{0}{0}{1}{0}{0}{0}{0}{1}',
'{0}{0}{1}{0}{0}{0}{0}{0}{0}{0}{1}{1}{0}{0}{1}{1}',
'{1}{1}{1}{0}{0}{0}{0}{0}{0}{0}{1}{1}{1}{1}{1}{0}',
'{0}{0}{1}{1}{0}{0}{0}{0}{0}{0}{1}{1}{1}{1}{0}{0}',
'{0}{0}{0}{1}{1}{1}{0}{0}{0}{1}{1}{1}{1}{1}{0}{0}',
'{0}{0}{0}{1}{1}{1}{1}{1}{1}{1}{0}{0}{0}{1}{1}{0}',
'{0}{0}{1}{1}{0}{0}{0}{1}{1}{0}{0}{0}{0}{0}{1}{0}',
'{1}{1}{1}{0}{0}{0}{0}{1}{0}{0}{0}{0}{0}{0}{0}{1}',
'{0}{0}{1}{1}{0}{0}{0}{1}{0}{0}{0}{0}{0}{0}{0}{1}',
'{0}{0}{0}{1}{0}{0}{1}{1}{0}{0}{0}{0}{0}{0}{0}{1}',
'{0}{0}{0}{1}{1}{1}{1}{1}{0}{0}{0}{0}{0}{0}{1}{0}',
'{0}{0}{0}{0}{1}{0}{1}{1}{1}{0}{0}{0}{0}{1}{1}{0}',
'{0}{0}{0}{0}{1}{0}{0}{0}{1}{1}{1}{1}{1}{1}{1}{0}',
'{0}{0}{0}{1}{0}{0}{0}{0}{0}{1}{0}{0}{0}{1}{1}{1}',
'{0}{1}{1}{1}{0}{0}{0}{0}{1}{0}{0}{0}{0}{0}{1}{1}'][::-1])
image_bytes = image_string.format('\x64\xb0\xff\xff','\xc0\xdf\xff\xff')
image = pyglet.image.create(16, 16)
image.set_data('RGBA', 64, image_bytes)
if __name__ == "__main__":
window = pyglet.window.Window(256, 240)
tile = Water()
@window.event
def on_draw():
window.clear()
pyglet.gl.gl.glScalef(12.0, 12.0, 12.0)
tile.image.blit(0, 0, 0)
pyglet.app.run()
| [
"manoftheponcho@gmail.com"
] | manoftheponcho@gmail.com |
5631019e2a0582cfac20c14cc117a6191b418a7a | 5cdc169119d0b11c7cafea3bc7e8c4c091cb0d77 | /exl.py | 0c37ccb2f67838cba5236f891598cd0c4b90c477 | [] | no_license | rashodqaim/lp3thw | 8aa5283d299fbdb329a8a43a1e1361ab031c57f3 | c1f8206e9ecb4d817a8d1ce1eaa3655b1d9279b9 | refs/heads/master | 2020-06-14T20:34:52.853203 | 2019-08-09T13:28:42 | 2019-08-09T13:28:42 | 195,118,578 | 0 | 0 | null | 2019-07-11T14:32:49 | 2019-07-03T19:55:59 | Python | UTF-8 | Python | false | false | 498 | py | print(" will now count my chickens")
print("Hens", 25 + 30/6)
print("Roosters", 100 - 25 * 3 % 4)
print("Now I will count the eggs:")
print(3 + 2 + 1 - 5 +4 % 2 -1 / 4 +6)
print("Is it true that 3 + 2 < 5 - 7?")
print(3 + 2 < 5 - 7)
print("What is 3 +2?", 3 + 2)
print("What is 5 - 7?", 5-7)
print("Oh, that's why its's False.")
print("How about some more.")
print("Is it greater?", 5 > -2)
print("Is it greater or equal?", 5 >= -2)
print("Is it less or equal?", 5 <= -2)
print(100 % 16)
| [
"rashod@basketsavings.com"
] | rashod@basketsavings.com |
841b17f63f4c3de36fb341cff7247e985e79a433 | 5f99605987e9237054bbf0b0063f7846516052f9 | /loop/for_range.py | 4419c97bc7a385a5b9c1af610f2be005700e6ecf | [] | no_license | MiranLeeeee/Python-Study | ce4bb23de926b949aa1320fb194c58c64d436841 | b02b0b34e8eb577442e064327b73817626412479 | refs/heads/master | 2023-08-28T06:48:16.375322 | 2021-10-03T13:56:04 | 2021-10-03T13:56:04 | 370,056,910 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 163 | py | '''
for_range문
1. for 변수 in range(시작,끝+1)
2. 시작 값 생략하면 0부터 시작
'''
total = 0
for i in range(1,101):
total += i
print(total)
| [
"noreply@github.com"
] | MiranLeeeee.noreply@github.com |
901d4093c507a7f21145a84dbc7d64cb4a65b5ab | ae7e769844f67da2985d02532d250330c73e0250 | /1 laboratory/1d.py | 26787090e2514c16f8a26ddf31cc6fbea6986750 | [] | no_license | nikolaykochubeev/itmo_AlgorithmsAndDataStructures | ca21ffb62d7758562102db0a0dff4b9f048d5726 | 3f237ef83032d518a7dfa44228ef7a2b87ff23a6 | refs/heads/master | 2023-05-09T12:31:16.849175 | 2021-06-04T22:31:46 | 2021-06-04T22:31:46 | 336,846,370 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 684 | py | from random import choice
def quick_sort(list_):
if len(list_) <= 1:
return list_
else:
random_number = choice(list_)
smaller, larger, equal = [], [], []
for i in list_:
if i > random_number:
larger.append(i)
elif i < random_number:
smaller.append(i)
else:
equal.append(i)
return quick_sort(smaller) + equal + quick_sort(larger)
smallsort_in = [int(item) for item in open('smallsort.in').read().split()]
smallsort_out = open('smallsort.out', 'w')
smallsort_out.write(' '.join([str(item) for item in quick_sort(smallsort_in[1:])]))
smallsort_out.close()
| [
"nikolay.kochubeev@gmail.com"
] | nikolay.kochubeev@gmail.com |
8785a675a85b032f21d392fa7b228c87a0d876d1 | 76d77142a14aa22c9c81db0948c420eba11876ea | /python/foo.py | ebfdd650f20edc265d61d235dc7a269cb861f2c2 | [] | no_license | taeyoungchoon/t-shell | 8cdf97062b697e932cbacbe15a5e539815805375 | 8eb68897fe263710e360eea4f99af2ea1fdeb3c1 | refs/heads/master | 2023-07-11T17:32:07.118847 | 2023-06-26T23:59:46 | 2023-06-26T23:59:46 | 35,950,587 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 218 | py | #!/usr/bin/env python3
l, d, kv = [1,2,3], (1,2,3), {1:2,3:4}
s = 'hello'
print("%s, %d%d%d%d" % (s, l[0], d[1], 3, kv[3]))
print("{}, {}{}{}{}".format(s, l[0], d[1], 3, kv[3]))
print(f"{s}, {l[0]}{d[1]}3{kv[3]}")
| [
"taeyoungchoon@gmail.com"
] | taeyoungchoon@gmail.com |
4c19051a43c291779e8c00d44bd6b787249af569 | 20b2d61c0959023cb51be92fafe54877aecb9887 | /pabi_utils/models/ir_attachment.py | 574f5bb0a1d036cefea059529c50c697e945ffb3 | [] | no_license | BTCTON/pb2_addons | 6841a23554054f859b0c4acafb4e91bd0c3a14e4 | a5bfd90c202cea894690c96d74a74fa96eb79468 | refs/heads/master | 2021-09-07T16:55:41.195667 | 2018-02-26T11:27:01 | 2018-02-26T11:27:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,864 | py | # -*- coding: utf-8 -*-
import logging
import os
from openerp import models, fields, api
_logger = logging.getLogger(__name__)
class IrAttachment(models.Model):
_inherit = 'ir.attachment'
@api.model
def name_search(self, name, args=None, operator='ilike', limit=80):
if self._context.get('domain_template_ids', False):
args += [('id', 'in', self._context['domain_template_ids'][0][2])]
return super(IrAttachment, self).name_search(name=name, args=args,
operator=operator,
limit=limit)
# @api.model
# def load_xlsx_template(self, addon, template_ids, file_dir):
# print addon
# print template_ids
# print file_dir
# for xml_id in template_ids:
# try:
# xmlid = '%s.%s' % (addon, xml_id)
# att = self.env.ref(xmlid)
# file_path = '%s/%s' % (file_dir, att.datas_fname)
# att.datas = open(file_path, 'rb').read().encode('base64')
# except ValueError, e:
# _logger.exception(e.message)
@api.model
def load_xlsx_template(self, att_ids, folder):
for att in self.browse(att_ids):
try:
file_dir = os.path.dirname(os.path.realpath(__file__))
# While can't find better solution, we get the addon dir by
# so, make sure that the calling addon in in the same foloer
# with this pabi_utils
file_dir = file_dir.replace('/pabi_utils/models', '')
file_path = '%s/%s/%s' % (file_dir, folder, att.datas_fname)
att.datas = open(file_path, 'rb').read().encode('base64')
except ValueError, e:
_logger.exception(e.message)
| [
"kittiu@gmail.com"
] | kittiu@gmail.com |
1d35f60ece3de5bddb70323af263aefce183ca2a | a74edcfad49e443fe43aca2e373fd3b734aee5f2 | /chapter-10/process_monitor.py | 0afcf71c143b9fcbf930678e0e1d23c0ff3349e6 | [] | no_license | LukeEdward21/Black-Hat-Python-2nd-Edition | c136b085456d728052a6c9016008318a3cbd295a | e14ad320e1c43bb13558037ca397230afe1f2f21 | refs/heads/main | 2023-07-06T23:09:33.485437 | 2021-08-01T21:57:36 | 2021-08-01T21:57:36 | 391,745,680 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 2,003 | py | #!/usr/bin/env python3
import os
import sys
import win32api
import win32con
import win32security
import wmi
def get_process_privileges(pid):
try:
hproc = win32api.OpenProcess(
win32con.PROCESS_QUERY_INFORMATION, False, pid
)
htok = win32security.OpenProcessToken(hproc, win32con.TOKEN_QUERY)
privs = win32security.GetTokenInformation(
htok, win32security.TokenPrivileges
)
privileges = ''
for priv_id, flags in privs:
if flags == (win32security.SE_PRIVILEGE_ENABLED |
win32security.SE_PRIVILEGE_ENABLED_BY_DEFAULT):
privileges += f'{win32security.LookupPrivilegeName(None, priv_id)}|'
except Exception as e:
print(e)
privileges = 'N/A'
return privileges
def log_to_file(message):
with open('process_monitor_log.csv', 'a') as fd:
fd.write(f'{message}\r\n')
def monitor():
head = 'CommandLine, Time, Executable, Parent PID, PID, User, Privileges'
log_to_file(head)
c = wmi.WMI()
process_watcher = c.Win32_Process.watch_for('creation')
while True:
try:
new_process = process_watcher()
cmdline = new_process.CommandLine
create_date = new_process.CreationDate
executable = new_process.ExecutablePath
parent_pid = new_process.ParentProcessId
pid = new_process.ProcessId
proc_owner = new_process.GetOwner()
privileges = get_process_privileges(pid)
process_log_message = (
f'{cmdline}, {create_date}, {executable},'
f'{parent_pid}, {pid}, {proc_owner}, {privileges}'
)
print(process_log_message)
print()
log_to_file(process_log_message)
except Exception as e:
print(e)
pass
if __name__ == '__main__':
monitor()
| [
"lucasedward2019@hotmail.com"
] | lucasedward2019@hotmail.com |
485e5433667081aaf4dc508002d827c07367437d | 6bc485e593a24354e8ec6ad1284809c5748b7995 | /workon/contrib/admin2/templatetags/workon_admin_forms.py | 5e50c0aa768171d3c1ca93e280ff13d4969dbcbe | [
"BSD-3-Clause"
] | permissive | dalou/django-workon | fba87b6951540d7f059c8fcb79cd556573f56907 | ef63c0a81c00ef560ed693e435cf3825f5170126 | refs/heads/master | 2021-01-20T11:09:49.314839 | 2018-12-29T16:56:08 | 2018-12-29T16:56:08 | 50,340,299 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,936 | py | from django import template
from ..config import get_config
register = template.Library()
def get_form_size(fieldset):
default_label_class = get_config('form_size').split(':')
# Try fieldset definition at first
size_by_fieldset = get_fieldset_size(fieldset)
if size_by_fieldset:
return size_by_fieldset
# Fallback to model admin definition
ma_sizes = getattr(fieldset.model_admin, 'workon_admin_form_size', None)
if ma_sizes:
return ma_sizes.split(':')
# Use default values at last
return default_label_class
def get_fieldset_size(fieldset):
if fieldset and fieldset.classes and ':' in fieldset.classes:
for cls in fieldset.classes.split(' '):
if ':' in cls:
return cls.split(':')
@register.filter
def workon_admin_form_label_class(field, fieldset):
default_class = get_form_size(fieldset)[0]
if not hasattr(field, 'field'):
return default_class
label_class = field.field.widget.attrs.get('label_class')
if label_class:
return label_class
return default_class
@register.filter
def workon_admin_form_field_class(field, fieldset):
"""
Return classes for form-column
"""
css_classes = []
default_class = get_form_size(fieldset)[1]
css_classes.append('form-column')
if not hasattr(field.field, 'field'):
css_classes.append(default_class)
return ' '.join(css_classes)
widget_py_cls = field.field.field.widget.__class__.__name__
css_classes.append('widget-%s' % widget_py_cls)
if 'RawIdWidget' in widget_py_cls:
css_classes.append('form-inline')
class_by_widget = field.field.field.widget.attrs.get('column_class')
if class_by_widget:
del field.field.field.widget.attrs['column_class']
css_classes.append(class_by_widget)
else:
css_classes.append(default_class)
return ' '.join(css_classes)
| [
"autrusseau.damien@gmail.com"
] | autrusseau.damien@gmail.com |
1e8ae10587f880414d32d2dd2fc75d6a585e9e66 | 48e66c53cb340435369a0e6420bb30140f501505 | /Chapter12/ABQ_Data_Entry/abq_data_entry/mainmenu.py | 3063dc96c2bb4899869b5582f1bf59370dd155e6 | [
"MIT"
] | permissive | PacktPublishing/Python-GUI-Programming-with-Tkinter | d38278555408bf8c6dba3b12b4b963f987abf7ab | 217ff90413dc2813a1b29d5ade52e23a72efadf5 | refs/heads/master | 2023-07-25T15:05:12.357484 | 2023-01-30T10:23:35 | 2023-01-30T10:23:35 | 133,041,882 | 236 | 127 | MIT | 2023-07-10T14:26:58 | 2018-05-11T13:17:01 | Python | UTF-8 | Python | false | false | 15,028 | py | import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from functools import partial
class GenericMainMenu(tk.Menu):
"""The Application's main menu"""
def __init__(self, parent, settings, callbacks, **kwargs):
"""Constructor for MainMenu
arguments:
parent - The parent widget
settings - a dict containing Tkinter variables
callbacks - a dict containing Python callables
"""
super().__init__(parent, **kwargs)
self.settings = settings
self.callbacks = callbacks
self._build_menu()
self._bind_accelerators()
def _build_menu(self):
# The file menu
file_menu = tk.Menu(self, tearoff=False)
file_menu.add_command(
label="Select file…",
command=self.callbacks['file->select'],
accelerator='Ctrl+O'
)
file_menu.add_separator()
file_menu.add_command(
label="Quit",
command=self.callbacks['file->quit'],
accelerator='Ctrl+Q'
)
self.add_cascade(label='File', menu=file_menu)
#Tools menu
tools_menu = tk.Menu(self, tearoff=False)
tools_menu.add_command(
label="Update Weather Data",
command=self.callbacks['update_weather_data']
)
tools_menu.add_command(
label="Upload CSV to corporate REST",
command=self.callbacks['upload_to_corporate_rest']
)
tools_menu.add_command(
label="Upload CSV to corporate FTP",
command=self.callbacks['upload_to_corporate_ftp']
)
self.add_cascade(label='Tools', menu=tools_menu)
# The options menu
options_menu = tk.Menu(self, tearoff=False)
options_menu.add_checkbutton(
label='Autofill Date',
variable=self.settings['autofill date']
)
options_menu.add_checkbutton(
label='Autofill Sheet data',
variable=self.settings['autofill sheet data']
)
# font size submenu
font_size_menu = tk.Menu(self, tearoff=False)
for size in range(6, 17, 1):
font_size_menu.add_radiobutton(
label=size, value=size,
variable=self.settings['font size']
)
options_menu.add_cascade(label='Font size', menu=font_size_menu)
# themes menu
style = ttk.Style()
themes_menu = tk.Menu(self, tearoff=False)
for theme in style.theme_names():
themes_menu.add_radiobutton(
label=theme, value=theme,
variable=self.settings['theme']
)
options_menu.add_cascade(label='Theme', menu=themes_menu)
self.settings['theme'].trace('w', self.on_theme_change)
self.add_cascade(label='Options', menu=options_menu)
# switch from recordlist to recordform
go_menu = tk.Menu(self, tearoff=False)
go_menu.add_command(
label="Record List",
command=self.callbacks['show_recordlist'],
accelerator='Ctrl+L'
)
go_menu.add_command(
label="New Record",
command=self.callbacks['new_record'],
accelerator='Ctrl+N'
)
self.add_cascade(label='Go', menu=go_menu)
# The help menu
help_menu = tk.Menu(self, tearoff=False)
help_menu.add_command(label='About…', command=self.show_about)
self.add_cascade(label='Help', menu=help_menu)
def get_keybinds(self):
return {
'<Control-o>': self.callbacks['file->select'],
'<Control-q>': self.callbacks['file->quit'],
'<Control-n>': self.callbacks['new_record'],
'<Control-l>': self.callbacks['show_recordlist']
}
@staticmethod
def _argstrip(function, *args):
return function()
def _bind_accelerators(self):
keybinds = self.get_keybinds()
for key, command in keybinds.items():
self.bind_all(
key,
partial(self._argstrip, command)
)
def on_theme_change(self, *args):
"""Popup a message about theme changes"""
message = "Change requires restart"
detail = (
"Theme changes do not take effect"
" until application restart")
messagebox.showwarning(
title='Warning',
message=message,
detail=detail)
def show_about(self):
"""Show the about dialog"""
about_message = 'ABQ Data Entry'
about_detail = (
'by Alan D Moore\n'
'For assistance please contact the author.'
)
messagebox.showinfo(
title='About',
message=about_message,
detail=about_detail
)
class WindowsMainMenu(GenericMainMenu):
"""
Changes:
- Windows uses file->exit instead of file->quit,
and no accelerator is used.
- Windows can handle commands on the menubar, so
put 'Record List' / 'New Record' on the bar
- Put 'options' under 'Tools' with separator
"""
def _build_menu(self):
file_menu = tk.Menu(self, tearoff=False)
file_menu.add_command(
label="Select file…",
command=self.callbacks['file->select'],
accelerator='Ctrl+O'
)
file_menu.add_separator()
file_menu.add_command(
label="Exit",
command=self.callbacks['file->quit']
)
self.add_cascade(label='File', menu=file_menu)
self.add_command(
label="Record List",
command=self.callbacks['show_recordlist'],
accelerator='Ctrl+L'
)
self.add_command(
label="New Record",
command=self.callbacks['new_record'],
accelerator='Ctrl+N'
)
# The Tools menu
tools_menu = tk.Menu(self, tearoff=False)
# update weather
tools_menu.add_command(
label="Update weather data",
command=self.callbacks['update_weather_data'],
)
tools_menu.add_command(
label="Upload CSV to corporate REST",
command=self.callbacks['upload_to_corporate_rest']
)
tools_menu.add_command(
label="Upload CSV to corporate FTP",
command=self.callbacks['upload_to_corporate_ftp']
)
# The options menu
options_menu = tk.Menu(tools_menu, tearoff=False)
options_menu.add_checkbutton(
label='Autofill Date',
variable=self.settings['autofill date']
)
options_menu.add_checkbutton(
label='Autofill Sheet data',
variable=self.settings['autofill sheet data']
)
# font size submenu
font_size_menu = tk.Menu(self, tearoff=False)
for size in range(6, 17, 1):
font_size_menu.add_radiobutton(
label=size, value=size,
variable=self.settings['font size']
)
options_menu.add_cascade(label='Font size', menu=font_size_menu)
# themes menu
style = ttk.Style()
themes_menu = tk.Menu(self, tearoff=False)
for theme in style.theme_names():
themes_menu.add_radiobutton(
label=theme, value=theme,
variable=self.settings['theme']
)
options_menu.add_cascade(label='Theme', menu=themes_menu)
self.settings['theme'].trace('w', self.on_theme_change)
tools_menu.add_separator()
tools_menu.add_cascade(label='Options', menu=options_menu)
self.add_cascade(label='Tools', menu=tools_menu)
# The help menu
help_menu = tk.Menu(self, tearoff=False)
self.add_cascade(label='Help', menu=help_menu)
def get_keybinds(self):
return {
'<Control-o>': self.callbacks['file->select'],
'<Control-n>': self.callbacks['new_record'],
'<Control-l>': self.callbacks['show_recordlist']
}
class LinuxMainMenu(GenericMainMenu):
"""Differences for Linux:
- Edit menu for autofill options
- View menu for font & theme options
"""
def _build_menu(self):
file_menu = tk.Menu(self, tearoff=False)
file_menu.add_command(
label="Select file…",
command=self.callbacks['file->select'],
accelerator='Ctrl+O'
)
file_menu.add_separator()
file_menu.add_command(
label="Quit",
command=self.callbacks['file->quit'],
accelerator='Ctrl+Q'
)
self.add_cascade(label='File', menu=file_menu)
# The edit menu
edit_menu = tk.Menu(self, tearoff=False)
edit_menu.add_checkbutton(
label='Autofill Date',
variable=self.settings['autofill date']
)
edit_menu.add_checkbutton(
label='Autofill Sheet data',
variable=self.settings['autofill sheet data']
)
self.add_cascade(label='Edit', menu=edit_menu)
# The View menu
view_menu = tk.Menu(self, tearoff=False)
# font size submenu
font_size_menu = tk.Menu(view_menu, tearoff=False)
for size in range(6, 17, 1):
font_size_menu.add_radiobutton(
label=size, value=size,
variable=self.settings['font size']
)
view_menu.add_cascade(label='Font size', menu=font_size_menu)
# themes menu
style = ttk.Style()
themes_menu = tk.Menu(view_menu, tearoff=False)
for theme in style.theme_names():
themes_menu.add_radiobutton(
label=theme, value=theme,
variable=self.settings['theme']
)
view_menu.add_cascade(label='Theme', menu=themes_menu)
self.settings['theme'].trace('w', self.on_theme_change)
self.add_cascade(label='View', menu=view_menu)
# switch from recordlist to recordform
go_menu = tk.Menu(self, tearoff=False)
go_menu.add_command(
label="Record List",
command=self.callbacks['show_recordlist'],
accelerator='Ctrl+L'
)
go_menu.add_command(
label="New Record",
command=self.callbacks['new_record'],
accelerator='Ctrl+N'
)
self.add_cascade(label='Go', menu=go_menu)
#Tools menu
tools_menu = tk.Menu(self, tearoff=False)
tools_menu.add_command(
label="Update Weather Data",
command=self.callbacks['update_weather_data']
)
tools_menu.add_command(
label="Upload CSV to corporate REST",
command=self.callbacks['upload_to_corporate_rest']
)
tools_menu.add_command(
label="Upload CSV to corporate FTP",
command=self.callbacks['upload_to_corporate_ftp']
)
self.add_cascade(label='Tools', menu=tools_menu)
# The help menu
help_menu = tk.Menu(self, tearoff=False)
help_menu.add_command(label='About…', command=self.show_about)
self.add_cascade(label='Help', menu=help_menu)
class MacOsMainMenu(GenericMainMenu):
"""
Differences for MacOS:
- Create App Menu
- Move about to app menu, remove 'help'
- Remove redundant quit command
- Change accelerators to Command-[]
- Add View menu for font & theme options
- Add Edit menu for autofill options
- Add Window menu for navigation commands
"""
def _build_menu(self):
app_menu = tk.Menu(self, tearoff=False, name='apple')
app_menu.add_command(
label='About ABQ Data Entry',
command=self.show_about
)
self.add_cascade(label='ABQ Data Entry', menu=app_menu)
file_menu = tk.Menu(self, tearoff=False)
file_menu.add_command(
label="Select file…",
command=self.callbacks['file->select'],
accelerator="Cmd-O"
)
self.add_cascade(label='File', menu=file_menu)
edit_menu = tk.Menu(self, tearoff=False)
edit_menu.add_checkbutton(
label='Autofill Date',
variable=self.settings['autofill date']
)
edit_menu.add_checkbutton(
label='Autofill Sheet data',
variable=self.settings['autofill sheet data']
)
self.add_cascade(label='Edit', menu=edit_menu)
# View menu
view_menu = tk.Menu(self, tearoff=False)
# font size submenu
font_size_menu = tk.Menu(view_menu, tearoff=False)
for size in range(6, 17, 1):
font_size_menu.add_radiobutton(
label=size, value=size,
variable=self.settings['font size']
)
view_menu.add_cascade(label='Font size', menu=font_size_menu)
# themes menu
style = ttk.Style()
themes_menu = tk.Menu(view_menu, tearoff=False)
for theme in style.theme_names():
themes_menu.add_radiobutton(
label=theme, value=theme,
variable=self.settings['theme']
)
view_menu.add_cascade(label='Theme', menu=themes_menu)
self.settings['theme'].trace('w', self.on_theme_change)
self.add_cascade(label='View', menu=view_menu)
#Tools menu
tools_menu = tk.Menu(self, tearoff=False)
tools_menu.add_command(
label="Update Weather Data",
command=self.callbacks['update_weather_data']
)
tools_menu.add_command(
label="Upload CSV to corporate REST",
command=self.callbacks['upload_to_corporate_rest']
)
tools_menu.add_command(
label="Upload CSV to corporate FTP",
command=self.callbacks['upload_to_corporate_ftp']
)
self.add_cascade(label='Tools', menu=tools_menu)
# Window Menu
window_menu = tk.Menu(self, name='window', tearoff=False)
window_menu.add_command(
label="Record List",
command=self.callbacks['show_recordlist'],
accelerator="Cmd-L"
)
window_menu.add_command(
label="New Record",
command=self.callbacks['new_record'],
accelerator="Cmd-N"
)
self.add_cascade(label='Window', menu=window_menu)
def get_keybinds(self):
return {
'<Command-o>': self.callbacks['file->select'],
'<Command-n>': self.callbacks['new_record'],
'<Command-l>': self.callbacks['show_recordlist']
}
def get_main_menu_for_os(os_name):
menus = {
'Linux': LinuxMainMenu,
'Darwin': MacOsMainMenu,
'freebsd7': LinuxMainMenu,
'Windows': WindowsMainMenu
}
return menus.get(os_name, GenericMainMenu)
| [
"vibhutig@packtpub.com"
] | vibhutig@packtpub.com |
dd28d707952416bdc81300997ff938f57efdb5cc | 0910f22b83bc43252d57f876f2a6f8a6e9a888c4 | /shortest_chain.py | abc50ba84d9f554601586198842fa0d1db2aa157 | [] | no_license | priyankaauti123/Algo | ab12926efcb8821826066c296dc7d45a6e23b902 | 6a56b5133b4672448cc37789317966cf2e1f34ba | refs/heads/master | 2021-05-08T21:11:32.734211 | 2018-01-31T03:37:10 | 2018-01-31T03:37:10 | 119,630,775 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 859 | py | input_data=["POON","PLEE","SAME","POLE","POIE","PLEA","PLIE","POIN"]
start="TOON"
target="ZZZZ"
def search_start_with_arr(start,target,input_data,count):
j=0
#print start
for word in input_data:
cnt=0
j+=1
for letter in range(len(word)):
if word[letter]==start[letter]:
cnt+=1
else:
pass
if cnt>=3:
count+=1
start=word
input_data[j-1]=""
print start
if start==target:
# count+=1
# print start,target,count
print count
return
search_start_with_arr(start,target,input_data,count)
else:
pass
print "combination no"
return
count=1
search_start_with_arr(start,target,input_data,count)
#print count
| [
"priya@localhost.localdomain"
] | priya@localhost.localdomain |
7fdde892e2c0e0851f6916a5c570cff1a5cdc47c | ab156995505f1d732484a62306f01a8329657918 | /basedbot/confmgr.py | 8aa32bcc385a313f633c107792aef6ee2eae20d1 | [] | no_license | OnlyNightCoder/tumbot | 968d481fa09042550972082bc40a250cc485657f | 3d7bcf6387c2e8934f7059ebb439f85d114c52d7 | refs/heads/master | 2023-09-04T01:56:52.139602 | 2021-10-26T19:45:13 | 2021-10-26T19:45:13 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,939 | py | from enum import Enum
from typing import Optional
from .converter import converter_from_def
class UnregisteredVariableException(Exception):
""" Thrown when a non-existing configuration variable is queried """
class ConflictingVariableException(Exception):
""" Thrown when two different configuration variables are defined using the same name """
class ConfigAccessLevel(Enum):
""" Constants for configuration variable access levels """
ADMIN = 1
OWNER = 2
INTERNAL = 3
class ConfigVar:
""" A single configuration variable and its properties """
def __init__(self, db, name, default=None, access=ConfigAccessLevel.ADMIN,
description=None, scope='guild', conv=Optional[str]):
self._db = db
self.name = name
self.default = default
self.access = access
self.description = description
self.scope = scope
self.conv = converter_from_def(conv)
def get(self, ctx):
""" Gets the raw configuration value for a given context """
with self._db.get(ctx, self.scope) as db:
result = db.execute("SELECT value FROM config WHERE name = ?",
(self.name,)).fetchall()
if len(result) < 1:
return self.default
return str(result[0][0])
async def cget(self, ctx):
""" Gets the converted configuration value for a given context """
value = self.get(ctx)
return await self.conv.load(ctx, value)
def set(self, ctx, value):
""" Sets the raw configuration value for a given context """
with self._db.get(ctx, self.scope) as db:
db.execute("REPLACE INTO config (name, value) VALUES (?, ?)", (self.name, value))
async def cset(self, ctx, value):
""" Converts the given value and sets it for a given context """
value = await self.conv.store(ctx, value)
self.set(ctx, value)
def unset(self, ctx):
""" Resets the configuration variable to the default value """
with self._db.get(ctx, self.scope) as db:
db.execute("DELETE FROM config WHERE name = ?", (self.name,))
async def show(self, ctx):
""" Converts the stored value to a human-readable representation """
return await self.conv.show(ctx, self.get(ctx))
class ConfigManager:
""" Manages a collection of configuration variables """
def __init__(self, db):
self.db = db
self._vars = {}
def register(self, name, **kwargs):
""" Adds a new configuration variable with the given name and properties """
if name not in self._vars:
self._vars[name] = ConfigVar(self.db, name, **kwargs)
return self._vars[name]
existing = self._vars[name]
for key, value in kwargs.items():
if not hasattr(existing, key):
continue
if getattr(existing, key) != value:
raise ConflictingVariableException(f"Attribute `{key}` conflicts with "
f"existing variable definition.")
return self._vars[name]
@property
def registered_variables(self):
""" Returns the list of registered variables """
return self._vars.keys()
def var(self, name):
""" Gets the stored variable object for a given name """
if name not in self._vars:
raise UnregisteredVariableException(f"Variable `{name}` is not registered.")
return self._vars[name]
def get(self, ctx, name, **kwargs):
""" Legacy interface for getting raw configuration variable values """
existing = self.var(name)
return existing.get(ctx, **kwargs)
def set(self, ctx, name, **kwargs):
""" Legacy interface for setting raw configuration variable values """
existing = self.var(name)
existing.set(ctx, **kwargs)
| [
"timschumi@gmx.de"
] | timschumi@gmx.de |
f95b3ee3fe611007015802c0361cebe21cdbccd6 | 2b398353f5b0529ac666ef180e9dc966474a70c0 | /vspk/v6/nulink.py | 7802d9c7190be35e9f30fde7416b604ce123d54f | [
"BSD-3-Clause"
] | permissive | nuagenetworks/vspk-python | e0c4570be81da2a4d8946299cb44eaf9559e0170 | 9a44d3015aa6424d0154c8c8a42297669cce11f9 | refs/heads/master | 2023-06-01T01:12:47.011489 | 2023-05-12T19:48:52 | 2023-05-12T19:48:52 | 53,171,411 | 21 | 18 | BSD-3-Clause | 2020-12-16T12:36:58 | 2016-03-04T23:10:58 | Python | UTF-8 | Python | false | false | 19,510 | py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2015, Alcatel-Lucent Inc, 2017 Nokia
# 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 holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from .fetchers import NUDemarcationServicesFetcher
from .fetchers import NUPermissionsFetcher
from .fetchers import NUMetadatasFetcher
from .fetchers import NUNextHopsFetcher
from .fetchers import NUGlobalMetadatasFetcher
from .fetchers import NUPolicyStatementsFetcher
from .fetchers import NUCSNATPoolsFetcher
from .fetchers import NUPSNATPoolsFetcher
from .fetchers import NUOverlayAddressPoolsFetcher
from bambou import NURESTObject
class NULink(NURESTObject):
""" Represents a Link in the VSD
Notes:
Border router links provide a way to interconnect VNS domains in the wide-area to datacenter domains. Service chaining links allow domain leaking in order to simplify and enhance capabilities of doing service chaining and traffic steering for NFV and service-provider-grade VPN services.
"""
__rest_name__ = "link"
__resource_name__ = "links"
## Constants
CONST_ASSOCIATED_DESTINATION_TYPE_DOMAIN = "DOMAIN"
CONST_TYPE_BORDER_ROUTER = "BORDER_ROUTER"
CONST_TYPE_SERVICE_CHAINING = "SERVICE_CHAINING"
CONST_ENTITY_SCOPE_GLOBAL = "GLOBAL"
CONST_TYPE_OVERLAY_ADDRESS_TRANSLATION = "OVERLAY_ADDRESS_TRANSLATION"
CONST_ACCEPTANCE_CRITERIA_SUBNETS_ONLY = "SUBNETS_ONLY"
CONST_ENTITY_SCOPE_ENTERPRISE = "ENTERPRISE"
CONST_ACCEPTANCE_CRITERIA_ALL = "ALL"
CONST_TYPE_BIDIR = "BIDIR"
CONST_TYPE_HUB_AND_SPOKE = "HUB_AND_SPOKE"
def __init__(self, **kwargs):
""" Initializes a Link instance
Notes:
You can specify all parameters while calling this methods.
A special argument named `data` will enable you to load the
object from a Python dictionary
Examples:
>>> link = NULink(id=u'xxxx-xxx-xxx-xxx', name=u'Link')
>>> link = NULink(data=my_dict)
"""
super(NULink, self).__init__()
# Read/Write Attributes
self._last_updated_by = None
self._last_updated_date = None
self._acceptance_criteria = None
self._read_only = None
self._embedded_metadata = None
self._entity_scope = None
self._creation_date = None
self._associated_destination_id = None
self._associated_destination_name = None
self._associated_destination_type = None
self._associated_source_id = None
self._associated_source_name = None
self._associated_source_type = None
self._owner = None
self._external_id = None
self._type = None
self.expose_attribute(local_name="last_updated_by", remote_name="lastUpdatedBy", attribute_type=str, is_required=False, is_unique=False)
self.expose_attribute(local_name="last_updated_date", remote_name="lastUpdatedDate", attribute_type=str, is_required=False, is_unique=False)
self.expose_attribute(local_name="acceptance_criteria", remote_name="acceptanceCriteria", attribute_type=str, is_required=False, is_unique=False, choices=[u'ALL', u'SUBNETS_ONLY'])
self.expose_attribute(local_name="read_only", remote_name="readOnly", attribute_type=bool, is_required=False, is_unique=False)
self.expose_attribute(local_name="embedded_metadata", remote_name="embeddedMetadata", attribute_type=list, is_required=False, is_unique=False)
self.expose_attribute(local_name="entity_scope", remote_name="entityScope", attribute_type=str, is_required=False, is_unique=False, choices=[u'ENTERPRISE', u'GLOBAL'])
self.expose_attribute(local_name="creation_date", remote_name="creationDate", attribute_type=str, is_required=False, is_unique=False)
self.expose_attribute(local_name="associated_destination_id", remote_name="associatedDestinationID", attribute_type=str, is_required=False, is_unique=False)
self.expose_attribute(local_name="associated_destination_name", remote_name="associatedDestinationName", attribute_type=str, is_required=False, is_unique=False)
self.expose_attribute(local_name="associated_destination_type", remote_name="associatedDestinationType", attribute_type=str, is_required=False, is_unique=False, choices=[u'DOMAIN'])
self.expose_attribute(local_name="associated_source_id", remote_name="associatedSourceID", attribute_type=str, is_required=False, is_unique=False)
self.expose_attribute(local_name="associated_source_name", remote_name="associatedSourceName", attribute_type=str, is_required=False, is_unique=False)
self.expose_attribute(local_name="associated_source_type", remote_name="associatedSourceType", attribute_type=str, is_required=False, is_unique=False)
self.expose_attribute(local_name="owner", remote_name="owner", attribute_type=str, is_required=False, is_unique=False)
self.expose_attribute(local_name="external_id", remote_name="externalID", attribute_type=str, is_required=False, is_unique=True)
self.expose_attribute(local_name="type", remote_name="type", attribute_type=str, is_required=False, is_unique=False, choices=[u'BIDIR', u'BORDER_ROUTER', u'HUB_AND_SPOKE', u'OVERLAY_ADDRESS_TRANSLATION', u'SERVICE_CHAINING'])
# Fetchers
self.demarcation_services = NUDemarcationServicesFetcher.fetcher_with_object(parent_object=self, relationship="child")
self.permissions = NUPermissionsFetcher.fetcher_with_object(parent_object=self, relationship="child")
self.metadatas = NUMetadatasFetcher.fetcher_with_object(parent_object=self, relationship="child")
self.next_hops = NUNextHopsFetcher.fetcher_with_object(parent_object=self, relationship="child")
self.global_metadatas = NUGlobalMetadatasFetcher.fetcher_with_object(parent_object=self, relationship="child")
self.policy_statements = NUPolicyStatementsFetcher.fetcher_with_object(parent_object=self, relationship="child")
self.csnat_pools = NUCSNATPoolsFetcher.fetcher_with_object(parent_object=self, relationship="child")
self.psnat_pools = NUPSNATPoolsFetcher.fetcher_with_object(parent_object=self, relationship="child")
self.overlay_address_pools = NUOverlayAddressPoolsFetcher.fetcher_with_object(parent_object=self, relationship="child")
self._compute_args(**kwargs)
# Properties
@property
def last_updated_by(self):
""" Get last_updated_by value.
Notes:
ID of the user who last updated the object.
This attribute is named `lastUpdatedBy` in VSD API.
"""
return self._last_updated_by
@last_updated_by.setter
def last_updated_by(self, value):
""" Set last_updated_by value.
Notes:
ID of the user who last updated the object.
This attribute is named `lastUpdatedBy` in VSD API.
"""
self._last_updated_by = value
@property
def last_updated_date(self):
""" Get last_updated_date value.
Notes:
Time stamp when this object was last updated.
This attribute is named `lastUpdatedDate` in VSD API.
"""
return self._last_updated_date
@last_updated_date.setter
def last_updated_date(self, value):
""" Set last_updated_date value.
Notes:
Time stamp when this object was last updated.
This attribute is named `lastUpdatedDate` in VSD API.
"""
self._last_updated_date = value
@property
def acceptance_criteria(self):
""" Get acceptance_criteria value.
Notes:
A route filtering criteria enum. Defaults to ALL.
This attribute is named `acceptanceCriteria` in VSD API.
"""
return self._acceptance_criteria
@acceptance_criteria.setter
def acceptance_criteria(self, value):
""" Set acceptance_criteria value.
Notes:
A route filtering criteria enum. Defaults to ALL.
This attribute is named `acceptanceCriteria` in VSD API.
"""
self._acceptance_criteria = value
@property
def read_only(self):
""" Get read_only value.
Notes:
This is set to true if a link has been created in the opposite direction
This attribute is named `readOnly` in VSD API.
"""
return self._read_only
@read_only.setter
def read_only(self, value):
""" Set read_only value.
Notes:
This is set to true if a link has been created in the opposite direction
This attribute is named `readOnly` in VSD API.
"""
self._read_only = value
@property
def embedded_metadata(self):
""" Get embedded_metadata value.
Notes:
Metadata objects associated with this entity. This will contain a list of Metadata objects if the API request is made using the special flag to enable the embedded Metadata feature. Only a maximum of Metadata objects is returned based on the value set in the system configuration.
This attribute is named `embeddedMetadata` in VSD API.
"""
return self._embedded_metadata
@embedded_metadata.setter
def embedded_metadata(self, value):
""" Set embedded_metadata value.
Notes:
Metadata objects associated with this entity. This will contain a list of Metadata objects if the API request is made using the special flag to enable the embedded Metadata feature. Only a maximum of Metadata objects is returned based on the value set in the system configuration.
This attribute is named `embeddedMetadata` in VSD API.
"""
self._embedded_metadata = value
@property
def entity_scope(self):
""" Get entity_scope value.
Notes:
Specify if scope of entity is Data center or Enterprise level
This attribute is named `entityScope` in VSD API.
"""
return self._entity_scope
@entity_scope.setter
def entity_scope(self, value):
""" Set entity_scope value.
Notes:
Specify if scope of entity is Data center or Enterprise level
This attribute is named `entityScope` in VSD API.
"""
self._entity_scope = value
@property
def creation_date(self):
""" Get creation_date value.
Notes:
Time stamp when this object was created.
This attribute is named `creationDate` in VSD API.
"""
return self._creation_date
@creation_date.setter
def creation_date(self, value):
""" Set creation_date value.
Notes:
Time stamp when this object was created.
This attribute is named `creationDate` in VSD API.
"""
self._creation_date = value
@property
def associated_destination_id(self):
""" Get associated_destination_id value.
Notes:
This is the ID of the domain receiving the routes from the source. This can only be set for links of type OVERLAY_ADDRESS_TRANSLATION.
This attribute is named `associatedDestinationID` in VSD API.
"""
return self._associated_destination_id
@associated_destination_id.setter
def associated_destination_id(self, value):
""" Set associated_destination_id value.
Notes:
This is the ID of the domain receiving the routes from the source. This can only be set for links of type OVERLAY_ADDRESS_TRANSLATION.
This attribute is named `associatedDestinationID` in VSD API.
"""
self._associated_destination_id = value
@property
def associated_destination_name(self):
""" Get associated_destination_name value.
Notes:
None
This attribute is named `associatedDestinationName` in VSD API.
"""
return self._associated_destination_name
@associated_destination_name.setter
def associated_destination_name(self, value):
""" Set associated_destination_name value.
Notes:
None
This attribute is named `associatedDestinationName` in VSD API.
"""
self._associated_destination_name = value
@property
def associated_destination_type(self):
""" Get associated_destination_type value.
Notes:
Type of the entity type for the source
This attribute is named `associatedDestinationType` in VSD API.
"""
return self._associated_destination_type
@associated_destination_type.setter
def associated_destination_type(self, value):
""" Set associated_destination_type value.
Notes:
Type of the entity type for the source
This attribute is named `associatedDestinationType` in VSD API.
"""
self._associated_destination_type = value
@property
def associated_source_id(self):
""" Get associated_source_id value.
Notes:
The ID of the domain receiving the routes from another domain
This attribute is named `associatedSourceID` in VSD API.
"""
return self._associated_source_id
@associated_source_id.setter
def associated_source_id(self, value):
""" Set associated_source_id value.
Notes:
The ID of the domain receiving the routes from another domain
This attribute is named `associatedSourceID` in VSD API.
"""
self._associated_source_id = value
@property
def associated_source_name(self):
""" Get associated_source_name value.
Notes:
None
This attribute is named `associatedSourceName` in VSD API.
"""
return self._associated_source_name
@associated_source_name.setter
def associated_source_name(self, value):
""" Set associated_source_name value.
Notes:
None
This attribute is named `associatedSourceName` in VSD API.
"""
self._associated_source_name = value
@property
def associated_source_type(self):
""" Get associated_source_type value.
Notes:
This is the source object type for the associatedSourceID
This attribute is named `associatedSourceType` in VSD API.
"""
return self._associated_source_type
@associated_source_type.setter
def associated_source_type(self, value):
""" Set associated_source_type value.
Notes:
This is the source object type for the associatedSourceID
This attribute is named `associatedSourceType` in VSD API.
"""
self._associated_source_type = value
@property
def owner(self):
""" Get owner value.
Notes:
Identifies the user that has created this object.
"""
return self._owner
@owner.setter
def owner(self, value):
""" Set owner value.
Notes:
Identifies the user that has created this object.
"""
self._owner = value
@property
def external_id(self):
""" Get external_id value.
Notes:
External object ID. Used for integration with third party systems
This attribute is named `externalID` in VSD API.
"""
return self._external_id
@external_id.setter
def external_id(self, value):
""" Set external_id value.
Notes:
External object ID. Used for integration with third party systems
This attribute is named `externalID` in VSD API.
"""
self._external_id = value
@property
def type(self):
""" Get type value.
Notes:
This is used to distinguish between different type of links: hub and spoke, IP address, VNS border router links.
"""
return self._type
@type.setter
def type(self, value):
""" Set type value.
Notes:
This is used to distinguish between different type of links: hub and spoke, IP address, VNS border router links.
"""
self._type = value
| [
"corentin.henry@nokia.com"
] | corentin.henry@nokia.com |
05f5b4b803f832e142b31039492bf546a7f2bcbe | 1a86700d558fe8f174afbf100c9c65290ccb7de6 | /src/adnymics/munging_pipeline.py | f1db02524ee1903e4d5a0b90f1113aeb29066c2e | [
"MIT"
] | permissive | juls-dotcom/adnymics | ad914ac119ed404706ec30f51ae37e654035b116 | 40ad2f7679e3438a5257735c8f9ebb50f363c318 | refs/heads/master | 2021-05-16T23:38:37.092101 | 2020-03-27T15:21:35 | 2020-03-27T15:21:35 | 250,519,262 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,788 | py | import pandas as pd
# Extract coupon codes
def extract_coupons(dataf):
"""
This function extract coupon as pd.Series and concatenates
Parameters:
dataf (pandas dataframe), which contains main data
Returns
dataf (pandas dataframe), which contains main data
Julien Hernandez Lallement
ORSAY, Willstaett, Germany
11-12-2019
"""
coupon_code = pd.DataFrame(dataf['coupon_code']
.apply(pd.Series))
return pd.concat([dataf, coupon_code], axis=1, join='outer').reset_index(drop=True)
# Extract item_numbers
def extract_item_number(dataf):
"""
This function extract each of the 4 items into separate columns
Parameters:
dataf (pandas dataframe), which contains main data
Returns
dataf (pandas dataframe), which contains main data
Julien Hernandez Lallement
ORSAY, Willstaett, Germany
11-12-2019
"""
item_number = pd.DataFrame(dataf['recommendations']
.apply(pd.Series)).T
dataf = (dataf
.assign(item_0=item_number.apply(pd.Series).iloc[0].apply(pd.Series)['item_number'])
.assign(item_1=item_number.apply(pd.Series).iloc[1].apply(pd.Series)['item_number'])
.assign(item_2=item_number.apply(pd.Series).iloc[2].apply(pd.Series)['item_number'])
.assign(item_3=item_number.apply(pd.Series).iloc[3].apply(pd.Series)['item_number'])
)
return dataf.reset_index()
# Clean dataset
def drop_cols(dataf):
"""
This function drops columns
Parameters:
dataf (pandas dataframe), which contains main data
Returns
dataf (pandas dataframe), which contains main data
Julien Hernandez Lallement
ORSAY, Willstaett, Germany
11-12-2019
"""
dataf = dataf.drop(columns=['recommendations',
'index',
'coupon_code',
'language', ])
# 'is_printed'])
return dataf
def split_data(dataf):
"""
This function splits the data into printed & not printed in separate dataframes
Parameters:
dataf (pandas dataframe), which contains main data
Returns
data_false (pandas dataframe), which contains not printed data
data_true (pandas dataframe), which contains printed data
Julien Hernandez Lallement
ORSAY, Willstaett, Germany
11-12-2019
"""
data_false = dataf.loc[dataf['is_printed'] == False].drop(columns={'is_printed'})
# data_false = data_false.drop(columns = {'is_printed'})
data_true = dataf.loc[dataf['is_printed'] == True].drop(columns={'is_printed'})
# data_true = data_true.drop(columns = {'is_printed'})
return data_false, data_true
| [
"Julien.Hernandez-lallement@orsay.com"
] | Julien.Hernandez-lallement@orsay.com |
3f7aea8dd45ab64b5359dbe2fce4e42044a15399 | 233fd5199c4fff7e44510ff011e6d49b7a598b63 | /functions.py | ff227676a2a1606c416b93319843a3eb3bd41f3c | [] | no_license | ashana03060907/collaborative-filtering-python | b0ca9fc42a5a1960b52c6e7b1e5ac6bb1c87eefb | 8196bce6135bc42a40b36c2f7a1c214dddcf09b1 | refs/heads/master | 2022-04-04T03:40:34.452032 | 2020-02-14T12:38:03 | 2020-02-14T12:38:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,657 | py | import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from string import ascii_letters, digits
from surprise.model_selection import cross_validate
### DataFrame operations
def k_from_details(details):
try:
return details['actual_k']
except KeyError:
return 1000
def short_title(title, max_len=40):
title = str(title).split(' ')
short_title = ''
for i in range(len(title)):
if len(short_title) < max_len:
short_title = ' '.join([short_title, title[i]])
short_title = short_title.strip()
return short_title
def ascii_check(item):
for letter in str(item):
if letter not in ascii_letters + digits:
return 1
else:
return 0
def ascii_check_bulk(df):
for col in df.columns:
print('items with non-ascii characters in %s: %d' % (col, df[col].apply(ascii_check).sum()))
print('')
def colname_fix(colname):
return colname.lower().replace('-','_')
### New DataFrames
def df_dist(df, colname, norm=False):
new_df = df[colname].value_counts(normalize=norm).reset_index()
new_df.columns = [colname, 'count']
return new_df
def books_groupby(df, column, new_colname):
df_groupby = df.groupby(column).agg({'isbn': 'count', 'book_rating': 'mean'}).reset_index()
df_groupby.columns = [new_colname, 'count', 'avg_rating']
return df_groupby
### Visualizations
def draw_distribution(data, title_part, threshold=20):
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(14, 4))
sns.distplot(data['count'], color='#2f6194', ax=ax1)
ax1.set_title('Distribution of number of ratings per %s' % title_part)
sns.countplot(data[data['count']<=threshold]['count'], color='#2f6194', ax=ax2)
ax2.set_title('Distribution of number of ratings per %s (<= %d ratings)' % (title_part, threshold))
plt.show()
def draw_top_chart(data, x, y_list, title):
fig, ax1 = plt.subplots(figsize=(14, 6))
plt.xticks(rotation=90)
palette = sns.color_palette("RdBu", len(data))
sns.barplot(x=x, y=y_list[0], data=data, palette=palette, ax=ax1)
ax1.set_title(title)
ax2 = ax1.twinx()
sns.scatterplot(x=x, y=y_list[1], data=data, color='black', ax=ax2)
plt.show()
### Model-related functions
def get_model_name(model):
return str(model).split('.')[-1].split(' ')[0].replace("'>", "")
def cv_multiple_models(data, models_dict, cv=3):
results = pd.DataFrame()
for model_name, model in models_dict.items():
print('\n---> CV for %s...' % model_name)
cv_results = cross_validate(model, data, cv=cv)
tmp = pd.DataFrame(cv_results).mean()
tmp['model'] = model_name
results = results.append(tmp, ignore_index=True)
return results
def generate_models_dict(models, sim_names, user_based):
models_dict = {}
for sim_name in sim_names:
sim_dict = {
'name': sim_name,
'user_based': user_based
}
for model in models:
model_name = get_model_name(model) + ' ' + sim_name
models_dict[model_name] = model(sim_options=sim_dict)
return models_dict
def draw_model_results(results):
fig, ax1 = plt.subplots(figsize=(10, 6))
plt.xticks(rotation=90)
palette = sns.color_palette("RdBu", len(results))
sns.barplot(x='model', y='test_rmse', data=results, palette=palette, ax=ax1)
ax1.set_title('Test RMSE and fit time of evaluated models')
ax2 = ax1.twinx()
sns.scatterplot(x='model', y='fit_time', data=results, color='black', ax=ax2)
ax2.set(ylim=(0, results['fit_time'].max() * 1.1))
plt.show() | [
"klaudia.nazarko+data@gmail.com"
] | klaudia.nazarko+data@gmail.com |
a26339c88ad3939115cd0cd0d9cdc11b37c13c62 | 2ac24e7f7f13cbd7dd715eb8b0607266bf7eb97e | /alltours_tsp.py | ad2cb99a2d38e1102e5ef5dc2f05d565a8a84204 | [] | no_license | downingstreet/Travelling-Salesman | e03eecaa258fc47fbec95ce29c812379afd1b318 | 924b4928679c06d92d21d41d9d50b9418f23b8ff | refs/heads/master | 2020-04-24T23:28:42.045167 | 2015-05-10T20:49:06 | 2015-05-10T20:49:06 | 35,387,267 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 405 | py | import tsp
def alltours_tsp(cities):
#Generate all possible tours of the cities
#and choose the shortest tour.
return shortest_tour(alltours(cities))
def alltours(cities):
#Return a list of tours, each a permutation of cities,
#but each one starting with the same city.
start = first(cities)
Tour = list
return [[start] + Tour(rest)
for rest in itertools.permutations(cities - {start})]
| [
"simba@Varuns-MacBook-Air.local"
] | simba@Varuns-MacBook-Air.local |
fac9d6b19b17e6d66d78e7e4b7b2a75719067a7c | 5e1e0b9a87fd888a195785b38ec520bc496f4f5b | /main.py | c0f1ae8ca2bddd140c83fdaa54c3da59c4bb421c | [
"MIT"
] | permissive | ztt0810/general_img_cls_template | 4a8476692cd15bc5f1042c7ecfb358af4c763114 | 2ae164d14e1abca1cdcf327acf306dd0415fd3ac | refs/heads/main | 2023-04-20T18:29:59.903589 | 2021-05-11T06:33:24 | 2021-05-11T06:33:24 | 343,769,297 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 887 | py | from tools import Trainer
from tools import Inference
from config import Config
import argparse
def cmd_param():
parser = argparse.ArgumentParser()
parser.add_argument('--train', type=bool, default=True, help='start training')
parser.add_argument('--test', type=bool, default=True, help='test and get the result')
parser.add_argument('--use_tta', type=bool, default=False, help='use test time augmentation')
# parser.add_argument('--mix_prec', type=bool, default=False, help='train with mixed precision')
return parser.parse_args()
def _main():
opt = cmd_param()
if opt.train:
trainer = Trainer()
trainer.run_train()
if opt.test:
if opt.use_tta:
pass
else:
infer = Inference(Config.load_model)
infer.predict()
if __name__ == '__main__':
_main() | [
"1963016648@qq.com"
] | 1963016648@qq.com |
0f0e568fe9e6739b7988322ffa85007a00d95efd | 523bfc73dcad5bcec5c143af6594854bdd2b8879 | /Python-164/chapter.4/lab4.13/lab_program.py | 3c65c8ba4f36bb8d4a2aed78fc8729257bd76f92 | [] | no_license | Treelovah/Colorado-State-University | 2355383b235f339337a7052a8e13833396fec274 | 495ad8114894676529183859199ca4485a19fdaf | refs/heads/master | 2023-02-26T07:44:38.254487 | 2021-02-02T00:41:36 | 2021-02-02T00:41:36 | 279,498,923 | 0 | 0 | null | 2020-10-15T18:18:47 | 2020-07-14T06:13:21 | Java | UTF-8 | Python | false | false | 764 | py | # Instructions are imported from java 164 class
# The syntax && logic flow might not follow exact instructions.
'''
/*
One lap around a standard high-school running track is exactly 0.25 miles. Write a program that takes a number of miles as input, and outputs the number of laps.
Output each floating-point value with two digits after the decimal point, which can be achieved as follows:
System.out.printf("%.2f", yourValue);
Ex: If the input is:
1.5
the output is:
6.00
Ex: If the input is:
2.2
the output is:
8.80
Your program must define and call a method:
public static double milesToLaps(double userMiles)
*/
'''
def milesToLaps(userMiles):
return float(userMiles) / .25
def main():
print("{:0.2f}".format(milesToLaps(input())))
main() | [
"mltechi@pm.me"
] | mltechi@pm.me |
302ab075f44fb0f900ecba2daf05cad108a223eb | b0d53f7062f6fa8ead5325be8c26e1eafab9ba13 | /dbmodels/dictionaries/season_type.py | 4bcf73554ba12b522e10e4156c9c80610bb0b4eb | [] | no_license | eta-development-team/poweraccounting | 004fc7d47e0bf27c15019ab80c974f3797d4b18f | cc2e9bc9b644d8c9e8efe4f7b3d7b7fe4246e951 | refs/heads/master | 2020-07-13T21:59:06.243050 | 2019-09-03T19:05:32 | 2019-09-03T19:05:32 | 205,148,941 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 172 | py | from dbaccess.dbcontext import Base
from dbmodels.abstract.dictionary_base import DictionaryBase
class SeasonType(DictionaryBase, Base):
__tablename__ = "SeasonType"
| [
"eta.development.leo@outlook.com"
] | eta.development.leo@outlook.com |
7bd2cd396668704600a2866c5f2ccab656f178e6 | d402e0b476f4383adf8036ba03ab41000d65a743 | /eval.py | ae78f76354902eb730b83ad45518f0eec0fe01ad | [] | no_license | psungu/Multi-Layer-Perceptron-From-Scratch | 13094480b8b07364ca9e36d3bfe8b282f424d667 | 5ca284b7f5fbc0e914d7c81601991f966a968488 | refs/heads/main | 2023-04-16T04:31:23.858050 | 2021-05-02T15:10:09 | 2021-05-02T15:10:09 | 356,641,151 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,717 | py | import numpy as np
import pickle
def read_data():
X = np.load('test_inputs.npy')
Y = np.load('test_targets.npy')
codebook = np.load('vocab.npy')
word1_target = X[:,0].reshape(-1)
Word1_encoding = np.eye(len(codebook))[word1_target]
word2_target = X[:,1].reshape(-1)
Word2_encoding = np.eye(len(codebook))[word2_target]
word3_target = X[:,2].reshape(-1)
Word3_encoding = np.eye(len(codebook))[word3_target]
return Word1_encoding, Word2_encoding, Word3_encoding, Y, codebook
def load_model(path):
file = open("modelweights.pkl",'rb')
object_file = pickle.load(file)
return object_file
Word1_encoding, Word2_encoding, Word3_encoding, Word4, codebook = read_data()
model = load_model("./")
def softmax(Z):
expZ = np.exp(Z - np.max(Z))
return expZ / expZ.sum(axis=0, keepdims=True)
def sigmoid(S):
return (1 / (1 + np.exp(-S)))
def predict(model, Word1_encoding, Word2_encoding, Word3_encoding):
embedding_layer1 = model[0] @ Word1_encoding.T
embedding_layer2 = model[0] @ Word2_encoding.T
embedding_layer3 = model[0] @ Word3_encoding.T
H1 = model[1] @ embedding_layer1
H2 = model[2] @ embedding_layer2
H3 = model[3] @ embedding_layer3
hidden_layer = sigmoid(H1+H2+H3 + model[5])
prediction = softmax(model[4] @ hidden_layer + model[6])
return prediction
def calculate_accuracy(target):
prediction = predict(model, Word1_encoding, Word2_encoding, Word3_encoding)
predict_index = np.argmax(prediction, axis=0)
counter = 0
for j in range(len(target)):
if (target[j] == predict_index[j]):
counter+=1
return counter/len(target)
def predict_given_sequence(X1, X2, X3, codebook, model):
Word1_encoding = np.zeros([1,250])
Word2_encoding = np.zeros([1,250])
Word3_encoding = np.zeros([1,250])
X1_ind=np.where(codebook == X1)[0][0]
X2_ind=np.where(codebook == X2)[0][0]
X3_ind=np.where(codebook == X3)[0][0]
Word1_encoding[:,X1_ind] = 1
Word2_encoding[:,X2_ind] = 1
Word3_encoding[:,X3_ind] = 1
prediction = predict(model, Word1_encoding, Word2_encoding, Word3_encoding)
result_ind = np.argmax(prediction)
return codebook[result_ind]
accuracy = calculate_accuracy(Word4)
print("Test accuracy is: {0}".format(accuracy))
text_result1 = predict_given_sequence("city", "of", "new", codebook, model)
print("city of new: {0}".format(text_result1))
text_result2 = predict_given_sequence("life", "in", "the", codebook, model)
print("life in the: {0}".format(text_result2))
text_result3 = predict_given_sequence("he", "is", "the", codebook, model)
print("he is the: {0}".format(text_result3))
| [
"psungu@ku.edu.tr"
] | psungu@ku.edu.tr |
e7fe710c9c2d6ebda3fbd6abeb440116a6fe2d4b | 90c6262664d013d47e9a3a9194aa7a366d1cabc4 | /tests/storage/cases/test_KT1EyeTPvtVgJHhrUaVSNQo75AKQZSGwu9aM.py | 4057d7a5c0281d83115c8389161a41dd451ce6df | [
"MIT"
] | permissive | tqtezos/pytezos | 3942fdab7aa7851e9ea81350fa360180229ec082 | a4ac0b022d35d4c9f3062609d8ce09d584b5faa8 | refs/heads/master | 2021-07-10T12:24:24.069256 | 2020-04-04T12:46:24 | 2020-04-04T12:46:24 | 227,664,211 | 1 | 0 | MIT | 2020-12-30T16:44:56 | 2019-12-12T17:47:53 | Python | UTF-8 | Python | false | false | 1,130 | py | from unittest import TestCase
from tests import get_data
from pytezos.michelson.converter import build_schema, decode_micheline, encode_micheline, micheline_to_michelson
class StorageTestKT1EyeTPvtVgJHhrUaVSNQo75AKQZSGwu9aM(TestCase):
@classmethod
def setUpClass(cls):
cls.maxDiff = None
cls.contract = get_data('storage/zeronet/KT1EyeTPvtVgJHhrUaVSNQo75AKQZSGwu9aM.json')
def test_storage_encoding_KT1EyeTPvtVgJHhrUaVSNQo75AKQZSGwu9aM(self):
type_expr = self.contract['script']['code'][1]
val_expr = self.contract['script']['storage']
schema = build_schema(type_expr)
decoded = decode_micheline(val_expr, type_expr, schema)
actual = encode_micheline(decoded, schema)
self.assertEqual(val_expr, actual)
def test_storage_schema_KT1EyeTPvtVgJHhrUaVSNQo75AKQZSGwu9aM(self):
_ = build_schema(self.contract['script']['code'][0])
def test_storage_format_KT1EyeTPvtVgJHhrUaVSNQo75AKQZSGwu9aM(self):
_ = micheline_to_michelson(self.contract['script']['code'])
_ = micheline_to_michelson(self.contract['script']['storage'])
| [
"mz@baking-bad.org"
] | mz@baking-bad.org |
cf40ffeb60f9a5f0ec2ecf352aa3ba3e6b7cf2ef | d5eadb8842addba288be849d3b8da61d788e3722 | /workers/oldclassifier/config.py | 6c39b168f4fbfd5a6c1d4b1281227f6594b744f0 | [] | no_license | kslat3r/consensus | 01266e96e0c2ffedb03f75cf009e2ce07e8e13ff | d675414331bce56c83693ae452de688e46d226f7 | refs/heads/master | 2021-01-01T03:35:11.650305 | 2016-11-12T13:29:40 | 2016-11-12T13:29:40 | 58,327,008 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 138 | py | class Mongo:
host = 'dharma.mongohq.com'
port = 10026
username = 'consensus'
password = 'A9RD9PXT'
db_name = 'app16750045' | [
"me@edkelly.co.uk"
] | me@edkelly.co.uk |
43aae0f35f4646fd503cc7b38f744584ccd1400b | e3c3f9d061afd64a6a007d4e5217fae7ab4eed33 | /commondtools/filehandling/csvmanager.py | 1b93bafe0e2b6ae23e37104e5e99efa4449a397a | [
"MIT"
] | permissive | M0Rph3U56031769/commondtools | fb683de3c7984ca9d3210ad48739c59847b5606c | 297271d731a8fbd11b797ecdcd9eaf738017616e | refs/heads/master | 2023-08-04T18:31:48.239497 | 2023-03-16T20:52:03 | 2023-03-16T20:52:03 | 236,422,761 | 1 | 0 | MIT | 2023-08-01T23:32:35 | 2020-01-27T05:02:42 | Python | UTF-8 | Python | false | false | 3,980 | py | """
Managing csv files with data type(float, str) validator
"""
import csv
import logging
import sys
from os import listdir
from os.path import isfile, join
import pandas as pd
class CSVManager:
"""
CSVManager is able to handle easily csv files with validation.
"""
csv_path: str
csv_files: list
logger = logging.getLogger('Importer')
handler = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
def __init__(self, current_path: str):
self.csv_path = current_path
self.logger.setLevel(logging.DEBUG)
self.handler.setLevel(logging.INFO)
self.handler.setFormatter(self.formatter)
self.logger.addHandler(self.handler)
def get_all_data_as_list(self):
"""
Getting all the csv data as a list.
:return: all the csv content in a list.
"""
return self.read_all_csv()
def get_csv_files(self): # pragma: no cover
"""
Get the list of csv file names
:return: list of csv file names
"""
module_path = self.csv_path
csv_files = [f for f in listdir(module_path) if isfile(join(module_path, f))
and ".csv" in f]
self.csv_files = list(csv_files)
return csv_files
def check_csv_for_diff_types(self, csv_reader: list):
"""
Checking for different types in rows
NOTE: only checking str and float types (no datetime and such)
NOTE2: sale/incoming can be used as a boolean type
:param csv_reader: csv file content
:type csv_reader: list
:return: Bool
"""
self.logger.debug(csv_reader)
# read content by rows without header
dataframe = pd.DataFrame(csv_reader)
columns = []
for column_name in dataframe.columns.array:
columns.append(dataframe[column_name].to_numpy())
for column in columns:
data_type = ''
for cell in column:
try:
float(cell)
data_type = 'float'
except ValueError:
if data_type == 'float':
logging.error('cannot convert to a float: ' + str(cell))
return False
return True
def check_csv_for_empty_cells(self, csv_reader: list):
"""
Checking for empty cells
:param csv_reader: csv file content
:type csv_reader: list
:return: Bool: integrity
"""
self.logger.debug(csv_reader)
integrity = True
for row in csv_reader:
for cell in row:
if cell in (None, ""):
logging.error("Empty cell found at: " + str(row))
integrity = False
return integrity
def read_all_csv(self):
"""
reading all csv files
:return: list: all the csv contents in a list
"""
content = []
try:
self.get_csv_files()
except AttributeError:
self.get_csv_files()
self.logger.debug(self.csv_files)
for file in self.csv_files:
print(file)
content.append(self.read_csv_file(file=file))
return content
def read_csv_file(self, file: str):
"""
read the content of a single csv file
:param file: csv file name
:type file: str
:return: list: csv content
"""
content = []
with open(self.csv_path + "/" + file, 'r') as csv_file:
csv_reader = csv.reader(csv_file)
self.check_csv_for_empty_cells(csv_reader=list(csv_reader))
self.check_csv_for_diff_types(csv_reader=list(csv_reader))
with open(self.csv_path + "/" + file, 'r') as csv_file:
for row in csv.reader(csv_file):
content.append(row)
return content
| [
"nagydaniel1337@gmail.com"
] | nagydaniel1337@gmail.com |
4585344632ff740555f8db7cd149794e566b2a04 | 7ab987d420aae51f70981899c3d4305f8a31a00a | /adminzone/models.py | f32e8ba333395f98a2d3c1b3ca100590b0e7b488 | [] | no_license | vishalsrivastava99/speedex.github.io | c4cde1204a847c4879c5ccfbc64277e22e653f81 | 5eb1feb26a3fd7eafb4a4cce4c9c1f4aee364e5f | refs/heads/main | 2023-05-05T08:07:19.688891 | 2021-06-01T10:35:29 | 2021-06-01T10:35:29 | 301,391,512 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 800 | py | from django.db import models
# Create your models here.
class Notification(models.Model):
notificationtext=models.TextField()
posteddate=models.CharField(max_length=20)
class City(models.Model):
cityname=models.CharField(max_length=200)
class Consignment(models.Model):
refno=models.CharField(max_length=50,primary_key=True)
sendername=models.CharField(max_length=50)
senderaddress=models.TextField()
sendercontactno = models.CharField(max_length=15)
receivername=models.CharField(max_length=50)
receiveraddress=models.TextField()
source=models.CharField(max_length=200)
currentcity=models.CharField(max_length=200)
destination=models.CharField(max_length=200)
status=models.CharField(max_length=20)
posteddate=models.CharField(max_length=30)
| [
"vishalstu2017@gmail.com"
] | vishalstu2017@gmail.com |
44e13ba6e02675fd116c7dd58f4d358f5ff5f7b8 | 38e338b2878b0428d8b61fe11336b7ed938ce5fb | /examples/read_INA219.py | ba026254c35bb0ecab09333eb531f3bbc182e6b0 | [
"BSD-2-Clause"
] | permissive | GuenterQuast/PhyPiDAQ | a989008d2da57120927828ab70574b8f7a4d54ad | 476baab96e8e7311b686fddd3b9cea5ab59cebc6 | refs/heads/master | 2022-06-03T12:52:29.726274 | 2022-03-13T08:36:38 | 2022-03-13T08:36:38 | 140,086,415 | 8 | 16 | BSD-2-Clause | 2022-04-22T22:41:28 | 2018-07-07T13:23:49 | Python | UTF-8 | Python | false | false | 848 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''read data from digital sensor:
this script illustrates the general usage of package phypidaq
prints data read from a digital sensor
INA219 Current & Voltage sensor
'''
import time, numpy as np
# import module controlling readout device
from phypidaq.INA219Config import *
# create an instance of the device
cdict={'maxAmp': 0.1, 'maxVolt': 16.}
device = INA219Config(cdict)
# initialize the device
device.init()
# reserve space for data (two channels here)
dat = np.array([0., 0.])
print(' starting readout, type <ctrl-C> to stop')
# read-out interval in s
dt = 2.
# start time
T0 = time.time()
# readout loop, stop with <crtl>-C
while True:
device.acquireData(dat)
dT = time.time() - T0
print('%.2g, %.4gmA %.4gV' %(dT, dat[0], dat[1]) )
time.sleep(dt)
| [
"guenter.quast@online.de"
] | guenter.quast@online.de |
6f50d5f2a0f722718cb1480dd3c12c423f57a9ac | 5f13ce6fb06d86f99ddcc0d8aa16cc4817ec4b03 | /api.py | 9c029c70498dce7666c1bcb59689c55d50bada12 | [] | no_license | news-ai/news-processing | 1b59f17c24da9f48d35c09db64c98fca18471bb6 | 1b874e186f8b9d8510dd3b47a672a7c08f98e082 | refs/heads/master | 2021-03-19T16:42:57.783382 | 2016-06-11T18:26:31 | 2016-06-11T18:26:31 | 58,774,781 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,493 | py | # Stdlib imports
import logging
# Third-party app imports
from flask import Flask, request, jsonify
from flask.ext.cors import CORS
from flask_restful import Resource, Api, reqparse
from raven.contrib.flask import Sentry
# Imports from app
from middleware.config import (
SENTRY_USER,
SENTRY_PASSWORD,
SENTRY_APP_ID,
)
from processing.process_article import process_article
from taskrunner import app as celery_app
# Setting up Flask and API
app = Flask(__name__)
api = Api(app)
CORS(app)
# Setting up Sentry
sentry = Sentry(
app, dsn='https://' + SENTRY_USER + ':' + SENTRY_PASSWORD + '@app.getsentry.com/' + SENTRY_APP_ID)
logger = logging.getLogger("sentry.errors")
handler = logging.StreamHandler()
formatter = logging.Formatter("[%(levelname)s] %(name)s: %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
# Setting up parser
parser = reqparse.RequestParser()
parser.add_argument('url')
parser.add_argument('added_by')
parser.add_argument('rss_id')
# Route to POST data for news processing
class Processing(Resource):
def post(self):
args = parser.parse_args()
if 'added_by' in args and args['added_by'] is not None:
return process_article(args)
res = celery_app.send_task(
'processing.process_article.process_article', ([args]))
return jsonify({'id': res.task_id})
api.add_resource(Processing, '/processing')
if __name__ == '__main__':
app.run(port=int('8000'), debug=False)
| [
"me@abhiagarwal.com"
] | me@abhiagarwal.com |
5cd73ae6709a3381454fc929bbc69341835742df | 63f0d1df7e5407812e5f1fa2053adc6570d52127 | /class 9/dictionary.py | 9cc6be2826fbdbdf0e02c626b85da127a853bd9d | [] | no_license | Nalinswarup123/python | d5012c8c3030fbd82a01445ce8a343afb06cdcd2 | 37c1c0d50115b82d7f11f65834da87b3f28b4051 | refs/heads/master | 2021-09-01T09:10:40.360738 | 2017-12-26T05:42:11 | 2017-12-26T05:42:11 | 115,388,078 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 410 | py | d={'vamsi':'bc','nalin':'chutiya','nalin':'9','akanksha':'sarjaa','akanksha':'marjaa'}
print(max(d.values()))
print(d.items())
print(sorted(d.values()))
#s={(0,3):1,(2,1):2,(4,4):3}
#print(s[(4,4)])
print(sorted(zip(d.values(),d.keys())))
print(min(d.values()))
d['vamsi']='mc'
print(d.items())
l=['1','2','3']
b=''.join(l)
print(b)
l.extend(['4','5'])
print(l)
l.append(['6','7'])
print(l)
| [
"noreply@github.com"
] | Nalinswarup123.noreply@github.com |
44850d3c9ff9ea00920d7afb229fd58dbca022c4 | a2a88ddd6debc302318cd900c2f21e5fe8923427 | /game_stats.py | afbf22f38b9ced9ccb7d0fc28e15e766a337e0db | [] | no_license | raymondbrianhernandez/voltes_v_crewzer | 4adb4a182f1855502dab51d876a3c108beb0fbc1 | a720cb1396e06a52017fb477be0cc9f931bb156d | refs/heads/main | 2023-01-07T03:30:31.546200 | 2020-11-05T01:50:44 | 2020-11-05T01:50:44 | 310,151,100 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 322 | py | class GameStats():
def __init__(self, ai_settings):
self.ai_settings = ai_settings
self.reset_stats()
self.game_active = False
self.high_score = 0
def reset_stats(self):
self.ships_left = self.ai_settings.ship_limit
self.score = 0
self.level = 1 | [
"noreply@github.com"
] | raymondbrianhernandez.noreply@github.com |
e43214c77952dce47e2d045ce472965f6df8b5c6 | 46371a22cd36a3914b4f9e13e3d0d29d3aba35bc | /problem1.py | 494dc2576c93e3dcfaaac95546bd9b31b25ceef6 | [] | no_license | archit-55/Python | da19f08d0e38b0e9446b3930e5cf1421b3c59982 | ba222e4c55fabfaa2cc62bae5d6162ecba9cd9ce | refs/heads/master | 2020-05-31T10:35:40.304096 | 2019-06-16T18:03:26 | 2019-06-16T18:03:26 | 190,243,757 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 238 | py | #!/usr/bin/python3
import datetime
name=input("Enter name:")
age=int(input("enter age:"))
print("Name:",name)
print("Age:",age)
x=95-age
current_year=datetime.datetime.now()
print("You will turn 95 in the year" ,x+current_year.year)
| [
"architagrawal55@gmail.com"
] | architagrawal55@gmail.com |
61278a8e0f81a93f5b6d2fa0a095f83a653c44c9 | e3dce7e01b7dfb8c6b413d9119390f3bcd93c7cd | /wunderground_pws.py | 2cc7b68f0e173833ca80eb620d9d3074b9f987c5 | [
"MIT"
] | permissive | lfhohmann/wunderground-pws | 5d3ab142f797dbea61ac48d8f8afa683be9c882e | b3d95b8facb41ba7c18b7efccc7cd8e45bb16393 | refs/heads/main | 2023-05-11T05:21:52.421666 | 2021-05-29T14:57:06 | 2021-05-29T14:57:06 | 371,988,066 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 10,011 | py | from bs4 import BeautifulSoup as bs
import requests
import math
"""
TODO
Standard deviation calculation
Calculate weight based on distance
Add 3 weights (User set, distance, last_updated)
Add wind bearing last_updated weights
"""
def process(config):
def scrape(station, units):
USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36"
LANGUAGE = "en-US,en;q=0.5"
URL = "https://www.wunderground.com/dashboard/pws/"
try:
session = requests.Session()
session.headers["User-Agent"] = USER_AGENT
session.headers["Accept-Language"] = LANGUAGE
session.headers["Content-Language"] = LANGUAGE
html = session.get(URL + station["id"])
soup = bs(html.text, "html.parser")
except:
return None
if (
soup.findAll("span", attrs={"_ngcontent-app-root-c173": ""})[21].text
== "Online"
):
data = {}
# Last updated value
data["LAST_UPDATED"] = soup.findAll(
"span", attrs={"class": "ng-star-inserted"}
)[0].text
strings = data["LAST_UPDATED"].split()
if (strings[0] == "(updated") and (strings[3] == "ago)"):
value = int(strings[1])
if (value >= 0) and (value <= 60):
if strings[2][0:6] == "second":
data["LAST_UPDATED"] = 1 / value
elif strings[2][0:6] == "minute":
data["LAST_UPDATED"] = 1 / (value * 60)
elif strings[2][0:4] == "hour":
if (value >= 0) and (value <= 24):
data["LAST_UPDATED"] = 1 / (value * 3600)
else:
return None
else:
return None
else:
return None
# Get Temperature
if "temp" in station["parameters"]:
data["temp"] = soup.find("span", attrs={"class": "wu-value"})
data["temp"] = round(float(data["temp"].text))
if units["temp"] == "c":
data["temp"] = round((data["temp"] - 32) * (5 / 9), 1)
# Get Wind Speed
if "wind_speed" in station["parameters"]:
data["wind_speed"] = soup.findAll("span", attrs={"class": "wu-value"})
data["wind_speed"] = round(float(data["wind_speed"][2].text), 1)
if units["speed"] == "kmph":
data["wind_speed"] = round(data["wind_speed"] * 1.6, 1)
elif units["speed"] == "mps":
data["wind_speed"] = round(data["wind_speed"] * (4 / 9), 1)
# Get Wind Gust
if "wind_gust" in station["parameters"]:
data["wind_gust"] = soup.findAll("span", attrs={"class": "wu-value"})
data["wind_gust"] = round(float(data["wind_gust"][3].text), 1)
if units["speed"] == "kmph":
data["wind_gust"] = round(data["wind_gust"] * 1.6, 1)
elif units["speed"] == "mps":
data["wind_gust"] = round(data["wind_gust"] * (4 / 9), 1)
# # Get Wind Direction
# if "wind_direction" in station["parameters"]:
# data["wind_direction"] = soup.find(
# "span", attrs={"class": "text-bold"}
# ).text
# Get Wind Bearing
if "wind_bearing" in station["parameters"]:
data["wind_bearing"] = soup.find(
"div", attrs={"class": "arrow-wrapper"}
)
string_full = ((data["wind_bearing"]["style"]).split())[1]
string_start = string_full[0:7]
string_end = string_full[-5:-1]
if (string_start == "rotate(") and (string_end == "deg)"):
data["wind_bearing"] = int(string_full[7:-5]) - 180
else:
data["wind_bearing"] = None
# Get Precipitation Rate
if "precip_rate" in station["parameters"]:
data["precip_rate"] = soup.findAll("span", attrs={"class": "wu-value"})
data["precip_rate"] = round(float(data["precip_rate"][5].text), 2)
if units["precip"] == "mm":
data["precip_rate"] = round(data["precip_rate"] * 25.4, 2)
# Get Precipitation Total
if "precip_total" in station["parameters"]:
data["precip_total"] = soup.findAll("span", attrs={"class": "wu-value"})
data["precip_total"] = round(float(data["precip_total"][8].text), 2)
if units["precip"] == "mm":
data["precip_total"] = round(data["precip_total"] * 25.4, 2)
# Get Pressure
if "pressure" in station["parameters"]:
data["pressure"] = soup.findAll("span", attrs={"class": "wu-value"})
data["pressure"] = round(float(data["pressure"][6].text), 2)
if units["pressure"] == "hpa":
data["pressure"] = round(data["pressure"] * 33.86, 2)
# Get Humidity
if "humidity" in station["parameters"]:
data["humidity"] = soup.findAll("span", attrs={"class": "wu-value"})
data["humidity"] = round(float(data["humidity"][7].text))
# Get UV Index
if "uv_index" in station["parameters"]:
data["uv_index"] = soup.findAll("span", attrs={"class": "wu-value"})
data["uv_index"] = round(float(data["uv_index"][9].text))
# Get Solar Radiation
if "radiation" in station["parameters"]:
data["radiation"] = soup.findAll(
"div", attrs={"class": "weather__text"}
)
strings = data["radiation"][-1].text.split()
if strings[1][-8:-3] == "watts":
data["radiation"] = round(float(strings[0]), 1)
else:
data["radiation"] = None
station["data"] = data
return station
stations = []
avg_values = {}
for station in config["stations"]:
stations.append(scrape(station, config["units"]))
# Get average values, except wind bearing and wind direction
for parameter in [
"temp",
"wind_speed",
"wind_gust",
"pressure",
"humidity",
"precip_rate",
"precip_total",
"uv_index",
"radiation",
]:
last_updated_total = 0
for station in stations:
if parameter in station["data"] and station["data"][parameter] != None:
last_updated_total += station["data"]["LAST_UPDATED"]
avg_values[parameter] = 0
for station in stations:
if parameter in station["data"] and station["data"][parameter] != None:
last_updated_weight = (
station["data"]["LAST_UPDATED"] / last_updated_total
)
avg_values[parameter] += (
last_updated_weight * station["data"][parameter]
)
avg_values[parameter] = round(avg_values[parameter], 2)
# Get average wind bearing
winds = []
wind_vectors = []
for station in stations:
if (
"wind_bearing" in station["data"]
and station["data"]["wind_bearing"] != None
):
winds.append(
(station["data"]["wind_bearing"], station["data"]["wind_speed"])
)
for i, wind in enumerate(winds):
wind_vectors.append([None, None])
wind_vectors[i][0] = math.sin(math.radians(wind[0])) * wind[1]
wind_vectors[i][1] = math.cos(math.radians(wind[0])) * wind[1]
avg_x, avg_y = 0, 0
for wind_vector in wind_vectors:
avg_x += wind_vector[0]
avg_y += wind_vector[1]
avg_values["wind_bearing"] = round(math.degrees(math.atan2(avg_x, avg_y)))
avg_values["wind_speed"] = round(
math.sqrt(avg_x ** 2 + avg_y ** 2) / len(wind_vectors), 2
)
if avg_values["wind_bearing"] < 0:
avg_values["wind_bearing"] += 360
return avg_values
if __name__ == "__main__":
config = {
"units": {
"temp": "c",
"pressure": "hpa",
"speed": "kmph",
"precip": "mm",
},
"stations": [
{
"id": "ICURITIB24",
"parameters": [
"temp",
"wind_speed",
"wind_gust",
"wind_bearing",
"pressure",
"humidity",
"precip_rate",
"precip_total",
"uv_index",
"radiation",
],
},
{
"id": "ICURITIB28",
"parameters": [
"temp",
"wind_speed",
"wind_gust",
"wind_bearing",
"pressure",
"humidity",
"precip_rate",
"precip_total",
"uv_index",
"radiation",
],
},
{
"id": "IPRCURIT2",
"parameters": [
"temp",
"wind_speed",
"wind_gust",
"wind_bearing",
"pressure",
"humidity",
"precip_rate",
"precip_total",
],
},
],
}
for k, v in process(config).items():
print(f"{k}\t{v}")
| [
"lfhohmann@gmail.com"
] | lfhohmann@gmail.com |
87bc9e57bfdc8136d7454cbf455ebe81167c29bd | 0b069c40ffdbf117170e411598181380f768f338 | /flaskr/flask_app/helper.py | 8ec26ae26b58196ad163df9d098ec1279ffe34df | [] | no_license | evarum/flask_wildcam | 6a5d28f7478bb4e818b3dd68368a20557e3f6b57 | 462e8a946c096cfc17505d7fc3a0d43d757fc954 | refs/heads/master | 2022-11-29T21:59:31.613350 | 2020-08-12T19:17:21 | 2020-08-12T19:17:21 | 286,428,180 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,730 | py | import os
from flaskr.flask_app.config import PATH, PIC_ENDUNG, VID_ENDUNG, DATE_FORMAT, TIME_FORMAT
# creates dictionary with two connected keys date, time
def get_file_meta(filename):
# cut includes time information
cut = filenames_split(filename)
# cut out needed parts
year = cut[0:4]
month = cut[4:6]
day = cut[6:8]
hour = cut[8:10]
minute = cut[10:12]
second = cut[12:14]
# format it
date = DATE_FORMAT.format(day, month, year)
time = TIME_FORMAT.format(hour, minute, second)
meta = {}
meta['date'] = date
meta['time'] = time
return meta
# assignment of date,time to element in folder (picture or video)
def data_to_html_file():
filenames = pic_vid_connection()
files = []
# gradually assigning and saving of filename
for file_pair in filenames:
vid_file = file_pair[0]
pic_file = file_pair[1]
meta = get_file_meta(vid_file)
meta['picture'] = pic_file
meta['video'] = vid_file
files.append(meta)
return files
# split filename in event, date/time, ending
def filenames_split(video):
cut = video.split('.')
cut = cut[0]
cut = cut.split('-')
cut = cut[1]
return cut
def cut_data_fixed_to_filename(end):
list_cut_element, cut_elements = data_to_cut(end)
# filenames will be sorted list of cut_elements' values
filenames = []
for i in list_cut_element:
# element_value list filled with responding values to list_cut_element
element_value = cut_elements[i]
filenames.append(element_value)
return filenames
def data_to_cut(end):
ext = end
direc = PATH
# list of all elements in Path-folder (filenames not sorted)
elements_list = []
for i in os.listdir(direc):
if os.path.splitext(i)[1] == ext:
elements_list.append(i)
# Dictionary to store eventual date/time together with filename
cut_elements = {}
for element in elements_list:
# filename shortened to date/time
cut_element = filenames_split(element)
# Dictionary-entry cut_element(date/time): element(filename)
cut_elements[cut_element] = element
# keys of cut_elements to list
list_cut_element = list(cut_elements.keys())
# sorted list old to new
list_cut_element.sort()
return list_cut_element, cut_elements
# Elfi
# two sorted lists are compared and written down if they fullfill the following condition: lower_limit <= element_between < upper_limit
def paar_sort(list1, list2):
# limits_list sets the borders of possible placement for elements of liste_between
limits_list = list1
liste_between = list2
paar = []
# iteration through limits_list
for lower_limit in limits_list:
lower_limit_int = int(lower_limit)
# print(lower_limit)
# defining upper_limit
lower_limit_index = limits_list.index(lower_limit)
upper_limit_index = lower_limit_index + 1
if upper_limit_index >= len(limits_list):
# last element has no upper_limit in list
upper_limit = None
else:
upper_limit = int(limits_list[upper_limit_index])
for element_between in liste_between:
element_between_int = int(element_between)
# is element_between bigger/equal than the lower_limit?
if element_between_int >= lower_limit_int:
# special case last element
if upper_limit is None:
paar.append([lower_limit, element_between])
break
# is element_between bigger than the upper_limit?
if element_between_int > upper_limit:
# exit loop and go to next element_between
continue
else:
# appending lower_limit and element_between to list paar
paar.append([lower_limit,element_between])
break
liste_between.remove(element_between)
# giving back the finished sets
return paar
def pic_vid_connection():
limit_list, limit_dict = data_to_cut(VID_ENDUNG)
# print(limit_list)
# print(limit_dict)
pic_list, pic_dict = data_to_cut(PIC_ENDUNG)
# sorted lists are being connected to one
paar_list = paar_sort(limit_list, pic_list)
results = []
# for loop takes cut videos and pictures, puts it into the list limit_dict and pic_dict, then appends it to list results
for paar in paar_list:
cut_vid = paar[0]
cut_pic = paar[1]
video_value = limit_dict[cut_vid]
picture_value = pic_dict[cut_pic]
results.append([video_value, picture_value])
return results | [
"eva.rum@gmx.de"
] | eva.rum@gmx.de |
64323185ac880aec9653bf9fa0d3cb3e19fc36fc | 8dd70faef176c3aef5f048ba4b88b00df602181c | /code/utils/tests/test_qda.py | 9c488a3ca611973f5584b708561e335fdbcb6389 | [] | no_license | foolshin/project-kappa | 6f5bf844899ab87c943ef7c7898abeb20c782ecc | a6df9455dc037ef789c2aab52d8342cfbbb74ad0 | refs/heads/master | 2020-11-23T19:37:40.467798 | 2015-12-17T01:56:18 | 2015-12-17T01:56:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 149 | py | # # This file is for quadratic discriminant analysis
# import numpy as np
# from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
| [
"iyousuf@Ebay.com"
] | iyousuf@Ebay.com |
9bb432e6572b6e4e0f6cfb8d6ad619c7c12364f0 | d854e866978591cf80e1f89898dec032376252b7 | /Age.py | e21dfb3c75ca897bb0ca31b0ed1047dfa3956a34 | [] | no_license | notsamicc/CollegePython | e43c957bb23cf6a4daad032d7c0713717f7b847c | c5fc62983934e1566ba19f8a4f335da29b184b06 | refs/heads/main | 2023-08-14T12:10:08.330370 | 2021-09-21T18:11:24 | 2021-09-21T18:11:24 | 408,927,614 | 1 | 0 | null | 2021-09-21T18:15:06 | 2021-09-21T18:15:05 | null | UTF-8 | Python | false | false | 350 | py | age = int(input('Enter your age: '))
shoeSize = float(input('Enter your shoe size: '))
itemCost = float(input('Enter cost of item: '))
postCode = str(input('Enter your Postcode: '))
lengthHeight = float(input('Enter your height (cm): '))
stockQuantity = int(input('Amount in stock: '))
mobileNumber = str(input('Enter your phone number: '))
| [
"noreply@github.com"
] | notsamicc.noreply@github.com |
707fdc78163097b7977c00186c2f29a449fb33d7 | a90ea38bdc8c620e73fce2da58c9a61d649d8a5b | /nn_architecture/.env/lib/python3.6/reprlib.py | f3f54ead62cf34554556042215b70bcfa1468633 | [] | no_license | shaimsn/deepblurr | ab15af22b8a1605113bcb4684325529f4d6b86ba | 39f272b11813fa710de0affe129fe6c288e8d720 | refs/heads/master | 2021-04-28T01:20:45.494180 | 2018-03-17T03:28:16 | 2018-03-17T03:28:16 | 122,271,996 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 63 | py | /Users/shaimsn/Applications/miniconda3/lib/python3.6/reprlib.py | [
"shaimsn@chardit.lan"
] | shaimsn@chardit.lan |
b04fc33a9eb8f824a93714a4d4800f24bef66b79 | cf1484c6a885173a766d180561b1fd917751000b | /user_credentials.py | 9a8890c00d86ae74b10f1919365bc3c4a2d550fb | [
"MIT"
] | permissive | paulettemaina/password_locker | a68ea795317b8cf2225fe9149da8cc47e3910cfc | e1e1f61e5ac03870e5d2306d519ce326d30f32db | refs/heads/master | 2020-03-19T14:21:36.546124 | 2018-06-12T09:10:23 | 2018-06-12T09:10:23 | 136,618,819 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,487 | py | import pyperclip
import string
import random
import secrets
class User:
'''
Class that generates new instances of users
'''
user_list = [] # Empty user list
def __init__(self,login_name,password):
self.login_name = login_name
self.password = password
def save_user(self):
'''
save_user method saves user object into user_list
'''
User.user_list.append(self)
@classmethod
def find_by_login_name(cls,login_name):
'''
Method that takes in a login_name and returns a user that matched that login_name.
Args:
login_name: Phone login_name to search for
Returns:
Credentials of person that matched the login_name.
'''
for user in cls.user_list:
if user.login_name == login_name:
return user
@classmethod
def user_exist(cls,login_name):
'''
Method that checks if a credentials exists from the credentials list.
Args:
login_name: Phone login_name to search if it exists
Returns :
Boolean: True or false depending if the credentials exists
'''
for user in cls.user_list:
if user.login_name == login_name:
return True
return False
class Credentials:
'''
Class that generates new instances of credentials
'''
credentials_list = []
def __init__(self,site,user_id,pass_key):
self.site = site
self.user_id = user_id
self.pass_key = pass_key
def save_credentials(self):
'''
save_credentials method saves credentials object into credentials_list
'''
Credentials.credentials_list.append(self)
def delete_credentials(self):
'''
delete_credentials method deletes a saved credentials from the credentials_list
'''
Credentials.credentials_list.remove(self)
def generate_passwords(self):
alphabet = string.ascii_letters + string.digits
generated_password = ''.join(secrets.choice(alphabet) for i in range(20)) # for a 20-character password
return generated_password
@classmethod
def find_by_user_id(cls,user_id):
'''
Method that takes in a login_name and returns a credentials that matched that login_name.
Args:
login_name: login_name to search for credentials
Returns:
Credentials of person that matched the login_name.
'''
for credentials in cls.credentials_list:
if credentials.user_id == user_id:
return credentials
@classmethod
def credentials_exist(cls,user_id):
'''
Method that checks if a credentials exists from the credentials list.
Args:
user_id: user_id to search if it exists
Returns :
Boolean: True or false depending if the credentials exists
'''
for credentials in cls.credentials_list:
if credentials.user_id == user_id:
return True
return False
@classmethod
def display_credentials(cls):
'''
method that returns the credentials list
'''
return cls.credentials_list
@classmethod
def copy_pass_key(cls,user_id):
credentials_found = Credentials.find_by_user_id(user_id)
pyperclip.copy(credentials_found.pass_key)
| [
"paulettemaina@gmail.com"
] | paulettemaina@gmail.com |
b4118ccd20e3a44af5e0864ac2e03dd8488f8d35 | a6d62bb9f4cb00fea89ff10e27b516890dc8a49a | /utils/generic_utils.py | 57536f8847a50c7ab234709d48cbf404620729cc | [
"MIT"
] | permissive | WeberJulian/Wav2Vec-Wrapper | dca6be0edd25f67b9a3e2719dc5bee8b0bbdfb4f | 84519cd51a4f3d9cb61de99c5712640f3cf5213d | refs/heads/main | 2023-06-11T15:26:53.754106 | 2021-07-06T17:13:38 | 2021-07-06T17:13:38 | 383,545,362 | 0 | 0 | MIT | 2021-07-06T17:14:03 | 2021-07-06T17:14:03 | null | UTF-8 | Python | false | false | 2,816 | py | import os
import re
import yaml
import json
import torch
import numpy as np
from datasets import load_metric
wer_metric = load_metric("wer")
def calculate_wer(pred_ids, labels, processor, debug=False):
labels[labels == -100] = processor.tokenizer.pad_token_id
pred_string = processor.batch_decode(pred_ids)
label_string = processor.batch_decode(labels, group_tokens=False)
wer = wer_metric.compute(predictions=pred_string, references=label_string)
if debug:
print(" > DEBUG: \n\n PRED:", pred_string, "\n Label:", label_string)
return wer
class AttrDict(dict):
"""A custom dict which converts dict keys
to class attributes"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__dict__ = self
def read_json_with_comments(json_path):
# fallback to json
with open(json_path, "r", encoding="utf-8") as f:
input_str = f.read()
# handle comments
input_str = re.sub(r"\\\n", "", input_str)
input_str = re.sub(r"//.*\n", "\n", input_str)
data = json.loads(input_str)
return data
def load_config(config_path: str) -> AttrDict:
"""Load config files and discard comments
Args:
config_path (str): path to config file.
"""
config = AttrDict()
ext = os.path.splitext(config_path)[1]
if ext in (".yml", ".yaml"):
with open(config_path, "r", encoding="utf-8") as f:
data = yaml.safe_load(f)
else:
data = read_json_with_comments(config_path)
config.update(data)
return config
def load_vocab(voba_path):
config = AttrDict()
config.update(read_json_with_comments(voba_path))
return config
def save_best_checkpoint(log_dir, model, optimizer, lr_scheduler, scaler, step, epoch, val_loss, best_loss, early_epochs=None):
if val_loss < best_loss:
best_loss = val_loss
if early_epochs is not None:
early_epochs = 0
model_save_path = os.path.join(log_dir, 'pytorch_model.bin')
# model.save_pretrained(log_dir) # export model with transformers for save the config too
torch.save(model.state_dict(), model_save_path)
optimizer_save_path = os.path.join(log_dir, 'optimizer.pt')
checkpoint_dict = {
'optimizer': optimizer.state_dict(),
'scheduler': lr_scheduler.state_dict(),
'step': step,
'epoch': epoch
}
if scaler is not None:
checkpoint_dict['scaler'] = scaler.state_dict()
torch.save(checkpoint_dict, optimizer_save_path)
print("\n > BEST MODEL ({0:.5f}) saved at {1:}".format(
val_loss, model_save_path))
else:
if early_epochs is not None:
early_epochs += 1
return best_loss, early_epochs | [
"edresson1@gmail.com"
] | edresson1@gmail.com |
93a06ba7285e8c66a9172967a58504e89cbb7c8c | 3170b5a2bbc6aca1394a598e1616e07649d125ae | /auctions/models.py | 4c20b80e389eabf207d081d88b16f32e8bcf1479 | [] | no_license | claytonandersoncode/Commerce | 8ab0d44b4cb2d485d4b7cb028d5e5159e18a79a6 | ea3daf2e77365d3afdd77adcc326c2f4974b22ef | refs/heads/master | 2023-01-20T03:38:09.963396 | 2020-11-18T03:54:53 | 2020-11-18T03:54:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,912 | py | from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
pass
class Category(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
def __str__(self):
return f"{self.title}"
class Listing(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
startbid = models.FloatField(null=True)
imageurl = models.URLField()
category = models.ForeignKey(Category, null=True, on_delete=models.CASCADE, related_name="category")
is_active = models.BooleanField(default=True)
who_created = models.ForeignKey(User, on_delete=models.CASCADE, related_name="who_created")
who_won = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, related_name="who_won")
def __str__(self):
return f"{self.title} by {self.who_created}"
class Bid(models.Model):
bid = models.FloatField()
who_bid = models.ForeignKey(User, on_delete=models.CASCADE)
time = models.DateTimeField(auto_now=True)
which_listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="bids")
def __str__(self):
return f"{self.who_bid} bid {self.bid} on {self.which_listing} at {self.time}"
class Comment(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
who_commented = models.CharField(max_length=100)
time = models.DateTimeField(auto_now=True)
which_listing = models.ForeignKey(Listing, on_delete=models.CASCADE)
def __str__(self):
return f"{self.title} by {self.who_commented} on {self.which_listing}"
class Watchlist(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
listing = models.ForeignKey(Listing, on_delete=models.CASCADE)
def __str__(self):
return f"{self.user} is watching {self.listing}"
| [
"claytonanderson@Claytons-Mac-mini.local"
] | claytonanderson@Claytons-Mac-mini.local |
f2c94b0335e7ebd36679aa87368c676aeed4b5da | f44b8532427b82d8682d01d4a55a2fd701e901d7 | /tests/__init__.py | 2ce5b7944ccae8bb434ac2fda3af848f2b8cd7b8 | [
"Apache-2.0"
] | permissive | fengyc/gwapp | 8be2e30a074a98acc94251c2083f13bed7aae925 | 74d8c9fac4171133fe8ab63572b5161cfa5890b1 | refs/heads/master | 2021-01-20T20:35:51.331959 | 2016-07-04T15:49:55 | 2016-07-04T15:49:55 | 61,725,501 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 98 | py | # -*- coding:utf-8 -*-
# Copyright (c) 2016 Yingcai FENG
#
# 2016/6/24 fengyc: Create __init__.py. | [
"fengyc.work@gmail.com"
] | fengyc.work@gmail.com |
47e279735f840d1e03f6ec23975d5337aa5da6bc | 376e4114a1ef612ae5d0d2a53a74076870562067 | /2017/R1CA/Pancake.py | 91a0621901dc3c2ad74766f7eec04f93645d6b25 | [] | no_license | jacegem/google-codejam-py | 1890e895c56ceb6c4cbcaa4c5cae213f1cb2dd6a | 4e3300021c7f54c339da92afc0974d5076d60499 | refs/heads/master | 2021-06-06T07:45:53.946239 | 2021-04-10T03:30:49 | 2021-04-10T03:30:49 | 89,255,303 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 445 | py |
class Pancake:
def __init__(self, r, h, top, surface):
self.r = r
self.h = h
self.top = top
self.surface = surface
self.used = False
self.top_surface = top + surface
def set_used(self, used):
self.used = used
def is_used(self):
return self.used
def get_top_surace(self):
return self.top_surface
def sort_surface(self):
return self.surface
| [
"jacegem@gmail.com"
] | jacegem@gmail.com |
4fb3c5df8ef6d11c3abad44c7c3764e291a1ca22 | 11e46b70f32f4c4871e7a19c8e6d8104f428e306 | /SPP.py | 6602ffbf98efeed7c8c8027b4bad25807e2b5dc9 | [] | no_license | leobossi/Transfer-Matrix-Method | 494cb11b24c0b2b8ba8596d0dd9e4064988dedef | c3d6d5cbb7d2c7ec43fe1639d6657ac96a6a8b61 | refs/heads/main | 2023-03-13T22:43:56.801846 | 2021-03-08T17:36:56 | 2021-03-08T17:36:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,070 | py | import numpy as np
import tmmfile as tmm
import matplotlib.pyplot as plt
import matplotlib as mpl
import cmath as cm
# Importing different materials
MgF2 = np.loadtxt("MgF2.txt", skiprows=1, unpack=True)
BK7 = np.loadtxt("BK7.txt", skiprows=1, unpack=True)
Au = np.loadtxt('Au.txt', skiprows = 1, unpack = True)
Ta2O5 = np.loadtxt("Ta2O5.csv", skiprows=1, unpack=True, delimiter=",")
TiO2 = np.loadtxt("Devore-o.csv", skiprows=1, unpack=True, delimiter=",")
SiO2 = np.loadtxt("Malitson.csv", skiprows=1, unpack=True, delimiter=",")
# Converting from micrometers to nanometers
Ta2O5[0] = Ta2O5[0] * 1000
TiO2[0] = TiO2[0] * 1000
SiO2[0] = SiO2[0] * 1000
# Adding a k column to TiO2 and SiO2 so they fit the expected format
TiO2 = list(TiO2)
SiO2 = list(SiO2)
Timgs = list(np.zeros(len(TiO2[0])))
Simgs = list(np.zeros(len(SiO2[0])))
TiO2.append(Timgs)
SiO2.append(Simgs)
# Set the default color cycle
mpl.rcParams['axes.prop_cycle'] = mpl.cycler(color=["b", "k", "r"])
# comparison between p (TM) polarisation and s
inc_lam = 633
d_gold = [49]
nB = (tmm.complx_n(inc_lam, *BK7))
nG = (tmm.complx_n(inc_lam, *Au))
nA = 1.0003 #refractive index of air
critical_ang = np.arcsin(nA/ nB)
spr_ang = np.arcsin(((1/nB) * (nA*nG) / cm.sqrt((nA**2 + nG**2))))
n_list = [nG, nA]
angles = np.arange(0, np.pi / 2, 0.001)
r_p = []
r_s = []
for ang in angles:
rp, tp, = tmm.TMM(inc_lam, ang, 'p', n_list, d_gold, glass_inc=True, material=BK7)
r_p.append(rp)
rs, ts, = tmm.TMM(inc_lam, ang, 's', n_list, d_gold, glass_inc=True, material=BK7)
r_s.append(rs)
plt.figure()
plt.plot(angles, r_p, label='p polarisation')
plt.plot(angles, r_s, label='s polarisation')
plt.title("SPP from BK7 to air through Gold")
plt.xlabel('Angle of incidence (rad)')
plt.ylabel('Total reflection')
plt.vlines(critical_ang, 0, 1, color='g', label='critical angle')
plt.vlines(spr_ang, 0, 1, color = 'r', label = "Expected angle for SPP")
plt.grid()
plt.legend()
#%%
#modelling SPP from BK7 to SiO2 Substrate using thin Gold film
inc_lam = 633
d_gold = [17]
nB = (tmm.complx_n(inc_lam, *BK7))
nG = (tmm.complx_n(inc_lam, *Au))
nA = (tmm.complx_n(inc_lam, *SiO2))
critical_ang = np.arcsin(nA/ nB)
spr_ang = np.arcsin(((1/nB) * (nA*nG) / cm.sqrt((nA**2 + nG**2))))
n_list = [nG, nA]
angles = np.arange(0, np.pi / 2, 0.001)
r_p = []
r_s = []
for ang in angles:
rp, tp, = tmm.TMM(inc_lam, ang, 'p', n_list, d_gold, glass_inc=True, material=BK7)
r_p.append(rp)
rs, ts, = tmm.TMM(inc_lam, ang, 's', n_list, d_gold, glass_inc=True, material=BK7)
r_s.append(rs)
plt.figure()
plt.plot(angles, r_p, label='p polarisation')
plt.plot(angles, r_s, label='s polarisation')
plt.title("SPP from BK7 to SiO2 using Gold")
plt.xlabel('Angle of incidence (rad)')
plt.ylabel('Total reflection')
plt.vlines(critical_ang, 0, 1, color='r', label='critical angle')
plt.vlines(spr_ang, 0, 1, color = 'c', label = "Expected SPP angle")
plt.grid()
plt.legend()
| [
"noreply@github.com"
] | leobossi.noreply@github.com |
ef2462a271d262f5f3b3a636ac884b3dcd3f93ff | 4cec717b8fe683580919ca7d51acba9f04a1eed6 | /script/test_login.py | a16a1993b854b47da980aba2054117118bc3df58 | [] | no_license | waicl/practice | 7e22382f316509423c2f944aa316da7870edf1c4 | 9fd8782767508707ea13e94c2fa26e30e6986b91 | refs/heads/master | 2021-05-17T09:56:13.466262 | 2020-03-28T07:49:35 | 2020-03-28T07:49:35 | 250,731,812 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 942 | py | #导包
import unittest
import requests
import data
from api.login_api import LoginApi
from parameterized import parameterized
from app import BASE_DIR
from utils import read_login_data
# 创建测试类
class TestIHRMLogin(unittest.TestCase):
# 进行初始化
def setUp(self) -> None:
self.login_api = LoginApi()
def tearDown(self) -> None:
pass
# 创建测试方法
filename = BASE_DIR + '/data/login.json'
@parameterized.expand(read_login_data(filename=filename))
def test01_login(self,mobile,password,success,code):
#使用requests模块发送登录接口请求
response = self.login_api.login(mobile,password)
# 打印登录结果
print('登录结果为:',response.json())
# 对登录结果进行断言
self.assertEqual(success,response.json().get('success'))
self.assertEqual(code,response.json().get('code'))
| [
"1091924611@qq.com"
] | 1091924611@qq.com |
54635ee2f2519f8561c12f95036c1a7b40c38e95 | 59a3732650e965e07986765686765abaf673700e | /pyExp/.venv/bin/slugify | 52c595da1257012132d1124f1505c3bd8dc01985 | [] | no_license | Anisha95/python-super-experiment | 7e8e8c8dc3eec3048c686d8801cc8bc1793c3424 | 9f55a998d98fc39969a5742b45cd66afa4d32ac0 | refs/heads/master | 2020-05-27T16:27:07.404188 | 2019-06-06T10:17:07 | 2019-06-06T10:17:07 | 188,698,891 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 266 | #!/home/anisha/PyExp/python-super-experiment/pyExp/.venv/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from slugify.slugify import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())
| [
"pal.anisha26@gmail.com"
] | pal.anisha26@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.